-
Notifications
You must be signed in to change notification settings - Fork 11
/
UI.js
2079 lines (1833 loc) · 70.3 KB
/
UI.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
var UI = (function(){
/**
* mapping between html classnames and MPD client methods to call to update them
*/
var UI = {
clients: [],
active_client:0,
onChange:{
state:[],
queue:[],
playlist:[]
},
history_state:[],
active_history_state:-1,
last_clicked_file_element:null
};
/********\
|* INIT *|
\********/
$(function(){
//try to load custom configuration
//when done (wether it succeeds or fails) init the page
$.getScript( "config.js" ).done(init).fail(init);
});
/**
* one time setup function
*/
function init(){
//load theme if it exsists
if(CONFIG.theme){
CONFIG.theme.forEach(function(theme_file){
$('<link>')
.appendTo('head')
.attr({type : 'text/css', rel : 'stylesheet'})
.attr('href', theme_file);
});
}
setupFeatureDisabling();
overrideMpd();
setupInstances();
$(".LIST_queue_find_value").keyup(function(e){
queueFindchange(e.target, e);
});
$(".MPD_queue .LIST_contents").on('scroll', function(e){
$(".MPD_queue .LIST_contents .found").removeClass('found');
});
$(".MPD_search form [name=hide_queue_songs]").on('click',function(){
var parent = $(this).closest('.MPD_search');
if($(this).is(':checked')){
parent.addClass('hide_on_queue');
}
else{
parent.removeClass('hide_on_queue');
}
});
CONFIG.clients.forEach(function(client_config, idx){
var client = setupClient(client_config, idx);
client.on('StateChanged',updateState);
client.on('QueueChanged',updateQueue);
client.on('OutputChanged',updateOutputs);
client.on('PlaylistsChanged',updatePlaylists);
client.on('DataLoaded', updateFiles);
client.on('Connect', onConnect);
client.on('Disconnect', onDisconnect);
client.on('Error', onError);
client.on('AuthFailure', onAuthFailure);
UI.clients.push(client);
});
setInterval(function(){
updatePlaytime(getClient());
}, 250);
if(!mobileCheck()){
setInterval(function(){
updatePageTitle(getClient());
}, 250);
}
//setup event handlers for marque elements
setupMarque();
//initialize 'static' variables here so we don't have to check if they're set all the time
updatePageTitle.offset = 0;
seek.last_seek = 0;
onStreamError.last_error = 0;
}
/*******************\
|* private methods *|
\*******************/
/**
* make sure the given input is a string
*/
function stringClean(str){
if(!str){
return '';
}
else{
return str+'';
}
}
/**
* go through the list of config features and add css rules for all disabled features
*/
function setupFeatureDisabling(){
var disable_styles = '';
CONFIG.clients.forEach(function(config,idx){
var disabled_selectors = flattenFeatureConfig(config.disabled_features);
disabled_selectors.forEach(function(selector){
disable_styles += '\n[data-active_client="'+idx+'"] '+selector+'{\n\tdisplay:none !important;\n}\n'
});
});
if(disable_styles !== ''){
//if we got any, make a new style element in the head with the rules in them
$('head').append('<style>'+disable_styles+'</style>');
}
}
/**
* take a feature config object and return a simple set of css selectors
*/
function flattenFeatureConfig(config){
if(typeof config === 'undefined'){
return [];
}
else if(typeof config === 'string' || config instanceof String){
return [config];
}
else if(Object.prototype.toString.call(config) === '[object Array]'){
return config;
}
else if(config === Object(config)){
var out = [];
for(var key in config){
var val = config[key];
if(typeof val === 'boolean'){
out.push(key);
}
else{
val = flattenFeatureConfig(val);
out.push.apply(out,val.map(function(d){return key+' '+d;}));
}
}
return out;
}
else{
throw new Error('unsupported feature config format');
}
}
/**
* read from the config and make a client
*/
function setupClient(client_config, idx){
var password = localStorage.getItem('password_'+client_config.name);
if(!password){
if(client_config.needs_auth){
password = prompt(client_config.name+" needs a password");
localStorage.setItem('password_'+client_config.name, password);
}
}
else{
client_config.needs_auth = true; //has a password, so it must have needed it at one point
}
if(!password){
password = undefined;
}
var client = MPD(client_config.port, client_config.hostname, password);
client.name = client_config.name;
client.idx = idx;
client.needs_auth = client_config.needs_auth;
if(client_config.local_volume) {
client.local_volume = true;
}
else{
client.local_volume = false;
}
if(client_config.stream_port) {
client.stream_port = client_config.stream_port;
//sometimes MPD.getHost() returns protocol and port, so we need to get rid of those
var hostname = client.getHost().toLowerCase().replace('http://', '').replace('https://', '').split(':')[0];
client.stream_url = 'http://' + hostname + ':' + client.stream_port + '/';
}
else{
client.stream_port = 0;
client.stream_url = '';
}
if(client.needs_auth){
$('[data-instance_idx='+idx+'].INSTANCE_instance .INSTANCE_password').val(password);
}
else{
$('[data-instance_idx='+idx+'].INSTANCE_instance .INSTANCE_password').closest('tr').css({display:'none'});
}
if(client_config.debug){
client.enableLogging();
}
return client
}
/**
* override a few of the MPD classes to add some additional functionality to them
*/
function overrideMpd(){
//override the default MPD Song class to add some methods to it
var OrigonalSong = MPD.Song;
MPD.Song = function(client, source){
var me = OrigonalSong(client, source);
/**
* get a DOM subtree for this song
*/
me.getItemUI = function(template_id){
if(typeof template_id === 'undefined'){
template_id = 'template_LIST_song';
}
var contents = $($('#'+template_id).html());
contents.find('.LIST_song_title').html(me.getDisplayName());
contents.find('.LIST_song_artist').html(me.getArtist());
contents.find('.LIST_song_album').html(me.getAlbum());
contents.find('.LIST_song_genre').html(me.getGenre());
contents.find('.LIST_song_path').html(me.getPath());
contents.find('.LIST_song_track').html(me.getTrack());
contents.find('.LIST_song_disk').html(me.getDisk());
contents.find('.LIST_song_duration').html(formatTime(me.getDuration()));
return contents;
}
return me;
}
//override the default MPD Song class to add some methods to it
var OrigonalQueueSong = MPD.QueueSong;
MPD.QueueSong = function(client, source){
var me = OrigonalQueueSong(client, source);
/**
* get a DOM subtree for this song
*/
var getItemUI = me.getItemUI;
me.getItemUI = function(template_id){
if(typeof template_id === 'undefined'){
template_id = 'template_LIST_queue_song';
}
var contents = getItemUI(template_id);
contents.attr('data-mpd_queue_song_id', me.getId());
contents.attr('data-mpd_songlist_position', me.getQueuePosition());
return contents;
}
return me;
}
//override the default MPD Song class to add some methods to it
var OrigonalPlaylistSong = MPD.PlaylistSong;
MPD.PlaylistSong = function(client, source){
var me = OrigonalPlaylistSong(client, source);
/**
* get a DOM subtree for this song
*/
var getItemUI = me.getItemUI;
me.getItemUI = function(template_id){
if(typeof template_id === 'undefined'){
template_id = 'template_LIST_playlist_song';
}
var contents = getItemUI(template_id);
contents.attr('data-mpd_file_path', me.getPath());
contents.attr('data-mpd_songlist_position', me.getPlaylistPosition());
return contents;
}
return me;
}
//override the default MPD Song class to add some methods to it
var OrigonalFileSong = MPD.FileSong;
MPD.FileSong = function(client, source){
var me = OrigonalFileSong(client, source);
/**
* get a DOM subtree for this song
*/
var getItemUI = me.getItemUI;
me.getItemUI = function(template_id){
if(typeof template_id === 'undefined'){
template_id = 'template_LIST_file_song';
}
var contents = getItemUI(template_id);
contents.attr('data-mpd_file_path', me.getPath());
return contents;
}
return me;
}
//override the default MPD Song class to add some methods to it
var OrigonalSearchSong = MPD.SearchSong;
MPD.SearchSong = function(client, source){
var me = OrigonalSearchSong(client, source);
/**
* get a DOM subtree for this song
*/
var getItemUI = me.getItemUI;
me.getItemUI = function(template_id){
if(typeof template_id === 'undefined'){
template_id = 'template_LIST_file_song';
}
var contents = getItemUI(template_id);
contents.attr('data-mpd_file_path', me.getPath());
return contents;
}
return me;
}
//override the default MPD directory class to add some methods to it
var OrigonalDirectory = MPD.Directory;
MPD.Directory = function(client, source){
var me = OrigonalDirectory(client, source);
/**
* get a DOM subtree for this directory
*/
me.getItemUI = function(){
var contents = $($('#template_LIST_directory').html());
contents.find('.LIST_directory_path').html(me.getPath());
contents.attr('data-mpd_file_path', me.getPath());
return contents;
}
return me;
}
}
/**
* do the one time setup of multiple instances
*/
function setupInstances(){
if(CONFIG.clients.length === 1){
//if there is only one instance there is no point in showing the instances tab
//even 0 instances will show an error message
$('.TAB_control [data-tab_page=instance].TAB_button').hide();
}
if(CONFIG.clients.length !== 0){
$('.MPD_instances .empty').remove();
}
CONFIG.clients.forEach(function(client_config, idx){
var contents = $($('#template_INSTANCE').html());
if(idx === 0){
contents.addClass('selected');
}
contents.attr('data-instance_idx', idx);
contents.find('.INSTANCE_name').html(client_config.name);
contents.find('.INSTANCE_port').html(client_config.port);
if(client_config.hostname){
contents.find('.INSTANCE_host').html(client_config.hostname);
}
else{
contents.find('.INSTANCE_host').closest('tr').remove();
}
if(client_config.stream_port){
contents.find('.INSTANCE_stream_port').html(client_config.stream_port);
}
else{
contents.find('.INSTANCE_stream_port').closest('tr').remove();
}
if(client_config.local_volume){
contents.find('.INSTANCE_local_volume').html('Yes');
}
else{
contents.find('.INSTANCE_local_volume').html('No');
}
var connection_element = contents.find('.INSTANCE_connection_status');
connection_element.html('Not Connected!');
connection_element.addClass('bad');
$('.MPD_instances').append(contents);
});
$('body').attr('data-active_client',0);
}
/**
* update our UI on a state change
*/
function updateState(state, client){
if(client != getClient()){
return;
}
var stream = $('audio.MPD_stream')[0];
var playing = (client.getPlaystate() == 'play');
if(client.stream_port && playing){
//make sure the stream keeps playing. UI.streamError() gives up after a few errors, so try playing now that state has changed
playStream(stream);
}
else{
//no point in having the stream playing now
stopStream(stream);
}
if(playing){
//show pause
$('.MPD_play').hide();
$('.MPD_pause').show();
}
else{
//show play
$('.MPD_play').show();
$('.MPD_pause').hide();
}
var volume;
if(client.local_volume){
volume = localStorage.getItem('setting_local_volume');
if(volume === null){
volume = 0.5;
}
stream.volume = volume;
if(playing && stream.src && stream.paused){
//show the user that we don't have permission to play the stream by putting the slider at the bottom
volume = 0;
}
}
else{
volume = client.getVolume();
}
$('input.MPD_volume').val(volume);
var current_song = client.getCurrentSong();
if(current_song){
$('.MPD_controller_current_song_title').html(stringClean(current_song.getDisplayName()));
$('.MPD_controller_current_song_artist').html(stringClean(current_song.getArtist()));
$('.MPD_controller_current_song_album').html(stringClean(current_song.getAlbum()));
$('.MPD_queue [data-mpd_queue_song_id]').removeClass('selected');
$('.MPD_queue [data-mpd_queue_song_id="'+client.getCurrentSongID()+'"]').addClass('selected');
//there is a mix of div/span/td type html and input/select typeelements
$('.MPD_controller_current_song_duration').html(formatTime(current_song.getDuration()));
$('input.MPD_seek').prop('max',current_song.getDuration());
$('input.MPD_seek').val(Math.round(client.getCurrentSongTime()));
}
//settings
$('.MPD_setting [data-setting=repeat]').prop('checked',client.isRepeat());
$('.MPD_setting [data-setting=single]').prop('checked',client.isSingle());
$('.MPD_setting [data-setting=consume]').prop('checked',client.isConsume());
$('.MPD_setting [data-setting=random]').prop('checked',client.isRandom());
$('.MPD_setting [data-setting=crossfade]').val(client.getCrossfadeTime());
while(UI.onChange.state.length > 0){
UI.onChange.state.shift()();
}
if(document.hidden && current_song && updateState.last_state && updateState.last_state.current_song.id != state.current_song.id){
showNotification(
current_song.getDisplayName(),
'by: '+current_song.getArtist()
)
}
updateState.last_state = state;
}
/**
* update our UI for outputs
*/
function updateOutputs(outputs, client){
if(client != getClient()){
return;
}
$('.MPD_outputs').empty();
if(outputs.length == 1){
//if there is only one then there really isn't any need for this tab
$('.TAB_control [data-tab_page=output].TAB_button').css({display:'none'});
}
else{
$('.TAB_control [data-tab_page=output].TAB_button').css({display:''});
outputs.forEach(function(output){
var contents = $($('#template_OUTPUT').html());
contents.attr('data-output_id', output.getId());
contents.find('.OUTPUT_name').html(output.getName());
if(output.isEnabled()){
contents.addClass('selected');
contents.find('.OUTPUT_enabled').html('Yes');
contents.find('.OUTPUT_enabled').addClass('good');
}
else{
contents.removeClass('selected');
contents.find('.OUTPUT_enabled').html('No');
contents.find('.OUTPUT_enabled').addClass('bad');
}
$('.MPD_outputs').append(contents);
});
}
}
/**
* update our UI on a Queue change
*/
function updateQueue(queue, client){
if(client != getClient()){
return;
}
$('.MPD_queue').each(function(i,queue_element){
queue_element.setItems(queue.getSongs());
});
$('.MPD_queue [data-mpd_queue_song_id="'+client.getCurrentSongID()+'"]').addClass('selected');
if(queue.getSongs().length < 1){
//if there are no songs, nothing is playing
//we don't get a state change notification about this
$('.MPD_play').show();
$('.MPD_pause').hide();
}
while(UI.onChange.queue.length > 0){
UI.onChange.queue.shift()();
}
calculateOnQueueSearchResults();
}
/**
* update our UI on a playlist change
*/
function updatePlaylists(playlists, client){
if(client != getClient()){
return;
}
var playlist_selector = $('.MPD_playlist select.MPD_playlist_list');
var old_selected = playlist_selector.val();
if(updatePlaylists.on_update_select){
old_selected = updatePlaylists.on_update_select;
delete updatePlaylists.on_update_select;
}
var option_code = '';
playlists.forEach(function(playlist){
option_code += '<option value="'+playlist+'">'+playlist+'</option>';
});
playlist_selector.html(option_code);
if(old_selected !== null && playlist_selector.find('option[value="'+old_selected+'"]').length){
playlist_selector.val(old_selected);
}
selectPlaylist(playlist_selector);
while(UI.onChange.playlist.length > 0){
UI.onChange.playlist.shift()();
}
}
/**
* setup the file browser
*/
function updateFiles(state,client){
if(client != getClient()){
return;
}
var element = $('.MPD_file_placeholder');
if(element.length){
//manually make the file root if it does not exsist
var contents = $($('#template_LIST_directory').html());
element.replaceWith(contents);
}
else{
//empty out anexsisting root
$('[data-tab_page=files] .LIST_directory .MPD_directory_children').empty();
}
//populate the file root
var root = $('[data-tab_page=files] .LIST_directory');
if(UI.last_clicked_file_element === null){
UI.last_clicked_file_element = root;
}
populateFileList(root);
//the root is treated differently than the rest of the oflders
//you can't close it and it shouldn't have the common tools
//because 'add all music' is a sort of dangerous button on root
root.addClass('expanded root');
root.find('.LIST_directory_path').html('Music Files');
root.find('.MPD_button').remove();
resetSearch(null, true);
}
/**
* called when a client (re)connects
*/
function onConnect(connect_event, client){
var element = $('[data-instance_idx='+client.idx+'] .INSTANCE_connection_status');
element.html('Connected!');
element.addClass('good');
element.removeClass('bad');
if(client == getClient()){
$('.MPD_disconnected').css({display:'none'});
}
}
/**
* called when a client disconnects
*/
function onDisconnect(disconnect_event, client){
var element = $('[data-instance_idx='+client.idx+'] .INSTANCE_connection_status');
element.html('Not Connected!');
element.addClass('bad');
element.removeClass('good');
if(client == getClient()){
$('.MPD_disconnected').css({display:''});
}
}
/**
* called when an error happens
*/
function onError(error, client){
debugger;
var msg = '***ERROR*** ' + error.message;
if(error.stack){
msg += '\n' + error.stack;
}
else if(error.lineNumber && error.fileName){
msg += '\non line ' + error.lineNumber + '\n';
msg += 'of file ' + error.fileName;
}
alert(msg);
}
/**
* called when some sort of permissions issue arizes
*/
function onAuthFailure(error, client){
var instance_element = $('[data-instance_idx='+client.idx+'].INSTANCE_instance');
var password = localStorage.getItem('password_'+client.name);
// we\the user tried to do something we are not allowed to do
if(UI.clients.length === 1){
var password = prompt('Please enter password for '+client.name);
localStorage.setItem('password_'+client.name, password);
client.authorize(password);
}
else{
if(client === getClient() && client.last_failed_password != password ){
alert('Your password was rejected for '+client.name);
}
instance_element.find('.INSTANCE_password').closest('tr').css({display:''});
instance_element.find('.INSTANCE_password_message').html('(rejected)');
client.last_failed_password = password;
}
}
/**
* update our UI for ticking of play time
*/
function updatePlaytime(client){
var current_song = client.getCurrentSong();
if(current_song){
//there is a mix of div/span/td type html and input/select typeelements
if(getTime() - seek.last_seek > 2) {
//update the seekbar only if the user hasn't touched it in a bit
$('input.MPD_seek').val(Math.round(client.getCurrentSongTime()));
}
var formatted_time = formatTime(client.getCurrentSongTime());
$('.MPD_controller_current_song_time').html(formatted_time);
}
}
/**
*return true if this is a mobile device
*/
function mobileCheck() {
var check = false;
(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
return check;
}
/**
* update our UI for ticking of play time
*/
function updatePageTitle(client){
var current_song = client.getCurrentSong();
if(current_song){
var title = current_song.getDisplayName()+' - ';
if(current_song.getArtist()){
title += current_song.getArtist()+' - ';
}
updatePageTitle.offset++;
if(updatePageTitle.offset > title.length){
updatePageTitle.offset = 0;
}
document.title = title.substring(updatePageTitle.offset)+title.substring(0,updatePageTitle.offset);
}
else{
document.title = 'MPD Client';
}
}
/**
* look for the 'nearest' element matching the passed selector
*/
function searchUp(element, selector){
var elements = $($(element).parents().addBack().get().reverse());
element = null;
elements.each(function(i, test_element){
var maybe = $(test_element).find(selector);
if(maybe.length > 0){
element = maybe;
return false;
}
});
return element;
}
/**
* gets the appropriate client
*/
function getClient(){
return UI.clients[UI.active_client];
}
/**
* assuming this element is under a playlist or a queue, get it
*/
function getSonglist(element){
var playlist = $(element).closest('.MPD_playlist').data('playlist');
if(playlist){
return playlist;
}
return getClient().getQueue();
}
/**
* assuming this element is under a playlist, get the playlist
*/
function getPlaylist(element){
return $(element).closest('.MPD_playlist').data('playlist');
}
/**
* maybe show a notification if they ever settle on a consistent API
*/
function showNotification(title, body){
try{
if(Notification.permission === "granted" && localStorage.getItem('setting_notifications') == 'true'){
var n = new Notification(
title,
{
body:body,
icon: '/img/bragi-192.png'
}
);
setTimeout(n.close.bind(n), 4000);
if(showNotification.last_notification){
setTimeout(showNotification.last_notification.close.bind(showNotification.last_notification), 4);
}
showNotification.last_notification = n;
}
}
catch(err){
console.log(err);
}
}
/**
* given a number print out a nicer looking string with minutes/hours/seconds
*/
function formatTime(seconds, precision){
if(typeof precision === 'undefined'){
precision = 0;
}
var minutes = Math.floor(seconds/60);
seconds -= minutes*60;
//hey, it could happen
var hours = Math.floor(minutes/60);
minutes -= hours*60;
//not doing days
//special formatting on seconds becaue they might be fractional
var text_seconds = ('00'+Math.floor(seconds)).slice(-2); //leftpadded whole number part
if(precision > 1){
text_seconds += (seconds-Math.floor(seconds)).toFixed(precision); //decimal part
}
if(hours){
return hours+':'+('00'+minutes).slice(-2)+':'+text_seconds;
}
else if(minutes){
return minutes+':'+text_seconds;
}
else{
return seconds.toFixed(precision);
}
}
/**
* setup elements that are supposed have a marque effect when they overflow
*/
function setupMarque(){
function updateMarqueEffect(element){
if(!element.updating){
if(!element.timer){
element.timer = setTimeout(function(){
element.updating = true;
$(element).find('.copy').remove();
if($(element).width() < $(element).children().width()){
//turn on the marque effect
startMarque($(element));
}
else{
//turn off the marque effect
stopMarque($(element));
}
delete element.timer;
delete element.updating;
},100);
}
}
}
//wrap the element in a outter div
var element = $('.marque_overflow');
element.removeClass('marque_overflow');
element.wrap('<div class="marque_overflow"></div>');
$('.marque_overflow').on('DOMSubtreeModified',function(){
updateMarqueEffect(this);
});
$(window).resize(function(){
$('.marque_overflow').each(function(i,element){
updateMarqueEffect(element);
})
});
}
/**
* turn on marque
*/
function startMarque(element){
//first thing, duplicate the content
var content = element.children('div');
content.find('.copy').remove();//get rid of already copied stuff if it exsists
content.html(content.html().replace(/\s+/g,' '));
content.append('<span class="copy" style="margin:0 30px;">'+content.html()+'</span>');
if(!content.is(':animated')){
(function doAnimation(){
content.css({'left':0});
content.animate({'left': '-'+(content.width()/2)}, content.width()*10, 'linear', doAnimation);
})();
}
}
/**
* turn on marque
*/
function stopMarque(element){
var content = element.children('div');
content.find('.copy').remove();//get rid of already copied stuff if it exsists
content.stop();
content.css({'left':0});
//element.removeClass('marquee_effect');
}
/**
* given a select element and an array of contents fill the select element
*/
function fillSelect(select_element, contents){
var options_code = '';
contents.forEach(function(option){
if(typeof option === 'object'){
options_code += '<option value="'+option.value+'">'+option.display+'</option>';
}
else{
options_code += '<option value="'+option+'">'+option+'</option>';
}
});
$(select_element).html(options_code);
}
/**
* given an element find a parent element that has the given data
*/
function getData(element, data){
var data_element = $(element).closest('[data-'+data+']');
return data_element.data(data);
}
/**
* set the active client to the one specified
*/
function setInstance(idx){
if(idx === UI.active_client){
return;
}
UI.active_client = idx;
var client = getClient();
//Reset current song data. It's strange to keep the data if
//the new instance don't have a curent song
$('.MPD_controller_current_song_title').empty();
$('.MPD_controller_current_song_artist').empty();
$('.MPD_controller_current_song_album').empty();
$('.MPD_controller_current_song_time').empty();
$('.MPD_controller_current_song_duration').empty();
$('input.MPD_seek').prop('max', 100);
$('input.MPD_seek').val(0);
stopStream($('audio.MPD_stream')[0]);
//update the UI
$('.INSTANCE_instance').removeClass('selected');
$('[data-instance_idx='+idx+'].INSTANCE_instance').addClass('selected');
if(client.isConnected()){
updateState(client.getState(), client);
updateQueue(client.getQueue(), client);
updatePlaylists(client.getPlaylists(), client);
updateOutputs(client.getOutputs(), client);
$('.MPD_disconnected').css({display:'none'});
}
else{
$('.MPD_disconnected').css({display:''});
}
$('body').attr('data-active_client',idx);
}
/**
* scrolls the given song
*/
function scrollToSong(song_id, position){
var queue_element = $('.MPD_queue .LIST_content_container');
var song_element = $('.MPD_queue .LIST_content_container [data-mpd_queue_song_id='+song_id+']');
queue_element.animate({
scrollTop: queue_element.scrollTop() + song_element.position().top - queue_element.height()*position
}, 500);
}
/**
* find songs on the queue
*/
function queueFind(value){
value = value.toLowerCase();
//the songs on the queue that have the search criteria
return $('.MPD_queue .LIST_content_container .LIST_song')
.filter(function(){
return $(this).find('.LIST_song_title, .LIST_song_artist, .LIST_song_album')
.filter(function(){
return $(this).html().toLowerCase().indexOf(value) > -1;
}
).length > 0;
});
}
/**
* update the on_queue class of all the songs in search results
*/
function calculateOnQueueSearchResults(){