forked from jellyfin/jellyfin-web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplugin.js
642 lines (505 loc) · 16.7 KB
/
plugin.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
import { playbackManager } from '../../components/playback/playbackmanager';
import serverNotifications from '../../scripts/serverNotifications';
import ServerConnections from '../../components/ServerConnections';
import { PluginType } from '../../types/plugin.ts';
import Events from '../../utils/events.ts';
function getActivePlayerId() {
const info = playbackManager.getPlayerInfo();
return info ? info.id : null;
}
function sendPlayCommand(apiClient, options, playType) {
const sessionId = getActivePlayerId();
const ids = options.ids || options.items.map(function (i) {
return i.Id;
});
const remoteOptions = {
ItemIds: ids.join(','),
PlayCommand: playType
};
if (options.startPositionTicks) {
remoteOptions.StartPositionTicks = options.startPositionTicks;
}
if (options.mediaSourceId) {
remoteOptions.MediaSourceId = options.mediaSourceId;
}
if (options.audioStreamIndex != null) {
remoteOptions.AudioStreamIndex = options.audioStreamIndex;
}
if (options.subtitleStreamIndex != null) {
remoteOptions.SubtitleStreamIndex = options.subtitleStreamIndex;
}
if (options.startIndex != null) {
remoteOptions.StartIndex = options.startIndex;
}
return apiClient.sendPlayCommand(sessionId, remoteOptions);
}
function sendPlayStateCommand(apiClient, command, options) {
const sessionId = getActivePlayerId();
apiClient.sendPlayStateCommand(sessionId, command, options);
}
function getCurrentApiClient(instance) {
const currentServerId = instance.currentServerId;
if (currentServerId) {
return ServerConnections.getApiClient(currentServerId);
}
return ServerConnections.currentApiClient();
}
function sendCommandByName(instance, name, options) {
const command = {
Name: name
};
if (options) {
command.Arguments = options;
}
instance.sendCommand(command);
}
function unsubscribeFromPlayerUpdates(instance) {
instance.isUpdating = true;
const apiClient = getCurrentApiClient(instance);
apiClient.sendMessage('SessionsStop');
if (instance.pollInterval) {
clearInterval(instance.pollInterval);
instance.pollInterval = null;
}
}
async function updatePlaylist(instance, queue) {
instance.playlist = [];
const max = 100;
const apiClient = getCurrentApiClient(instance);
const fetch = async (newQueue) => {
const options = {
ids: newQueue.map(i => i.Id ),
serverId: apiClient.serverId()
};
const result = await playbackManager.getItemsForPlayback(options.serverId, {
Ids: options.ids.join(',')
});
const items = await playbackManager.translateItemsForPlayback(result.Items, options);
for (let i = 0, length = items.length; i < length; i++) {
items[i].PlaylistItemId = newQueue[i].PlaylistItemId;
}
return items;
};
const n = Math.floor(queue.length / max) + 1;
for (let i = 0; i < n; i++) {
instance.playlist.push(...await fetch(queue.slice(max * i, max * (i + 1))));
}
}
function compareQueues(q1, q2) {
if (q1.length !== q2.length)
return true;
for (let i = 0, length = q1.length; i < length; i++) {
if (q1[i].Id !== q2[i].Id || q1[i].PlaylistItemId !== q2[i].PlaylistItemId) {
return true;
}
}
return false;
}
function updateCurrentQueue(instance, session) {
const current = session.NowPlayingQueue;
if (instance.updating_playlist)
return;
if (instance.lastPlayerData && !compareQueues(current, instance.playlist))
return;
instance.updating_playlist = true;
const finish = () => {
instance.updating_playlist = false;
instance.render_playlist = true;
};
updatePlaylist(instance, current).then(finish, finish);
}
function processUpdatedSessions(instance, sessions, apiClient) {
const serverId = apiClient.serverId();
sessions.forEach(s => {
if (s.NowPlayingItem) {
s.NowPlayingItem.ServerId = serverId;
}
});
const currentTargetId = getActivePlayerId();
const session = sessions.filter(function (s) {
return s.Id === currentTargetId;
})[0];
if (session) {
normalizeImages(session, apiClient);
const eventNames = getChangedEvents(instance.lastPlayerData);
updateCurrentQueue(instance, session);
instance.lastPlayerData = session;
for (let i = 0, length = eventNames.length; i < length; i++) {
Events.trigger(instance, eventNames[i], [session]);
}
} else {
instance.lastPlayerData = session;
playbackManager.setDefaultPlayerActive();
}
}
function getChangedEvents(state1) {
const names = [];
if (!state1) {
names.push('statechange');
names.push('timeupdate');
names.push('pause');
return names;
}
// TODO: Trim these down to prevent the UI from over-refreshing
names.push('statechange');
names.push('timeupdate');
names.push('pause');
return names;
}
function onPollIntervalFired() {
const instance = this;
const apiClient = getCurrentApiClient(instance);
if (!apiClient.isMessageChannelOpen()) {
apiClient.getSessions().then(function (sessions) {
processUpdatedSessions(instance, sessions, apiClient);
});
}
}
function subscribeToPlayerUpdates(instance) {
instance.isUpdating = true;
const apiClient = getCurrentApiClient(instance);
apiClient.sendMessage('SessionsStart', '100,800');
if (instance.pollInterval) {
clearInterval(instance.pollInterval);
instance.pollInterval = null;
}
instance.pollInterval = setInterval(onPollIntervalFired.bind(instance), 5000);
}
function normalizeImages(state, apiClient) {
if (state?.NowPlayingItem) {
const item = state.NowPlayingItem;
if (!item.ImageTags || !item.ImageTags.Primary && item.PrimaryImageTag) {
item.ImageTags = item.ImageTags || {};
item.ImageTags.Primary = item.PrimaryImageTag;
}
if (item.BackdropImageTag && item.BackdropItemId === item.Id) {
item.BackdropImageTags = [item.BackdropImageTag];
}
if (item.BackdropImageTag && item.BackdropItemId !== item.Id) {
item.ParentBackdropImageTags = [item.BackdropImageTag];
item.ParentBackdropItemId = item.BackdropItemId;
}
if (!item.ServerId) {
item.ServerId = apiClient.serverId();
}
}
}
class SessionPlayer {
constructor() {
const self = this;
this.name = 'Remote Control';
this.type = PluginType.MediaPlayer;
this.isLocalPlayer = false;
this.id = 'remoteplayer';
this.playlist = [];
this.render_playlist = true;
this.updating_playlist = false;
this.last_song_playlist_id = 0;
Events.on(serverNotifications, 'Sessions', function (e, apiClient, data) {
processUpdatedSessions(self, data, apiClient);
});
}
beginPlayerUpdates() {
this.playerListenerCount = this.playerListenerCount || 0;
if (this.playerListenerCount <= 0) {
this.playerListenerCount = 0;
subscribeToPlayerUpdates(this);
}
this.playerListenerCount++;
}
endPlayerUpdates() {
this.playerListenerCount = this.playerListenerCount || 0;
this.playerListenerCount--;
if (this.playerListenerCount <= 0) {
unsubscribeFromPlayerUpdates(this);
this.playerListenerCount = 0;
}
}
getPlayerState() {
return this.lastPlayerData || {};
}
getTargets() {
const apiClient = getCurrentApiClient(this);
const sessionQuery = {
ControllableByUserId: apiClient.getCurrentUserId()
};
if (apiClient) {
const name = this.name;
return apiClient.getSessions(sessionQuery).then(function (sessions) {
return sessions.filter(function (s) {
return s.DeviceId !== apiClient.deviceId();
}).map(function (s) {
return {
name: s.DeviceName,
deviceName: s.DeviceName,
deviceType: s.DeviceType,
id: s.Id,
playerName: name,
appName: s.Client,
playableMediaTypes: s.PlayableMediaTypes,
isLocalPlayer: false,
supportedCommands: s.Capabilities.SupportedCommands,
user: s.UserId ? {
Id: s.UserId,
Name: s.UserName,
PrimaryImageTag: s.UserPrimaryImageTag
} : null
};
});
});
} else {
return Promise.resolve([]);
}
}
sendCommand(command) {
const sessionId = getActivePlayerId();
const apiClient = getCurrentApiClient(this);
apiClient.sendCommand(sessionId, command);
}
play(options) {
options = Object.assign({}, options);
if (options.items) {
options.ids = options.items.map(function (i) {
return i.Id;
});
options.items = null;
}
return sendPlayCommand(getCurrentApiClient(this), options, 'PlayNow');
}
shuffle(item) {
sendPlayCommand(getCurrentApiClient(this), { ids: [item.Id] }, 'PlayShuffle');
}
instantMix(item) {
sendPlayCommand(getCurrentApiClient(this), { ids: [item.Id] }, 'PlayInstantMix');
}
queue(options) {
sendPlayCommand(getCurrentApiClient(this), options, 'PlayLast');
}
queueNext(options) {
sendPlayCommand(getCurrentApiClient(this), options, 'PlayNext');
}
canPlayMediaType(mediaType) {
mediaType = (mediaType || '').toLowerCase();
return mediaType === 'audio' || mediaType === 'video';
}
canQueueMediaType(mediaType) {
return this.canPlayMediaType(mediaType);
}
stop() {
sendPlayStateCommand(getCurrentApiClient(this), 'stop');
}
nextTrack() {
sendPlayStateCommand(getCurrentApiClient(this), 'nextTrack');
}
previousTrack() {
sendPlayStateCommand(getCurrentApiClient(this), 'previousTrack');
}
seek(positionTicks) {
sendPlayStateCommand(getCurrentApiClient(this), 'seek',
{
SeekPositionTicks: positionTicks
});
}
currentTime(val) {
if (val != null) {
return this.seek(val * 10000);
}
let state = this.lastPlayerData || {};
state = state.PlayState || {};
return state.PositionTicks / 10000;
}
duration() {
let state = this.lastPlayerData || {};
state = state.NowPlayingItem || {};
return state.RunTimeTicks;
}
paused() {
let state = this.lastPlayerData || {};
state = state.PlayState || {};
return state.IsPaused;
}
getVolume() {
let state = this.lastPlayerData || {};
state = state.PlayState || {};
return state.VolumeLevel;
}
isMuted() {
let state = this.lastPlayerData || {};
state = state.PlayState || {};
return state.IsMuted;
}
pause() {
sendPlayStateCommand(getCurrentApiClient(this), 'Pause');
}
unpause() {
sendPlayStateCommand(getCurrentApiClient(this), 'Unpause');
}
playPause() {
sendPlayStateCommand(getCurrentApiClient(this), 'PlayPause');
}
setMute(isMuted) {
if (isMuted) {
sendCommandByName(this, 'Mute');
} else {
sendCommandByName(this, 'Unmute');
}
}
toggleMute() {
sendCommandByName(this, 'ToggleMute');
}
setVolume(vol) {
sendCommandByName(this, 'SetVolume', {
Volume: vol
});
}
volumeUp() {
sendCommandByName(this, 'VolumeUp');
}
volumeDown() {
sendCommandByName(this, 'VolumeDown');
}
toggleFullscreen() {
sendCommandByName(this, 'ToggleFullscreen');
}
audioTracks() {
let state = this.lastPlayerData || {};
state = state.NowPlayingItem || {};
const streams = state.MediaStreams || [];
return streams.filter(function (s) {
return s.Type === 'Audio';
});
}
getAudioStreamIndex() {
let state = this.lastPlayerData || {};
state = state.PlayState || {};
return state.AudioStreamIndex;
}
playTrailers(item) {
sendCommandByName(this, 'PlayTrailers', {
ItemId: item.Id
});
}
setAudioStreamIndex(index) {
sendCommandByName(this, 'SetAudioStreamIndex', {
Index: index
});
}
subtitleTracks() {
let state = this.lastPlayerData || {};
state = state.NowPlayingItem || {};
const streams = state.MediaStreams || [];
return streams.filter(function (s) {
return s.Type === 'Subtitle';
});
}
getSubtitleStreamIndex() {
let state = this.lastPlayerData || {};
state = state.PlayState || {};
return state.SubtitleStreamIndex;
}
setSubtitleStreamIndex(index) {
sendCommandByName(this, 'SetSubtitleStreamIndex', {
Index: index
});
}
setRepeatMode(mode) {
sendCommandByName(this, 'SetRepeatMode', {
RepeatMode: mode
});
}
getRepeatMode() {
// not supported?
}
setQueueShuffleMode(mode) {
sendCommandByName(this, 'SetShuffleQueue', {
ShuffleMode: mode
});
}
getQueueShuffleMode() {
// not supported?
}
displayContent(options) {
sendCommandByName(this, 'DisplayContent', options);
}
isPlaying(mediaType) {
const state = this.lastPlayerData || {};
return state.NowPlayingItem != null && (state.NowPlayingItem.MediaType === mediaType || !mediaType);
}
isPlayingVideo() {
let state = this.lastPlayerData || {};
state = state.NowPlayingItem || {};
return state.MediaType === 'Video';
}
isPlayingAudio() {
let state = this.lastPlayerData || {};
state = state.NowPlayingItem || {};
return state.MediaType === 'Audio';
}
getTrackIndex(PlaylistItemId) {
for (let i = 0, length = this.playlist.length; i < length; i++) {
if (this.playlist[i].PlaylistItemId === PlaylistItemId) {
return i;
}
}
}
getPlaylist() {
let song_id = 0;
if (this.lastPlayerData) {
song_id = this.lastPlayerData.PlaylistItemId;
}
if (this.playlist.length > 0 && (this.render_playlist || song_id !== this.last_song_playlist_id)) {
this.render_playlist = false;
this.last_song_playlist_id = song_id;
return Promise.resolve(this.playlist);
}
return Promise.resolve([]);
}
movePlaylistItem(playlistItemId, newIndex) {
const index = this.getTrackIndex(playlistItemId);
if (index === newIndex)
return;
const current = this.getCurrentPlaylistItemId();
let current_pos = 0;
if (current === playlistItemId)
current_pos = newIndex;
const append = (newIndex + 1 >= this.playlist.length);
if (newIndex > index)
newIndex++;
const ids = [];
const item = this.playlist[index];
for (let i = 0, length = this.playlist.length; i < length; i++) {
if (i === index)
continue;
if (i === newIndex)
ids.push(item.Id);
if (this.playlist[i].PlaylistItemId === current)
current_pos = ids.length;
ids.push(this.playlist[i].Id);
}
if (append)
ids.push(item.Id);
const options = {
ids: ids,
startIndex: current_pos
};
return sendPlayCommand(getCurrentApiClient(this), options, 'PlayNow');
}
getCurrentPlaylistItemId() {
return this.lastPlayerData.PlaylistItemId;
// not supported?
}
setCurrentPlaylistItem(PlaylistItemId) {
const options = {
ids: this.playlist.map(i => i.Id),
startIndex: this.getTrackIndex(PlaylistItemId)
};
return sendPlayCommand(getCurrentApiClient(this), options, 'PlayNow');
}
removeFromPlaylist() {
return Promise.resolve();
}
tryPair() {
return Promise.resolve();
}
}
export default SessionPlayer;