-
Notifications
You must be signed in to change notification settings - Fork 39
/
index.js
3949 lines (3460 loc) · 127 KB
/
index.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
'use strict';
var cacheManager = require('cache-manager');
var memoryCache = cacheManager.caching({store: 'memory', max: 100, ttl: 0});
var libMpd = require('./lib/mpd.js');
var libQ = require('kew');
var libFast = require('fast.js');
var libFsExtra = require('fs-extra');
var fs = require('fs');
var exec = require('child_process').exec;
var parser = require('cue-parser');
var mm = require('music-metadata');
var os = require('os');
var execSync = require('child_process').execSync;
var ignoreupdate = false;
// tracknumbers variable below adds track numbers to titles if set to true. Set to false for normal behavour.
var tracknumbers = false;
// compilation array below adds different strings used to describe albumartist in compilations or 'multiple artist' albums
var compilation = ['Various', 'various', 'Various Artists', 'various artists', 'VA', 'va'];
// atistsort variable below will list artists by albumartist if set to true or artist if set to false
var artistsort = true;
var dsd_autovolume = false;
var singleBrowse = false;
var startup = true;
var stickingMusicLibrary = false;
// Define the ControllerMpd class
module.exports = ControllerMpd;
function ControllerMpd (context) {
// This fixed variable will let us refer to 'this' object at deeper scopes
this.context = context;
this.commandRouter = this.context.coreCommand;
this.logger = this.context.logger;
this.configManager = this.context.configManager;
this.config = new (require('v-conf'))();
this.registeredCallbacks = [];
}
// Public Methods ---------------------------------------------------------------------------------------
// These are 'this' aware, and return a promise
// Define a method to clear, add, and play an array of tracks
// MPD Play
ControllerMpd.prototype.play = function (N) {
this.logger.info('ControllerMpd::play ' + N);
return this.sendMpdCommand('play', [N]);
};
// MPD Add
ControllerMpd.prototype.add = function (data) {
var self = this;
this.commandRouter.pushToastMessage('success', data + self.commandRouter.getI18nString('COMMON.ADD_QUEUE_TEXT_1'));
return this.sendMpdCommand('add', [data]);
};
// MPD Remove
ControllerMpd.prototype.remove = function (position) {
this.logger.info('ControllerMpd::remove ' + position);
return this.sendMpdCommand('delete', [position]);
};
// MPD Next
ControllerMpd.prototype.next = function () {
this.logger.info('ControllerMpd::next');
return this.sendMpdCommand('next', []);
};
// MPD Previous
ControllerMpd.prototype.previous = function () {
this.logger.info('ControllerMpd::previous');
return this.sendMpdCommand('previous', []);
};
// MPD Seek
ControllerMpd.prototype.seek = function (timepos) {
this.logger.info('ControllerMpd::seek to ' + timepos);
return this.sendMpdCommand('seekcur', [timepos]);
};
// MPD Random
ControllerMpd.prototype.random = function (randomcmd) {
var self = this;
var string = randomcmd ? 1 : 0;
this.commandRouter.pushToastMessage('success', 'Random', string === 1 ? self.commandRouter.getI18nString('COMMON.ON') : self.commandRouter.getI18nString('COMMON.OFF'));
return this.sendMpdCommand('random', [string]);
};
// MPD Repeat
ControllerMpd.prototype.repeat = function (repeatcmd) {
var self = this;
var string = repeatcmd ? 1 : 0;
this.commandRouter.pushToastMessage('success', 'Repeat', string === 1 ? self.commandRouter.getI18nString('COMMON.ON') : self.commandRouter.getI18nString('COMMON.ON'));
return this.sendMpdCommand('repeat', [string]);
};
// MPD clear
ControllerMpd.prototype.clear = function () {
this.logger.info('ControllerMpd::clear');
return this.sendMpdCommand('clear', []);
};
// MPD enable output
ControllerMpd.prototype.enableOutput = function (output) {
this.logger.info('Enable Output ' + output);
return this.sendMpdCommand('enableoutput', [output]);
};
// MPD disable output
ControllerMpd.prototype.disableOutput = function (output) {
this.logger.info('Disable Output ' + output);
return this.sendMpdCommand('disableoutput', [output]);
};
// UpdateDB
ControllerMpd.prototype.updateMpdDB = function () {
this.logger.info('Update mpd DB');
return this.sendMpdCommand('update', []);
};
ControllerMpd.prototype.addPlay = function (fileName) {
var self = this;
this.logger.info('ControllerMpd::addPlay');
this.commandRouter.pushToastMessage('Success', '', fileName + self.commandRouter.getI18nString('COMMON.ADD_QUEUE_TEXT_1'));
// Add playlists and cue with load command
if (fileName.endsWith('.cue') || fileName.endsWith('.pls') || fileName.endsWith('.m3u')) {
this.logger.info('Adding Playlist: ' + fileName);
return this.sendMpdCommandArray([
{command: 'clear', parameters: []},
{command: 'load', parameters: [fileName]},
{command: 'play', parameters: []}
]);
} else if (fileName.startsWith('albums')) {
return self.playAlbum(fileName);
} else {
return this.sendMpdCommandArray([
{command: 'clear', parameters: []},
{command: 'add', parameters: [fileName]},
{command: 'play', parameters: []}
]);
}
/* .then(function() {
self.commandRouter.volumioPlay();
}); */
};
ControllerMpd.prototype.addPlayCue = function (data) {
var self = this;
if (data.number !== undefined) {
this.logger.info('Adding CUE individual entry: ' + data.number + ' ' + data.uri);
var cueItem = this.explodeCue(data.uri, data.number);
this.commandRouter.addQueueItems([{
uri: cueItem.uri,
type: cueItem.type,
service: cueItem.service,
name: cueItem.name,
artist: cueItem.artist,
album: cueItem.album,
number: cueItem.number,
albumart: cueItem.albumart,
year: cueItem.date,
}]);
var index = this.commandRouter.stateMachine.playQueue.arrayQueue.length;
this.commandRouter.volumioPlay(index);
}
};
// MPD music library
ControllerMpd.prototype.getTracklist = function () {
var self = this;
this.logger.info('ControllerMpd::getTracklist');
return self.mpdReady
.then(function () {
return libQ.nfcall(self.clientMpd.sendCommand.bind(self.clientMpd), libMpd.cmd('listallinfo', []));
})
.then(function (objResult) {
var listInfo = self.parseListAllInfoResult(objResult);
return listInfo.tracks;
});
};
// Internal methods ---------------------------------------------------------------------------
// These are 'this' aware, and may or may not return a promise
// Parses the info out of the 'listallinfo' MPD command
// Metadata fields to roughly conform to Ogg Vorbis standards (http://xiph.org/vorbis/doc/v-comment.html)
ControllerMpd.prototype.parseListAllInfoResult = function (sInput) {
var arrayLines = sInput.split('\n');
var objReturn = {};
var curEntry = {};
objReturn.tracks = [];
objReturn.playlists = [];
var nLines = arrayLines.length;
for (var i = 0; i < nLines; i++) {
var arrayLineParts = libFast.map(arrayLines[i].split(':'), function (sPart) {
return sPart.trim();
});
if (arrayLineParts[0] === 'file') {
curEntry = {
'name': '',
'service': this.servicename,
'uri': arrayLineParts[1],
'browsepath': [this.displayname].concat(arrayLineParts[1].split('/').slice(0, -1)),
'artists': [],
'album': '',
'genres': [],
'performers': [],
'tracknumber': 0,
'year': '',
'duration': 0
};
objReturn.tracks.push(curEntry);
} else if (arrayLineParts[0] === 'playlist') {
// Do we even need to parse MPD playlists?
} else if (arrayLineParts[0] === 'Time') {
curEntry.duration = arrayLineParts[1];
} else if (arrayLineParts[0] === 'Title') {
curEntry.name = arrayLineParts[1];
} else if (arrayLineParts[0] === 'Artist') {
curEntry.artists = libFast.map(arrayLineParts[1].split(','), function (sArtist) {
// TODO - parse other options in artist string, such as "feat."
return sArtist.trim();
});
} else if (arrayLineParts[0] === 'AlbumArtist') {
curEntry.performers = libFast.map(arrayLineParts[1].split(','), function (sPerformer) {
return sPerformer.trim();
});
} else if (arrayLineParts[0] === 'Album') {
curEntry.album = arrayLineParts[1];
} else if (arrayLineParts[0] === 'Track') {
curEntry.tracknumber = Number(arrayLineParts[1]);
} else if (arrayLineParts[0] === 'Date') {
// TODO - parse into a date object
curEntry.year = arrayLineParts[1];
}
}
return objReturn;
};
// Define a method to get the MPD state
ControllerMpd.prototype.getState = function () {
this.logger.info('ControllerMpd::getState');
var timeCurrentUpdate = Date.now();
this.timeLatestUpdate = timeCurrentUpdate;
var self = this;
return self.sendMpdCommand('status', [])
/* .then(function(data) {
return self.haltIfNewerUpdateRunning(data, timeCurrentUpdate);
}) */
.then(function (objState) {
var collectedState = self.parseState(objState);
// If there is a track listed as currently playing, get the track info
if (collectedState.position !== null) {
return self.sendMpdCommand('playlistinfo', [collectedState.position])
/* .then(function(data) {
return self.haltIfNewerUpdateRunning(data, timeCurrentUpdate);
}) */
.then(function (objTrackInfo) {
var trackinfo = self.parseTrackInfo(objTrackInfo);
collectedState.isStreaming = trackinfo.isStreaming != undefined ? trackinfo.isStreaming : false;
collectedState.title = trackinfo.title;
collectedState.artist = trackinfo.artist;
collectedState.album = trackinfo.album;
collectedState.year = trackinfo.year;
// collectedState.albumart = trackinfo.albumart;
collectedState.uri = trackinfo.uri;
collectedState.trackType = trackinfo.trackType.split('?')[0];
return collectedState;
});
// Else return null track info
} else {
collectedState.isStreaming = false;
collectedState.title = null;
collectedState.artist = null;
collectedState.album = null;
// collectedState.albumart = null;
collectedState.uri = null;
return collectedState;
}
});
};
// Stop the current status update thread if a newer one exists
ControllerMpd.prototype.haltIfNewerUpdateRunning = function (data, timeCurrentThread) {
var self = this;
this.logger.info('ControllerMpd::haltIfNewerUpdateRunning');
if (self.timeLatestUpdate > timeCurrentThread) {
return libQ.reject('Alert: Aborting status update - newer one detected');
} else {
return libQ.resolve(data);
}
};
// Announce updated MPD state
ControllerMpd.prototype.pushState = function (state) {
var self = this;
this.logger.info('ControllerMpd::pushState');
return self.commandRouter.servicePushState(state, self.servicename);
};
// Pass the error if we don't want to handle it
ControllerMpd.prototype.pushError = function (sReason) {
var self = this;
self.logger.error('ControllerMpd::pushError: ' + sReason);
// Return a resolved empty promise to represent completion
return libQ.resolve();
};
// Define a general method for sending an MPD command, and return a promise for its execution
ControllerMpd.prototype.sendMpdCommand = function (sCommand, arrayParameters) {
var self = this;
self.logger.verbose('ControllerMpd::sendMpdCommand ' + sCommand);
const start=Date.now()
return self.mpdReady
.then(function () {
return libQ.nfcall(self.clientMpd.sendCommand.bind(self.clientMpd), libMpd.cmd(sCommand, arrayParameters));
})
.then(function (response) {
var respobject = libMpd.parseKeyValueMessage.call(libMpd, response);
// If there's an error show an alert on UI
if ('error' in respobject) {
self.commandRouter.broadcastToastMessage('error', 'Error', respobject.error);
self.sendMpdCommand('clearerror', []);
}
const stop=Date.now()
self.logger.info("sendMpdCommand "+sCommand+" took "+(stop-start)+" milliseconds")
return libQ.resolve(respobject);
});
};
// Define a general method for sending an array of MPD commands, and return a promise for its execution
// Command array takes the form [{command: sCommand, parameters: arrayParameters}, ...]
ControllerMpd.prototype.sendMpdCommandArray = function (arrayCommands) {
var self = this;
return self.mpdReady
.then(function () {
return libQ.nfcall(self.clientMpd.sendCommands.bind(self.clientMpd),
libFast.map(arrayCommands, function (currentCommand) {
self.logger.verbose('MPD COMMAND ' + currentCommand);
return libMpd.cmd(currentCommand.command, currentCommand.parameters);
})
);
})
.then(libMpd.parseKeyValueMessage.bind(libMpd));
};
// Parse MPD's track info text into Volumio recognizable object
ControllerMpd.prototype.parseTrackInfo = function (objTrackInfo) {
var self = this;
self.logger.verbose('ControllerMpd::parseTrackInfo');
// this.commandRouter.logger.info("OBJTRACKINFO "+JSON.stringify(objTrackInfo));
var resp = {};
if (objTrackInfo.Time === 0) {
resp.isStreaming = true;
}
if (objTrackInfo.file != undefined) {
resp.uri = objTrackInfo.file;
resp.trackType = objTrackInfo.file.split('.').pop();
if (resp.trackType.length > 10) {
resp.trackType = '';
}
if (resp.uri.indexOf('cdda:///') >= 0) {
resp.trackType = 'CD Audio';
resp.title = resp.uri.replace('cdda:///', 'Track ');
} else if (resp.uri.indexOf('qobuz.com') >= 0) {
resp.trackType = 'qobuz';
} else if (resp.uri.indexOf('tidal.com') >= 0) {
resp.trackType = 'tidal';
} else if (resp.uri.indexOf('http://') >= 0) {
resp.service = 'dirble';
if (objTrackInfo.file.indexOf('bbc') >= 0 && objTrackInfo.Name) {
objTrackInfo.Name = objTrackInfo.Name.replace(/_/g, ' ').replace('bbc', 'BBC');
objTrackInfo.file = objTrackInfo.Name;
}
}
} else {
resp.uri = null;
}
if (objTrackInfo.Title != undefined) {
resp.title = objTrackInfo.Title;
} else {
var file = objTrackInfo.file;
if (file !== undefined) {
var filetitle = file.replace(/^.*\/(?=[^\/]*$)/, '');
resp.title = filetitle;
}
}
if (objTrackInfo.Artist != undefined) {
resp.artist = objTrackInfo.Artist;
} else if (objTrackInfo.Name != undefined) {
resp.artist = objTrackInfo.Name;
} else {
resp.artist = null;
}
if (objTrackInfo.Album != undefined) {
resp.album = objTrackInfo.Album;
} else {
resp.album = null;
}
var web;
if (objTrackInfo.Artist != undefined) {
if (objTrackInfo.Album != undefined) {
web = {artist: objTrackInfo.Artist, album: objTrackInfo.Album};
} else {
web = {artist: objTrackInfo.Artist};
}
}
var artUrl;
if (resp.isStreaming) {
artUrl = this.getAlbumArt(web);
} else {
artUrl = this.getAlbumArt(web, file);
}
if (objTrackInfo.bitrate) {
resp.bitrate = objTrackInfo.bitrate;
} else {
resp.bitrate = null;
}
resp.albumart = artUrl;
return resp;
};
// Parse MPD's text playlist into a Volumio recognizable playlist object
ControllerMpd.prototype.parsePlaylist = function (objQueue) {
var self = this;
// objQueue is in form {'0': 'file: http://uk4.internet-radio.com:15938/', '1': 'file: http://2363.live.streamtheworld.com:80/KUSCMP128_SC'}
// We want to convert to a straight array of trackIds
return libQ.fcall(libFast.map, Object.keys(objQueue), function (currentKey) {
return convertUriToTrackId(objQueue[currentKey]);
});
};
// Parse MPD's text status into a Volumio recognizable status object
ControllerMpd.prototype.parseState = function (objState) {
var self = this;
// console.log(objState);
self.logger.verbose('ControllerMpd::parseState');
// Pull track duration out of status message
var nDuration = null;
if ('time' in objState) {
var arrayTimeData = objState.time.split(':');
nDuration = Math.round(Number(arrayTimeData[1]));
}
// Pull the elapsed time
var nSeek = null;
if ('elapsed' in objState) {
nSeek = Math.round(Number(objState.elapsed) * 1000);
}
// Pull the queue position of the current track
var nPosition = null;
if ('song' in objState) {
nPosition = Number(objState.song);
}
// Pull audio metrics
var nBitDepth = null;
var nSampleRate = null;
var nChannels = null;
if ('audio' in objState) {
var objMetrics = objState.audio.split(':');
var nSampleRateRaw = Number(objMetrics[0]) / 1000;
nBitDepth = Number(objMetrics[1]) + ' bit';
nChannels = Number(objMetrics[2]);
if (objMetrics[1] == 'f') {
nBitDepth = '32 bit';
} else if (objMetrics[0] == 'dsd64') {
var nSampleRateRaw = '2.82 MHz';
nBitDepth = '1 bit';
nChannels = 2;
} else if (objMetrics[0] == 'dsd128') {
var nSampleRateRaw = '5.64 MHz';
nBitDepth = '1 bit';
nChannels = 2;
} else if (objMetrics[0] == 'dsd256') {
var nSampleRateRaw = '11.28 MHz';
nBitDepth = '1 bit';
nChannels = 2;
} else if (objMetrics[0] == 'dsd512') {
var nSampleRateRaw = '22.58 MHz';
nBitDepth = '1 bit';
nChannels = 2;
} else if (objMetrics[1] == 'dsd') {
if (nSampleRateRaw === 352.8) {
var nSampleRateRaw = '2.82 MHz';
nBitDepth = '1 bit';
} else if (nSampleRateRaw === 705.6) {
var nSampleRateRaw = '5.64 MHz';
nBitDepth = '1 bit';
} else if (nSampleRateRaw === 1411.2) {
var nSampleRateRaw = '11.2 MHz';
nBitDepth = '1 bit';
} else {
var nSampleRateRaw = nSampleRateRaw + ' kHz';
}
} else {
var nSampleRateRaw = nSampleRateRaw + ' kHz';
}
nSampleRate = nSampleRateRaw;
}
var random = null;
if ('random' in objState) {
random = objState.random == 1;
}
var repeat = null;
if ('repeat' in objState) {
repeat = objState.repeat == 1;
}
var sStatus = null;
if ('state' in objState) {
sStatus = objState.state;
}
var updatedb = false;
if ('updating_db' in objState) {
updatedb = true;
}
var bitrate = null;
if ('bitrate' in objState) {
if (objState.bitrate !== '0') {
bitrate = objState.bitrate + ' Kbps';
}
}
return {
status: sStatus,
position: nPosition,
seek: nSeek,
duration: nDuration,
samplerate: nSampleRate,
bitdepth: nBitDepth,
channels: nChannels,
random: random,
updatedb: updatedb,
repeat: repeat,
bitrate: bitrate
};
};
ControllerMpd.prototype.logDone = function (timeStart) {
var self = this;
self.commandRouter.pushConsoleMessage('------------------------------ ' + (Date.now() - timeStart) + 'ms');
return libQ.resolve();
};
ControllerMpd.prototype.logStart = function (sCommand) {
var self = this;
self.commandRouter.pushConsoleMessage('\n' + '---------------------------- ' + sCommand);
return libQ.resolve();
};
/*
* This method can be defined by every plugin which needs to be informed of the startup of Volumio.
* The Core controller checks if the method is defined and executes it on startup if it exists.
*/
ControllerMpd.prototype.onVolumioStart = function () {
var self = this;
this.commandRouter.sharedVars.registerCallback('alsa.outputdevice', this.outputDeviceCallback.bind(this));
var configFile = self.commandRouter.pluginManager.getConfigurationFile(self.context, 'config.json');
self.config.loadFile(configFile);
self.loadLibrarySettings();
dsd_autovolume = self.config.get('dsd_autovolume', false);
self.getPlaybackMode();
return self.mpdInit();
};
ControllerMpd.prototype.mpdInit = function () {
var self = this;
var defer = libQ.defer()
if (process.env.WRITE_MPD_CONFIGURATION_ON_STARTUP === 'true') {
self.logger.info('Creating MPD Configuration file');
self.createMPDFile(function (error) {
if (error !== undefined && error !== null) {
self.logger.error('Could not create MPD File on system start: ' + error);
defer.resolve();
} else {
self.restartMpd(function (error) {
if (error !== null && error != undefined) {
self.logger.error('Cannot start MPD on system Start: ' + error);
defer.resolve();
} else {
defer.resolve(self.initializeMpdConnection());
}
});
}
});
} else {
defer.resolve(self.initializeMpdConnection());
}
return defer.promise;
};
ControllerMpd.prototype.initializeMpdConnection = function () {
var self = this;
var defer = libQ.defer()
// Connect to MPD only if process MPD is running
exec('/bin/pidof mpd', {uid: 1000, gid: 1000}, function (error, stdout, stderr) {
if (error) {
self.logger.error('Cannot initialize MPD Connection: MPD is not running');
defer.resolve();
} else {
if (stdout && stdout.length) {
self.logger.info('MPD running with PID' + stdout + ' ,establishing connection');
self.mpdEstablish();
} else {
self.logger.error('Cannot initialize MPD Connection: MPD is not running');
}
defer.resolve();
}
});
};
ControllerMpd.prototype.mpdEstablish = function () {
var self = this;
// TODO use names from the package.json instead
self.servicename = 'mpd';
self.displayname = 'MPD';
// getting configuration
// Save a reference to the parent commandRouter
self.commandRouter = self.context.coreCommand;
// Connect to MPD
self.mpdConnect();
// Make a promise for when the MPD connection is ready to receive events
self.mpdReady = libQ.nfcall(self.clientMpd.on.bind(self.clientMpd), 'ready');
self.mpdReady.then(function () {
if (startup) {
startup = false;
self.checkUSBDrives();
self.listAlbums();
}
});
// Catch and log errors
self.clientMpd.on('error', function (err) {
self.logger.error('MPD error: ' + err);
if (err = "{ [Error: This socket has been ended by the other party] code: 'EPIPE' }") {
// Wait 5 seconds before trying to reconnect
setTimeout(function () {
self.mpdEstablish();
}, 5000);
} else {
self.logger.error(err);
}
});
// This tracks the the timestamp of the newest detected status change
self.timeLatestUpdate = 0;
self.updateQueue();
// TODO remove pertaining function when properly found out we don't need em
// self.fswatch();
// When playback status changes
self.clientMpd.on('system', function (status) {
var timeStart = Date.now();
if (!ignoreupdate && status != 'playlist' && status != undefined) {
self.logStart('MPD announces state update: ' + status)
.then(self.getState.bind(self))
.then(self.pushState.bind(self))
.fail(self.pushError.bind(self))
.done(function () {
return self.logDone(timeStart);
});
} else {
self.logger.info('Ignoring MPD Status Update');
}
});
self.clientMpd.on('system-playlist', function () {
var timeStart = Date.now();
if (!ignoreupdate) {
self.logStart('MPD announces system playlist update')
.then(self.updateQueue.bind(self))
.fail(self.pushError.bind(self))
.done(function () {
return self.logDone(timeStart);
});
} else {
self.logger.info('Ignoring MPD Status Update');
}
});
// Notify that The mpd DB has changed
self.clientMpd.on('system-database', function () {
// return self.commandRouter.fileUpdate();
// return self.reportUpdatedLibrary();
// Refresh AlbumList - delete the current AlbumList cache entry
memoryCache.del('cacheAlbumList', function (err) {});
// Store new AlbumList in cache
self.listAlbums();
self.logger.info('MPD Database updated - AlbumList cache refreshed');
});
self.clientMpd.on('system-update', function () {
if (!ignoreupdate) {
self.sendMpdCommand('status', [])
.then(function (objState) {
var state = self.parseState(objState);
execSync('/bin/sync', { uid: 1000, gid: 1000});
return self.commandRouter.fileUpdate(state.updatedb);
});
} else {
self.logger.info('Ignoring MPD Status Update');
}
});
};
ControllerMpd.prototype.mpdConnect = function () {
var self = this;
var nHost = self.config.get('nHost');
var nPort = self.config.get('nPort');
self.clientMpd = libMpd.connect({port: nPort, host: nHost});
};
ControllerMpd.prototype.outputDeviceCallback = function () {
var self = this;
var defer = libQ.defer();
self.logger.info('Output device has changed, restarting MPD');
self.createMPDFile(function (error) {
if (error !== undefined && error !== null) {
self.commandRouter.pushToastMessage('error', self.commandRouter.getI18nString('COMMON.CONFIGURATION_UPDATE'), self.commandRouter.getI18nString('COMMON.CONFIGURATION_UPDATE_ERROR'));
defer.resolve({});
} else {
// self.commandRouter.pushToastMessage('success', self.commandRouter.getI18nString('mpd_configuration_update'), self.commandRouter.getI18nString('mpd_playback_configuration_error'));
self.restartMpd(function (error) {
if (error !== null && error != undefined) {
self.logger.info('Cannot restart MPD: ' + error);
// self.commandRouter.pushToastMessage('error', self.commandRouter.getI18nString('mpd_player_restart'), self.commandRouter.getI18nString('mpd_player_restart_error'));
} else {
self.commandRouter.pushToastMessage('success', self.commandRouter.getI18nString('COMMON.CONFIGURATION_UPDATE'), self.commandRouter.getI18nString('COMMON.PLAYER_RESTARTED'));
}
defer.resolve({});
});
}
});
};
ControllerMpd.prototype.savePlaybackOptions = function (data) {
var self = this;
var defer = libQ.defer();
self.config.set('dsd_autovolume', data['dsd_autovolume']);
self.config.set('volume_normalization', data['volume_normalization']);
self.config.set('audio_buffer_size', data['audio_buffer_size'].value);
self.config.set('buffer_before_play', data['buffer_before_play'].value);
self.config.set('dop', data['dop'].value);
dsd_autovolume = data['dsd_autovolume'];
var isonew = data.iso;
var iso = self.config.get('iso', false);
if (self.config.get('persistent_queue') == null) {
self.config.addConfigValue('persistent_queue', 'boolean', data['persistent_queue']);
} else {
self.config.set('persistent_queue', data['persistent_queue']);
}
var playbackModeNew = data['playback_mode_list'].value;
if (playbackModeNew !== process.env.PLAYBACK_MODE) {
self.setPlaybackMode(playbackModeNew);
}
if (isonew != iso) {
self.config.set('iso', data['iso']);
if (isonew) {
// iso enabled
execSync('/usr/bin/sudo /bin/systemctl stop mpd', {uid: 1000, gid: 1000, encoding: 'utf8'});
execSync('echo "volumio" | sudo -S /bin/cp -f /usr/bin/mpdsacd /usr/bin/mpd', {
uid: 1000,
gid: 1000,
encoding: 'utf8'
});
execSync('/bin/sync', {uid: 1000, gid: 1000, encoding: 'utf8'});
setTimeout(function () {
exec('/usr/bin/mpc update', {uid: 1000, gid: 1000},
function (error, stdout, stderr) {
if (error) {
self.logger.error('Cannot Update MPD DB: ' + error);
}
});
var responseData = {
title: self.commandRouter.getI18nString('PLAYBACK_OPTIONS.PLAYBACK_OPTIONS_TITLE') + ': ISO Playback',
message: 'ISO Playback ' + self.commandRouter.getI18nString('PLAYBACK_OPTIONS.I2S_DAC_ACTIVATED_MESSAGE'),
size: 'lg',
buttons: [
{
name: self.commandRouter.getI18nString('COMMON.RESTART'),
class: 'btn btn-info',
emit: 'reboot',
payload: ''
}
]
};
self.commandRouter.broadcastMessage('openModal', responseData);
}, 1000);
} else {
execSync('/usr/bin/sudo /usr/bin/killall mpd', {uid: 1000, gid: 1000, encoding: 'utf8'});
execSync('echo "volumio" | sudo -S /bin/cp -f /usr/bin/mpdorig /usr/bin/mpd', {
uid: 1000,
gid: 1000,
encoding: 'utf8'
});
execSync('/bin/sync', {uid: 1000, gid: 1000, encoding: 'utf8'});
setTimeout(function () {
exec('/usr/bin/mpc update', {uid: 1000, gid: 1000},
function (error, stdout, stderr) {
if (error) {
self.logger.error('Cannot Update MPD DB: ' + error);
}
});
}, 5000);
}
}
self.createMPDFile(function (error) {
if (error !== undefined && error !== null) {
// self.commandRouter.pushToastMessage('error', self.commandRouter.getI18nString('mpd_configuration_update'), self.commandRouter.getI18nString('mpd_configuration_update_error'));
defer.resolve({});
} else {
// self.commandRouter.pushToastMessage('success', self.commandRouter.getI18nString('mpd_configuration_update'), self.commandRouter.getI18nString('mpd_playback_configuration_error'));
self.restartMpd(function (error) {
if (error !== null && error != undefined) {
self.logger.error('Cannot restart MPD: ' + error);
self.commandRouter.pushToastMessage('error', self.commandRouter.getI18nString('PLAYBACK_OPTIONS.PLAYBACK_OPTIONS_TITLE'), self.commandRouter.getI18nString('COMMON.SETTINGS_SAVE_ERROR'));
} else {
self.commandRouter.pushToastMessage('success', self.commandRouter.getI18nString('PLAYBACK_OPTIONS.PLAYBACK_OPTIONS_TITLE'), self.commandRouter.getI18nString('COMMON.SETTINGS_SAVED_SUCCESSFULLY'));
}
defer.resolve({});
});
}
});
return defer.promise;
};
ControllerMpd.prototype.saveResampleOptions = function (data) {
var self = this;
var defer = libQ.defer();
self.createMPDFile(function (error) {
if (error !== undefined && error !== null) {
// self.commandRouter.pushToastMessage('error', self.commandRouter.getI18nString('mpd_configuration_update'), self.commandRouter.getI18nString('mpd_configuration_update_error'));
defer.resolve({});
} else {
// self.commandRouter.pushToastMessage('success', self.commandRouter.getI18nString('mpd_configuration_update'), self.commandRouter.getI18nString('mpd_playback_configuration_error'));
self.restartMpd(function (error) {
if (error !== null && error != undefined) {
self.logger.error('Cannot restart MPD: ' + error);
// self.commandRouter.pushToastMessage('error', self.commandRouter.getI18nString('mpd_player_restart'), self.commandRouter.getI18nString('mpd_player_restart_error'));
} else
// self.commandRouter.pushToastMessage('success', self.commandRouter.getI18nString('mpd_player_restart'), self.commandRouter.getI18nString('mpd_player_restart_success'));
{ defer.resolve({}); }
});
}
});
return defer.promise;
};
ControllerMpd.prototype.restartMpd = function (callback) {
var self = this;
if (callback) {
exec('/usr/bin/sudo /bin/systemctl restart mpd.service ', {uid: 1000, gid: 1000},
function (error, stdout, stderr) {
self.mpdEstablish();
callback(error);
});
} else {
exec('/usr/bin/sudo /bin/systemctl restart mpd.service ', {uid: 1000, gid: 1000},
function (error, stdout, stderr) {
if (error) {
self.logger.error('Cannot restart MPD: ' + error);
} else {
self.mpdEstablish();
}
});
}
};
ControllerMpd.prototype.createMPDFile = function (callback) {
var self = this;
exec('/usr/bin/sudo /bin/chmod 777 /etc/mpd.conf', {uid: 1000, gid: 1000},
function (error, stdout, stderr) {
if (error != null) {
self.logger.info('Error setting mpd conf file perms: ' + error);
} else {
self.logger.info('MPD Permissions set');
}
});
try {
fs.readFile(__dirname + '/mpd.conf.tmpl', 'utf8', function (err, data) {
if (err) {
return self.logger.error(err);
}
var outdev = self.getAdditionalConf('audio_interface', 'alsa_controller', 'outputdevice');
var mixer = self.getAdditionalConf('audio_interface', 'alsa_controller', 'mixer');
var resampling = self.getAdditionalConf('audio_interface', 'alsa_controller', 'resampling');
var resampling_bitdepth = self.getAdditionalConf('audio_interface', 'alsa_controller', 'resampling_target_bitdepth');
var resampling_samplerate = self.getAdditionalConf('audio_interface', 'alsa_controller', 'resampling_target_samplerate');
var resampling_quality = self.getAdditionalConf('audio_interface', 'alsa_controller', 'resampling_quality');
var ffmpeg = self.config.get('ffmpegenable', false);
var mixerdev = '';
var mixerstrings = '';
if (process.env.MODULAR_ALSA_PIPELINE === 'true') {
var realDev = outdev;
outdev = self.commandRouter.sharedVars.get('alsa.outputdevice');
if(self.getAdditionalConf('audio_interface', 'alsa_controller', 'softvolume')) {
mixerdev = 'SoftMaster';
} else {
if (realDev.indexOf(',') >= 0) {
mixerdev = 'hw:' + realDev;
} else {
mixerdev = 'hw:' + realDev + ',0';
}
}
} else {
if (outdev != 'softvolume') {
var realDev = outdev;
if (outdev.indexOf(',') >= 0) {
mixerdev = 'hw:' + outdev;
outdev = 'hw:' + outdev;
} else {
mixerdev = 'hw:' + outdev;
outdev = 'hw:' + outdev + ',0';
}
} else {
mixerdev = 'SoftMaster';
var realDev = self.getAdditionalConf('audio_interface', 'alsa_controller', 'softvolumenumber');
}
}
var mpdvolume = self.getAdditionalConf('audio_interface', 'alsa_controller', 'mpdvolume');
if (mpdvolume == undefined) {
mpdvolume = false;