-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
1723 lines (1620 loc) · 65.7 KB
/
db.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//initialize global variable.
var db, syncHandler, remoteDb;
function updateOnlineStatus(event) {
const condition = navigator.onLine ? "online" : "offline";
document.documentElement.classList.add(condition);
document.documentElement.classList.remove(condition === "online" ? "offline" : "online");
console.log(`Event: ${event.type}; Status: ${condition}`);
logData('connection', condition);
}
window.addEventListener('load', function() {
//Update Online status
updateOnlineStatus(event);
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);
window.currentWakeLock = navigator.wakeLock.request();
//Login listener
document.getElementById('db_select').addEventListener('change', async function(e){
const loginElement = document.getElementById('login');
const selectedValue = document.getElementById('db_select').value;
loginElement.removeAttribute('class'); // Remove all classes
if (selectedValue === 'create_local') {
loginElement.classList.add('create_local');
} else if (selectedValue === 'connect_remote') {
loginElement.classList.add('connect_remote');
} else if (selectedValue.endsWith('(local)')) {
loginElement.classList.add('login_local');
} else if (selectedValue.endsWith('(remote)')) {
loginElement.classList.add('login_remote');
}
//All Demo login and import code happens here.
if(e.target.value == 'demo(local)') {
let databases = JSON.parse(localStorage.getItem('databases'));
if(databases && databases[e.target.value]) {
dbLogin('login_local', 'demo(local)','Johannes Gutenberg', 42);
notyf.info('<b>Login Info</b><br>Username: Johannes Gutenberg<br> Pin: 42', 'green');
}
else {
dbLogin('create_local', 'demo(local)','Johannes Gutenberg', 42);
notyf.info('<b>Login Info</b><br>Username: Johannes Gutenberg<br> Pin: 42', 'green');
//add import process to happen as soon as possible afterwards.
try {
const response = await fetch('https://ycanta.canaanf.org/Public Domain.json');
const blob = await response.blob();
const file = new File([blob], 'Public Domain.json', { type: 'TEXT/JSON' });
setTimeout(function(){
handleFile(file);
notyf.info('Imported Public Domain songs', 'green');
},500);
} catch (error) {
console.error('Error fetching file:', error);
}
}
}
});
setTimeout(function(){document.getElementById('db_select').dispatchEvent(new Event('change'));},50);
});
async function checkRemoteDBandSyncHandler(){
if(!db) {
console.log('no db!')
notyf.info('Logging out, something broke!', 'red');
dbLogout();
}
//get user from local db, pwd, and remote url...
let user = await db.get('_local/'+window.user._id);
let pwd = user.pwd;
let username = user._id.slice(9);
let remote_url = user.remote_url;
if(!remoteDb && remote_url) {
console.log('setting up remoteDb')
await loginRemoteDb(remote_url, username, pwd);
}
if(!syncHandler && remote_url) {
console.log('setting up sync handler')
await setUpSyncHandler();
}
}
async function loginRemoteDb(remote_url, username, pwd) {
remoteDb = new PouchDB(remote_url, {skip_setup: true});
const ajaxOpts = {
ajax: {
headers: {
Authorization: getBasicAuthHeader(username, pwd),
},
},
};
const batman = await remoteDb.logIn(username, pwd, ajaxOpts);
console.log("I'm Batman.", batman);
//check access, admin different than user
let info = await remoteDb.info();
const userJS = await remoteDb.getUser(username);
if(!userJS.roles.some((role) => role.startsWith(info.db_name))) {
dbLogout();
alert('you do not have access to this database');
return;
}
window.roles = batman.roles.reduce((a, v) => ({ ...a, [v]: true}), {});
notyf.info('Connected to server', 'green');
}
function clearAllData() {
try {
window.indexedDB.databases().then((r) => {
for (var i = 0; i < r.length; i++) window.indexedDB.deleteDatabase(r[i].name);
}).then(() => {
localStorage.clear();
location.reload();
});
}
catch (error) { //If there's an error, we fall back to our local storage list of databases, and do our best to clear.
console.log(error.message);
let databases = JSON.parse(localStorage.getItem('databases'));
for (db of Object.keys(databases)) { //iterate through our listed databases and remove all we know of.
removeDbfromLocalStorage(databases[db].name);
}
localStorage.clear();
location.reload();
}
}
function dbChanges() {
window.changeHandler = db.changes({
since: 'now',
live: true,
include_docs: true
}).on('change', function (change) {
// received a change
if (change.deleted) {
// document was deleted
console.log('deleted: ' + change.doc._id);
} else {
// document was added/modified
}
//what type?
//song?
if(change.doc._id.startsWith('s-')){
loadRecentSongs();
//only load song if it's the one that's up.
if(window.song._id === change.doc._id && document.body.classList.contains('song')){ //if we're viewing this song.
delete window.song;
Promise.all([loadSong(change.doc._id)]) //little bit of a hack - had an issue where the url update reloads the songbook and song, then this triggers causing the edit buttons to not work...
.then(function(values) {
updateAllLinks();
});
notyf.info('Song updated', 'var(--song-color)');
} else {
notyf.info(`Song "${change.doc.title}" updated by ${window.users[change.doc.editedBy]}`,
'var(--song-color)',
`#${window.songbook._id}&${change.doc._id}`);
}
//update all songs in songbooks
if(window.songbook_list != undefined ){
window.songbook_list.get('song-id',change.doc._id)
.forEach(function(song){
let new_change = mapSongRowToValue(change);
new_change['song-status'] = song.values()['song-status'];
song.values(new_change);
});
}
if(window.songbook_edit_togglesongs_list != undefined){
window.songbook_edit_togglesongs_list.get('song-id',change.doc._id)
.forEach(function(song){song.values(mapSongRowToValue(change))});
}
if(window.songbook._id == 'sb-allSongs') {
window.songbook._id = '';
loadSongbook('sb-allSongs');
}
}
//songbook?
else if(change.doc._id.startsWith('sb-')){
if(window.songbook._id === change.doc._id && (document.body.classList.contains('songList') || document.body.classList.contains('song'))){
window.songbook = '';
loadSongbook(change.doc._id);
notyf.info('Songbook updated', 'var(--songList-color)');
} else {
notyf.info(`Songbook "${change.doc.title}" updated by ${window.users[change.doc.editedBy]}`,
'var(--songList-color)',
`#${change.doc._id}`);
}
//update the songbook entry in songbooks_list
if(window.songbooks_list != undefined){
window.songbooks_list.get('songbook-id',change.doc._id)
.forEach(function(songbook){songbook.values(mapSongbookRowToValue(change))});
window.songbooks_list.sort('user-fav', {order: 'desc', sortFunction: sortFavSongbooks});
}
}
else if(change.doc._id.startsWith('c_')){
let songbook_id = change.doc._id.match(/sb-.*?_/g)[0].replace('_','');
if(window.songbook._id == songbook_id && window.songbook.showComments){
let song_id = change.doc._id.match(/s-.*?$/g)[0];
$('li[data-song-id="'+song_id+'"] .toggle_comment').attr('data-comment-number', change.doc.comments.length);
let comments = '';
for(comment of change.doc.comments){
comments += `<div><b>${comment.user} </b>${new Date(comment.date).toLocaleTimeString(undefined, { weekday: 'long', year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit'})}<pre>${comment.comment}</pre></div>`;
}
$('li[data-song-id="'+song_id+'"] .comments').html(comments);
notyf.info(`Comment added to "${song_id}" by ${change.doc.comments[change.doc.comments.length - 1].user}`,
'var(--songList-color)');
}
}
else if(change.doc._id.startsWith('u-')){
if(!window.users){window.users={};} //doesn't always exist.
window.users[change.doc._id] = change.doc.name;
if(change.doc._id === window.user._id){
let fav_sbs = change.doc.fav_sbs;
//jquery remove all favs
$('#songbooks .list li').each(function(){
let fav = false;
if(fav_sbs.indexOf($(this).attr('data-songbook-id')) > -1) {
fav = true;
}
$(this).attr('data-user-fav', fav);
})
if(fav_sbs.indexOf(window.songbook._id) > -1) {
$('#songbook_header .title').attr('data-user-fav', 'true');
}
else {
$('#songbook_header .title').attr('data-user-fav', 'false');
}
window.user = change.doc;
if(window.songbook._id == 'sb-favoriteSongs') {
window.songbook._id = '';
loadSongbook('sb-favoriteSongs');
}
updateUser();
notyf.info(`User Updated "${change.doc.name}"`, 'var(--edit-color)');
window.songbooks_list.reIndex();
window.songbooks_list.sort('user-fav', {order: 'desc', sortFunction: sortFavSongbooks});
$('#song song').attr('data-user-fav', (window.user.fav_songs.indexOf($('#song song').attr('data-id'))> -1 ? 'true': 'false'))
}
}
//New default config saved
else if(change.doc._id.startsWith('cfg-') && change.doc._id.match(window.user._id)){ //Change to be more specific.
if(change.deleted){
notyf.info((change.doc.name || 'Default') + ' config deleted','var(--export-color)');
}
else {
notyf.info((change.doc.name || 'Default') + ' config saved','var(--export-color)');
}
}
//else... let it go! for now
else {
console.log('changed:', change.doc._id);
}
}).on('error', function (err) {
// handle errors
console.log('Error in db.changes('+err);
});
}
async function destroyDb(dbName){
new PouchDB(dbName).destroy().then(function() {
console.log('Database deleted:', dbName);
removeDbfromLocalStorage(dbName);
location.reload(); // Reload immediately after successful deletion
}).catch(function(err) {
console.error('Error deleting database:', err); // Log the error for debugging
alert(`Could not delete database: ${err.message}`); // Provide a more specific error message
});
}
async function dbLogin(type, dbName=false, username=false, pin=false, pwd=false, remote_url=false) {
let keep_logged_in = document.getElementById('keep_logged_in').checked + (remote_url != false);
dbName = dbName || document.getElementById('db_select').value;
if(type=="login"){
if(dbName.endsWith('(local)')){type+='_local'}
else if(dbName.endsWith('(remote)')){type+='_remote'}
}
username = username || document.getElementById('username').value.trim();
pin = pin || document.getElementById('pin').value.trim();
pwd = pwd || document.getElementById('pwd').value.trim();
if(!remote_url && type == 'connect_remote'){
remote_url = $('#remote_url').val();
}
else if(!remote_url && type == 'login_remote'){
remote_url = $('#db_select :selected').attr('data-url');
}
if(type=="create_local"){
dbName = (dbName == 'create_local' ? document.getElementById('newDbName').value.trim() + '(local)' : dbName);
console.log('New local DB: '+dbName);
//initialize local database;
db = new PouchDB(dbName);
//UPDATE LOCAL STORAGE DATABASES
addDBtoLocalStorage(dbName, 'local');
window.roles = {'_admin':true,'editor':true};
takeNextStep(username,dbName);
}
else if(type=="login_local"){
console.log('Logging in locally');
db = new PouchDB(dbName);
//check if pin matches
db.get('_local/u-'+username).then(function(localUser){
if(localUser.pin == pin) {
console.log('Pin is correct!');
window.roles = {'_admin':true,'editor':true};
takeNextStep(username,dbName);
}
else { //if not then close the db
console.log('Username or pin was incorrect');
alert('Username or pin was incorrect');
dbLogout();
}
}).catch(function(err){
console.log(err);
alert('Username or pin was incorrect');
dbLogout();
});
}
else if(type=="connect_remote"){
console.log('Connecting to remote db');
remote_url = parseUrl(remote_url, username, pwd);
try {
loginRemoteDb(remote_url, username, pwd);
//UPDATE LOCAL STORAGE DATABASES
addDBtoLocalStorage(dbName, 'remote', remote_url); //shouldn't we move this into the going on disk block?
if(!keep_logged_in){
console.log('going with memory!')
db = new PouchDB(dbName, {adapter: 'memory'});
} else {
console.log('going with on disk!')
db = new PouchDB(dbName);
}
takeNextStep(username,dbName);
}
catch(error) {
dbLogout();
if(error.name == 'unauthorized' || error.name == 'forbidden'){
alert('Username or Password are incorrect');
}
else {
alert('there was an error, please check your login information');
console.log('Log in error:', error);
}
}
}
else if(type=="login_remote"){
console.log('Logging in to remote db');
if(!keep_logged_in){
console.log('going with memory!')
db = new PouchDB(dbName, {adapter: 'memory'});
} else {
console.log('going with on disk!')
db = new PouchDB(dbName);
}
try {
if(navigator.onLine) {
remote_url = parseUrl(remote_url, username, pwd);
await loginRemoteDb(remote_url, username, pwd);
takeNextStep(username,dbName);
}
else {
console.log('attempting offline login');
let localUser = await db.get('_local/u-'+username);
console.log(localUser)
if(localUser.pwd == pwd) {
console.log('offline login successful');
window.roles = localUser.roles;
notyf.info('Offline login successful', 'green');
takeNextStep(username, dbName);
}
}
} catch (error) {
if(error.name == 'unauthorized' || error.name == 'forbidden'){
console.log(error)
alert('Username or Password are incorrect');
dbLogout();
}
else {
console.log('Log in error:', error);
dbLogout();
alert('you are offline and pwd or username are incorrect');
}
}
}
else {
dbLogout();
console.log('not sure what you want to login to');
}
async function takeNextStep(username, dbName) { //after login
//initialized
window.songbook = {};
window.song = {};
let categories = {
_id: 'categories',
categories: ["Adoration", "Aspiration/Desire", "Assurance", "Atonement", "Awe", "Bereavement", "Brokenness", "Calvary", "Christ as Bridegroom", "Christ as King", "Christ as Lamb", "Christ as Redeemer", "Christ as Savior", "Christ as Shepherd", "Christ as Son", "Christ's Blood", "Christ's Return", "Church as Christ's Body", "Church as Christ's Bride", "Church as God's House", "Cleansing", "Comfort", "Commitment", "Compassion", "Condemnation", "Consecration", "Conviction of Sin", "Courage", "Creation", "The Cross", "Dedication/Devotion", "Dependence on God", "Encouragement", "Endurance", "Eternal Life", "Evangelism", "Faith", "Faithfulness", "Fear", "Fear of God", "Fellowship", "Forgiveness", "Freedom", "God as Creator", "God as Father", "God as Friend", "God as Refuge", "God's Creation", "God's Faithfulness", "God's Glory", "God's Goodness", "God's Guidance", "God's Harvest", "God's Holiness", "God's Love", "God's Mercy", "God's Power", "God's Presence", "God's Strength", "God's Sufficiency", "God's Timelessness", "God's Victory", "God's Wisdom", "God's Word", "Godly Family", "Grace", "Gratefulness", "Healing", "Heaven", "Holiness", "Holy Spirit", "Hope", "Humility", "Hunger/Thirst for God", "Incarnation", "Invitation", "Jesus as Messiah", "Joy", "Kingdom of God", "Knowing Jesus", "Lordship of Christ", "Love for God", "Love for Jesus", "Love for Others", "Majesty", "Meditation", "Mercy", "Missions", "Mortality", "Neediness", "New Birth", "Obedience", "Oneness in Christ", "Overcoming Sin", "Patience", "Peace", "Persecution", "Praise", "Prayer", "Proclamation", "Provision", "Purity", "Purpose", "Quietness", "Redemption", "Refreshing", "Repentance", "Rest", "Resurrection", "Revival", "Righteousness", "Salvation", "Sanctification", "Security", "Seeking God", "Service", "Servanthood", "Sorrow", "Spiritual Warfare", "Submission to God", "Suffering for Christ", "Surrender", "Temptation", "Trials", "Trust", "Victorious Living", "Waiting on God", "Worship", "-----", "Christmas", "Easter", "Good Friday", "Thanksgiving", "-----", "Baptism", "Birth", "Closing Worship", "Communion", "Death", "Engagement", "Opening Worship", "Table Songs", "Wedding", "-----", "Children's Songs", "Rounds", "Scripture Reading", "Scripture Songs", "-----", "Needs Work", "Needs Chord Work", "Needs Categorical Work", "Duplicate", "-----", "Norway", "Secular", "Delete", "Spanish words", "Celebration", "Add category", "Palm Sunday", "God's Holiness"]
}
let info;
//setup user
let user = {
_id: 'u-'+username,
name: username,
fav_sbs: [],
fav_songs: []
}
if(remoteDb) {
await remoteDb.putIfNotExists(user)
await remoteDb.putIfNotExists(categories);
user = await remoteDb.get('u-'+username);
info = await remoteDb.info();
}
else {
await db.putIfNotExists(user)
await db.putIfNotExists(categories);
user = await db.get('u-'+username);
}
window.user = user;
//User Preferences
let userId = window.user._id;
let fontSize = localStorage.getItem(userId+'fontSize') || 16;
let darkMode = localStorage.getItem(userId+'darkMode') || 'auto';
let analytics = localStorage.getItem(userId+'analytics');
//check dark mode and set for app
document.getElementById(darkMode+'Radio').checked = true;
handleDarkMode();
//set font size;
document.documentElement.style.fontSize = fontSize+'px';
document.getElementById('fontSize').value = fontSize;
document.getElementById('fontSizeOutput').value = fontSize + 'px';
//set analytics
if(analytics == 'false') {
document.getElementById('analytics').checked = false;
} else {
document.getElementById('analytics').checked = true;
}
document.body.classList.remove('loading');
//Store logged in status: pin for local, for remote we store pwd.
localStorage.setItem('defaultdbName', dbName);
let userData = {
dbName,
username,
roles: window.roles,
};
if (dbName.endsWith("(local)")) {
userData.pin = pin;
} else if (keep_logged_in && dbName.endsWith("(remote)")) {
userData.pwd = pwd;
userData.remote_url = remote_url;
}
localStorage.setItem('loggedin',JSON.stringify(userData));
//update local user document
db.upsert('_local/u-'+username, function(doc){
for(key of Object.keys(userData)) {
if( key != 'username' && key != 'dbName'){ //don't want to store username and dbName
doc[key] = userData[key];
}
}
return doc;
}).then(function () {
console.log("updated user's data");
}).catch(function (err) {
console.log(err);
});
setLoginState();
//Setup sync for remote database connections
if(navigator.onLine && db.name.endsWith('(remote)')){
console.log('doing a onetime sync...');
let startTime = new Date();
let firstSync = await db.sync(remoteDb).on('change', function (change) {
let percentage = parseInt(parseInt(change.change.last_seq.split('-')[0].replace('-',''))/parseInt(info.update_seq.replace('-',''))*100);
if (!document.documentElement.classList.contains('barLoading')) {
document.documentElement.classList.add('barLoading');
}
if(new Date() - startTime > 4000 && !document.documentElement.classList.contains('circleLoading')) {
document.documentElement.classList.add('circleLoading');
}
if((new Date() - startTime) > 10000) {
document.documentElement.classList.remove('circleLoading');
startTime = false;
}
document.documentElement.style.setProperty('--status-text',`"Downloading song files to your device . . . ${percentage}%${(startTime ? ' \\a If this happens every time you log in, try clicking \\"Keep me logged in\\" :)' : '')}"`);
document.documentElement.style.setProperty('--animation',`3s loading infinite`);
}).catch(function (error) {
//alert(error.message || 'error in one time sync');
console.log(error);
});
document.documentElement.classList.remove('circleLoading');
document.documentElement.classList.remove('barLoading');
document.documentElement.style.setProperty('--status-text',`""`);
document.documentElement.style.setProperty('--animation',`"unset"`);
console.log('sync complete');
//now set up the live sync
setUpSyncHandler();
setLoginState();
}
//Update ui when db changes]s
dbChanges();
window.dbName = db.name.replace(/\(.+?\)/,''); //this is used for permissions/roles.
//wipe login cause we were successfull!
$('#login :input').each(function(){$(this).val('')});
//ANalytics - could be nice to move this elsewhere...?
//DeviceInfo(deviceID, os, screen dimensions, touch capable, )
if(!localStorage.getItem('analyticID')){
localStorage.setItem('analyticID',self.crypto.randomUUID()); //random anyonymous id
logData('platform', getOS());
logData('screenSize', getScreenSize());
logData('touch', isTouchCapable());
logData('darkMode', localStorage.getItem(window.user._id+'darkMode') || 'def');
logData('fontSize', localStorage.getItem(window.user._id+'fontSize') || 'def');
dysmyssable.info('yCanta has been updated to send information to help improve how it works. You can toggle this in settings.', 'var(--song-color)', '#');
}
else {
console.log(localStorage.getItem('analyticID'));
}
logData('username', window.user._id);
let condition = navigator.onLine ? "online" : "offline";
logData('connection', condition); //Condition?
if(window.loadData){
logData('loadTime', window.performance.timing.domContentLoadedEventEnd - window.performance.timing.navigationStart);
logData('installed', isInstalled());
let analytics = localStorage.getItem(window.user._id+'analytics');
console.log(analytics);
if(analytics != 'false') {
fetch('https://ipapi.co/json/')
.then(function(response) {
return response.json();
})
.then(function(data) {
logData('location', `${data.country_name}, ${data.region}, ${data.city}`);
});
}
delete window.loadData;
}
document.documentElement.classList.add(...Object.keys(window.roles));
return true;
}
return false;
}
function setUpSyncHandler() {
try {
syncHandler = db.sync(remoteDb, {
live: true,
retry: true
}).on('change', function (change) {
console.log('Synced some stuff', parseInt(parseInt(change.change.last_seq.split('-')[0].replace('-',''))/parseInt(info.update_seq.replace('-',''))*100)+'%');
// yo, something changed!
}).on('paused', function (info) {
// replication was paused, usually because of a lost connection
}).on('active', function (info) {
// replication was resumed
}).on('complete', function (err) {
//replication canceled
console.log('complete');
});
notyf.info('Sync established', 'green');
}
catch(err) {
if(err.name == 'unauthorized' || err.name == 'forbidden'){
console.log(err)
alert('Username or Password are incorrect');
}
else {
console.log(err) // totally unhandled error (shouldn't happen)
}
dbLogout();
}
}
async function dbLogout() {
if (!confirmWhenEditing()) {
try {
await db.close();
console.log("Closed local database");
if (remoteDb) { // Check if remoteDb is initialized
await remoteDb.close();
console.log("Closed remote database");
remoteDb = null; // Explicitly set to null
syncHandler = null; // Explicitly set to null
}
} catch (err) {
console.error("Error closing databases:", err);
}
setLogoutState();
}
}
function loadUsersObject() {
db.allDocs({
include_docs: true,
startkey: 'u-',
endkey: 'u-\ufff0',
}).then(function(result){
let usersOb = result.rows.reduce((previousObject, currentObject) => {
return Object.assign(previousObject, {
[currentObject.doc._id]: currentObject.doc.name
})
},
{});
window.users = usersOb;
}).catch(function(err){
console.log(err);
});
}
function loadRecentSongs(days=1000, number=15){
db.changes({
include_docs: true,
startkey: 's-',
endkey: 's-\ufff0',
since: 0,
filter: function (doc) {
return (doc.edited > (new Date().getTime() - days*24*60*60*1000))*!doc._id.includes('sb');
}
}).then(function(result){
result.results.sort(function(a, b){
if(a.doc){
if(a.doc.edited > b.doc.edited) { return -1; }
if(a.doc.edited < b.doc.edited) { return 1; }
return 0;
}
else {
return 0;
}
});
let songs = result.results.slice(0, number);
let ul_list = '', date_hour, old_date_hour;
for(rec_song of songs) {
old_date_hour = date_hour;
date_hour = new Date(rec_song.doc.edited).toLocaleTimeString(undefined, { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit'});
if(date_hour != old_date_hour){
ul_list += `<div style="margin-top: 1rem; font-weight: bold;">${date_hour}</div>`
}
ul_list += `<li><a class="link" href="#sb-allSongs&${rec_song.doc._id}">${rec_song.doc.title}</a></li>`
}
$('.updatedSongs .list').html(ul_list);
}).catch(function(err){
console.log(err);
});
}
function initializeSongbooksList(){
db.allDocs({
include_docs: true,
startkey: 'sb-',
endkey: 'sb-\ufff0',
}).then(function(result){
//first delete all songbooks in list
if(window.songbooks_list != undefined){
window.songbooks_list.clear();
}
//then add and update the new ones
function buildSongbooksList(songbooks) {
let user_sb_favs = window.user.fav_sbs;
var options = {
valueNames: [
{ data: ['songbook-id'] },
{ data: ['songbook-rev'] },
{ data: ['songbook-title'] },
{ data: ['user-fav'] },
//{ data: ['songbook-authors'] },
//{ data: ['songbook-categories'] },
//{ data: ['songbooks-songs'] },
//{ data: ['songbook-copyright'] },
{ name: 'link', attr: 'href'},
'name'
],
item: 'songbook-item-template'
};
var values = [{'songbook-id': 'sb-allSongs',
'songbook-rev': 'n/a',
'songbook-title': 't:All Songs',
'user-fav': 'false',
'link': '#sb-allSongs',
'name': 'All Songs'},
{'songbook-id': 'sb-favoriteSongs',
'songbook-rev': 'n/a',
'songbook-title': 't:Favorite Songs',
'user-fav': 'false',
'link': '#sb-favoriteSongs',
'name': 'Favorite Songs'}];
songbooks.map(function(row) {
if(window.songbooks_list != undefined){
var songbookIdInList = window.songbooks_list.get('songbook-id',row.doc._id);
if(songbookIdInList.length > 0){
// we need to update if the revision is different.
var songbookRevInList = window.songbooks_list.get('songbook-rev', row.doc._rev);
if(songbookRevInList < 1){
let sb_vals = mapSongbookRowToValue(row);
sb_vals['user-fav'] = (user_sb_favs.indexOf(row.doc._id) == -1 ? 'false' : 'true');
songbookIdInList[0].values(sb_vals);
}
return
}
}
let sb_vals = mapSongbookRowToValue(row);
sb_vals['user-fav'] = (user_sb_favs.indexOf(row.doc._id) == -1 ? 'false' : 'true');
values.push(sb_vals);
});
//Creates list.min.js list for viewing all the songbooks
window.songbooks_list = new List('songbooks', options, values);
window.songbooks_list.sort('user-fav', {order: 'desc', sortFunction: sortFavSongbooks});
bindSearchToList(window.songbooks_list, '#songbooks');
return
}
buildSongbooksList(result.rows);
}).catch(function(err){
console.log(err);
});
}
async function addAdminUser() {
if (!remoteDb) {
console.log("There is no remoteDb");
return;
}
let users = await getAllUsers('adminSignup');
if (users instanceof Error) {
alert('You are offline perhaps! Error: ' + users.message);
return;
}
const username = prompt('What Admin username do you want to add?');
if (!username) return;
if (users.admins.includes(username) || users.users.some(usr => usr.doc.name === username)) {
alert(`${username} is already used by a user`);
return;
}
const password = prompt('What password?');
if (!password) return;
const passwordAgain = prompt('Please enter it again.');
if (password !== passwordAgain) {
alert('Passwords did not match, please try again');
return;
}
try {
await remoteDb.signUpAdmin(username, password);
await remoteDb.signUp(username, password, { roles: [window.dbName+"-admin"] });
loadAllUsers();
notyf.info(`Added Admin: ${username}`, 'green');
} catch (err) {
handleError(err);
}
}
async function changeAdminPassword(username) { // Pass user explicitly
const password = prompt(`What do you want to change the password for ${username} to?`);
if (!password) return;
const passwordAgain = prompt('Please enter it again.');
if (password !== passwordAgain) {
alert('Passwords did not match, please try again');
return;
}
try {
if ('u-' + username === window.user._id) { // Check against the passed currentUser
const tempAdminName = username + '-temp3';
const ajaxOpts = { ajax: { headers: { Authorization: null } } };
const tempAdmin = await remoteDb.signUpAdmin(tempAdminName, 'brucewayne');
// Ensure temp admin login is successful BEFORE logging out the current user
ajaxOpts.ajax.headers.Authorization = getBasicAuthHeader(tempAdminName, 'brucewayne');
await remoteDb.logOut(); // Now logout the original user
await remoteDb.logIn(tempAdminName, 'brucewayne', ajaxOpts);
await remoteDb.deleteAdmin(username);
await remoteDb.signUpAdmin(username, password);
await remoteDb.logOut();
ajaxOpts.ajax.headers.Authorization = getBasicAuthHeader(username, password); // Use original username and new password
await remoteDb.logIn(username, password, ajaxOpts);
await remoteDb.deleteAdmin(tempAdminName);
let localStorageUser = JSON.parse(localStorage.getItem('loggedin'));
localStorageUser.pwd = password;
localStorage.setItem('loggedin',JSON.stringify(localStorageUser));
} else {
await remoteDb.deleteAdmin(username);
await remoteDb.signUpAdmin(username, password);
}
loadAllUsers();
notyf.info(`Password changed for Admin: ${username}`, 'olive');
} catch (err) {
handleError(err);
}
}
async function deleteAdminUser(username) { // Pass current user explicitly
// Ensure the user isn't trying to delete themselves
if ('u-' + username === window.user._id) {
alert('You cannot delete your own admin account. Try logging in as a different admin.');
return;
}
// Confirm deletion
if (!confirm(`Are you sure you want to delete Admin: ${username}?`)) {
console.log('Decided not to delete them');
return;
}
try {
await remoteDb.deleteAdmin(username);
await remoteDb.deleteUser(username);
loadAllUsers();
notyf.info(`Admin: ${username} deleted`, 'red');
} catch (err) {
handleError(err);
}
}
async function addUser() {
let users = await getAllUsers("userSignup");
if (users instanceof Error) {
alert("You are offline perhaps! Error: " + users.message);
return;
}
const username = prompt("What username do you want to add?");
if (!username) return;
if (users.admins.includes(username) || users.users.some((usr) => usr.doc.name === username) ) {
alert(`${username} is already a user in your database`);
return;
}
const password = prompt("What password?");
if (!password) return;
const passwordAgain = prompt("Please enter it again.");
if (password !== passwordAgain) {
alert("Passwords did not match, please try again");
return;
}
const viewerName = window.dbName + "-viewer";
try {
await remoteDb.signUp(username, password, { roles: [viewerName] });
} catch (err) {
if (err.name === "conflict") {
try {
const userJS = await remoteDb.getUser(username);
const roles = { roles: userJS.roles.concat([viewerName]) };
await remoteDb.putUser(username, roles);
alert("This user already exists but did not have access to this database. They have been added. Their password was not changed.");
} catch (updateErr) {
handleError(updateErr); // Handle errors during role update
}
} else {
handleError(err); // Handle other errors
}
}
notyf.info(`Added ${username}`, 'green');
loadAllUsers();
}
async function toggleUserEditor(username, editor) { // Pass dbName explicitly
try {
const userJS = await remoteDb.getUser(username);
const editorName = window.dbName + "-editor";
let roles;
if (editor) {
roles = Array.from(new Set(userJS.roles.concat([editorName]))); // Avoid duplicates
} else {
roles = userJS.roles.filter((e) => e !== editorName);
}
await remoteDb.putUser(username, { roles }); // Use async/await consistently
loadAllUsers();
notyf.info(`Updated ${username}`, 'green');
} catch (err) {
handleError(err);
}
}
async function changeUserPassword(username) {
const password = prompt(`What do you want to change the password for ${username} to?`);
if (!password) return;
const passwordAgain = prompt("Please enter it again.");
if (password !== passwordAgain) {
alert("Passwords did not match, please try again");
return;
}
try {
await remoteDb.changePassword(username, password);
if ('u-' + username === window.user._id) { // Check against the passed currentUser also check if we are on memory version
let localStorageUser = JSON.parse(localStorage.getItem('loggedin'));
localStorageUser.pwd = password;
localStorage.setItem('loggedin',JSON.stringify(localStorageUser));
location.reload();
}
notyf.info(`Password changed for ${username}`, "olive");
} catch (err) {
handleError(err);
}
}
async function deleteUser(username) {
const response = confirm(`Are you sure you want to remove ${username}?`);
if (!response) return;
try {
const userJS = await remoteDb.getUser(username);
const roles = userJS.roles.filter(e => !e.includes(window.dbName)); // Create a new array
await remoteDb.putUser(username, { roles });
loadAllUsers();
notyf.info(`Removed user: ${username}`, 'red');
} catch (err) {
handleError(err);
}
}
function handleError(err){
if (err.name === 'not_found') {
alert('You do not have permission to see this user');
} else if(err.name ==='conflict') {
alert('That already exists');
} else if(!navigator.onLine){
alert('you are offline, try again when you are reconnected');
} else {
console.error("An unexpected error occurred:", err); // Log detailed error
alert(
`Sorry, something went wrong: ${err.message}`
);
}
}
function saveSong(song_id, song_html=$('#song song'), change_url=true) {
return new Promise(function(resolve, reject) {
var new_song = false;
function loadSongContent(song) {
if(song._rev != undefined) {
song._rev = song_html.attr('data-rev'); //need a _rev if updating a document
}
var stitle = song_html.find('stitle').text().trim();
if (stitle == "" || stitle == undefined){
stitle = "New Song";
}
let regex = /(https?:\/\/)?(?:www\.)?(youtu(?:\.be\/([-\w]+)|be\.com\/watch\?v=([-\w]+)))\w/g;
song.title = stitle;
song.authors = song_html.find('authors').text().replace(/\|/g,',').split(',').map(Function.prototype.call, String.prototype.trim);
song.scripture_ref= song_html.find('scripture_ref').text().split(',').map(Function.prototype.call, String.prototype.trim);
song.introduction = song_html.find('introduction').text();
song.key = song_html.find('key').text();
song.categories = song_html.find('categories').text().split(',').map(Function.prototype.call, String.prototype.trim);
song.cclis = song_html.find('cclis').text();
song.yt = (regex.test(song_html.find('line').text()) ? song_html.find('line').text().match(regex).length : '');
song.chords = (song_html.find('c').length > 0 ? 'chords' : '');
if(song.cclis & isNaN(song.cclis)){
song.cclis = 'on';
}
//Compile Song Content, a list of lists. Chunks and lines
var chunks = [];
song_html.find('chunk').each(function(){
var lines = [];
$(this).children().each(function(){ //add line contents
if($(this).html().trim().length != 0) {
lines.push($(this).html().replace(/\n/g, ""));
}
});
chunks.push([{'type': $(this).attr('type').toLowerCase()}, lines]);
});
song.content = chunks;
song.copyright = song_html.find('copyright').text().replace(/\([cC]\)/,'©');
//Put together Search field.
let punctuation = /[^a-zA-Z0-9\s:-]/g;
let duplicateWhitespace = /\s{2,}/g;
let returnCharacters = /[\n\r]/g;
function formatArray(array, letter){
return (array != '' ? array.join(' '+letter+':') : '!'+letter).replace(duplicateWhitespace, ' ');
}
function formatText(text, letter){
return (text != '' ? text : '!'+letter).replace(duplicateWhitespace, ' ');
}
function formatNumber(number, letter){
return (number != '' ? letter + number : '!'+letter).replace(duplicateWhitespace, ' ');
}
function formatSongContent(content){
var song_content = '';
var i, j;
for (i = 0; i < content.length; i++) {