-
-
Notifications
You must be signed in to change notification settings - Fork 131
/
middleware.js
executable file
·2412 lines (2065 loc) · 88.8 KB
/
middleware.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
import ReactGA from 'react-ga';
import Mopidy from 'mopidy';
import { sha256 } from 'js-sha256';
import * as helpers from '../../helpers';
const mopidyActions = require('./actions.js');
const coreActions = require('../core/actions.js');
const uiActions = require('../ui/actions.js');
const spotifyActions = require('../spotify/actions.js');
const pusherActions = require('../pusher/actions.js');
const googleActions = require('../google/actions.js');
const lastfmActions = require('../lastfm/actions.js');
const discogsActions = require('../discogs/actions.js');
const MopidyMiddleware = (function () {
// container for the actual Mopidy socket
let socket = null;
// play position timer
let progress_interval = null;
let progress_interval_counter = 0;
// handle all manner of socket messages
const handleMessage = (ws, store, type, data) => {
// if debug enabled
if (store.getState().ui.log_mopidy) {
console.log('Mopidy', type, data);
}
switch (type) {
case 'state:online':
store.dispatch({ type: 'MOPIDY_CONNECTED' });
store.dispatch(mopidyActions.getPlayState());
store.dispatch(mopidyActions.getVolume());
store.dispatch(mopidyActions.getMute());
store.dispatch(mopidyActions.getConsume());
store.dispatch(mopidyActions.getRandom());
store.dispatch(mopidyActions.getRepeat());
store.dispatch(mopidyActions.getQueue());
store.dispatch(mopidyActions.getCurrentTrack());
store.dispatch(mopidyActions.getTimePosition());
store.dispatch(mopidyActions.getUriSchemes());
// Every 1s update our play position (when playing)
progress_interval = setInterval(() => {
if (store.getState().mopidy.play_state == 'playing') {
// Every 10s get real position from server, provided we're in-focus
if (progress_interval_counter % 5 == 0 && store.getState().ui.window_focus === true) {
store.dispatch(mopidyActions.getTimePosition());
// Otherwise we just assume to add 1000ms every 1000ms of play time
} else {
store.dispatch(mopidyActions.timePosition(store.getState().mopidy.time_position + 1000));
}
progress_interval_counter++;
}
}, 1000);
break;
case 'state:offline':
store.dispatch({ type: 'MOPIDY_DISCONNECTED' });
store.dispatch(mopidyActions.clearCurrentTrack());
// reset our playback interval timer
clearInterval(progress_interval);
progress_interval_counter = 0;
break;
case 'event:tracklistChanged':
store.dispatch(mopidyActions.getQueue());
// Wait a jiffy before we get the next track
// We don't want to impede snappyness for this luxury request
setTimeout(
() => {
store.dispatch(mopidyActions.getNextTrack());
},
1000,
);
break;
case 'event:playbackStateChanged':
store.dispatch({
type: 'MOPIDY_PLAY_STATE',
play_state: data.new_state,
});
store.dispatch(mopidyActions.getTimePosition());
break;
case 'event:seeked':
store.dispatch({
type: 'MOPIDY_TIME_POSITION',
time_position: data.time_position,
});
break;
case 'event:trackPlaybackEnded':
store.dispatch(mopidyActions.clearCurrentTrack());
store.dispatch({
type: 'MOPIDY_TIME_POSITION',
time_position: 0,
});
break;
case 'event:trackPlaybackStarted':
store.dispatch(mopidyActions.currentTrackLoaded(data.tl_track));
// Wait a jiffy before we get the next track
// We don't want to impede snappyness for this luxury request
setTimeout(
() => {
store.dispatch(mopidyActions.getNextTrack());
},
1000,
);
break;
case 'event:volumeChanged':
store.dispatch({ type: 'MOPIDY_VOLUME', volume: data.volume });
break;
case 'event:muteChanged':
store.dispatch({ type: 'MOPIDY_MUTE', mute: data.mute });
break;
case 'event:optionsChanged':
store.dispatch(mopidyActions.getConsume());
store.dispatch(mopidyActions.getRandom());
store.dispatch(mopidyActions.getRepeat());
break;
default:
// console.log('MopidyService: Unhandled message', type, message );
}
};
/**
* Call something with Mopidy
*
* Sends request to Mopidy server, and updates our local storage on return
* @param object ws = Mopidy class that wraps a Websocket
* @param string model = which Mopidy model (playback, tracklist, etc)
* @param string property = TlTracks, Consume, etc
* @param string value (optional) = value of the property to pass
* @return promise
* */
const request = (ws, store, call, value = {}) => {
if (!store.getState().mopidy.connected) {
return false;
}
const callParts = call.split('.');
const model = callParts[0];
const method = callParts[1];
return new Promise((resolve, reject) => {
if (method in ws[model]) {
var mopidyObject = ws[model][method];
var property = method;
} else {
var mopidyObject = ws[model];
var property = model;
}
// Detect invalid model.method calls, which result in an empty mopidyObject
if (!mopidyObject || typeof (mopidyObject) !== 'function') {
const error = {
message: 'Call to an invalid object. Check you are calling a valid Mopidy object.',
call,
value,
};
store.dispatch(coreActions.handleException(
`Mopidy: ${error.message}`,
error,
));
reject(error);
}
const loader_key = helpers.generateGuid();
store.dispatch(uiActions.startLoading(loader_key, `mopidy_${property}`));
// Start our 15 second timeout
const timeout = setTimeout(
() => {
store.dispatch(uiActions.stopLoading(loader_key));
reject({ message: 'Request timed out', call, value });
},
30000,
);
mopidyObject(value)
.then(
(response) => {
clearTimeout(timeout);
store.dispatch(uiActions.stopLoading(loader_key));
resolve(response);
},
(error) => {
clearTimeout(timeout);
store.dispatch(uiActions.stopLoading(loader_key));
reject(error);
},
);
});
};
/**
* Middleware
*
* This behaves like an action interceptor. We listen for specific actions
* and handle special functionality. If the action is not in our switch, then
* it just proceeds to the next middleware, or default functionality
* */
return (store) => (next) => (action) => {
switch (action.type) {
case 'MOPIDY_CONNECT':
if (socket != null) {
socket.close();
}
store.dispatch({ type: 'MOPIDY_CONNECTING' });
var state = store.getState();
socket = new Mopidy({
webSocketUrl: `ws${window.location.protocol === 'https:' ? 's' : ''}://${state.mopidy.host}:${state.mopidy.port}/mopidy/ws/`,
callingConvention: 'by-position-or-by-name',
});
socket.on((type, data) => handleMessage(socket, store, type, data));
break;
case 'MOPIDY_CONNECTED':
if (store.getState().ui.allow_reporting) {
ReactGA.event({
category: 'Mopidy',
action: 'Connected',
label: sha256(window.location.hostname),
});
}
next(action);
break;
case 'MOPIDY_DISCONNECT':
if (socket != null) socket.close();
socket = null;
store.dispatch({ type: 'MOPIDY_DISCONNECTED' });
break;
case 'MOPIDY_DISCONNECTED':
helpers.setFavicon('favicon_error.png');
break;
case 'MOPIDY_DEBUG':
request(socket, store, action.call, action.value)
.then((response) => {
store.dispatch({ type: 'DEBUG', response });
});
break;
case 'MOPIDY_SET_CONNECTION':
store.dispatch(mopidyActions.set(action.data));
// Wait 250 ms and then retry connection
setTimeout(
() => {
store.dispatch(mopidyActions.connect());
store.dispatch(pusherActions.connect());
},
250,
);
break;
case 'SET_WINDOW_FOCUS':
// Focus has just been regained
if (action.window_focus === true) {
store.dispatch(mopidyActions.getPlayState());
store.dispatch(mopidyActions.getVolume());
store.dispatch(mopidyActions.getMute());
store.dispatch(mopidyActions.getConsume());
store.dispatch(mopidyActions.getRandom());
store.dispatch(mopidyActions.getRepeat());
store.dispatch(mopidyActions.getCurrentTrack());
store.dispatch(mopidyActions.getTimePosition());
}
break;
case 'MOPIDY_REQUEST':
request(socket, store, action.method, action.params)
.then(
(response) => {
if (action.response_callback) {
store.dispatch(action.response_callback.call(this, response));
}
},
(error) => {
if (action.error_callback) {
store.dispatch(action.error_callback.call(this, error));
} else {
store.dispatch(coreActions.handleException(
'Mopidy request failed',
error,
action.method,
action,
));
}
},
);
break;
/**
* General playback
* */
case 'MOPIDY_PLAY_STATE':
store.dispatch(uiActions.setWindowTitle(null, action.play_state));
if (action.play_state == 'playing') {
helpers.setFavicon('favicon.png');
} else {
helpers.setFavicon('favicon_paused.png');
}
next(action);
break;
case 'MOPIDY_GET_PLAY_STATE':
request(socket, store, 'playback.getState')
.then(
(response) => {
store.dispatch({
type: 'MOPIDY_PLAY_STATE',
play_state: response,
});
},
);
break;
case 'MOPIDY_PLAY':
request(socket, store, 'playback.play')
.then(
(response) => {
store.dispatch({
type: 'MOPIDY_PLAY_STATE',
play_state: 'playing',
});
},
);
store.dispatch(pusherActions.deliverBroadcast(
'notification',
{
notification: {
content: `${store.getState().pusher.username + (store.getState().mopidy.play_state == 'paused' ? ' resumed' : ' started')} playback`,
icon: (store.getState().core.current_track ? helpers.getTrackIcon(store.getState().core.current_track, store.getState().core) : false),
},
},
));
break;
case 'MOPIDY_PAUSE':
request(socket, store, 'playback.pause')
.then((response) => {
store.dispatch({
type: 'MOPIDY_PLAY_STATE',
play_state: 'paused',
});
store.dispatch(pusherActions.deliverBroadcast(
'notification',
{
notification: {
content: `${store.getState().pusher.username} paused playback`,
icon: (store.getState().core.current_track ? helpers.getTrackIcon(store.getState().core.current_track, store.getState().core) : false),
},
},
));
});
break;
case 'MOPIDY_PREVIOUS':
// Let the UI know we're in transition
store.dispatch(uiActions.setCurrentTrackTransition('previous'));
request(socket, store, 'playback.previous');
break;
case 'MOPIDY_NEXT':
// Let the UI know we're in transition
store.dispatch(uiActions.setCurrentTrackTransition('next'));
request(socket, store, 'playback.next')
.then((response) => {
store.dispatch(pusherActions.deliverBroadcast(
'notification',
{
notification: {
content: `${store.getState().pusher.username} skipped "${store.getState().core.current_track.name}"`,
icon: (store.getState().core.current_track ? helpers.getTrackIcon(store.getState().core.current_track, store.getState().core) : false),
},
},
));
});
break;
case 'MOPIDY_STOP':
request(socket, store, 'playback.stop')
.then((response) => {
store.dispatch(mopidyActions.clearCurrentTrack());
store.dispatch(pusherActions.deliverBroadcast(
'notification',
{
notification: {
content: `${store.getState().pusher.username} stopped playback`,
icon: (store.getState().core.current_track ? helpers.getTrackIcon(store.getState().core.current_track, store.getState().core) : false),
},
},
));
});
break;
case 'MOPIDY_CHANGE_TRACK':
request(socket, store, 'playback.play', { tlid: action.tlid })
.then((response) => {
store.dispatch(pusherActions.deliverBroadcast(
'notification',
{
notification: {
content: `${store.getState().pusher.username} changed track`,
},
},
));
});
break;
case 'MOPIDY_REMOVE_TRACKS':
request(socket, store, 'tracklist.remove', { tlid: action.tlids })
.then((response) => {
store.dispatch(pusherActions.deliverBroadcast(
'notification',
{
notification: {
content: `${store.getState().pusher.username} removed ${action.tlids.length} tracks`,
},
},
));
});
break;
case 'MOPIDY_GET_REPEAT':
request(socket, store, 'tracklist.getRepeat')
.then((response) => {
store.dispatch({
type: 'MOPIDY_REPEAT',
repeat: response,
});
});
break;
case 'MOPIDY_SET_REPEAT':
request(socket, store, 'tracklist.setRepeat', [action.repeat]);
break;
case 'MOPIDY_GET_RANDOM':
request(socket, store, 'tracklist.getRandom')
.then((response) => {
store.dispatch({
type: 'MOPIDY_RANDOM',
random: response,
});
});
break;
case 'MOPIDY_SET_RANDOM':
request(socket, store, 'tracklist.setRandom', [action.random]);
break;
case 'MOPIDY_GET_CONSUME':
request(socket, store, 'tracklist.getConsume')
.then((response) => {
store.dispatch({
type: 'MOPIDY_CONSUME',
consume: response,
});
});
break;
case 'MOPIDY_SET_CONSUME':
request(socket, store, 'tracklist.setConsume', [action.consume]);
break;
case 'MOPIDY_GET_MUTE':
request(socket, store, 'mixer.getMute')
.then((response) => {
store.dispatch({
type: 'MOPIDY_MUTE',
mute: response,
});
});
break;
case 'MOPIDY_SET_MUTE':
request(socket, store, 'mixer.setMute', [action.mute])
.then((response) => {
store.dispatch(pusherActions.deliverBroadcast(
'notification',
{
notification: {
content: `${store.getState().pusher.username + (action.mute ? ' muted' : ' unmuted')} playback`,
},
},
));
});
break;
case 'MOPIDY_GET_VOLUME':
request(socket, store, 'playback.getVolume')
.then(
(response) => {
store.dispatch({
type: 'MOPIDY_VOLUME',
volume: response,
});
},
);
break;
case 'MOPIDY_SET_VOLUME':
request(socket, store, 'playback.setVolume', { volume: action.volume })
.then(
(response) => {
store.dispatch({
type: 'MOPIDY_VOLUME',
volume: action.volume,
});
},
);
break;
case 'MOPIDY_SET_TIME_POSITION':
request(socket, store, 'playback.seek', { time_position: action.time_position })
.then(
(response) => {
store.dispatch({
type: 'MOPIDY_TIME_POSITION',
time_position: action.time_position,
});
},
);
break;
case 'MOPIDY_GET_TIME_POSITION':
request(socket, store, 'playback.getTimePosition')
.then(
(response) => {
store.dispatch({
type: 'MOPIDY_TIME_POSITION',
time_position: response,
});
},
);
break;
case 'MOPIDY_GET_URI_SCHEMES':
request(socket, store, 'getUriSchemes')
.then(
(response) => {
const uri_schemes = response;
const remove = ['http', 'https', 'mms', 'rtmp', 'rtmps', 'rtsp', 'sc', 'yt'];
// remove all our ignored types
for (var i = 0; i < remove.length; i++) {
const index = uri_schemes.indexOf(remove[i]);
if (index > -1) uri_schemes.splice(index, 1);
}
// append with ':' to make them a mopidy URI
for (var i = 0; i < uri_schemes.length; i++) {
uri_schemes[i] = `${uri_schemes[i]}:`;
}
// Enable Iris providers when the backend is available
store.dispatch(spotifyActions.set({ enabled: uri_schemes.includes('spotify:') }));
store.dispatch(googleActions.set({ enabled: uri_schemes.includes('gmusic:') }));
// If we haven't customised our search schemes, add all to search
if (store.getState().ui.uri_schemes_search_enabled === undefined) {
store.dispatch(uiActions.set({ uri_schemes_search_enabled: uri_schemes }));
}
store.dispatch({ type: 'MOPIDY_URI_SCHEMES', uri_schemes });
},
);
break;
/**
* Advanced playback events
* */
case 'MOPIDY_PLAY_PLAYLIST':
var playlist = store.getState().core.playlists[action.uri];
// We have the playlist loaded already, and we've got at least 1 track to start playing
if (playlist && playlist.tracks_uris && playlist.tracks_uris.length > 0) {
// We've got all of the tracks, so just play those; no further action required
if (playlist.tracks_total == playlist.tracks_uris.length) {
store.dispatch(mopidyActions.playURIs(playlist.tracks_uris, action.uri, action.shuffle));
break;
}
// Spotify-provided playlists need to be handled by the Spotify service
if (playlist.provider == 'spotify') {
store.dispatch(spotifyActions.getAllPlaylistTracks(action.uri, action.shuffle, 'play'));
break;
}
// It's a Spotify playlist that we haven't loaded yet, so Spotify HTTP API needs to go get it
} else if (helpers.uriSource(action.uri) == 'spotify' && store.getState().spotify.enabled) {
store.dispatch(spotifyActions.getAllPlaylistTracks(action.uri, action.shuffle, 'play'));
break;
}
// Not in index, and Spotify HTTP not enabled, so just play it as-is
// Fetch the playlist tracks via backend and add each track by URI
request(socket, store, 'playlists.lookup', { uri: action.uri })
.then(
(response) => {
if (!response || response.tracks === undefined || !response.tracks) {
store.dispatch(uiActions.createNotification({ content: 'Failed to load playlist tracks', type: 'bad' }));
} else {
let tracks_uris = helpers.arrayOf('uri', response.tracks);
if (action.shuffle) {
tracks_uris = helpers.shuffle(tracks_uris);
}
store.dispatch(mopidyActions.playURIs(tracks_uris, action.uri));
}
},
(error) => {
store.dispatch(coreActions.handleException(
`Mopidy: ${error.message ? error.message : 'Lookup failed'}`,
error,
));
},
);
break;
case 'MOPIDY_ENQUEUE_PLAYLIST':
var playlist = store.getState().core.playlists[action.uri];
// We have the playlist loaded already, and we've got at least 1 track to start playing
if (playlist && playlist.tracks_uris && playlist.tracks_uris.length > 0) {
// We've got all of the tracks, so just play those; no further action required
if (playlist.tracks_total == playlist.tracks_uris.length) {
let tracks_uris = Object.assign([], playlist.tracks_uris);
if (action.shuffle) {
tracks_uris = helpers.shuffle(tracks_uris);
}
store.dispatch(mopidyActions.enqueueURIs(tracks_uris, action.uri, action.play_next, action.at_position, action.offset));
break;
}
// Spotify-provided playlists need to be handled by the Spotify service
if (playlist.provider == 'spotify') {
store.dispatch(spotifyActions.getAllPlaylistTracks(action.uri, action.shuffle, 'enqueue', action.play_next));
break;
}
// It's a Spotify playlist that we haven't loaded yet, so Spotify HTTP API needs to go get it
} else if (helpers.uriSource(action.uri) == 'spotify' && store.getState().spotify.enabled) {
store.dispatch(spotifyActions.getAllPlaylistTracks(action.uri, action.shuffle, 'enqueue', action.play_next));
break;
}
// Not in index, and Spotify HTTP not enabled, so just play it as-is
// Fetch the playlist tracks via backend and add each track by URI
request(socket, store, 'playlists.lookup', { uri: action.uri })
.then(
(response) => {
if (response.tracks === undefined) {
store.dispatch(uiActions.createNotification({ content: 'Failed to load playlist tracks', type: 'bad' }));
} else {
let tracks_uris = helpers.arrayOf('uri', response.tracks);
if (action.shuffle) {
tracks_uris = helpers.shuffle(tracks_uris);
}
store.dispatch(mopidyActions.enqueueURIs(tracks_uris, action.uri, action.play_next, action.at_position, action.offset));
}
},
(error) => {
store.dispatch(coreActions.handleException(
`Mopidy: ${error.message ? error.message : 'Lookup failed'}`,
error,
));
},
);
break;
case 'MOPIDY_ENQUEUE_URIS':
if (!action.uris || action.uris.length <= 0) {
this.props.uiActions.createNotification({ content: 'No URIs to enqueue', type: 'warning' });
break;
}
store.dispatch(pusherActions.deliverBroadcast(
'notification',
{
notification: {
content: `${store.getState().pusher.username} is adding ${action.uris.length} URIs to queue`,
icon: (store.getState().core.current_track ? helpers.getTrackIcon(store.getState().core.current_track, store.getState().core) : false),
},
},
));
// split into batches
var uris = Object.assign([], action.uris);
var batches = [];
var batch_size = 5;
while (uris.length > 0) {
batches.push({
uris: uris.splice(0, batch_size),
at_position: action.at_position,
play_next: action.play_next,
offset: action.offset + (batch_size * batches.length),
from_uri: action.from_uri,
});
}
// pass this modified action to the reducer (and other middleware)
action.batches = batches;
next(action);
// start our processor
store.dispatch(uiActions.startProcess(
'MOPIDY_ENQUEUE_URIS_PROCESSOR',
`Adding ${action.uris.length} URI(s)`,
{
batches,
remaining: action.uris.length,
total: action.uris.length,
},
));
break;
case 'MOPIDY_ENQUEUE_URIS_PROCESSOR':
var last_run = store.getState().ui.processes.MOPIDY_ENQUEUE_URIS_PROCESSOR;
// Cancelling
if (last_run && last_run.status == 'cancelling') {
store.dispatch(uiActions.processCancelled('MOPIDY_ENQUEUE_URIS_PROCESSOR'));
return;
// make sure we have some uris in the queue
} if (action.data.batches && action.data.batches.length > 0) {
var batches = Object.assign([], action.data.batches);
var batch = batches[0];
let total_uris = 0;
for (var i = 0; i < batches.length; i++) {
total_uris += batches[i].uris.length;
}
batches.shift();
store.dispatch(uiActions.updateProcess(
'MOPIDY_ENQUEUE_URIS_PROCESSOR',
`Adding ${total_uris} URI(s)`,
{
remaining: total_uris,
},
));
// no batches means we're done here
} else {
store.dispatch(uiActions.processFinishing('MOPIDY_ENQUEUE_URIS_PROCESSOR'));
break;
}
var { current_track } = store.getState().core;
var { queue } = store.getState().core;
var current_track_index = -1;
if (current_track) {
for (var i = 0; i < queue.length; i++) {
if (queue[i].tlid == current_track.tlid) {
current_track_index = i;
break;
}
}
}
var params = { uris: batch.uris };
// Play this batch next
if (batch.play_next) {
// Make sure we're playing something first
if (current_track_index > -1) {
params.at_position = current_track_index + batch.offset + 1;
// Default to top of queue if we're not playing
} else {
params.at_position = 0 + batch.offset;
}
// A specific position has been defined
// NOTE: This is likely to be wrong as the original action is unaware of batches or other client requests
} else if (batch.at_position) {
params.at_position = batch.at_position + batch.offset;
}
request(socket, store, 'tracklist.add', params)
.then(
(response) => {
// add metadata to queue
const tlids = [];
for (let i = 0; i < response.length; i++) {
tlids.push(response[i].tlid);
}
store.dispatch(pusherActions.addQueueMetadata(tlids, batch.from_uri));
// Re-run the batch checker in 100ms. This allows a small window for other
// server requests before our next batch. It's a little crude but it means the server isn't
// locked until we're completely done.
setTimeout(
() => {
store.dispatch(uiActions.runProcess(action.type, { batches }));
},
100,
);
},
(error) => {
store.dispatch(coreActions.handleException(
`Mopidy: ${error.message ? error.message : 'Adding tracks failed'}`,
error,
));
},
);
break;
case 'MOPIDY_PLAY_URIS':
if (!action.uris || action.uris.length <= 0) {
this.props.uiActions.createNotification({ content: 'No URIs to play', type: 'warning' });
break;
}
// Stop the radio
if (store.getState().core.radio && store.getState().core.radio.enabled) {
store.dispatch(pusherActions.stopRadio());
}
// Clear tracklist (if set)
if (store.getState().ui.clear_tracklist_on_play) {
store.dispatch(mopidyActions.clearTracklist());
}
// Shuffle/random mode
if (store.getState().mopidy.random) {
var first_uri_index = Math.floor(Math.random() * action.uris.length);
} else {
var first_uri_index = 0;
}
var first_uri = action.uris[first_uri_index];
// add our first track
request(socket, store, 'tracklist.add', { uri: first_uri, at_position: 0 })
.then(
(response) => {
// play it (only if we got a successful lookup)
if (response.length > 0) {
store.dispatch(mopidyActions.changeTrack(response[0].tlid));
const tlids = [];
for (let i = 0; i < response.length; i++) {
tlids.push(response[i].tlid);
}
store.dispatch(pusherActions.addQueueMetadata(tlids, action.from_uri));
} else {
store.dispatch(coreActions.handleException(
'Mopidy: Failed to add some tracks',
response,
));
}
// Remove our first_uri as we've already added it
action.uris.splice(first_uri_index, 1);
// And add the rest of our uris (if any)
if (action.uris.length > 0) {
// Wait a moment so the server can trigger track_changed etc
// this means our UI feels snappier as the first track shows up quickly
setTimeout(
() => {
store.dispatch(mopidyActions.enqueueURIs(action.uris, action.from_uri, null, 1));
},
100,
);
}
},
(error) => {
store.dispatch(coreActions.handleException(
`Mopidy: ${error.message ? error.message : 'Adding tracks failed'}`,
error,
));
},
);
break;
case 'MOPIDY_REORDER_TRACKLIST':
// add our first track
request(socket, store, 'tracklist.move', { start: action.range_start, end: action.range_start + action.range_length, to_position: action.insert_before })
.then(
(response) => {
// TODO: when complete, send event to confirm success/failure
},
(error) => {
store.dispatch(coreActions.handleException(
`Mopidy: ${error.message ? error.message : 'Reorder failed'}`,
error,
));
},
);
break;
case 'MOPIDY_CLEAR_TRACKLIST':
request(socket, store, 'tracklist.clear')
.then(
(response) => {
store.dispatch(coreActions.clearCurrentTrack());
store.dispatch(pusherActions.deliverBroadcast(
'notification',
{
notification: {
content: `${store.getState().pusher.username} cleared queue`,
},
},
));
},
);
break;
/**
* =============================================================== SEARCHING ============
* ======================================================================================
* */
case 'MOPIDY_GET_SEARCH_RESULTS':
// Flush out our previous results
store.dispatch({ type: 'MOPIDY_CLEAR_SEARCH_RESULTS' });
var uri_schemes_to_ignore = ['spotify:'];
var uri_schemes = Object.assign([], store.getState().ui.uri_schemes_search_enabled);
for (var i = 0; i < uri_schemes.length; i++) {
if (uri_schemes_to_ignore.includes(uri_schemes[i])) {
uri_schemes.splice(i, 1);
}
}
var uri_schemes_total = uri_schemes.length;
var uri_scheme = uri_schemes.shift();
if (uri_schemes_total <= 0) {
store.dispatch(uiActions.createNotification({ content: 'No sources selected', type: 'warning' }));
} else {
store.dispatch(uiActions.startProcess(
'MOPIDY_GET_SEARCH_RESULTS_PROCESSOR',
`Searching ${uri_schemes_total} Mopidy providers`,
{
context: action.context,
query: action.query,
limit: action.limit,
total: uri_schemes_total,
remaining: uri_schemes.length,
uri_scheme,
uri_schemes,
},
));
}
break;
case 'MOPIDY_GET_SEARCH_RESULTS_PROCESSOR':