-
-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathsetup.js
More file actions
1415 lines (1375 loc) · 65.6 KB
/
Copy pathsetup.js
File metadata and controls
1415 lines (1375 loc) · 65.6 KB
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
var serverFields = {
jellyfin: [
{name: 'JELLYFIN_URL', label: 'Jellyfin URL', placeholder: 'http://your-jellyfin-server:8096', tooltip: 'Base URL of your Jellyfin server, including http:// or https:// and the port. Must be reachable from the AudioMuse-AI container.'},
{name: 'JELLYFIN_USER_ID', label: 'Jellyfin user ID', placeholder: 'your-user-id', tooltip: "The Jellyfin user whose library AudioMuse-AI will read. Find the ID in Jellyfin under Dashboard \u2192 Users \u2192 (your user) \u2192 the URL contains userId=..."},
{name: 'JELLYFIN_TOKEN', label: 'Jellyfin API token', placeholder: 'your-api-token', tooltip: 'API key for that Jellyfin user. Create one in Jellyfin under Dashboard \u2192 API Keys.'}
],
navidrome: [
{name: 'NAVIDROME_URL', label: 'Navidrome URL', placeholder: 'http://your-navidrome-server:4533', tooltip: 'Base URL of your Navidrome server, including http:// or https:// and the port.'},
{name: 'NAVIDROME_USER', label: 'Navidrome username', placeholder: 'your-username', tooltip: 'Username of a Navidrome account that can read the music library.'},
{name: 'NAVIDROME_PASSWORD', label: 'Navidrome password', placeholder: 'your-password', tooltip: 'Password for the Navidrome user above.'}
],
lyrion: [
{name: 'LYRION_URL', label: 'Lyrion URL', placeholder: 'http://your-lyrion-server:9000', tooltip: 'Base URL of your Lyrion (Logitech Media Server) instance, including http:// and the port.'}
],
emby: [
{name: 'EMBY_URL', label: 'Emby URL', placeholder: 'http://your-emby-server:8096', tooltip: 'Base URL of your Emby server, including http:// or https:// and the port.'},
{name: 'EMBY_USER_ID', label: 'Emby user ID', placeholder: 'your-user-id', tooltip: 'The Emby user whose library AudioMuse-AI will read. Find the ID in Emby under Dashboard \u2192 Users \u2192 (your user).'},
{name: 'EMBY_TOKEN', label: 'Emby API token', placeholder: 'your-api-token', tooltip: 'API key for that Emby user. Create one in Emby under Dashboard \u2192 API Keys.'}
]
};
var testFeedback = document.getElementById('test-feedback');
var saveFeedback = document.getElementById('save-feedback');
var saveButton = document.getElementById('save-button');
var serverConfigFields = document.getElementById('server-config-fields');
var advancedFields = document.getElementById('advanced-fields');
var authCredentials = document.getElementById('auth-credentials');
var authAdminExists = document.getElementById('auth-admin-exists');
var apiTokenRow = document.getElementById('api-token-row');
var authCredentialInputs = [
document.getElementById('AUDIOMUSE_USER'),
document.getElementById('AUDIOMUSE_PASSWORD'),
document.getElementById('AUDIOMUSE_PASSWORD_CONFIRM'),
document.getElementById('JWT_SECRET')
];
var setupForm = document.getElementById('setup-form');
var musicLibrariesSection = document.getElementById('music-libraries-section');
var musicLibrariesList = document.getElementById('music-libraries-list');
var musicLibrariesHint = document.getElementById('music-libraries-hint');
var serverValues = {};
var serverSecretHasValue = {};
var originalValues = {};
var currentSelectedLibraries = []; // comma-split MUSIC_LIBRARIES from /api/setup
var currentLibraryCheckboxes = []; // array of HTMLInputElement (checkbox) rendered in the section
var currentNoRestrictionCheckbox = null; // pseudo-entry: when checked, MUSIC_LIBRARIES = '' (scan all, auto-grow)
// Set from GET /api/setup: when true, an admin already exists in
// audiomuse_users and the setup wizard must not allow editing admin
// credentials here. User management happens in /users instead.
var hasAdminUser = false;
function updateAuthVisibility() {
var authEnabled = document.getElementById('AUTH_ENABLED').value === 'true';
var showAdminCreds = authEnabled && !hasAdminUser;
authCredentials.style.display = authEnabled ? 'grid' : 'none';
if (authAdminExists) {
authAdminExists.style.display = (authEnabled && hasAdminUser) ? 'block' : 'none';
}
// Hide the three admin-credential wrappers when an admin already exists.
var adminWrappers = document.querySelectorAll('.auth-admin-credential');
for (var i = 0; i < adminWrappers.length; i++) {
adminWrappers[i].style.display = showAdminCreds ? '' : 'none';
}
apiTokenRow.style.display = authEnabled ? 'block' : 'none';
authCredentialInputs.forEach(function(input) {
if (!input) {
return;
}
// JWT_SECRET stays editable whenever auth is enabled, regardless of
// whether an admin already exists.
var isAdminCred = input.id !== 'JWT_SECRET';
var enabledForInput = isAdminCred ? showAdminCreds : authEnabled;
input.disabled = !enabledForInput;
var label = document.querySelector('label[for="' + input.id + '"]');
if (isAdminCred) {
input.required = enabledForInput;
if (label) {
if (enabledForInput) {
label.classList.add('required-label');
} else {
label.classList.remove('required-label');
}
}
}
});
var apiTokenInput = document.getElementById('API_TOKEN');
if (apiTokenInput) {
apiTokenInput.disabled = !authEnabled;
apiTokenInput.required = false;
var label = document.querySelector('label[for="API_TOKEN"]');
if (label) {
// Update only the leading text node so the info-tooltip span is preserved.
var newText = authEnabled ? 'API token (optional) ' : 'API token ';
if (label.firstChild && label.firstChild.nodeType === Node.TEXT_NODE) {
label.firstChild.nodeValue = newText;
} else {
label.insertBefore(document.createTextNode(newText), label.firstChild);
}
}
}
}
function createInputField(field, value) {
var row = document.createElement('div');
row.className = 'field-row';
var label = document.createElement('label');
label.setAttribute('for', field.name);
if (field.tooltip) {
label.classList.add('label-with-tooltip');
label.appendChild(document.createTextNode(field.label));
var tt = document.createElement('span');
tt.className = 'info-tooltip';
tt.setAttribute('tabindex', '0');
var icon = document.createElement('span');
icon.className = 'info-icon';
var text = document.createElement('span');
text.className = 'tooltip-text';
text.textContent = field.tooltip;
tt.appendChild(icon);
tt.appendChild(text);
label.appendChild(document.createTextNode(' '));
label.appendChild(tt);
} else {
label.textContent = field.label;
}
var input;
var selectOptions = null;
if (Array.isArray(field.options) && field.options.length > 0) {
selectOptions = field.options.map(function(opt) { return String(opt); });
} else if (field.type === 'boolean' && !field.secret) {
selectOptions = ['true', 'false'];
}
if (selectOptions) {
input = document.createElement('select');
} else if (field.type === 'textarea') {
input = document.createElement('textarea');
} else {
input = document.createElement('input');
}
input.id = field.name;
input.name = field.name;
if (field.required) {
input.required = true;
}
if (selectOptions) {
// For booleans, normalize the incoming value (which may be 'True',
// 'False', '1', '0', etc. from the API) to canonical 'true'/'false'.
// For enums, do a case-insensitive match against the canonical
// options so legacy stale-cased entries (e.g. 'DBSCAN') still display
// selected — saving will persist the canonical casing.
var normalized = '';
if (value !== undefined && value !== null && String(value) !== '') {
var raw = String(value).trim();
if (field.type === 'boolean') {
var rl = raw.toLowerCase();
if (rl === '1' || rl === 'true' || rl === 'yes' || rl === 'on') {
normalized = 'true';
} else if (rl === '0' || rl === 'false' || rl === 'no' || rl === 'off') {
normalized = 'false';
}
} else {
for (var oi = 0; oi < selectOptions.length; oi++) {
if (selectOptions[oi].toLowerCase() === raw.toLowerCase()) {
normalized = selectOptions[oi];
break;
}
}
}
}
// Fall back to the python-side default if the stored value didn't
// match anything. field.placeholder was loaded from `field.default`
// by renderAdvancedFields, so it's the canonical default for enums.
if (!normalized && field.placeholder) {
for (var pi = 0; pi < selectOptions.length; pi++) {
if (selectOptions[pi].toLowerCase() === String(field.placeholder).toLowerCase()) {
normalized = selectOptions[pi];
break;
}
}
}
// Last-resort fallback so the <select> never reflects 'no choice'
// (which would silently submit the first option anyway).
if (!normalized) {
normalized = selectOptions[0];
}
selectOptions.forEach(function(opt) {
var optEl = document.createElement('option');
optEl.value = opt;
optEl.textContent = opt;
if (opt === normalized) {
optEl.selected = true;
}
input.appendChild(optEl);
});
input.value = normalized;
input.dataset.originalValue = field.originalValue !== undefined ? field.originalValue : normalized;
} else {
if (field.inputType) {
input.type = field.inputType;
} else {
input.type = 'text';
}
if (field.placeholder) {
input.placeholder = field.placeholder;
}
var hasSecretValue = false;
if (field.secret) {
if (field.has_value) {
hasSecretValue = true;
}
}
if (field.secret) {
if (field.name === 'AUDIOMUSE_PASSWORD') {
input.value = '';
input.dataset.originalValue = field.originalValue !== undefined ? field.originalValue : '';
} else if (hasSecretValue) {
input.value = '********';
input.dataset.originalValue = field.originalValue !== undefined ? field.originalValue : '********';
} else {
if (value) {
input.value = value;
} else {
input.value = '';
}
input.dataset.originalValue = field.originalValue !== undefined ? field.originalValue : input.value;
}
} else {
if (value) {
input.value = value;
} else {
input.value = '';
}
input.dataset.originalValue = field.originalValue !== undefined ? field.originalValue : input.value;
}
if (field.type === 'boolean') {
input.type = 'text';
input.placeholder = 'true or false';
}
if (field.secret) {
input.type = 'password';
}
}
if (field.required) {
label.classList.add('required-label');
}
row.appendChild(label);
row.appendChild(input);
if (field.description) {
var hint = document.createElement('small');
hint.textContent = field.description;
row.appendChild(hint);
}
return row;
}
function renderServerFields(serverType, values, hasValueMap) {
hasValueMap = hasValueMap || {};
serverConfigFields.innerHTML = '';
if (!serverFields[serverType]) {
updateTestButtonState();
return;
}
var fields = serverFields[serverType];
fields.forEach(function(field) {
var value = '';
if (values[field.name]) {
value = values[field.name];
}
var secret = false;
var secretKeys = ['NAVIDROME_PASSWORD', 'AUDIOMUSE_PASSWORD', 'API_TOKEN', 'JELLYFIN_TOKEN', 'EMBY_TOKEN'];
for (var i = 0; i < secretKeys.length; i++) {
if (secretKeys[i] === field.name) {
secret = true;
break;
}
}
if (field.name.indexOf('_API_KEY') !== -1) {
secret = true;
}
var hasValue = false;
if (hasValueMap) {
if (hasValueMap[field.name]) {
hasValue = true;
}
}
var fieldCopy = {
name: field.name,
label: field.label,
placeholder: field.placeholder,
required: true,
secret: secret,
has_value: hasValue,
tooltip: field.tooltip,
originalValue: originalValues[field.name] !== undefined ? originalValues[field.name] : value
};
serverConfigFields.appendChild(createInputField(fieldCopy, value));
});
updateTestButtonState();
}
function renderAdvancedFields(fields) {
advancedFields.innerHTML = '';
if (!fields) {
return;
}
fields.forEach(function(field) {
var secret = false;
if (field.secret) {
secret = true;
}
if (field.name.indexOf('_API_KEY') !== -1) {
secret = true;
}
var fieldConfig = {
name: field.name,
label: field.name,
placeholder: field.default ? field.default : '',
type: field.type === 'bool' ? 'boolean' : field.type,
inputType: 'text',
secret: secret,
has_value: field.has_value,
options: Array.isArray(field.options) ? field.options : null,
originalValue: originalValues[field.name] !== undefined ? originalValues[field.name] : (field.value || '')
};
advancedFields.appendChild(createInputField(fieldConfig, field.value));
});
}
function loadSetupData() {
fetch('/api/setup').then(function(response) {
if (!response.ok) {
throw new Error('Failed to load setup data');
}
return response.json();
}).then(function(data) {
hasAdminUser = !!data.has_admin_user;
var basicData = {};
var secretHasValue = {};
data.basic_fields.forEach(function(item) {
basicData[item.name] = item.value;
if (item.secret) {
secretHasValue[item.name] = item.has_value;
}
});
serverSecretHasValue = secretHasValue;
var advancedData = data.advanced_fields;
var mediaServerSelect = document.getElementById('MEDIASERVER_TYPE');
if (basicData.MEDIASERVER_TYPE) {
mediaServerSelect.value = basicData.MEDIASERVER_TYPE;
} else {
mediaServerSelect.value = 'jellyfin';
}
var authEnabledSelect = document.getElementById('AUTH_ENABLED');
if (basicData.AUTH_ENABLED) {
authEnabledSelect.value = String(basicData.AUTH_ENABLED).toLowerCase();
} else {
authEnabledSelect.value = 'true';
}
var usernameInput = document.getElementById('AUDIOMUSE_USER');
if (basicData.AUDIOMUSE_USER) {
usernameInput.value = basicData.AUDIOMUSE_USER;
} else {
usernameInput.value = '';
}
var passwordInput = document.getElementById('AUDIOMUSE_PASSWORD');
var confirmInput = document.getElementById('AUDIOMUSE_PASSWORD_CONFIRM');
var tokenInput = document.getElementById('API_TOKEN');
if (passwordInput && secretHasValue.AUDIOMUSE_PASSWORD) {
passwordInput.value = '********';
passwordInput.dataset.originalValue = '********';
passwordInput.placeholder = '********';
} else if (passwordInput) {
passwordInput.value = '';
passwordInput.dataset.originalValue = '';
}
if (confirmInput && secretHasValue.AUDIOMUSE_PASSWORD) {
confirmInput.value = '********';
confirmInput.dataset.originalValue = '********';
confirmInput.placeholder = '********';
} else if (confirmInput) {
confirmInput.value = '';
confirmInput.dataset.originalValue = '';
}
if (tokenInput) {
if (secretHasValue.API_TOKEN) {
tokenInput.value = '********';
tokenInput.dataset.originalValue = '********';
} else {
tokenInput.value = basicData.API_TOKEN || '';
tokenInput.dataset.originalValue = tokenInput.value;
}
}
var jwtInput = document.getElementById('JWT_SECRET');
if (jwtInput) {
if (secretHasValue.JWT_SECRET) {
jwtInput.value = '********';
jwtInput.dataset.originalValue = '********';
} else {
if (basicData.JWT_SECRET) {
jwtInput.value = basicData.JWT_SECRET;
} else {
jwtInput.value = '';
}
jwtInput.dataset.originalValue = jwtInput.value;
}
}
var visibleAdvancedData = Array.isArray(advancedData)
? advancedData.filter(function(f) { return f && f.name !== 'MUSIC_LIBRARIES'; })
: advancedData;
currentSelectedLibraries = splitLibraryList(data.music_libraries);
originalValues = {};
data.basic_fields.forEach(function(item) {
originalValues[item.name] = item.value || '';
if (item.secret && item.has_value && !item.value) {
originalValues[item.name] = '********';
}
});
data.advanced_fields.forEach(function(item) {
originalValues[item.name] = item.value || '';
if (item.secret && item.has_value && !item.value) {
originalValues[item.name] = '********';
}
});
serverValues = basicData; // keep the full current server-related values
renderServerFields(mediaServerSelect.value, basicData, secretHasValue);
renderAdvancedFields(visibleAdvancedData);
populateLyricsApiFields(data.lyrics_api_fields);
updateAuthVisibility();
// If the provider is already configured (server returned `has_value`
// for the credential fields), auto-fetch the library list so the
// checkbox state matches the saved MUSIC_LIBRARIES value.
if (providerCredsHaveSavedValues(mediaServerSelect.value, secretHasValue, basicData)) {
fetchProviderLibraries(mediaServerSelect.value);
}
}).catch(function(err) {
saveFeedback.className = 'status-failure inline-feedback';
saveFeedback.style.display = 'block';
saveFeedback.textContent = 'Unable to load setup data. Refresh the page or check the server logs.';
});
}
function saveCurrentServerValues() {
var currentServerType = document.getElementById('MEDIASERVER_TYPE').value;
var keys = ['JELLYFIN_URL', 'JELLYFIN_USER_ID', 'JELLYFIN_TOKEN', 'NAVIDROME_URL', 'NAVIDROME_USER', 'NAVIDROME_PASSWORD', 'LYRION_URL', 'EMBY_URL', 'EMBY_USER_ID', 'EMBY_TOKEN'];
keys.forEach(function(key) {
var input = document.getElementById(key);
if (input) {
serverValues[key] = input.value;
}
});
}
function testConfigFieldsFilled() {
var requiredFields = serverConfigFields.querySelectorAll('input[required], textarea[required], select[required]');
if (!requiredFields.length) {
return false;
}
return Array.prototype.every.call(requiredFields, function(input) {
if (input.disabled) {
return true;
}
return input.value.trim() !== '';
});
}
function updateTestButtonState() {
var testButton = document.getElementById('test-button');
testButton.disabled = !testConfigFieldsFilled();
}
function updateServerFields() {
saveCurrentServerValues();
var serverType = document.getElementById('MEDIASERVER_TYPE').value;
renderServerFields(serverType, serverValues, serverSecretHasValue);
// Hide the checkbox list (it only matches the prior provider's library
// names) but keep ``currentSelectedLibraries`` intact: it reflects the
// *saved* MUSIC_LIBRARIES value, which is provider-agnostic in storage.
// If the user flips back to the original provider, the next render will
// re-check the matching names. The renderer's case-insensitive name
// match means stale names against a new provider's libraries simply
// miss and leave their boxes unchecked — no leakage into the save.
hideMusicLibrariesSection();
}
function splitLibraryList(value) {
if (!value) {
return [];
}
return String(value).split(',').map(function(s) { return s.trim(); }).filter(Boolean);
}
function providerCredsHaveSavedValues(serverType, secretHasValue, basicData) {
var fields = serverFields[serverType];
if (!fields) return false;
for (var i = 0; i < fields.length; i++) {
var name = fields[i].name;
// For secret fields the server returns has_value=true when a value is
// stored; for non-secret it just returns the actual string.
if (secretHasValue && secretHasValue[name]) continue;
if (basicData && basicData[name]) continue;
return false;
}
return true;
}
function hideMusicLibrariesSection() {
if (!musicLibrariesSection) return;
musicLibrariesSection.style.display = 'none';
musicLibrariesList.innerHTML = '';
currentLibraryCheckboxes = [];
currentNoRestrictionCheckbox = null;
if (musicLibrariesHint) musicLibrariesHint.style.display = 'none';
}
function fetchProviderLibraries(serverType, configOverride) {
if (!musicLibrariesSection) return;
if (!serverFields[serverType]) {
hideMusicLibrariesSection();
return;
}
var configPayload = configOverride || collectConfigFromForm(true);
// MEDIASERVER_TYPE may be dropped by collectConfigFromForm if unchanged.
configPayload.MEDIASERVER_TYPE = serverType;
fetch('/api/setup/providers/libraries', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ config: configPayload })
}).then(function(resp) {
return resp.json().then(function(data) {
if (!resp.ok) {
throw new Error(data.error || 'Unable to list libraries.');
}
return data;
});
}).then(function(data) {
if (data.unsupported || !Array.isArray(data.libraries) || data.libraries.length === 0) {
hideMusicLibrariesSection();
return;
}
// Preserve the user's in-flight checkbox toggles across re-renders
// (e.g. after clicking Test Connection again). Otherwise we would
// reset to currentSelectedLibraries, which only reflects the value
// last loaded from /api/setup.
var selectedForRender = currentSelectedLibraries;
var forceNoRestriction = false;
// Track whether this is a re-render (state from a previous render
// exists) vs the first render after page load. The "honor live UI
// state" fallback below must only run on re-renders, otherwise an
// empty DB selection would be treated as "user just unchecked
// everything" and we'd uncheck the default No-restriction box.
var isRerender = (currentLibraryCheckboxes.length > 0 || !!currentNoRestrictionCheckbox);
if (isRerender) {
// "No restriction" wins: render as the unrestricted state (empty list).
if (currentNoRestrictionCheckbox && currentNoRestrictionCheckbox.checked) {
selectedForRender = [];
forceNoRestriction = true;
} else {
var checkedNames = [];
for (var k = 0; k < currentLibraryCheckboxes.length; k++) {
if (currentLibraryCheckboxes[k].checked) {
checkedNames.push(currentLibraryCheckboxes[k].dataset.libraryName);
}
}
selectedForRender = checkedNames;
}
}
renderLibraryCheckboxes(data.libraries, selectedForRender);
// Re-render only: if the user explicitly turned No-restriction off
// and unchecked all rows, renderLibraryCheckboxes would have
// defaulted back to "no restriction" (stale-selection fallback).
// Honor the live UI state instead. On the first render we want the
// default behavior (empty saved selection → No-restriction checked).
if (isRerender && currentNoRestrictionCheckbox && !forceNoRestriction
&& Array.isArray(selectedForRender) && selectedForRender.length === 0) {
currentNoRestrictionCheckbox.checked = false;
applyNoRestrictionState();
updateMusicLibrariesHint();
}
}).catch(function() {
// Don't block the user on list failures — the free-text value still
// works on save (empty string = scan everything).
hideMusicLibrariesSection();
});
}
function renderLibraryCheckboxes(libraries, selectedNames) {
if (!musicLibrariesList) return;
musicLibrariesList.innerHTML = '';
currentLibraryCheckboxes = [];
currentNoRestrictionCheckbox = null;
// Map saved names to lowercase for case-insensitive lookup.
var selectedLower = {};
var rawHasSelection = Array.isArray(selectedNames) && selectedNames.length > 0;
if (rawHasSelection) {
for (var i = 0; i < selectedNames.length; i++) {
selectedLower[String(selectedNames[i]).toLowerCase()] = true;
}
}
// "No restriction" = empty saved selection. Backend reads MUSIC_LIBRARIES=''
// as "scan everything" across every media-server adapter, and new libraries
// added later are picked up automatically.
var noRestriction = !rawHasSelection;
// If a saved selection exists but has no overlap with this provider's
// libraries (e.g. names were saved for a different provider), treat it as
// stale and fall back to "no restriction" rather than rendering all
// unchecked which would look broken.
if (rawHasSelection) {
var anyMatch = false;
for (var j = 0; j < libraries.length; j++) {
var libName = libraries[j] && libraries[j].name ? String(libraries[j].name).toLowerCase() : '';
if (libName && selectedLower[libName]) { anyMatch = true; break; }
}
if (!anyMatch) noRestriction = true;
}
// --- "No restriction" pseudo-row at the top ---
var noRow = document.createElement('label');
noRow.style.display = 'flex';
noRow.style.alignItems = 'center';
noRow.style.gap = '0.5rem';
noRow.style.fontWeight = '500';
var noCb = document.createElement('input');
noCb.type = 'checkbox';
noCb.checked = noRestriction;
noCb.style.width = 'auto';
noCb.style.flex = '0 0 auto';
noCb.style.margin = '0';
noCb.addEventListener('change', function() {
applyNoRestrictionState();
updateMusicLibrariesHint();
});
noRow.appendChild(noCb);
noRow.appendChild(document.createTextNode('No restriction (scan all libraries, including ones added later)'));
musicLibrariesList.appendChild(noRow);
currentNoRestrictionCheckbox = noCb;
libraries.forEach(function(lib) {
var name = lib && lib.name ? String(lib.name) : '';
if (!name) return;
var row = document.createElement('label');
row.style.display = 'flex';
row.style.alignItems = 'center';
row.style.gap = '0.5rem';
row.style.fontWeight = '400';
var cb = document.createElement('input');
cb.type = 'checkbox';
cb.dataset.libraryName = name;
// When "No restriction" is on, individual rows are visually checked
// but disabled (the user shouldn't be picking from a list that is
// already overridden). When off, honor the saved selection.
cb.checked = noRestriction ? false : !!selectedLower[name.toLowerCase()];
// Override `.field-row input { width: 100% }` from setup.html — that
// global rule would stretch each checkbox across the row and push
// the label text to the far right.
cb.style.width = 'auto';
cb.style.flex = '0 0 auto';
cb.style.margin = '0';
cb.addEventListener('change', updateMusicLibrariesHint);
row.appendChild(cb);
row.appendChild(document.createTextNode(name));
row.dataset.libraryRow = '1';
musicLibrariesList.appendChild(row);
currentLibraryCheckboxes.push(cb);
});
applyNoRestrictionState();
musicLibrariesSection.style.display = 'flex';
updateMusicLibrariesHint();
}
function applyNoRestrictionState() {
// Disable per-library checkboxes (and dim their rows) whenever the
// "No restriction" pseudo-entry is checked, so the UI matches the
// semantics: empty MUSIC_LIBRARIES means "scan everything".
if (!currentNoRestrictionCheckbox) return;
var disabled = !!currentNoRestrictionCheckbox.checked;
for (var i = 0; i < currentLibraryCheckboxes.length; i++) {
var cb = currentLibraryCheckboxes[i];
cb.disabled = disabled;
if (disabled) cb.checked = false;
if (cb.parentElement) cb.parentElement.style.opacity = disabled ? '0.5' : '1';
}
}
function updateMusicLibrariesHint() {
if (!musicLibrariesHint) return;
// Hint = "you'll scan nothing": only relevant when No-restriction is OFF
// and the user has unchecked every library row.
var noRestriction = currentNoRestrictionCheckbox && currentNoRestrictionCheckbox.checked;
var anyChecked = currentLibraryCheckboxes.some(function(cb) { return cb.checked; });
musicLibrariesHint.style.display = (!noRestriction && currentLibraryCheckboxes.length > 0 && !anyChecked)
? 'block' : 'none';
}
function collectMusicLibrariesValue() {
// Returns the MUSIC_LIBRARIES value to store, or null to skip writing.
if (!currentLibraryCheckboxes.length && !currentNoRestrictionCheckbox) {
// Section isn't rendered (MPD or provider doesn't support it, or the
// fetch failed). Don't touch MUSIC_LIBRARIES.
return null;
}
// "No restriction" → empty (= scan everything, every adapter treats this
// as "no filter" and will include libraries added in the future).
if (currentNoRestrictionCheckbox && currentNoRestrictionCheckbox.checked) {
return '';
}
var checked = currentLibraryCheckboxes.filter(function(cb) { return cb.checked; });
// None checked while No-restriction is OFF → still empty (scan all).
// "Scan nothing" is a footgun and the hint already warns the user; we
// refuse to persist that state.
if (checked.length === 0) {
return '';
}
// MUSIC_LIBRARIES is stored as a comma-separated string, so a comma in a
// library name would corrupt the round-trip. Skip writing rather than
// sending a poisoned value; the hint makes the case visible to the user.
var names = checked.map(function(cb) { return cb.dataset.libraryName; });
if (names.some(function(n) { return n.indexOf(',') !== -1; })) {
return null;
}
return names.join(',');
}
function collectConfigFromForm(testMode) {
var formData = new FormData(setupForm);
var config = {};
formData.forEach(function(value, key) {
var input = document.getElementById(key);
if (!input) {
return;
}
var original = input.dataset.originalValue;
if (!testMode) {
if (original !== undefined && value === original) {
return;
}
if (value === '' && original === undefined) {
return;
}
} else {
if (input.type === 'password' && original === '********' && value === '********') {
return;
}
}
config[key] = value;
});
return config;
}
function testConnection() {
var testButton = document.getElementById('test-button');
var passwordInput = document.getElementById('AUDIOMUSE_PASSWORD');
var confirmInput = document.getElementById('AUDIOMUSE_PASSWORD_CONFIRM');
var passwordValue = '';
if (passwordInput) {
passwordValue = passwordInput.value;
}
var confirmValue = '';
if (confirmInput) {
confirmValue = confirmInput.value;
}
var passwordUnchanged = (passwordValue === '********');
if (passwordUnchanged && !confirmValue) {
passwordUnchanged = true;
} else {
passwordUnchanged = false;
}
if (!passwordUnchanged && (passwordValue || confirmValue)) {
if (passwordValue !== confirmValue) {
testFeedback.className = 'status-failure inline-feedback';
testFeedback.style.display = 'block';
testFeedback.textContent = 'Password and confirmation do not match.';
return;
}
}
testButton.disabled = true;
saveButton.disabled = true;
testFeedback.className = 'status-pending inline-feedback';
testFeedback.style.display = 'block';
testFeedback.textContent = 'Testing connection...';
var config = collectConfigFromForm(true);
fetch('/api/setup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ config: config, test_connection: true })
}).then(function(resp) {
return resp.json().then(function(data) {
if (!resp.ok) {
var structured = (typeof formatErrorText === 'function' && data.error_code) ? formatErrorText(data) : null;
throw new Error(structured || data.error || 'Unable to test connection.');
}
return data;
});
}).then(function(data) {
testFeedback.className = 'status-success inline-feedback';
testFeedback.style.display = 'block';
var serverName = data.media_server ? data.media_server.charAt(0).toUpperCase() + data.media_server.slice(1) : 'media server';
var count = (typeof data.probe_count === 'number') ? data.probe_count : 0;
if (data.probe_limit_hit) {
testFeedback.textContent = '✓ Connected to ' + serverName + '. At least ' + count + ' recent top-played items were returned.';
} else if (count === 1) {
testFeedback.textContent = '✓ Connected to ' + serverName + '. 1 top-played item was returned.';
} else {
testFeedback.textContent = '✓ Connected to ' + serverName + '. ' + count + ' top-played items were returned.';
}
// Populate the library checkbox list using the same config payload
// (so secret placeholders fall back to saved values server-side).
var serverType = document.getElementById('MEDIASERVER_TYPE').value;
fetchProviderLibraries(serverType, config);
}).catch(function(err) {
testFeedback.className = 'status-failure inline-feedback';
testFeedback.style.display = 'block';
testFeedback.textContent = '✕ Connection test failed: ' + err.message;
}).finally(function() {
testButton.disabled = false;
saveButton.disabled = false;
});
}
setupForm.addEventListener('submit', function(event) {
event.preventDefault();
saveButton.disabled = true;
saveFeedback.style.display = 'none';
var passwordInput = document.getElementById('AUDIOMUSE_PASSWORD');
var confirmInput = document.getElementById('AUDIOMUSE_PASSWORD_CONFIRM');
var passwordValue = '';
if (passwordInput) {
passwordValue = passwordInput.value;
}
var confirmValue = '';
if (confirmInput) {
confirmValue = confirmInput.value;
}
var passwordUnchanged = (passwordValue === '********');
if (passwordUnchanged && !confirmValue) {
passwordUnchanged = true;
} else {
passwordUnchanged = false;
}
if (!passwordUnchanged && (passwordValue || confirmValue)) {
if (passwordValue !== confirmValue) {
saveFeedback.className = 'status-failure inline-feedback';
saveFeedback.style.display = 'block';
saveFeedback.textContent = 'Password and confirmation do not match.';
saveButton.disabled = false;
return;
}
}
var config = collectConfigFromForm();
var mlValue = collectMusicLibrariesValue();
if (mlValue !== null) {
config.MUSIC_LIBRARIES = mlValue;
}
fetch('/api/setup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ config: config })
}).then(function(resp) {
return resp.json().then(function(data) {
if (!resp.ok) {
throw new Error(data.error || 'Unable to save configuration.');
}
return data;
});
}).then(function(data) {
saveFeedback.className = 'status-success inline-feedback';
saveFeedback.style.display = 'block';
var countdown = 20;
saveFeedback.textContent = 'Configuration saved. Redirecting in ' + countdown + ' seconds...';
var countdownInterval = setInterval(function() {
countdown -= 1;
if (countdown > 0) {
saveFeedback.textContent = 'Configuration saved. Redirecting in ' + countdown + ' seconds...';
} else {
clearInterval(countdownInterval);
window.location.href = '/';
}
}, 1000);
}).catch(function(err) {
saveFeedback.className = 'status-failure inline-feedback';
saveFeedback.style.display = 'block';
var message = err.message || 'Unable to save configuration.';
if (message === 'Forbidden' || message === 'Setup required' || message === 'Auth not configured') {
message = 'Error saving configuration. Please refresh the page and try again.';
} else if (!message.toLowerCase().includes('refresh')) {
message = message + ' Please refresh the page or check the server logs.';
}
saveFeedback.textContent = '✕ ' + message;
}).finally(function() {
saveButton.disabled = false;
});
});
document.getElementById('test-button').addEventListener('click', testConnection);
serverConfigFields.addEventListener('input', updateTestButtonState);
document.getElementById('MEDIASERVER_TYPE').addEventListener('change', updateServerFields);
document.getElementById('AUTH_ENABLED').addEventListener('change', updateAuthVisibility);
// ---------------------------------------------------------------------------
// Lyrics API section — interactive analyze & configure
// ---------------------------------------------------------------------------
var lyricsApiState = {};
[1, 2].forEach(function(s) {
lyricsApiState[s] = {exampleUrl: '', params: {}, paramRoles: {}, pathSegments: [], pathRoles: {}, jsonObj: null, selectedField: null};
});
function populateLyricsApiFields(lyricsApiData) {
if (!lyricsApiData) return;
[1, 2].forEach(function(slot) {
var pre = 'LYRICS_API_' + slot + '_';
var get = function(k) { return lyricsApiData[pre + k] || {}; };
var urlTemplate = get('URL_TEMPLATE').value || '';
var artistParam = get('ARTIST_PARAM').value || '';
var titleParam = get('TITLE_PARAM').value || '';
var lyricsField = get('LYRICS_FIELD').value || '';
var apikeyParam = get('APIKEY_PARAM').value || '';
var apikeyHasVal = get('APIKEY_VALUE').has_value || false;
var timeout = get('TIMEOUT').value || '5';
function setHidden(name, val) {
var el = document.getElementById(name);
if (el) { el.value = val; el.dataset.originalValue = val; }
}
setHidden(pre + 'URL_TEMPLATE', urlTemplate);
setHidden(pre + 'ARTIST_PARAM', artistParam);
setHidden(pre + 'TITLE_PARAM', titleParam);
setHidden(pre + 'LYRICS_FIELD', lyricsField);
setHidden(pre + 'APIKEY_PARAM', apikeyParam);
var akEl = document.getElementById(pre + 'APIKEY_VALUE');
if (akEl) { akEl.value = apikeyHasVal ? '********' : ''; akEl.dataset.originalValue = akEl.value; }
var toEl = document.getElementById(pre + 'TIMEOUT');
if (toEl) { toEl.value = timeout; toEl.dataset.originalValue = timeout; }
var isPathBased = urlTemplate.indexOf('{artist}') !== -1 && urlTemplate.indexOf('{title}') !== -1;
var configComplete = urlTemplate && lyricsField && (isPathBased || (artistParam && titleParam));
if (configComplete) {
showLyricsApiSlotSummary(slot, urlTemplate, artistParam, titleParam, lyricsField, apikeyParam, apikeyHasVal);
var inputRow = document.getElementById('lyrics-api-' + slot + '-input-row');
if (inputRow) inputRow.style.display = 'none';
var toRow = document.getElementById('lyrics-api-' + slot + '-timeout-row');
if (toRow) toRow.style.display = 'flex';
}
});
}
function showLyricsApiStatus(slot, type, msg) {
var row = document.getElementById('lyrics-api-' + slot + '-analyze-status');
var el = document.getElementById('lyrics-api-' + slot + '-status-msg');
if (!row || !el) return;
row.style.display = 'block';
el.className = 'inline-feedback status-' + type;
el.textContent = msg;
}
function analyzeLyricsApiSlot(slot) {
var urlEl = document.getElementById('lyrics-api-' + slot + '-example-url');
var url = urlEl ? urlEl.value.trim() : '';
if (!url) { showLyricsApiStatus(slot, 'failure', 'Please enter an example URL.'); return; }
var btn = document.getElementById('lyrics-api-' + slot + '-analyze-btn');
if (btn) btn.disabled = true;
showLyricsApiStatus(slot, 'pending', 'Calling the API\u2026');
fetch('/api/setup/lyrics-api/analyze', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({example_url: url})
}).then(function(r) { return r.json(); }).then(function(data) {
if (btn) btn.disabled = false;
if (data.error && !data.json_obj && !data.params) {
showLyricsApiStatus(slot, 'failure', '\u2715 ' + data.error);
return;
}
showLyricsApiStatus(slot, data.error ? 'pending' : 'success',
data.error ? ('\u26a0 HTTP error: ' + data.error) : '\u2713 API responded \u2014 select the lyrics field below.');
var state = lyricsApiState[slot];
state.exampleUrl = url;
state.params = data.params || {};
state.pathSegments = data.path_segments || [];
state.pathRoles = {};
state.jsonObj = (data.json_obj !== undefined) ? data.json_obj : null;
state.selectedField = (data.guesses && data.guesses.lyrics_field) || null;
state.paramRoles = {};
var g = data.guesses || {};
Object.keys(state.params).forEach(function(pname) {
if (pname === g.artist_param) state.paramRoles[pname] = 'artist';
else if (pname === g.title_param) state.paramRoles[pname] = 'title';
else if (pname === g.apikey_param) state.paramRoles[pname] = 'apikey';
else state.paramRoles[pname] = 'none';
});
// Apply server-side path-segment role guesses (e.g. last two segments => artist/title)
if (g.path_roles && typeof g.path_roles === 'object') {
Object.keys(g.path_roles).forEach(function(idx) {
state.pathRoles[idx] = g.path_roles[idx];
});
}
// Auto-suggest timeout: actual response time + 20%, minimum 2 extra seconds
if (data.elapsed_ms != null) {
var elapsed = data.elapsed_ms / 1000;
var suggested = Math.max(elapsed * 1.2, elapsed + 2);
suggested = Math.round(suggested * 2) / 2; // round to nearest 0.5s
state.suggestedTimeout = Math.max(suggested, 2);
} else {
state.suggestedTimeout = 5;
}