-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathmanage_database.js
1520 lines (1042 loc) · 49.3 KB
/
manage_database.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
//
// manage_database.js
//
// IndexedDB instrument sample database management
//
//
// Unregister the service worker and force an update
//
function UpdateToLatestVersion(){
sendGoogleAnalytics("action","UpdateToLatestVersion");
ForceUpdate(callback);
function callback(restartRequested){
// Hide the spinner
document.getElementById("loading-bar-spinner").style.display = "none";
if (restartRequested){
//debugger;
setTimeout(function(){
var thePrompt = "All changes applied. Click OK to restart the tool.";
// Center the string in the prompt
thePrompt = makeCenteredPromptString(thePrompt);
DayPilot.Modal.alert(thePrompt,{ theme: "modal_flat", top: 320, scrollWithPage: (AllowDialogsToScroll()) }).then(function(){
// Mostly for iOS which keeps the old page displayed during the update
if (isMobileBrowser()){
var thePrompt = "Tool is being updated and will restart when done.";
// Center the string in the prompt
thePrompt = makeCenteredPromptString(thePrompt);
DayPilot.Modal.alert(thePrompt,{ theme: "modal_flat", top: 320, scrollWithPage: (AllowDialogsToScroll()) });
}
// Show the spinner while waiting for the reload
document.getElementById("loading-bar-spinner").style.display = "block";
window.location.reload();
});
},1000);
}
}
}
function ForceUpdate(callback){
var thePrompt = "This will force the version of the tool stored in<br/>your browser to be updated after a restart.<br/><br/>After the restart, wait 10 seconds and then hard refresh<br/>the page one more time to use the update.<br/><br/>Are you sure?";
// Center the string in the prompt
thePrompt = makeCenteredPromptString(thePrompt);
DayPilot.Modal.confirm(thePrompt,{ top:262, theme: "modal_flat", scrollWithPage: (AllowDialogsToScroll()) }).then(function(args){
if (!args.canceled){
console.log("Tool update requested");
// Show the spinner
document.getElementById("loading-bar-spinner").style.display = "block";
// Give some time to show the spinner
setTimeout(function(){
if ('serviceWorker' in navigator) {
navigator.serviceWorker.getRegistrations().then(function(registrations) {
let unregisterPromises = [];
for (let registration of registrations) {
if (registration.scope.indexOf("abctools") != -1){
console.log("Unregistering service worker with scope: "+registration.scope);
unregisterPromises.push(registration.unregister());
}
}
Promise.all(unregisterPromises).then(function() {
console.log('All service workers unregistered');
// Call your callback function here
callback(true);
}).catch(function(error) {
console.error('Error unregistering service workers:', error);
// Optionally call the callback function in case of error
callback(true);
});
}).catch(function(error) {
console.error('Error getting service worker registrations:', error);
// Optionally call the callback function in case of error
callback(true);
});
}
else {
console.warn('Service workers are not supported in this browser.');
// Optionally call the callback function if service workers are not supported
callback(true);
}
},100);
}
else{
//console.log("Cancelled database delete");
callback(false);
}
});
}
//
// Clear all the databases
//
function DeleteAllDatabases(callback){
var thePrompt = "This will clear all the instrument notes, reverb settings, and tune search collections databases.<br/><br/>Are you sure?";
// Center the string in the prompt
thePrompt = makeCenteredPromptString(thePrompt);
DayPilot.Modal.confirm(thePrompt,{ top:262, theme: "modal_flat", scrollWithPage: (AllowDialogsToScroll()) }).then(function(args){
if (!args.canceled){
// Wipe all the databases
delete_all_DB();
//console.log("Deleting the databases");
callback(true);
}
else{
//console.log("Cancelled database delete");
callback(false);
}
});
}
//
// Reset all tool settings to the defaults
//
function resetAllSettingsToDefault(callback){
// No point asking if they don't have localstorage available
if (!gLocalStorageAvailable){
callback(false);
return;
}
var thePrompt = "This will reset the tool settings to the original defaults.<br/><br/>Are you sure?";
// Center the string in the prompt
thePrompt = makeCenteredPromptString(thePrompt);
DayPilot.Modal.confirm(thePrompt,{ top:262, theme: "modal_flat", scrollWithPage: (AllowDialogsToScroll()) }).then(function(args){
if (!args.canceled){
//console.log("Resetting the settings");
localStorage.clear();
callback(true);
}
else{
//console.log("Cancelled settings reset");
callback(false);
}
});
}
//
// Reset the settings and/or clear the databases
//
function ResetSettingsDialog(){
// Keep track of dialogs
sendGoogleAnalytics("dialog","ResetSettings");
// Setup initial values
const theData = {
resetsettings: false,
deletedatabases: false,
forceupdate: false
};
var form;
if (navigator.onLine){
form = [
{html: '<p style="text-align:center;margin-bottom:20px;font-size:16pt;font-family:helvetica;margin-left:15px;">Reset All Tool Settings, Clear Databases, Force Update <span style="font-size:24pt;" title="View documentation in new tab"><a href="https://michaeleskin.com/abctools/userguide.html#advanced_resetsettings" target="_blank" style="text-decoration:none;position:absolute;left:20px;top:20px" class="dialogcornerbutton">?</a></span></p>'},
{html: '<p style="margin-top:24px;margin-bottom:12px;font-size:12pt;line-height:18pt;font-family:helvetica">Checking <strong>Reset all settings to default</strong> will restore the tool settings to the original first-run state.</p>'},
{html: '<p style="margin-top:24px;margin-bottom:12px;font-size:12pt;line-height:18pt;font-family:helvetica">Checking <strong>Clear all databases</strong> will clear and delete the instrument notes, reverb settings, and tune search collections databases. New databases will be created after the tool is restarted.'},
{html: '<p style="margin-top:24px;margin-bottom:12px;font-size:12pt;line-height:18pt;font-family:helvetica">Checking <strong>Force tool update after restart</strong> will force the version of the tool stored in your browser to be updated to the latest version after the tool is restarted.'},
{html: '<p style="margin-top:24px;margin-bottom:8px;font-size:12pt;line-height:18pt;font-family:helvetica">If you enable any of these options, the tool will be restarted after the operation is complete.</p>'},
{name: " Reset all tool settings to default", id: "resetsettings", type:"checkbox", cssClass:"configure_resetsettings_text"},
{name: " Clear all databases", id: "deletedatabases", type:"checkbox", cssClass:"configure_resetsettings_text"},
{name: " Force tool update after restart", id: "forceupdate", type:"checkbox", cssClass:"configure_resetsettings_text"},
{html: '<p style="margin-top:24px;margin-bottom:8px;font-size:12pt;line-height:18pt;font-family:helvetica"> </p>'},
];
}
else{
form = [
{html: '<p style="text-align:center;margin-bottom:20px;font-size:16pt;font-family:helvetica;margin-left:15px;">Reset All Tool Settings <span style="font-size:24pt;" title="View documentation in new tab"><a href="https://michaeleskin.com/abctools/userguide.html#advanced_resetsettings" target="_blank" style="text-decoration:none;position:absolute;left:20px;top:20px" class="dialogcornerbutton">?</a></span></p>'},
{html: '<p style="margin-top:24px;margin-bottom:12px;font-size:12pt;line-height:18pt;font-family:helvetica">Checking <strong>Reset all settings to default</strong> will restore the tool settings to the original first-run state.</p>'},
{html: '<p style="margin-top:24px;margin-bottom:8px;font-size:12pt;line-height:18pt;font-family:helvetica">If you enable this option, the tool will be restarted after the operatation is complete.</p>'},
{html: '<p style="margin-top:24px;margin-bottom:8px;font-size:12pt;line-height:18pt;font-family:helvetica">When online, you also have the option to clear and delete the instrument notes, reverb settings, and tune search collections databases.</p>'},
{name: " Reset all tool settings to default", id: "resetsettings", type:"checkbox", cssClass:"configure_resetsettings_text"},
{html: '<p style="margin-top:24px;margin-bottom:8px;font-size:12pt;line-height:18pt;font-family:helvetica"> </p>'},
];
}
const modal = DayPilot.Modal.form(form, theData, { theme: "modal_flat", top: 100, width: 650, scrollWithPage: (AllowDialogsToScroll()), autoFocus: false } ).then(function(args){
// Get the results and store them in the global configuration
if (!args.canceled){
var doSettingsRestart = false;
var doDatabaseClear = false;
var doForceUpdate = false;
if (args.result.resetsettings){
// Clear the setttings
//console.log("reset settings requested");
sendGoogleAnalytics("action","ResetAllSettings");
resetAllSettingsToDefault(callback);
}
else{
callback(false);
}
function callback(restartRequested){
doSettingsRestart = restartRequested;
if (args.result.deletedatabases){
// Clear the setttings
//console.log("delete databases requested");
sendGoogleAnalytics("action","DeleteAllDatabases");
DeleteAllDatabases(callback2);
}
else{
callback2(false);
}
}
function callback2(restartRequested){
doDatabaseClear = restartRequested;
if (args.result.forceupdate){
// Clear the setttings
//console.log("force update requested");
sendGoogleAnalytics("action","ForceUpdateFromDialog");
ForceUpdate(callback3);
}
else{
callback3(false);
}
}
function callback3(restartRequested){
// Hide the spinner
document.getElementById("loading-bar-spinner").style.display = "none";
doForceUpdate = restartRequested;
if (doSettingsRestart || doDatabaseClear || doForceUpdate){
//debugger;
setTimeout(function(){
var thePrompt = "All changes applied. Click OK to restart the tool.";
// Center the string in the prompt
thePrompt = makeCenteredPromptString(thePrompt);
DayPilot.Modal.alert(thePrompt,{ theme: "modal_flat", top: 320, scrollWithPage: (AllowDialogsToScroll()) }).then(function(){
// Mostly for iOS which keeps the old page displayed during the update
if (isMobileBrowser()){
var thePrompt = "Tool is being updated and will restart when done.";
// Center the string in the prompt
thePrompt = makeCenteredPromptString(thePrompt);
DayPilot.Modal.alert(thePrompt,{ theme: "modal_flat", top: 320, scrollWithPage: (AllowDialogsToScroll()) });
}
// Show the spinner while waiting for the reload
document.getElementById("loading-bar-spinner").style.display = "block";
window.location.reload();
});
},1000);
}
}
}
});
}
//
// Manage databases dialog
//
function ManageDatabasesDialog(){
// Keep track of dialogs
sendGoogleAnalytics("dialog","ManageDatabasesDialog");
var modal_msg = '<p style="text-align:center;margin-bottom:36px;font-size:16pt;font-family:helvetica;margin-left:15px;">Manage Databases <span style="font-size:24pt;" title="View documentation in new tab"><a href="https://michaeleskin.com/abctools/userguide.html#manage_databases" target="_blank" style="text-decoration:none;position:absolute;left:20px;top:20px" class="dialogcornerbutton">?</a></span></p>';
// Only make the database management features available when online
if (navigator.onLine){
modal_msg += '<p style="text-align:center;"><input id="managesamples" class="btn btn-managesamples managesamples" onclick="ManageSamplesDialog(true)" type="button" value="Instrument Notes Database" title="Opens a dialog where you can view the instruments and notes in the instrument database and load/delete complete sets of notes for instruments">';
modal_msg += '<input id="managereverb" class="btn btn-managereverb managereverb" onclick="ManageReverbDialog()" type="button" value="Reverb Settings Database" title="Opens a dialog where you can load the reverb settings for offline use">';
modal_msg += '<input id="managesearch" class="btn btn-managesearch managesearch" onclick="ManageSearchCollectionsDialog()" type="button" value="Search Engine Libraries Database" title="Opens a dialog where you can load the search engine libraries for offline use"></p>';
}
else{
modal_msg += '<p style="text-align:center;"><input id="managesamples" style="margin-right:0px" class="btn btn-managesamples managesamples" onclick="ManageSamplesDialog(false)" type="button" value="View Instrument Notes Database" title="Opens a dialog where you can view the instruments and notes in the instrument database while offline">';
}
DayPilot.Modal.alert(modal_msg,{ theme: "modal_flat", top: 200, width: 770, scrollWithPage: (AllowDialogsToScroll()) });
}
//
//
// Manage instrument samples dialog
//
var gInSampleRetrieval = false;
var gInDownloadAll = false;
var gSamplesOKButton = null;
function idleManageSamplesDialog(showActionButtons){
const storeName = "samples";
var gLoadAllNotesSet = null;
// All the notes
// Get all the items in the database and populate the
fetchAndDisplayItems(showActionButtons);
function downloadAllNotes(){
// Disallow during other download operations
if (gInSampleRetrieval){
return;
}
var cancelRequested = false;
function gotCancelRequested(){
//debugger;
//console.log("gotCancelRequested");
cancelRequested = true;
if (gInDownloadAll){
document.getElementById("managedownloadall").value = "Cancel requested, waiting for current instrument download to finish...";
}
}
//console.log("downloadAllNotes");
if (gLoadAllNotesSet && gLoadAllNotesSet.length > 0){
// Find the OK button
var theOKButtons = document.getElementsByClassName("modal_flat_buttons");
// Find the button that says "OK" to use to close the dialog and hide it during the operation
gSamplesOKButton = null;
if (theOKButtons && (theOKButtons.length > 0)){
gSamplesOKButton = theOKButtons[theOKButtons.length-1];
}
if (gSamplesOKButton){
gSamplesOKButton.style.display = "none";
}
gInDownloadAll = true;
var nInstruments = gLoadAllNotesSet.length;
var thisInstrumentIndex = 0;
var isDone = false;
// Show the spinner
document.getElementById("loading-bar-spinner").style.display = "block";
document.getElementById("noteLoadProgress").style.display = "block";
var thisName = gLoadAllNotesSet[thisInstrumentIndex];
thisName = thisName.replace("https://michaeleskin.com/abctools/soundfonts/","");
thisName = thisName.replace("https://paulrosen.github.io/midi-js-soundfonts/","");
thisName = friendlyInstrumentName(thisName);
// Get the next one!
document.getElementById("managedownloadall").value = "Loading All Notes for Instrument "+(thisInstrumentIndex+1)+" of "+nInstruments + ": "+thisName+" - (Click to Cancel)";
document.getElementById("managedownloadall").onclick = gotCancelRequested;
function loadCallback(){
thisInstrumentIndex++;
//console.log("loadCallback thisInstrumentIndex: "+thisInstrumentIndex);
if ((thisInstrumentIndex == nInstruments) || cancelRequested){
//console.log("Done!")
document.getElementById("loading-bar-spinner").style.display = "none";
document.getElementById("noteLoadProgress").style.display = "none";
var thePrompt = "All notes for all instruments successfully saved!";
// Stopped because of a cancel request?
if (cancelRequested){
thePrompt = "Load All Notes Operation Cancelled";
}
// Center the string in the prompt
thePrompt = makeCenteredPromptString(thePrompt);
DayPilot.Modal.alert(thePrompt,{ theme: "modal_flat", top: 275, scrollWithPage: (AllowDialogsToScroll()) });
// Refresh the sample list
fetchAndDisplayItems(showActionButtons);
document.getElementById("managedownloadall").value = "Load All Notes for All Instruments";
gInSampleRetrieval = false;
gInDownloadAll = false;
if (gSamplesOKButton){
gSamplesOKButton.style.display = "block";
}
}
else{
//debugger;
//console.log("downloadAllNotes getting index "+thisInstrumentIndex);
var thisName = gLoadAllNotesSet[thisInstrumentIndex];
thisName = thisName.replace("https://michaeleskin.com/abctools/soundfonts/","");
thisName = thisName.replace("https://paulrosen.github.io/midi-js-soundfonts/","");
thisName = friendlyInstrumentName(thisName);
// Get the next one!
document.getElementById("managedownloadall").value = "Loading All Notes for Instrument "+(thisInstrumentIndex+1)+" of "+nInstruments + ": "+thisName+" - (Click to Cancel)";
loadItem(gLoadAllNotesSet[thisInstrumentIndex],loadCallback);
}
}
// Kick off the cascade
loadItem(gLoadAllNotesSet[thisInstrumentIndex],loadCallback);
}
}
function stripLastItem(url) {
// Create a new URL object
let parsedUrl = new URL(url);
// Split the pathname into parts
let parts = parsedUrl.pathname.split('/');
// Remove the last part if it's not empty
if (parts.length > 1 && parts[parts.length - 1] !== '') {
parts.pop();
}
// Join the parts back together
parsedUrl.pathname = parts.join('/');
// Return the modified URL as a string
return parsedUrl.toString();
}
function removeDuplicates(arr) {
return [...new Set(arr)];
}
function countDuplicates(arr) {
// Create a frequency map
let frequencyMap = {};
// Count the occurrences of each element
arr.forEach(item => {
if (frequencyMap[item]) {
frequencyMap[item]++;
} else {
frequencyMap[item] = 1;
}
});
// Extract counts of duplicate elements
let duplicatesCount = [];
for (let item in frequencyMap) {
duplicatesCount.push(frequencyMap[item]);
}
return duplicatesCount;
}
function startsWithDoctypeHtml(arrayBuffer) {
// Create a Uint8Array from the ArrayBuffer
const uint8Array = new Uint8Array(arrayBuffer);
// Convert the first few bytes to a string (length of "<!DOCTYPE html>" is 15 characters)
const textDecoder = new TextDecoder();
const startString = textDecoder.decode(uint8Array.slice(0, 15)); // Get the first 15 bytes
// Check if the string starts with "<!DOCTYPE html>"
return startString === "<!DOCTYPE html>";
}
function fetchUrlsSequentially(instrumentName,urls,callback) {
document.getElementById("loading-bar-spinner").style.display = "block";
// Initialize index to keep track of current URL being fetched
let index = 0;
function fetchNext() {
var elem = document.getElementById("noteLoadBar")
elem.style.width = Math.floor((index/urls.length)*100) + "%";
if (index < urls.length) {
let url = urls[index];
// Is this note already in the database?
getSample_DB(url, function(theNote){
//console.log(theNote);
if (!theNote){
//console.log(url+" not in database, fetching...");
fetch(url)
.then(response => {
//console.log("Got respose for "+url);
if (!response.ok) {
//console.log("Got error fetching sample")
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.arrayBuffer();
})
.then(theBuffer => {
//console.log(`Fetched URL: ${url}`, theBuffer);
// If redirected, the buffer will contain the start of my HTML redirect page
if (startsWithDoctypeHtml(theBuffer)){
//console.log("Was from redirect");
throw new Error(`Sample fetch was redirected`);
}
// Save the sample in the database
saveSample_DB(url,theBuffer);
index++;
fetchNext(); // Call fetchNext recursively to fetch the next URL
})
.catch(error => {
//console.error('Error fetching URL:', url, error);
index++; // Move to the next URL even if there's an error
fetchNext(); // Continue to fetch the next URL
});
}
else{
//console.log(url+" already in database, skipping...");
index++;
fetchNext();
}
});
} else {
//console.log('All URLs fetched');
// Using for sequenced loads, call back now
if (callback){
gInSampleRetrieval = false;
callback();
return;
}
// Hide the spinner
document.getElementById("loading-bar-spinner").style.display = "none";
// Hide the progress bar
document.getElementById("noteLoadProgress").style.display = "none";
// Show the OK button
if (gSamplesOKButton){
gSamplesOKButton.style.display = "block";
}
var thePrompt = "All notes for "+friendlyInstrumentName(instrumentName)+" successfully saved!";
// Center the string in the prompt
thePrompt = makeCenteredPromptString(thePrompt);
DayPilot.Modal.alert(thePrompt,{ theme: "modal_flat", top: 275, scrollWithPage: (AllowDialogsToScroll()) });
// Refresh the sample list
fetchAndDisplayItems(showActionButtons);
gInSampleRetrieval = false;
}
}
// Kick off the requst cascade
fetchNext();
}
function replaceAndCapitalize(str) {
// Replace all underscores with spaces
let result = str.replace(/_/g, ' ');
// Split the string into words
let words = result.split(' ');
// Capitalize each word if it is not a number
words = words.map(word => {
return isNaN(word) ? word.charAt(0).toUpperCase() + word.slice(1).toLowerCase() : word;
});
// Join the words back into a single string
return words.join(' ');
}
function capitalizeString(str) {
if (!str) return str; // Return if the string is empty
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}
// Get a friendly name from the path based name
function friendlyInstrumentName(theName){
var theSoundFont = "Custom: ";
var theNameLC = theName.toLowerCase();
if (theNameLC.indexOf("fluidhq") != -1){
theSoundFont = "FluidHQ: ";
}
else
if (theNameLC.indexOf("fluid") != -1){
theSoundFont = "Fluid: ";
}
else
if (theNameLC.indexOf("fatboy") != -1){
theSoundFont = "FatBoy: ";
}
else
if (theNameLC.indexOf("musyng") != -1){
theSoundFont = "Musyng: ";
}
else
if (theNameLC.indexOf("canvas") != -1){
theSoundFont = "Canvas: ";
}
else
if (theNameLC.indexOf("mscore") != -1){
theSoundFont = "MScore: ";
}
else
if (theNameLC.indexOf("arachno") != -1){
theSoundFont = "Arachno: ";
}
const parts = theName.split('/');
var theName = parts[parts.length - 1];
// Strip off format suffix
theName = theName.replace("-mp3","");
theName = theName.replace("-ogg","");
return theSoundFont + replaceAndCapitalize(theName);
}
function getLastSegment(url) {
// Remove any trailing slashes at the end of the URL
url = url.replace(/\/$/, "");
// Split the URL by slashes and return the last part
return url.substring(url.lastIndexOf('/') + 1);
}
function fetchAndDisplayItems(showActionButtons) {
gLoadAllNotesSet = null;
const transaction = gSamplesDB.transaction([storeName], "readonly");
const objectStore = transaction.objectStore(storeName);
let cursorRequest = objectStore.openCursor();
var items = [];
// Show the spinner
document.getElementById("loading-bar-spinner").style.display = "block";
cursorRequest.onsuccess = function(event) {
// Check for dialog closed before update response
const tableBody = document.querySelector("#notes-table tbody");
if (!tableBody){
//console.log("fetchAndDisplayItems: Got early out");
// Hide the spinner
document.getElementById("loading-bar-spinner").style.display = "none";
return;
}
let cursor = event.target.result;
if (cursor) {
//console.log(cursor.value);
items.push(cursor.value)
cursor.continue();
} else {
//console.log('No more entries!');
const tableBody = document.querySelector("#notes-table tbody");
tableBody.innerHTML = ''; // Clear previous content
// Sort them
items.sort((a, b) => {
let domainA = a.url;
let domainB = b.url;
if (domainA < domainB) return -1;
if (domainA > domainB) return 1;
return 0;}
);
var basePathArray = [];
items.forEach((item) => {
var thePath = stripLastItem(item.url);
basePathArray.push(thePath);
});
// Sort them
basePathArray.sort((a, b) => {
let domainA = getLastSegment(a);
let domainB = getLastSegment(b);
if (domainA < domainB) return -1;
if (domainA > domainB) return 1;
return 0;}
);
var duplicatesCount = countDuplicates(basePathArray);
var basePathSet = removeDuplicates(basePathArray);
// Save the complete set of notes for load all
gLoadAllNotesSet = basePathSet;
// Put the total in the table header
if (basePathSet && basePathSet.length > 0){
var elem = document.getElementById("notes_table_name");
if (elem){
elem.textContent = "Name ("+basePathSet.length+")";
}
}
basePathSet.forEach((item,index) => {
//console.log("item: "+item+" index: "+index+" duplicates: "+duplicatesCount[index])
// Remove soundfont base path
var originalPath = item;
item = item.replace("https://michaeleskin.com/abctools/soundfonts/","");
item = item.replace("https://paulrosen.github.io/midi-js-soundfonts/","");
item = friendlyInstrumentName(item);
const row = document.createElement('tr');
const nameCell = document.createElement('td');
nameCell.style.padding = "7px";
nameCell.style.height = "45px";
nameCell.textContent = item;
row.appendChild(nameCell);
const countCell = document.createElement('td');
countCell.style.padding = "7px";
countCell.style.textAlign = "center";
countCell.textContent = duplicatesCount[index];
row.appendChild(countCell);
// Only show action buttons if online
if (showActionButtons){
const actionsCell = document.createElement('td');
actionsCell.style.padding = "7px";
actionsCell.style.textAlign = "center";
// Load button
const loadButton = document.createElement('input');
loadButton.style.width = "100px";
loadButton.style.height = "36px";
loadButton.style.marginRight = "24px";
loadButton.style.textAlign = "center";
loadButton.style.cursor = "pointer";
loadButton.classList.add('btn','btn-managesamples','managenotes');
loadButton.type = 'button'
loadButton.value = 'Load All';
loadButton.onclick = (event) => {
// Disable when downloading all notes
if (gInDownloadAll){
return;
}
if (gInSampleRetrieval){
return;
}
event.target.value = "Loading";
loadItem(originalPath,null);
}
actionsCell.appendChild(loadButton);
// Delete button
const deleteButton = document.createElement('input');
deleteButton.style.width = "100px";
deleteButton.style.height = "36px";
deleteButton.style.textAlign = "center";
deleteButton.style.cursor = "pointer";
deleteButton.classList.add('btn','btn-deletesamples','managenotes');
deleteButton.type = 'button'
deleteButton.value = 'Delete';
deleteButton.onclick = (event) => {
// Disable when downloading all notes
if (gInDownloadAll){
return;
}
if (gInSampleRetrieval){
return;
}
var thisInstrument = originalPath
thisInstrument = thisInstrument.replace("https://michaeleskin.com/abctools/soundfonts/","");
thisInstrument = thisInstrument.replace("https://paulrosen.github.io/midi-js-soundfonts/","");
thisInstrument = friendlyInstrumentName(thisInstrument);
var thePrompt = "Are you sure you want to delete "+thisInstrument+"?";
// Center the string in the prompt
thePrompt = makeCenteredPromptString(thePrompt);
DayPilot.Modal.confirm(thePrompt,{ top:275, theme: "modal_flat", scrollWithPage: (AllowDialogsToScroll()) }).then(function(args){
if (!args.canceled){
event.target.value = "Deleting";
deleteItem(originalPath);
}
});
}
actionsCell.appendChild(deleteButton);
row.appendChild(actionsCell);
// Add the download all button
if (showActionButtons){
document.getElementById("managedownloadall").onclick = downloadAllNotes;
}
}
tableBody.appendChild(row);
});
// Hide the spinner
document.getElementById("loading-bar-spinner").style.display = "none";
};
}
}
function loadItem(item,callback) {
// Avoid re-entrancy
if (gInSampleRetrieval){
//console.log("loadItem got reentered");
return;
}
gInSampleRetrieval = true;
var i, j;
//console.log("Loading: "+item);
var noteNames = [
"C","Db","D","Eb","E","F","Gb","G","Ab","A","Bb","B"];
var noteNamesLen = noteNames.length;
// Build list of all note names to attempt to fetch from C0 to C8
var allNotes = [];
for (i=0;i<8;++i){
for (j=0;j<noteNamesLen;++j){
allNotes.push(noteNames[j]+i);
}
}