stremiok 2.3.1 → 2.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/js/jellyfin.js CHANGED
@@ -4,8 +4,8 @@
4
4
  and version, who's signed in and the sign-in it gave back (never the password).
5
5
  - Emby speaks the same API family (Jellyfin started as its fork): its paths under /emby, per
6
6
  user (/Users/<id>/Items…), its sign-in line as X-Emby-Authorization, api_key in links; no
7
- Quick Connect, trickplay or media segments, but intro and credits markers in its chapters
8
- (KINDS: what differs).
7
+ Quick Connect or media segments, but intro and credits markers in its chapters, and its seek
8
+ pictures in a BIF file, not trickplay (KINDS: what differs).
9
9
  - As local addons like Xtream's, one per kind ("Jellyfin", "Emby"): a catalog per Movies or
10
10
  Shows library (Home rows, Discover, Search); a title the server knows the IMDb id of is a
11
11
  card with that id (the usual title page, your addons' sources too), any other
@@ -15,12 +15,15 @@
15
15
  of films and series with their ids, read when first needed and again after INDEX_FRESH_MS.
16
16
  - Played as the file is (/Videos/<item>/stream.<container>?static=true: nothing converted),
17
17
  its subtitle files with it; what you play is reported back (Jellyfin's sessions: where you
18
- are, stopped, played), except during private viewing. Jellyfin 10.9 or newer, Emby 4.7. */
18
+ are, stopped, played), except during private viewing. Jellyfin 10.9 or newer, Emby 4.7.
19
+ - Watched marks: what each server (Plex's too) has played, by the ids its titles go by here,
20
+ read at launch and after MARKS_FRESH_MS; Player weighs them against its own by time
21
+ (player-store), as Trakt's. */
19
22
  var Jellyfin = (function () {
20
23
  'use strict';
21
24
 
22
25
  var KEY = 'stremiok.jellyfin.servers', DEV_KEY = 'stremiok.jellyfin.device', LIBS_KEY = 'stremiok.jellyfin.libs';
23
- var PAGE = 100, INDEX_FRESH_MS = 30 * 60000, INDEX_RETRY_MS = 60000, LIBS_FRESH_MS = 86400000;
26
+ var PAGE = 100, INDEX_FRESH_MS = 30 * 60000, INDEX_RETRY_MS = 60000, INDEX_SLOW_MS = 30 * 60000, LIBS_FRESH_MS = 86400000;
24
27
  var QC_EVERY = 3000, QC_FOR = 10 * 60000, REPORT_EVERY = 60000, TICKS = 10000000;
25
28
  var _changeFns = [];
26
29
  function onChange(fn) { _changeFns.push(fn); }
@@ -47,11 +50,30 @@ var Jellyfin = (function () {
47
50
  function uid(srv) { return enc(srv.userId); }
48
51
 
49
52
  // ---- Your servers ----
50
- function servers(kind) {
53
+ // (every one kept, on or off: Settings' list; servers: the ones on, all that's used)
54
+ function allServers(kind) {
51
55
  var l = U.store.get(KEY, []);
52
56
  return Array.isArray(l) ? l.filter(function (s) { return s && s.id && s.url && s.token && s.userId && (!kind || kindOf(s) === kind); }) : [];
53
57
  }
58
+ function servers(kind) { return allServers(kind).filter(function (s) { return !s.off; }); }
54
59
  function server(id) { return servers().filter(function (s) { return s.id === id; })[0] || null; }
60
+ function anyServer(id) { return allServers().filter(function (s) { return s.id === id; })[0] || null; }
61
+ // Turned off: its rows, sources and watched marks set aside, nothing asked of it, its sign-in
62
+ // kept; on again: its libraries read again.
63
+ function setOn(id, on) {
64
+ if (!anyServer(id)) { return; }
65
+ U.store.set(KEY, allServers().map(function (s) {
66
+ if (s.id !== id) { return s; }
67
+ var t = {};
68
+ Object.keys(s).forEach(function (k) { if (k !== 'off') { t[k] = s[k]; } });
69
+ if (!on) { t.off = true; }
70
+ return t;
71
+ }));
72
+ forget(id);
73
+ fillAll();
74
+ if (on) { delete _libsAsked[id]; _libsP[id] = refreshLibs(true, id); }
75
+ changed();
76
+ }
55
77
  function isEnabled(kind) { return servers(kind).length > 0; }
56
78
  function kindsOn() { return Object.keys(KINDS).filter(function (k) { return isEnabled(k); }); }
57
79
  function deviceId() {
@@ -78,7 +100,10 @@ var Jellyfin = (function () {
78
100
  if (json) { h['Content-Type'] = 'application/json'; }
79
101
  return h;
80
102
  }
81
- function get(srv, path, max) { return U.getJSON(api(srv) + path, 20000, max || 4 * 1048576, null, headers(srv, srv.token)); }
103
+ // How long to wait for its answer: Settings › Media servers › Wait for a server (Normal: 20 s;
104
+ // Plex's too).
105
+ function waitMs() { var w = typeof Stremio !== 'undefined' && Stremio.getPrefs ? +Stremio.getPrefs().serverWait : 0; return w > 0 ? w * 1000 : 20000; }
106
+ function get(srv, path, max) { return U.getJSON(api(srv) + path, waitMs(), max || 4 * 1048576, null, headers(srv, srv.token)); }
82
107
  function post(srv, path, body) { return U.getText(api(srv) + path, 15000, 65536, null, true, headers(srv, srv.token, true), body == null ? '' : JSON.stringify(body)); }
83
108
 
84
109
  // An address as typed (192.168.0.50, http://nas:8096/web/…, …/emby/web/…): with http:// and
@@ -113,7 +138,7 @@ var Jellyfin = (function () {
113
138
  // Signed in: kept (the same server and user again: in its place, its id kept).
114
139
  function added(info, r) {
115
140
  if (!r || !r.AccessToken || !r.User || !r.User.Id) { throw new Error(kindName(info) + ' didn’t sign in.'); }
116
- var list = servers(), old = list.filter(function (s) { return s.serverId === info.serverId && s.userId === '' + r.User.Id; })[0];
141
+ var list = allServers(), old = list.filter(function (s) { return s.serverId === info.serverId && s.userId === '' + r.User.Id; })[0];
117
142
  var srv = { id: old ? old.id : 's' + rand(8), url: info.url, kind: kindOf(info), serverId: info.serverId, name: info.name, version: info.version,
118
143
  user: ('' + (r.User.Name || '')).slice(0, 60), userId: '' + r.User.Id, token: '' + r.AccessToken, at: Date.now() };
119
144
  list = list.filter(function (s) { return s !== old; });
@@ -177,10 +202,10 @@ var Jellyfin = (function () {
177
202
  }
178
203
  // Sign out and remove: its sign-in ended on the server too (if it answers).
179
204
  function remove(id) {
180
- var srv = server(id);
205
+ var srv = anyServer(id);
181
206
  if (!srv) { return; }
182
207
  post(srv, '/Sessions/Logout', null).then(null, function () {});
183
- U.store.set(KEY, servers().filter(function (s) { return s.id !== id; }));
208
+ U.store.set(KEY, allServers().filter(function (s) { return s.id !== id; }));
184
209
  var libs = libsAll();
185
210
  delete libs[id];
186
211
  U.store.set(LIBS_KEY, libs);
@@ -220,7 +245,7 @@ var Jellyfin = (function () {
220
245
  });
221
246
  if (!server(srv.id)) { return; } // (removed meanwhile)
222
247
  var all = libsAll(), keep = {}, before = JSON.stringify(all[srv.id] && all[srv.id].list);
223
- servers().forEach(function (s) { if (all[s.id]) { keep[s.id] = all[s.id]; } });
248
+ allServers().forEach(function (s) { if (all[s.id]) { keep[s.id] = all[s.id]; } });
224
249
  keep[srv.id] = { at: Date.now(), list: list };
225
250
  _libs = keep;
226
251
  U.store.set(LIBS_KEY, keep);
@@ -258,7 +283,7 @@ var Jellyfin = (function () {
258
283
  kind = KINDS[kind] ? kind : 'jellyfin';
259
284
  if (!_addons[kind]) {
260
285
  _addons[kind] = { __local: true, __sources: true, url: 'local:' + kind, base: 'local:' + kind,
261
- __impl: { catalog: catalog, meta: meta, streams: function (type, id) { return streams(type, id, kind); } },
286
+ __impl: { catalog: catalog, meta: meta, streams: function (type, id, m) { return streams(type, id, kind, m); } },
262
287
  manifest: { id: 'org.stremiok.' + kind, name: KINDS[kind].name, version: '1.0.0', types: ['movie', 'series'], resources: RESOURCES, catalogs: [] } };
263
288
  }
264
289
  fillCatalogs(kind);
@@ -386,27 +411,81 @@ var Jellyfin = (function () {
386
411
  var x = _index[srv.id];
387
412
  if (x && x.map && (x.p || Date.now() - x.at < INDEX_FRESH_MS)) { return Promise.resolve(x.map); }
388
413
  if (x && x.p) { return x.p; }
389
- var p = get(srv, K(srv).items(uid(srv)) + 'recursive=true&includeItemTypes=Movie,Series&fields=ProviderIds&enableImages=false&enableUserData=false&enableTotalRecordCount=false', 16 * 1048576).then(function (r) {
390
- var map = { __ids: {} }; // (__ids: an item's IMDb id, for Next up's cards)
414
+ var p = get(srv, K(srv).items(uid(srv)) + 'recursive=true&includeItemTypes=Movie,Series&fields=ProviderIds&enableImages=false&enableUserData=true&enableTotalRecordCount=false', 16 * 1048576).then(function (r) {
415
+ var map = { __ids: {}, __tm: {}, __played: [] }; // (__ids, __tm: an item's IMDb, TMDB id, for Next up's cards and watched marks; __played: its played films and shows)
391
416
  function add(k, v) { (map[k] = map[k] || []).push(v); }
392
417
  U.listOf(r && r.Items, 100000).forEach(function (it) {
393
418
  var t = it.Type === 'Movie' ? 'movie' : it.Type === 'Series' ? 'series' : '', tt = imdbOf(it), tm = tmdbOf(it);
394
419
  if (!t || !it.Id) { return; }
395
420
  if (tt) { add(t + '|' + tt, '' + it.Id); map.__ids['' + it.Id] = tt; }
396
- if (tm) { add(t + '|tmdb:' + tm, '' + it.Id); }
421
+ if (tm) { add(t + '|tmdb:' + tm, '' + it.Id); map.__tm['' + it.Id] = tm; }
422
+ if (it.UserData && it.UserData.Played) { map.__played.push({ t: t, ids: titleIds(map, (t === 'movie' ? 'jfm.' : 'jfs.') + srv.id + '.', '' + it.Id), at: Date.parse(it.UserData.LastPlayedDate || '') || 1 }); }
397
423
  });
398
424
  if (_index[srv.id] && _index[srv.id].p === p) { _index[srv.id] = { at: Date.now(), map: map }; }
399
425
  return map;
400
426
  }, function (e) {
401
427
  U.log('jellyfin', '“' + srv.name + '” (' + kindName(srv) + '): its titles couldn’t be read (' + U.problem(e) + ')');
402
- var old = _index[srv.id], map = (old && old.map) || { __ids: {} };
403
- if (old && old.p === p) { _index[srv.id] = { at: Date.now() - INDEX_FRESH_MS + INDEX_RETRY_MS, map: map }; } // (asked again in a minute)
428
+ var old = _index[srv.id], map = (old && old.map) || { __ids: {}, __tm: {}, __played: [], __err: true }; // (__err: never read)
429
+ // (asked again in a minute; one that timed out — a list too big or slow for one answer, as a server
430
+ // presenting a whole catalog has — after 30 minutes, titles looked up one at a time meanwhile: idsFor)
431
+ var slow = /Timed out/i.test((e && e.message) || '');
432
+ if (old && old.p === p) { _index[srv.id] = { at: Date.now() - INDEX_FRESH_MS + (slow ? INDEX_SLOW_MS : INDEX_RETRY_MS), map: map }; }
404
433
  return map;
405
434
  });
406
435
  _index[srv.id] = { at: x ? x.at : 0, map: x ? x.map : null, p: p };
407
436
  return x && x.map ? Promise.resolve(x.map) : p;
408
437
  }
409
- function copies(type, id, kind) {
438
+ // The list as it is now: one being read again waited for (index answers with the old one).
439
+ function indexFresh(srv) { var p = index(srv), x = _index[srv.id]; return x && x.p ? x.p : p; }
440
+ // The ids a server's title goes by here: its IMDb and TMDB ones, and its own (own: its prefix).
441
+ function titleIds(map, own, id) {
442
+ var l = [own + id];
443
+ if (map.__ids[id]) { l.unshift(map.__ids[id]); }
444
+ if (map.__tm && map.__tm[id]) { l.push('tmdb:' + map.__tm[id]); }
445
+ return l;
446
+ }
447
+ // A title the server's list can't give (never read: too big or slow for one answer, as a server
448
+ // presenting a whole catalog is): searched for by its name, taken only when its IMDb or TMDB id
449
+ // is the one asked for. Kept FOUND_MS (a failed search: asked again next time).
450
+ var FOUND_MS = 30 * 60000, _found = U.lru(300);
451
+ function lookup(srv, type, key, name) {
452
+ name = ('' + (name || '')).replace(/\s+/g, ' ').trim().slice(0, 100);
453
+ if (!name) { return Promise.resolve([]); }
454
+ var k = srv.id + '|' + type + '|' + key, had = _found.get(k);
455
+ if (had && had.p && Date.now() - had.at < FOUND_MS) { return had.p; }
456
+ var p = get(srv, K(srv).items(uid(srv)) + 'recursive=true&includeItemTypes=' + (type === 'movie' ? 'Movie' : 'Series') + '&searchTerm=' + enc(name) +
457
+ '&fields=ProviderIds&enableImages=false&enableUserData=false&limit=40').then(function (r) {
458
+ return U.listOf(r && r.Items, 40, function (it) { return it && it.Id && (imdbOf(it) === key || (!!tmdbOf(it) && 'tmdb:' + tmdbOf(it) === key)); }).map(function (it) { return '' + it.Id; });
459
+ }, function (e) {
460
+ _found.set(k, null);
461
+ U.log('jellyfin', '“' + srv.name + '”: “' + name + '” couldn’t be looked up (' + U.problem(e) + ')');
462
+ return [];
463
+ });
464
+ _found.set(k, { at: Date.now(), p: p });
465
+ return p;
466
+ }
467
+ // The server's items for a title: from its list, as before; with no list yet, or none to be
468
+ // had, looked up by name meanwhile (lookup), the list's answer used when that finds none.
469
+ function idsFor(srv, type, key, name) {
470
+ var x = _index[srv.id];
471
+ var fromList = index(srv).then(function (map) { return map[type + '|' + key] || []; });
472
+ if (x && x.map && !x.map.__err) { return fromList; }
473
+ return lookup(srv, type, key, name).then(function (ids) { return ids.length ? ids : fromList; });
474
+ }
475
+ // A film or episode listed without its files (a server presenting remote ones gives them only
476
+ // when asked to play it: PlaybackInfo): asked for them then.
477
+ function withFiles(srv, it) {
478
+ if (!it || !it.Id || (it.MediaSources && it.MediaSources.length)) { return Promise.resolve(it); }
479
+ return U.getJSON(api(srv) + '/Items/' + enc(it.Id) + '/PlaybackInfo?userId=' + uid(srv), waitMs(), 8 * 1048576, null, headers(srv, srv.token, true), '{}').then(function (r) {
480
+ var l = U.listOf(r && r.MediaSources, 200, function (ms) { return ms && ms.Id; });
481
+ return l.length ? Object.assign({}, it, { MediaSources: l }) : it;
482
+ }, function (e) {
483
+ U.log('jellyfin', '“' + srv.name + '”: the files of “' + (it.Name || it.Id) + '” couldn’t be read (' + U.problem(e) + ')');
484
+ return it;
485
+ });
486
+ }
487
+ function filesOf(srv, it) { return withFiles(srv, it).then(function (x) { return sourcesOf(srv, x); }); }
488
+ function copies(type, id, kind, meta) {
410
489
  var key = '', season = null, episode = null;
411
490
  if (type === 'movie') { key = /^(tt\d+|tmdb:\d+)$/.test('' + id) ? '' + id : ''; }
412
491
  else if (type === 'series') {
@@ -414,15 +493,106 @@ var Jellyfin = (function () {
414
493
  if (mm) { key = mm[1]; season = +mm[2]; episode = +mm[3]; }
415
494
  }
416
495
  if (!key) { return Promise.resolve([]); }
496
+ var name = meta && typeof meta.name === 'string' ? meta.name : '';
417
497
  return Promise.all(servers(kind).map(function (srv) {
418
- return index(srv).then(function (map) {
419
- return Promise.all((map[type + '|' + key] || []).slice(0, 3).map(function (iid) {
420
- return type === 'movie' ? item(srv, iid).then(function (it) { return sourcesOf(srv, it); }, none) : episodeSources(srv, iid, season, episode);
498
+ return idsFor(srv, type, key, name).then(function (ids) {
499
+ return Promise.all(ids.slice(0, 3).map(function (iid) {
500
+ return type === 'movie' ? item(srv, iid).then(function (it) { return filesOf(srv, it); }, none) : episodeSources(srv, iid, season, episode);
421
501
  }));
422
502
  }).then(flat, none);
423
503
  })).then(flat);
424
504
  }
425
505
 
506
+ // ---- Watched marks (Jellyfin, Emby; Plex's from js/plex.js) ----
507
+ // { 'movie:<id>': when, 'series:<id>': when (the whole show), 'series:<show>:<s>:<e>': when }
508
+ // from [{ t, ids, at, s?, e? }].
509
+ var MARKS_MAX = 50000;
510
+ function marksFrom(list) {
511
+ var out = {}, n = 0;
512
+ (list || []).forEach(function (x) {
513
+ (x.ids || []).forEach(function (id) {
514
+ var k = x.t + ':' + id + (x.s != null ? ':' + x.s + ':' + x.e : '');
515
+ if (out[k] == null) { if (n >= MARKS_MAX) { return; } n++; }
516
+ out[k] = Math.max(out[k] || 0, x.at > 0 ? x.at : 1);
517
+ });
518
+ });
519
+ return out;
520
+ }
521
+ // Its played films and shows (its list of titles) and episodes.
522
+ function jfMarks(srv) {
523
+ return Promise.all([indexFresh(srv), get(srv, K(srv).items(uid(srv)) + 'recursive=true&includeItemTypes=Episode&isPlayed=true&enableImages=false&enableTotalRecordCount=false', 16 * 1048576)]).then(function (r) {
524
+ var map = r[0], list = map.__played.slice();
525
+ if (map.__err) { throw new Error('its titles couldn’t be read'); }
526
+ U.listOf(r[1] && r[1].Items, 100000, function (e) { return e.SeriesId && e.ParentIndexNumber >= 0 && e.IndexNumber >= 0 && (!e.UserData || e.UserData.Played !== false); }).forEach(function (e) {
527
+ list.push({ t: 'series', ids: titleIds(map, 'jfs.' + srv.id + '.', '' + e.SeriesId), s: +e.ParentIndexNumber, e: +e.IndexNumber, at: Date.parse((e.UserData && e.UserData.LastPlayedDate) || '') || 1 });
528
+ });
529
+ return marksFrom(list);
530
+ });
531
+ }
532
+ // Every server's, kept in the TV's database (U.store when it won't take them), read into
533
+ // memory at launch (watchedAt is synchronous; until then, none).
534
+ var MARKS_KEY = 'stremiok.media.watched', MARKS_FRESH_MS = 30 * 60000;
535
+ var _marks = null, _all = {}, _marksP = null, _marksSaved = null;
536
+ function merge() {
537
+ var all = {};
538
+ Object.keys(_marks || {}).forEach(function (id) {
539
+ var m = (_marks[id] && _marks[id].m) || {};
540
+ Object.keys(m).forEach(function (k) { if (!(all[k] >= m[k])) { all[k] = m[k]; } });
541
+ });
542
+ _all = all;
543
+ }
544
+ var _marksRead = (U.bigStore ? U.bigStore.get(MARKS_KEY) : Promise.resolve(null)).then(function (m) {
545
+ if (!m || typeof m !== 'object') { m = U.store.get(MARKS_KEY, null, true); }
546
+ if (m && typeof m === 'object' && !_marks) { _marks = m; _marksSaved = JSON.stringify(m); merge(); }
547
+ }, function () {});
548
+ function saveMarks() {
549
+ var text = JSON.stringify(_marks);
550
+ if (text === _marksSaved) { return; }
551
+ _marksSaved = text;
552
+ if (!U.bigStore) { U.store.set(MARKS_KEY, _marks); return; }
553
+ U.bigStore.set(MARKS_KEY, _marks).then(function (ok) {
554
+ if (ok) { return; }
555
+ U.bigStore.remove(MARKS_KEY, true);
556
+ U.store.set(MARKS_KEY, _marks);
557
+ });
558
+ }
559
+ function markSources() {
560
+ var l = servers().map(function (s) { return { id: s.id, name: s.name, read: function () { return jfMarks(s); } }; });
561
+ if (typeof Plex !== 'undefined' && Plex.servers && Plex.marksOf) {
562
+ Plex.servers().forEach(function (s) { l.push({ id: s.id, name: s.name, read: function () { return Plex.marksOf(s); } }); });
563
+ }
564
+ return l;
565
+ }
566
+ // Read again where older than MARKS_FRESH_MS (force: all), a removed server's dropped; a
567
+ // promise of whether they changed.
568
+ function refreshMarks(force) {
569
+ if (_marksP) { return _marksP; }
570
+ _marksP = _marksRead.then(function () {
571
+ var was = _marks || {}, list = markSources(), next = {}, changed = false;
572
+ if (!list.length && !Object.keys(was).length) { return false; } // (no servers, none kept: nothing saved)
573
+ Object.keys(was).forEach(function (id) { if (!list.some(function (x) { return x.id === id; })) { changed = true; } });
574
+ return Promise.all(list.map(function (x) {
575
+ var old = was[x.id];
576
+ if (old && !force && Date.now() - old.at < MARKS_FRESH_MS) { next[x.id] = old; return null; }
577
+ return x.read().then(function (m) {
578
+ if (!old || JSON.stringify(m) !== JSON.stringify(old.m)) { changed = true; }
579
+ next[x.id] = { at: Date.now(), m: m };
580
+ }, function (e) {
581
+ if (old) { next[x.id] = old; }
582
+ U.log('jellyfin', '“' + x.name + '”: its watched marks couldn’t be read (' + U.problem(e) + ')');
583
+ });
584
+ })).then(function () {
585
+ _marks = next;
586
+ merge();
587
+ saveMarks();
588
+ return changed;
589
+ });
590
+ }).then(function (ch) { _marksP = null; return ch; }, function () { _marksP = null; return false; });
591
+ return _marksP;
592
+ }
593
+ // When a server has it played (ms; 0: not, or not known): the latest of them.
594
+ function watchedAt(type, id) { return _all[type + ':' + id] || 0; }
595
+
426
596
  // ---- Sources ----
427
597
  var EXT = { mkv: 'mkv', matroska: 'mkv', webm: 'webm', mp4: 'mp4', mov: 'mp4', m4v: 'mp4', avi: 'avi', mpegts: 'ts', ts: 'ts', m2ts: 'm2ts', mpeg: 'mpg', mpg: 'mpg', flv: 'flv', wmv: 'wmv', asf: 'wmv', ogg: 'ogv' };
428
598
  function extOf(c) { var f = ('' + (c || '')).toLowerCase().split(',')[0].trim(); return EXT[f] || (/^[a-z0-9]{2,5}$/.test(f) ? f : 'mkv'); }
@@ -444,7 +614,7 @@ var Jellyfin = (function () {
444
614
  behaviorHints: { filename: file, videoSize: size || undefined, bingeGroup: 'stremiok-jellyfin-' + srv.id },
445
615
  _jf: placeOf({ srv: srv.id, kind: kindOf(srv), item: '' + it.Id, ms: '' + ms.Id }, it.UserData)
446
616
  };
447
- var ch = chapterSegments(it), mk = markerSegments(it), named = namedChapters(it), tp = trickplayOf(srv, it, ms);
617
+ var ch = chapterSegments(it), mk = markerSegments(it), named = namedChapters(it), tp = trickplayOf(srv, it, ms) || bifOf(srv, it, ms, v);
448
618
  if (ch) { st._jf.ch = ch; }
449
619
  if (mk) { st._jf.mk = mk; }
450
620
  if (named) { st._jf.chapters = named; }
@@ -529,10 +699,74 @@ var Jellyfin = (function () {
529
699
  return { w: +best.Width, h: +best.Height, cols: +best.TileWidth, rows: +best.TileHeight, n: +best.ThumbnailCount, every: +best.Interval,
530
700
  base: api(srv) + '/Videos/' + enc(it.Id) + '/Trickplay/' + (+best.Width) + '/', q: '.jpg?mediaSourceId=' + enc(ms.Id) + '&' + K(srv).key + '=' + enc(srv.token) };
531
701
  }
702
+ // Emby's seek pictures: its BIF file (the Roku format: the JPEGs and when each is), 320 wide,
703
+ // read at the first ◀ ▶ (bifAt). Emby makes them where the library's thumbnail extraction is on.
704
+ function bifOf(srv, it, ms, v) {
705
+ if (kindOf(srv) !== 'emby' || !(+it.RunTimeTicks > 0)) { return null; }
706
+ var w = +(v && v.Width) || 0, h = +(v && v.Height) || 0;
707
+ return { bif: api(srv) + '/Videos/' + enc(it.Id) + '/index.bif?width=320&mediaSourceId=' + enc(ms.Id) + '&' + K(srv).key + '=' + enc(srv.token),
708
+ w: 320, h: w > 0 && h > 0 ? Math.round(320 * h / w) : 180, cols: 1, rows: 1, every: 10000, n: 1 };
709
+ }
710
+ // The file being played's (one at a time): { url, p } while it's read, then { url, frames:
711
+ // [{ t (ms), a, b (where its JPEG is) }], bytes, pics: the latest pictures' links }, or
712
+ // { url, failed }.
713
+ var BIF_MAX = 40 * 1048576, BIF_PICS = 12, BIF_MAGIC = [0x89, 0x42, 0x49, 0x46, 0x0d, 0x0a, 0x1a, 0x0a], _bif = null;
714
+ function parseBif(b) {
715
+ for (var i = 0; i < 8; i++) { if (b[i] !== BIF_MAGIC[i]) { return null; } }
716
+ function u32(o) { return (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0; }
717
+ var n = u32(12), every = u32(16) || 1000, out = [];
718
+ for (var k = 0; k < n && 79 + k * 8 < b.length; k++) {
719
+ var t = u32(64 + k * 8), a = u32(68 + k * 8), z = u32(76 + k * 8);
720
+ if (t === 0xffffffff) { break; }
721
+ if (z > a && z <= b.length) { out.push({ t: t * every, a: a, b: z }); }
722
+ }
723
+ return out;
724
+ }
725
+ function dropBif() {
726
+ if (_bif && _bif.pics) { Object.keys(_bif.pics).forEach(function (k) { try { URL.revokeObjectURL(_bif.pics[k]); } catch (e) {} }); }
727
+ _bif = null;
728
+ }
729
+ function loadBif(tp) {
730
+ dropBif();
731
+ var b = { url: tp.bif };
732
+ _bif = b;
733
+ b.p = U.getBytes(tp.bif, 30000, BIF_MAX, true).then(function (bytes) {
734
+ var frames = parseBif(bytes);
735
+ if (_bif !== b) { return; }
736
+ if (!frames || !frames.length) { throw new Error('not a BIF file'); }
737
+ b.frames = frames; b.bytes = bytes; b.pics = {}; b.order = [];
738
+ if (frames.length > 1) { tp.every = Math.max(1000, Math.round((frames[frames.length - 1].t - frames[0].t) / (frames.length - 1))); }
739
+ tp.n = frames.length;
740
+ }).then(null, function (e) {
741
+ if (_bif !== b) { return; }
742
+ b.failed = true;
743
+ U.log('jellyfin', 'Emby has no seek pictures for this file (' + (/HTTP 404/.test(e && e.message) ? 'none made: the library’s thumbnail extraction' : U.problem(e)) + ')');
744
+ });
745
+ }
746
+ function bifPic(i) {
747
+ var b = _bif, f = b.frames[i];
748
+ if (b.pics[i]) { return b.pics[i]; }
749
+ var url = null;
750
+ try { url = URL.createObjectURL(new Blob([b.bytes.subarray(f.a, f.b)], { type: 'image/jpeg' })); } catch (e) { return null; }
751
+ b.pics[i] = url;
752
+ b.order.push(i);
753
+ if (b.order.length > BIF_PICS) { var old = b.order.shift(); try { URL.revokeObjectURL(b.pics[old]); } catch (e2) {} delete b.pics[old]; }
754
+ return url;
755
+ }
756
+ function bifAt(tp, sec) {
757
+ if (!_bif || _bif.url !== tp.bif) { loadBif(tp); return null; }
758
+ var f = _bif.frames;
759
+ if (!f) { return null; }
760
+ var ms = sec * 1000, lo = 0, hi = f.length - 1;
761
+ while (lo < hi) { var mid = (lo + hi + 1) >> 1; if (f[mid].t <= ms) { lo = mid; } else { hi = mid - 1; } }
762
+ var url = bifPic(lo);
763
+ return url ? { url: url, x: 0, y: 0, w: tp.w, h: tp.h, cols: 1, rows: 1 } : null;
764
+ }
532
765
  // The seek picture for a moment (seconds): its tile's link and where in it, or null.
533
- // (tp.one: a picture a link, base + its moment in ms, as Plex's are)
766
+ // (tp.one: a picture a link, base + its moment in ms, as Plex's are; tp.bif: Emby's file)
534
767
  function trickplayAt(tp, sec) {
535
768
  if (!tp || !(sec >= 0)) { return null; }
769
+ if (tp.bif) { return bifAt(tp, sec); }
536
770
  var i = Math.min(tp.n - 1, Math.floor(sec * 1000 / tp.every)), per = tp.cols * tp.rows, at = i % per;
537
771
  if (tp.one) { return { url: tp.base + (i * tp.every) + tp.q, x: 0, y: 0, w: tp.w, h: tp.h, cols: 1, rows: 1 }; }
538
772
  return { url: tp.base + Math.floor(i / per) + tp.q, x: (at % tp.cols) * tp.w, y: Math.floor(at / tp.cols) * tp.h, w: tp.w, h: tp.h, cols: tp.cols, rows: tp.rows };
@@ -574,24 +808,25 @@ var Jellyfin = (function () {
574
808
  }
575
809
  function sourcesOf(srv, it) {
576
810
  if (!it || !it.Id) { return []; }
577
- return U.listOf(it.MediaSources, 8, function (ms) { return ms.Id; }).map(function (ms) { return source(srv, it, ms); });
811
+ return U.listOf(it.MediaSources, 16, function (ms) { return ms.Id; }).map(function (ms) { return source(srv, it, ms); });
578
812
  }
579
813
  function episodeSources(srv, sid, season, episode) {
580
814
  return episodes(srv, sid).then(function (eps) {
581
815
  var e = eps.filter(function (x) { return x.season === season && x.episode === episode; })[0];
582
- return e ? sourcesOf(srv, e.it) : [];
583
- }, none);
816
+ return e ? filesOf(srv, e.it) : [];
817
+ }).then(null, none);
584
818
  }
585
819
  // A title's sources: its own (jfm / jfs ids), or the servers' copies (of that kind: each
586
820
  // kind's addon asks for its own) of a title from your addons.
587
- function streams(type, id, kind) {
821
+ // meta: the title's details (its name: lookup).
822
+ function streams(type, id, kind, meta) {
588
823
  var x = parseId(id);
589
824
  if (x) {
590
825
  if (!x.srv) { return Promise.resolve([]); }
591
- if (x.kind === 'm') { return item(x.srv, x.item).then(function (it) { return sourcesOf(x.srv, it); }, none); }
826
+ if (x.kind === 'm') { return item(x.srv, x.item).then(function (it) { return filesOf(x.srv, it); }).then(null, none); }
592
827
  return x.season != null ? episodeSources(x.srv, x.item, x.season, x.episode) : Promise.resolve([]);
593
828
  }
594
- return copies(type, id, kind);
829
+ return copies(type, id, kind, meta);
595
830
  }
596
831
  function isJellyfinId(id) { return /^jf[ms]\./.test('' + id); }
597
832
  function nameOfId(id) { var x = parseId(id); return x && x.srv ? kindName(x.srv) : 'Jellyfin'; }
@@ -622,6 +857,7 @@ var Jellyfin = (function () {
622
857
  if (srv) { post(srv, K(srv).played(uid(srv), enc(jf.item)), null).then(null, function (e) { U.log('jellyfin', '“' + srv.name + '”: not marked played (' + U.problem(e) + ')'); }); }
623
858
  return;
624
859
  }
860
+ if (ev === 'stop') { dropBif(); } // (Emby's seek pictures: given up with the playback)
625
861
  if (_play && (!srv || _play.ctx !== ctx || _play.item !== jf.item || _play.ms !== jf.ms)) { stopNow(); } // (another playback, or another source)
626
862
  if (!srv || ev === 'stop') { if (ev === 'stop') { stopNow(cur); } return; }
627
863
  if (!_play) { _play = { ctx: ctx, srv: srv.id, item: jf.item, ms: jf.ms, sid: rand(32), started: false, sent: 0, paused: false, cur: 0 }; }
@@ -633,10 +869,10 @@ var Jellyfin = (function () {
633
869
  }
634
870
 
635
871
  return {
636
- servers: servers, server: server, isEnabled: isEnabled, onChange: onChange, normAddress: normAddress, addressProblem: addressProblem, probe: probe,
872
+ servers: servers, allServers: allServers, server: server, setOn: setOn, isEnabled: isEnabled, onChange: onChange, normAddress: normAddress, addressProblem: addressProblem, probe: probe,
637
873
  signIn: signIn, quickConnect: quickConnect, remove: remove, reload: reload, libraries: libsOf, synthAddon: synthAddon, synthAddons: synthAddons, kindsOn: kindsOn,
638
874
  kindName: kindName, nameOfId: nameOfId, catalog: catalog, meta: meta, streams: streams, isJellyfinId: isJellyfinId, onPlayer: onPlayer, resumeFor: resumeFor,
639
- segments: segments, trickplayAt: trickplayAt, sourceKind: sourceKind,
640
- shared: { chapterSegments: chapterSegments, namedChapters: namedChapters } // (Plex's chapters read the same way)
875
+ segments: segments, trickplayAt: trickplayAt, waitMs: waitMs, sourceKind: sourceKind, refreshMarks: refreshMarks, watchedAt: watchedAt,
876
+ shared: { chapterSegments: chapterSegments, namedChapters: namedChapters, marksFrom: marksFrom } // (Plex's chapters and watched marks read the same way)
641
877
  };
642
878
  })();