-
Notifications
You must be signed in to change notification settings - Fork 207
Expand file tree
/
Copy pathplayerlib.js
More file actions
executable file
·5245 lines (4786 loc) · 217 KB
/
Copy pathplayerlib.js
File metadata and controls
executable file
·5245 lines (4786 loc) · 217 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
/*!
* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright 2014 The moOde audio player project / Tim Curtis
* Copyright 2013 The tsunamp player ui / Andrea Coiutti & Simone De Gregori
*/
// Features availability bitmask
const FEAT_HTTPS = 1; // y HTTPS mode
const FEAT_AIRPLAY = 2; // y AirPlay renderer
const FEAT_MINIDLNA = 4; // y DLNA server
const FEAT_RECORDER = 8; // Stream recorder
const FEAT_SQUEEZELITE = 16; // y Squeezelite renderer
const FEAT_UPMPDCLI = 32; // y UPnP client for MPD
const FEAT_DEEZER = 64; // n Deezer Connect renderer
const FEAT_ROONBRIDGE = 128; // y RoonBridge renderer
const FEAT_LOCALDISPLAY = 256; // y Local display
const FEAT_INPSOURCE = 512; // y Input source select
const FEAT_UPNPSYNC = 1024; // UPnP volume sync
const FEAT_SPOTIFY = 2048; // y Spotify Connect renderer
const FEAT_GPIO = 4096; // y GPIO button handler
const FEAT_PLEXAMP = 8192; // y Plexamp renderer
const FEAT_BLUETOOTH = 16384; // y Bluetooth renderer
const FEAT_DEVTWEAKS = 32768; // Developer tweaks
const FEAT_MULTIROOM = 65536; // y Multiroom audio
const FEAT_PEPPYDISPLAY = 131072; // y Peppy display
const FEAT_SENDSPIN = 262144; // y Sendspin renderer
// -------
// 490423
// Notifications
const NOTIFY_TITLE_INFO = '<i class="fa fa-solid fa-sharp fa-circle-check" style="color:#27ae60;"></i> Info';
const NOTIFY_TITLE_ALERT = '<i class="fa fa-solid fa-sharp fa-circle-xmark" style="color:#e74c3c;"></i> Alert';
const NOTIFY_TITLE_ERROR = '<i class="fa fa-solid fa-sharp fa-do-not-enter" style="color:#e74c3c;"></i> Error';
const NOTIFY_TITLE_WELCOME = '<i class="fa fa-solid fa-sharp fa-circle-check" style="color:#27ae60;"></i> Welcome!';
const NOTIFY_DURATION_SHORT = 2; // Seconds
const NOTIFY_DURATION_DEFAULT = 5;
const NOTIFY_DURATION_MEDIUM = 10;
const NOTIFY_DURATION_LONG = 30;
const NOTIFY_DURATION_INFINITE = 8640000; // 100 days
const NOTIFY_MSG_NO_USERID =
'Without a userid moOde will not function correctly.<br><br>'
+ 'Follow the'
+ ' <a href="https://github.com/moode-player/docs/blob/main/setup_guide.md#4-imager-tutorial"'
+ ' class="target-blank-link" target="_blank">Imager Tutorial</a>'
+ ' to create a new image with a userid, password and SSH enabled.';
const NOTIFY_MSG_WELCOME =
'<b>View</b> <span class="context-menu">'
+ ' <a href="#notarget" data-cmd="quickhelp">Quick help</a></span>'
+ ' for information on using the WebUI, configuring audio devices and setting up the Music Library.<br><br>'
+ '<b>Read</b> the <a href="https://moodeaudio.org/forum/forumdisplay.php?fid=17"'
+ ' class="target-blank-link" target="_blank">Release Announcement</a>'
+ ' for any special instructions or patches for this release.<br><br>'
+ '<b>Remember</b> to practice Volume Safety and make sure a physical'
+ ' volume control is downstream and set to a low volume before first use or'
+ ' whenever changing device or volume options.<br><br>'
+ '<button id="welcome-firstuse-help" aria-label="Dismiss" class="btn btn-primary btn-small modal-button-style">Dismiss</button>';
// System
const NO_USERID_DEFINED = 'userid does not exist';
// Timeouts in milliseconds
const DEFAULT_TIMEOUT = 250;
const CLRPLAY_TIMEOUT = 500;
const LAZYLOAD_TIMEOUT = 1000;
const SEARCH_TIMEOUT = 750;
const RALBUM_TIMEOUT = 500;
const ENGINE_TIMEOUT = 3000;
const CV_QUEUE_TIMEOUT = 60000;
const ONE_SEC_TIMEOUT = 1000;
const TWO_SEC_TIMEOUT = 2000;
// Album and Radio HD parameters
const ALBUM_HD_BADGE_TEXT = 'HiRes';
const ALBUM_BIT_DEPTH_THRESHOLD = 16;
const ALBUM_SAMPLE_RATE_THRESHOLD = 44100;
const RADIO_HD_BADGE_TEXT = 'HiRes';
const RADIO_BITRATE_THRESHOLD = 128;
// For legacy Radio Manager station export
const STATION_EXPORT_DIR = '/'; // var/www
// Library saved searches
const LIB_FULL_LIBRARY = 'Full Library (Default)';
// Library mount types
const LIB_MOUNT_TYPE_SMB = 'cifs';
const LIB_MOUNT_TYPE_NFS = 'nfs';
const LIB_MOUNT_TYPE_NVME = 'nvme';
// Default titles and covers
const DEFAULT_RADIO_TITLE = 'Radio station';
const DEFAULT_RADIO_COVER = 'images/default-album-cover.png';
const DEFAULT_ALBUM_COVER = 'images/default-album-cover.png';
const DEFAULT_UPNP_COVER = 'images/default-upnp-cover.jpg';
const DEFAULT_RX_COVER = 'images/default-rx-cover.jpg';
const DEFAULT_PLAYLIST_COVER = '/var/www/images/default-playlist-cover.jpg';
const DEFAULT_NOTFOUND_COVER = '/var/www/images/default-notfound-cover.jpg';
var UI = {
knob: null,
path: '',
restart: '',
currentFile: 'blank',
currentHash: 'blank',
currentSongId: 'blank',
knobPainted: false,
chipOptions: '',
hideReconnect: false,
bgImgChange: false,
dbPos: [0,0,0,0,0,0,0,0,0,0,0],
// - Used in Folder view
dbEntry: ['', '', '', '', '', ''],
// [0]: Item number or name used in various routines
// [1]: Used in bootstrap.contextmenu.js
// [2]: Used in bootstrap.contextmenu.js
// [3]: UI row num of song item so highlight can be removed after context menu action
// [4]: Num playlist items for use by delete/move item modals
// [5]: Playname for clock radio
dbCmd: '',
// Either 'lsinfo' or 'get_pl_items_fv'
radioPos: -1,
folderPos: -1,
libPos: [-1,-1,-1,-1],
// [0]: Album list pos (tag view)
// [1]: Album cover pos (album view)
// [2]: Artist list pos (tag view)
// [3]: Genre list pos (tag view)
// Special values for [0],[1]: -1 = full lib displayed, -2 = lib headers clicked, -3 = search performed
playlistPos: -1,
libAlbum: '',
mobile: false,
thumbHW: '0px'
};
// MPD state and metadata
var MPD = {
json: 0
};
// Session vars (cfg_system table)
var SESSION = {
json: 0
};
// Radio stations (cfg_radio table)
var RADIO = {
json: 0
};
// Themes (cfg_theme table)
var THEME = {
json: 0
};
// Networks (cfg_network table)
var NETWORK = {
json: 0
};
// SSID's (cfg_ssid table)
var SSID = {
json: 0
};
// TODO: Eventually migrate all global vars here
var GLOBAL = {
musicScope: 'all', // Or not defined if saved, but prob don't bother saving...
searchRadio: '',
searchFolder: '',
searchPlaylist: '',
scriptSection: 'panels',
regExIgnoreArticles: '',
libRendered: false,
libLoading: false,
cvQueueTimer: '',
pqActionClicked: false,
mpdMaxVolume: 0,
lastTimeCount: 0,
editStationId: '',
nativeLazyLoad: false,
playQueueChanged: false,
playQueueLength: 0,
initTime: 0,
searchOperators: ['==', '!=', '=~', '!~'],
oneArgFilters: ['full_lib', 'hdonly', 'lossless', 'lossy'],
twoArgFilters: ['album', 'albumartist', 'any', 'artist', 'composer', 'conductor', 'encoded', 'file', 'folder', 'format', 'genre', 'label', 'performer', 'title', 'work', 'year'],
allFilters: [],
sbw: 0,
backupCreate: false,
busySpinnerSVG: "<svg xmlns='http://www.w3.org/2000/svg' width='42' height='42' viewBox='0 0 42 42' stroke='#fff'><g fill='none' fill-rule='evenodd'><g transform='translate(3 3)' stroke-width='4'><circle stroke-opacity='.35' cx='18' cy='18' r='18'/><path d='M36 18c0-9.94-8.06-18-18-18'><animateTransform attributeName='transform' type='rotate' from='0 18 18' to='360 18 18' dur='1s' repeatCount='indefinite'/></path></g></g></svg>",
thisClientIP: '',
chromium: false,
ssClockIntervalID: '',
reconnecting: false,
searchTags: ['genre', 'artist', 'album', 'title', 'albumartist', 'date',
'composer', 'conductor', 'performer', 'work', 'comment', 'file'],
npIcon: '',
coverViewActive: false,
userAgent: '',
ralbumClickedClearPlay: false
};
// All Library filters
GLOBAL.allFilters = GLOBAL.oneArgFilters.concat(GLOBAL.twoArgFilters);
// Live timeline
var timeSliderMove = false;
// Adaptive theme
var themeColor;
var themeBack;
var themeMcolor;
var tempcolor;
var themeOp;
var themeMback;
var adaptColor;
var adaptBack;
var adaptMhalf;
var adaptMcolor;
var adaptMback;
var tempback;
var accentColor;
var abFound;
var showMenuTopW;
var showMenuTopR;
var thumbw = "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='13' height='20'><circle fill='%23f0f0f0' cx='6.5' cy='10' r='3.5'/></svg>";
var thumbd = "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='13' height='20'><circle fill='%23303030' cx='6.5' cy='10' r='3.5'/></svg>";
var fatthumbw = "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='13' height='20'><circle fill='%23f0f0f0' cx='6.5' cy='10' r='5.5'/></svg>";
var fatthumbd = "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='13' height='20'><circle fill='%23303030' cx='6.5' cy='10' r='5.5'/></svg>";
var blurrr = CSS.supports('-webkit-backdrop-filter','blur(1px)');
// Various flags and things
var dbFilterResults = [];
var searchTimer = '';
var showSearchResetPq = false;
var showSearchResetRa = false;
var showSearchResetPl = false;
var showSearchResetPh = false;
var eqGainUpdInterval = '';
var toolbarTimer = '';
var toggleSongId = 'blank';
var currentView = 'playback';
var alphabitsFilter;
var lastYIQ = ''; // Last yiq value from setColors
// Detect chromium browser
GLOBAL.userAgent = navigator.userAgent;
GLOBAL.userAgent.indexOf('CrOS') != -1 ? GLOBAL.chromium = true : GLOBAL.chromium = false;
function debugLog(msg) {
if (SESSION.json['debuglog'] == '1') {
console.log(Date.now() + ': ' + msg);
}
}
// MPD commands
function sendMpdCmd(cmd, async) {
if (typeof(async) === 'undefined') {async = true;}
//console.log(cmd);
if (cmd.includes('play') || cmd == 'pause' || cmd == 'stop') {
$('.play').addClass('active');
} else if (cmd == 'next' || cmd == 'previous') {
$('.' + cmd.substring(0, 4)).addClass('active');
}
$.ajax({
type: 'GET',
url: 'command/index.php?cmd=' + cmd,
async: async,
cache: false,
success: function(data) {
//console.log(data);
}
});
}
// Specifically for volume
function sendVolCmd(type, cmd, data, async) {
if (typeof(data) === 'undefined') {data = '';}
if (typeof(async) === 'undefined') {async = true;}
if (data['event'] == 'mute' || data['event'] == 'unmute') {
$('.volume-display').addClass('active');
} else if (data['event'] == 'volume_up') {
$('#volumeup').addClass('active');
} else if (data['event'] == 'volume_down') {
$('#volumedn').addClass('active');
}
$.ajax({
type: type,
url: 'command/playback.php?cmd=' + cmd,
async: async,
cache: false,
data: data,
success: function(data) {
//console.log(JSON.parse(data));
},
error: function() {
//console.log('NOK');
}
});
}
// MPD metadata engine
function engineMpd() {
$.ajax({
type: 'GET',
url: 'engine-mpd.php?state=' + MPD.json['state'],
async: true,
cache: false,
success: function(data) {
debugLog('engineMpd(): success branch: data=(' + data + ')');
// Always have valid json
try {
MPD.json = JSON.parse(data);
//console.log(MPD.json);
}
catch (e) {
MPD.json['error'] = e;
}
if (typeof(MPD.json['error']) === 'undefined') {
//console.log('engineMpd(): idle_timeout_event=(' + MPD.json['idle_timeout_event'] + ')', 'state', MPD.json['state']);
// MPD restarted by watchdog, worker, a2dp-autoconnect, manually via cli, etc
if (MPD.json['idle_timeout_event'] === '') {
// NOP
} else {
if (UI.hideReconnect === true) {
hideReconnect();
}
// Database update
if (MPD.json['idle_timeout_event'] == 'changed: update') {
if (typeof(MPD.json['updating_db']) != 'undefined') {
$('.busy-spinner').show();
}
else {
$('.busy-spinner').hide();
}
}
// Render volume
else if (MPD.json['idle_timeout_event'] == 'changed: mixer') {
renderUIVol();
}
// When last item in playlist finishes just update a few things
else if (MPD.json['idle_timeout_event'] == 'changed: player' && MPD.json['file'] == null) {
resetPlayCtls();
}
// Render full UI
else {
if (MPD.json['date']) MPD.json['date'] = MPD.json['date'].slice(0,4); // should fix in php but...
renderUI();
}
}
engineMpd();
}
// Error of some sort
else {
debugLog('engineMpd(): success branch: error=(' + MPD.json['error']['code'] + ' ' + MPD.json['error']['message'] + ')');
// JSON parse errors @ohinckel https: //github.com/moode-player/moode/pull/14/files
if (typeof(MPD.json['error']) == 'object') {
var errorCode = typeof(MPD.json['error']['code']) === 'undefined' ? '' : ' (' + MPD.json['error']['code'] + ')';
// These particular errors occur when front-end is simply trying to reconnect
if (MPD.json['error']['message'] == 'JSON Parse error: Unexpected EOF' ||
MPD.json['error']['message'] == 'Unexpected end of JSON input') {
if (!GLOBAL.reconnecting) {
notify(NOTIFY_TITLE_INFO, 'reconnect', NOTIFY_DURATION_INFINITE);
GLOBAL.reconnecting = true;
}
} else if (MPD.json['error']['message'] != 'Socket timed out') {
notify(NOTIFY_TITLE_ALERT, 'mpd_error', MPD.json['error']['message'] + errorCode);
}
}
// MPD output -> Bluetooth but no actual BT connection
else if (MPD.json['error'] == 'Failed to open "ALSA bluetooth" (alsa); Failed to open ALSA device "btstream": No such device') {
notify(NOTIFY_TITLE_ALERT, 'mpd_error', 'Output is set to Bluetooth speaker but there is no connection or configured device.');
}
// Client connects before MPD started by worker ?
else if (MPD.json['error'] == 'SyntaxError: JSON Parse error: Unexpected EOF') {
notify(NOTIFY_TITLE_ALERT, 'mpd_error', 'JSON Parse error: Unexpected EOF.');
}
// MPD bug may have been fixed in 0.20.20 ?
else if (MPD.json['error'] == 'Not seekable') {
// NOP
}
// Other MPD or network errors
else {
if (MPD.json['error'].includes('Unknown error 524') && MPD.json['error'].includes('Failed to open ALSA device')) {
// 'Failed to open "ALSA Default" (alsa); Failed to open ALSA device "_audioout": Unknown error 524'
var msg = 'Output is set to HDMI but no audio device was detected on the HDMI port.';
} else {
var msg = MPD.json['error'];
}
notify(NOTIFY_TITLE_ALERT, 'mpd_error', msg);
}
// Socket timeout is ok but no need to renderUI when it happens
if (MPD.json['error']['message'] != 'Socket timed out') {
renderUI();
}
setTimeout(function() {
engineMpd();
}, ENGINE_TIMEOUT);
}
},
// Network connection interrupted or client network stack timeout
error: function(data) {
debugLog('engineMpd(): error branch: data=(' + JSON.stringify(data) + ')');
setTimeout(function() {
if (data['statusText'] == 'error' && data['readyState'] == 0) {
renderReconnect();
}
MPD.json['state'] = 'reconnect';
engineMpd();
}, ENGINE_TIMEOUT);
}
});
}
// MPD metadata engine lite (for scripts-configs)
function engineMpdLite() {
//debugLog('engineMpdLite(): state=(' + MPD.json['state'] + ')');
$.ajax({
type: 'GET',
url: 'engine-mpd.php?state=' + MPD.json['state'],
async: true,
cache: false,
success: function(data) {
debugLog('engineMpdLite(): success branch: data=(' + data + ')');
// Always have valid json
try {
MPD.json = JSON.parse(data);
}
catch (e) {
MPD.json['error'] = e;
}
if (typeof(MPD.json['error']) === 'undefined') {
//console.log('engineMpdLite: idle_timeout_event=(' + MPD.json['idle_timeout_event'] + ')', 'state', MPD.json['state']);
// MPD restarted by watchdog, worker, a2dp-autoconnect, manually via cli, etc
if (MPD.json['idle_timeout_event'] === '') {
// NOP
} else {
if (UI.hideReconnect === true) {
hideReconnect();
}
// Database update
if (typeof(MPD.json['updating_db']) != 'undefined') {
$('.busy-spinner').show();
}
else {
$('.busy-spinner').hide();
}
}
engineMpdLite();
}
// Error of some sort
else {
setTimeout(function(data) {
// Client connects before MPD started by worker, various other issues
debugLog('engineMpd(): success branch: error=(' + MPD.json['error']['code'] + ' ' + MPD.json['error']['message'] + ')');
// TEST: Show reconnect overlay when on configs
if (typeof(data) !== 'undefined') {
if (data['statusText'] == 'error' && data['readyState'] == 0) {
renderReconnect();
}
}
MPD.json['state'] = 'reconnect';
if (typeof(MPD.json['error']) == 'object') {
var errorCode = typeof(MPD.json['error']['code']) === 'undefined' ? '' : ' (' + MPD.json['error']['code'] + ')';
// These particular errors occur when front-end is simply trying to reconnect
if (MPD.json['error']['message'] == 'JSON Parse error: Unexpected EOF' ||
MPD.json['error']['message'] == 'Unexpected end of JSON input') {
if (!GLOBAL.reconnecting) {
notify(NOTIFY_TITLE_INFO, 'reconnect', NOTIFY_DURATION_INFINITE);
GLOBAL.reconnecting = true;
}
} else {
if (MPD.json['error']['message'] != "Socket timed out") {
notify(NOTIFY_TITLE_ALERT, 'mpd_error', MPD.json['error']['message'] + errorCode);
}
}
}
engineMpdLite();
}, ENGINE_TIMEOUT);
}
},
// Network connection interrupted or client network stack timeout
error: function(data) {
debugLog('engineMpdLite(): error branch: data=(' + JSON.stringify(data) + ')');
//console.log('engineMpdLite: error branch: data=(' + JSON.stringify(data) + ')');
setTimeout(function() {
if (typeof(data) !== 'undefined') {
if (data['statusText'] == 'error' && data['readyState'] == 0) {
renderReconnect();
}
}
MPD.json['state'] = 'reconnect';
engineMpdLite();
}, ENGINE_TIMEOUT);
}
});
}
// Command engine
function engineCmd() {
var cmd;
$.ajax({
type: 'GET',
url: 'engine-cmd.php',
async: true,
cache: false,
success: function(data) {
//console.log('engineCmd: success branch: data=(' + data + ')');
cmd = JSON.parse(data).split(',');
switch (cmd[0]) {
case 'inpactive1':
case 'inpactive0':
// NOTE: cmd[1] is the input source name
var inputSourceName = typeof(cmd[1]) == 'undefined' ? 'Undefined' : cmd[1];
inpSrcIndicator(cmd[0],
'<span id="inpsrc-msg-text">' + inputSourceName +
' Input Active: <button class="btn volume-popup-btn" data-toggle="modal"><i class="fa-regular fa-sharp fa-volume-up"></i></button><span id="inpsrc-preamp-volume"></span>' +
'</span>' +
'<a class="btn configure-renderer" href="inp-config.php">Input Select</a>' +
audioInfoBtn());
break;
case 'btactive1':
case 'btactive0':
inpSrcIndicator(cmd[0],
'<span id="inpsrc-msg-text">Bluetooth Active</span>' +
'<a class="btn configure-renderer" href="blu-config.php">Bluetooth Control</a>' +
receiversBtn() +
audioInfoBtn());
break;
case 'aplactive1':
case 'aplactive0':
case 'deezactive1':
case 'deezactive0':
case 'spotactive1':
case 'spotactive0':
if (cmd[0].includes('apl')) {
var rendererName = 'AirPlay';
SESSION.json['aplactive'] = cmd[0].slice(-1);
} else if (cmd[0].includes('deez')){
var rendererName = 'Deezer';
SESSION.json['deezactive'] = cmd[0].slice(-1);
} else if (cmd[0].includes('spot')) {
var rendererName = 'Spotify';
SESSION.json['spotactive'] = cmd[0].slice(-1);
}
inpSrcIndicator(cmd[0],
'<span id="inpsrc-msg-text">' +
rendererName +
' Active</span>' +
'<button class="btn renderer-btn disconnect-' +
rendererName.toLowerCase() +
'" data-job="' +
rendererName.toLowerCase() + 'svc"><i class="fa-regular fa-sharp fa-xmark"></i></button>' +
receiversBtn(cmd[0]) +
audioInfoBtn(cmd[0]) +
rendererRefreshBtn()
);
$('#inpsrc-metadata-refresh').html('');
// Fetch from back-end for robustness
refreshInpsrcMeta();
break;
case 'update_aplmeta':
case 'update_deezmeta':
case 'update_spotmeta':
// Received from back-end
updateInpsrcMeta(cmd[0], cmd[1]); // cmd[1]: metadata
// Fetch from back-end again for robustness
setTimeout(function() {
refreshInpsrcMeta();
}, ONE_SEC_TIMEOUT);
break;
case 'slactive1':
case 'slactive0':
inpSrcIndicator(cmd[0],
'<span id="inpsrc-msg-text">Squeezelite Active</span>' +
'<button class="btn turnoff-renderer" data-job="slsvc">Turn off</button>' +
audioInfoBtn());
break;
case 'paactive1':
case 'paactive0':
inpSrcIndicator(cmd[0],
'<span id="inpsrc-msg-text">Plexamp Active</span>' +
'<button class="btn turnoff-renderer" data-job="pasvc">Turn off</button>' +
audioInfoBtn());
break;
case 'rbactive1':
case 'rbactive0':
inpSrcIndicator(cmd[0],
'<span id="inpsrc-msg-text">RoonBridge Active</span>' +
'<button class="btn disconnect-renderer" data-job="rbrestart">Disconnect</button>' +
audioInfoBtn());
break;
case 'rxactive1':
case 'rxactive0':
inpSrcIndicator(cmd[0],
'<span id="inpsrc-msg-text">Multiroom Receiver On</span>' +
'<button class="btn turnoff-receiver" data-job="multiroom_rx">Turn off</button>' +
'<br><a class="btn configure-renderer" href="trx-config.php">Configure</a>' +
audioInfoBtn());
break;
case 'scnactive1':
case 'scnactive0':
screenSaver(cmd[0]);
break;
case 'toggle_coverview1':
case 'toggle_coverview0':
if (GLOBAL.chromium) {
screenSaver(cmd[0]);
}
break;
case 'libupd_done':
$('.busy-spinner').hide();
loadLibrary();
break;
case 'set_cover_image1':
$('.busy-spinner').show();
break;
case 'set_cover_image0':
$('.busy-spinner').hide();
break;
case 'cdsp_update_config':
notify(NOTIFY_TITLE_INFO, 'cdsp_update_config', cmd[1], NOTIFY_DURATION_DEFAULT);
break;
case 'cdsp_config_updated':
if (typeof(cmd[1]) != 'undefined') {
SESSION.json['camilladsp'] = cmd[1];
}
break;
case 'cdsp_config_update_failed':
notify(NOTIFY_TITLE_ALERT, 'cdsp_config_update_failed');
break;
case 'recorder_tagged':
notify(NOTIFY_TITLE_INFO, 'recorder_tagged', cmd[1] + ' files tagged, updating library...', NOTIFY_DURATION_MEDIUM);
break;
case 'recorder_nofiles':
notify(NOTIFY_TITLE_ALERT, 'recorder_nofiles');
break;
case 'reset_view':
case 'refresh_screen':
setTimeout(function() {
location.reload(true);
}, DEFAULT_TIMEOUT);
break;
case 'close_notification':
$('.ui-pnotify-closer').click();
break;
case 'reduce_fpm_pool':
// This functions as a dummy command which has the effect of
// causing engine-cmd.php to start releasing idle connections
console.log(cmd[0]);
break;
default:
console.log('engineCmd(): ' + cmd[0]);
break;
}
engineCmd();
},
error: function(data) {
//console.log('engineCmd: error branch: data=(' + JSON.stringify(data) + ')');
setTimeout(function() {
engineCmd();
}, ENGINE_TIMEOUT);
}
});
}
// Command engine lite (for scripts-configs)
function engineCmdLite() {
var cmd;
$.ajax({
type: 'GET',
url: 'engine-cmd.php',
async: true,
cache: false,
success: function(data) {
//console.log('engineCmd: success branch: data=(' + data + ')');
cmd = JSON.parse(data).split(',');
switch (cmd[0]) {
case 'libregen_done':
$('.busy-spinner').hide();
loadLibrary();
break;
case 'nvme_formatting_drive':
notify(NOTIFY_TITLE_INFO, 'nvme_formatting_drive', NOTIFY_DURATION_INFINITE);
break;
case 'cdsp_update_config':
notify(NOTIFY_TITLE_INFO, 'cdsp_update_config', cmd[1], NOTIFY_DURATION_INFINITE);
break;
case 'cdsp_config_updated':
// NOP
break;
case 'cdsp_config_update_failed':
notify(NOTIFY_TITLE_ALERT, 'cdsp_config_update_failed', NOTIFY_DURATION_MEDIUM);
break;
case 'trx_discovering_receivers':
notify(NOTIFY_TITLE_INFO, 'trx_discovering_receivers', NOTIFY_DURATION_INFINITE);
break;
case 'trx_configuring_sender':
notify(NOTIFY_TITLE_INFO, 'trx_configuring_sender', NOTIFY_DURATION_MEDIUM);
break;
case 'trx_configuring_mpd':
notify(NOTIFY_TITLE_INFO, 'trx_configuring_mpd', NOTIFY_DURATION_DEFAULT);
break;
case 'downgrading_chromium':
notify(NOTIFY_TITLE_INFO, 'downgrading_chromium', NOTIFY_DURATION_INFINITE);
break;
case 'reset_view':
case 'refresh_screen':
if (cmd[0] == 'reset_view') {
window.location.replace('/index.php');
}
setTimeout(function() {
location.reload(true);
}, DEFAULT_TIMEOUT);
break;
case 'close_notification':
$('.ui-pnotify-closer').click();
break;
case 'reduce_fpm_pool':
// This functions as a dummy command which has the effect of
// causing engine-cmd.php to start releasing idle connections
console.log(cmd[0]);
break;
default:
console.log('engineCmdLite(): ' + cmd[0]);
break;
}
engineCmdLite();
},
error: function(data) {
//console.log('engineCmd: error branch: data=(' + JSON.stringify(data) + ')');
setTimeout(function() {
engineCmdLite();
}, ENGINE_TIMEOUT);
}
});
}
function inpSrcIndicator(cmd, msgText) {
UI.currentFile = 'blank';
$('#inpsrc-msg').removeClass('inpsrc-msg-metadata');
$('#inpsrc-msg').addClass('inpsrc-msg-default');
$('#inpsrc-msg').css({width:'100%', top:'50%', bottom:'unset'});
$('#inpsrc-metadata').hide();
// Set custom backdrop (if any)
if (cmd == 'rxactive1') {
$('#inpsrc-backdrop').html('<img class="ss-backdrop" ' + 'src="' + DEFAULT_RX_COVER + '">');
$('#inpsrc-backdrop').css('filter', 'blur(1.25px)');
$('#inpsrc-backdrop').css('transform', 'scale(1.0)');
} else if (SESSION.json['renderer_backdrop'] == 'Yes') {
if (SESSION.json['cover_backdrop'] == 'Yes' && MPD.json['coverurl'].indexOf(DEFAULT_ALBUM_COVER) === -1) {
$('#inpsrc-backdrop').html('<img class="ss-backdrop" ' + 'src="' + MPD.json['coverurl'] + '">');
$('#inpsrc-backdrop').css('filter', 'blur(' + SESSION.json['cover_blur'] + ')');
$('#inpsrc-backdrop').css('transform', 'scale(' + SESSION.json['cover_scale'] + ')');
} else if (SESSION.json['bgimage'] != '') {
$('#inpsrc-backdrop').html('<img class="ss-backdrop" ' + 'src="' + SESSION.json['bgimage'] + '">');
$('#inpsrc-backdrop').css('filter', 'blur(0px)');
$('#inpsrc-backdrop').css('transform', 'scale(1.0)');
}
}
// Set the button and preamp volume
// NOTE: Preamp volume #id will only exist if audioin != Local
if (cmd.slice(-1) == '1') {
$('#inpsrc-indicator').css('display', 'block');
$('#inpsrc-msg').html(msgText);
$('#inpsrc-preamp-volume').text(SESSION.json['mpdmixer'] == 'none' ? '0dB' : SESSION.json['volknob']);
$('#multiroom-receiver-volume').text(SESSION.json['volmute'] == '1' ? 'mute' :
(SESSION.json['mpdmixer'] == 'none' ? '0dB' : SESSION.json['volknob']));
}
else {
$('#inpsrc-msg').html('');
$('#inpsrc-indicator').css('display', '');
}
}
function refreshInpsrcMeta() {
if (SESSION.json['aplactive'] == '1') {
cmd = 'get_aplmeta';
} else if (SESSION.json['deezactive'] == '1') {
cmd = 'get_deezmeta';
} else if (SESSION.json['spotactive'] == '1') {
cmd = 'get_spotmeta';
} else {
cmd = '';
}
if (cmd != '') {
$.getJSON('command/renderer.php?cmd=' + cmd, function(data) {
updateInpsrcMeta(cmd, data);
});
}
}
function updateInpsrcMeta(cmd, data) {
$('#inpsrc-msg').removeClass('inpsrc-msg-default');
$('#inpsrc-msg').addClass('inpsrc-msg-metadata');
$('#inpsrc-msg-text').text('');
$('#inpsrc-backdrop').css('filter', 'blur(0px)');
$('#inpsrc-backdrop').css('transform', 'scale(1.0)');
// AirPlay: [0]:title [1]:artist [2]:album [3]:duration (in ms) [4];coverurl [5]:format
// Deezer: [0]:title [1]:artist [2]:album [3]:duration (in secs) [4];coverurl [5]:format [6]:decoder
// Spotify: [0]:title [1]:artists [2]:album [3]:duration (in ms) [4];coverurls [5]:format
var metadata = data.split('~~~');
var timeDivisor = (cmd.includes('_aplmeta') || cmd.includes('_spotmeta')) ? 1000 : 1;
var title = metadata[0];
var artist = cmd == 'get_spotmeta' ? metadata[1].split("\n")[0] : metadata[1];
var album = metadata[2];
var duration = formatSongTime(Math.round(parseInt(metadata[3]) / timeDivisor));
var coverURL = cmd == 'get_spotmeta' ? metadata[4].split("\n")[0] : metadata[4];
var format = metadata[5];
if (title == '' || duration == '') {
// Radio station
var metadataHTML = '<b>' + artist + '</b>' + '<br><span id="renderer-format-badge">' + format + '</span><br><span>Live</span>';
} else {
// Song file
// NOTE: duration not being displayed at this time
var metadataHTML = '<b>' + artist + ' - ' + title + '</b>' + '<br><span id="renderer-format-badge">' + format + '</span><br><span>' + album + '</span>';
}
$('#inpsrc-cover').html('<img class="inpsrc-metadata-cover" ' + 'src="' + coverURL + '">');
$('#inpsrc-backdrop').html('<img class="ss-backdrop" ' + 'src="' + coverURL + '">');
$('#inpsrc-backdrop').css('filter', 'blur(' + SESSION.json['cover_blur'] + ')');
$('#inpsrc-backdrop').css('transform', 'scale(' + SESSION.json['cover_scale'] + ')');
$('#inpsrc-style').css('display', 'block');
$('#inpsrc-metadata').html(metadataHTML);
inpSrcMetaRefreshBtn();
$('#inpsrc-metadata').show();
$('#inpsrc-msg').css({
'width':'unset',
'top':'unset',
'bottom':'0'
});
}
// Show/hide CoverView screen saver
function screenSaver(cmd) {
if ($('#inpsrc-indicator').css('display') == 'block' || UI.mobile) {
// Don't show CoverView
return;
} else if (cmd.slice(-1) == '1') {
// Show CoverView
GLOBAL.coverViewActive = true; // Reset in scripts-panels $('#screen-saver
if (GLOBAL.chromium) {
$.post('command/playback.php?cmd=upd_toggle_coverview', {'toggle_value': '-on'});
}
$('#ss-coverart-url').html($('#coverart-url').html());
$('body').addClass('cv')
if (SESSION.json['show_cvpb'] == 'Yes') {
$('body').addClass('cvpb');
}
if (SESSION.json['scnsaver_layout'] == 'Wide') {
$('body').addClass('cvwide');
if (SESSION.json['scnsaver_xmeta'] == 'Yes') {
$('body').addClass('cvwide-xmeta');
}
}
// Fixes issue where some elements briefly remain on-screen when entering or returning from CoverView
$('#lib-coverart-meta-area').hide();
if (SESSION.json['scnsaver_mode'].includes('clock')) {
$('#ss-coverart').css('display', 'none');
$('#ss-clock').css('display', 'block');
showSSClock();
}
} else if (cmd.slice(-1) == '0') {
// Hide CoverView
if (GLOBAL.chromium) {
$.post('command/playback.php?cmd=upd_toggle_coverview', {'toggle_value': '-off'});
}
$('#screen-saver').click();
}
}
function showSSClock() {
switch (SESSION.json['scnsaver_mode']) {
case 'Digital clock':
case 'Digital clock (24-hour)':
var showAMPM = SESSION.json['scnsaver_mode'] == 'Digital clock (24-hour)' ? false : true;
showSSDigitalClock(showAMPM);
GLOBAL.ssClockIntervalID = setInterval(showSSDigitalClock, 1000, showAMPM);
break;
// Analog clock functions are in analog-clock.js
case 'Analog clock':
case 'Analog clock (Sweep)':
var showSweepSecondHand = SESSION.json['scnsaver_mode'] == 'Analog clock (Sweep)' ? true : false;
showAnalogClock("ss-clock", ANALOGCLOCK_REFRESH_INTERVAL_SMOOTH, showSweepSecondHand);
break;
default: break;
}
}
function hideSSClock() {
switch (SESSION.json['scnsaver_mode']) {
case 'Digital clock':
case 'Digital clock (24-hour)':
clearInterval(GLOBAL.ssClockIntervalID);
$('#ss-clock').text('');
break;
// Analog clock functions are in analog-clock.js
case 'Analog clock':
case 'Analog clock (Sweep)':
hideAnalogClock();
break;
default: break;
}
}
// CoverView digital clock
function showSSDigitalClock(showAMPM = true) {
var date = new Date();
var h = date.getHours(); // 0 - 23
var m = date.getMinutes(); // 0 - 59
var s = date.getSeconds(); // 0 - 59
var ampm = " AM";
if (!showAMPM) {
ampm = "";
} else {
if (h == 0) {
h = 12;
} else if (h > 12) {
h = h - 12;
ampm = " PM";
}
}
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
var time = h + ':' + m + ':' + s + ampm;
$('#ss-clock').text(time);
//console.log(time);
}
// Reconnect/reboot/restart
function renderReconnect() {
//console.log('renderReconnect(): UI.restart=(' + UI.restart + ')');
if (UI.restart == 'restart') {
$('#restart').show();
}
else if (UI.restart == 'shutdown') {
$('#shutdown').show();
}
else if (GLOBAL.backupCreate) {
// Don't display the screen when a backup is being created/downloaded
}
else {
$('#reconnect').show();
}
if (GLOBAL.scriptSection == 'panels') {
$('#countdown-display').countdown('pause');
}
window.clearInterval(UI.knob);
UI.hideReconnect = true;
GLOBAL.backupCreate = false;
}
function hideReconnect() {
//console.log('hideReconnect(): (' + UI.hideReconnect + ')');