stremiok 2.3.2 → 2.3.4

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/player-core.js CHANGED
@@ -186,6 +186,7 @@ var PlayerParts = {};
186
186
  added: added || undefined };
187
187
  }
188
188
  writeProgress(all);
189
+ if (typeof StremioSync !== 'undefined' && StremioSync.onProgress) { StremioSync.onProgress(S.ctx, S.cur, S.dur, !fromTicker); } // (your Stremio account's place)
189
190
  }
190
191
  // What's saved to resume: a converted playback's own link (not the server's conversion), and a
191
192
  // torrent's infoHash, file and trackers (its link depends on the server set when it resumes).
@@ -401,7 +402,7 @@ var PlayerParts = {};
401
402
  // is what's learned from it (s.stream, through ctx.learnFor); the title, its episodes and
402
403
  // whether it's private stay.
403
404
  var SOURCE_FIELDS = ['url', 'variantUrl', 'initialQualityHeight', 'yt', 'ytLang', '_headers', 'localSubs', 'localFile', 'subExtra', 'sourceSubs', 'formatInfo', 'onStarted', 'onFailed', 'stream',
404
- '_reported', 'fromStart', 'resumeSec', 'switching', 'viaService', '_relay', '_relayFor', '_relayCc'];
405
+ '_reported', 'fromStart', 'resumeSec', 'switching', 'viaService', '_relay', '_relayFor', '_relayCc', '_relayFix'];
405
406
  // keep: a source that didn't start gives way to the next (nextSourceOnFail): the same place to
406
407
  // resume, and Play from the start as it was.
407
408
  function replaceSource(s, keep) {
@@ -954,6 +955,7 @@ var PlayerParts = {};
954
955
  if (loaded || !S.active || token !== _playToken) { return; }
955
956
  reportStart(false, 'TIMEOUT');
956
957
  U.spinner(false);
958
+ if (!drm) { U.log('player', 'Not played (the page’s video player): no start in ' + Math.round(HTML5_START_MS / 1000) + ' s (' + where(url) + ')'); }
957
959
  U.toast('This stream didn\'t start'); exitLater();
958
960
  }, drm ? SHAKA_START_MS : HTML5_START_MS);
959
961
  S.videoEl.onloadedmetadata = function () {
@@ -977,7 +979,11 @@ var PlayerParts = {};
977
979
  };
978
980
  S.videoEl.onerror = function () {
979
981
  if (!S.active || token !== _playToken || drm) { return; } // (Shaka's own errors: see shakaLoadInto)
980
- reportStart(false, S.videoEl.error && S.videoEl.error.code === 2 ? 'NETWORK' : 'MEDIA_ERR');
982
+ var me = S.videoEl.error, mcode = me ? me.code : 0;
983
+ reportStart(false, mcode === 2 ? 'NETWORK' : 'MEDIA_ERR');
984
+ // (the page's player says little: its code, and a message where the engine has one)
985
+ U.log('player', (loaded ? 'Stopped' : 'Not played') + ' (the page’s video player): ' + (['', 'aborted', 'a network error', 'the file couldn’t be decoded', 'a format or link it can’t play'][mcode] || 'an error') +
986
+ (me && me.message ? ' (' + me.message + ')' : '') + ' (' + where(url) + ')');
981
987
  U.toast('Playback error'); exitLater();
982
988
  };
983
989
  if (drm) {
@@ -1352,24 +1358,33 @@ var PlayerParts = {};
1352
1358
  // there, remembered for the channel, or in your default subtitle language), the channel plays
1353
1359
  // through the relay with them as subtitle tracks (ctx._relayCc), the sound as it is unless it
1354
1360
  // needs repacking too.
1355
- var LIVE_KEY = 'stremiok.livefix', LIVE_KEEP = 300, LIVE_DAYS = 14;
1361
+ // Your own choice for a channel (the audio menu: its sound straight from the server or repacked,
1362
+ // setLiveSound) is kept as its answer (mine), a year, over the look's.
1363
+ var LIVE_KEY = 'stremiok.livefix', LIVE_KEEP = 300, LIVE_DAYS = 14, LIVE_MINE_DAYS = 365;
1356
1364
  function liveFixable(ctx) {
1357
1365
  return useAV && S.isLive && !!ctx && !ctx.yt && !ctx.trailer && !(ctx.stream && ctx.stream._drm) && /^https?:\/\//i.test(ctx.url || '') &&
1358
1366
  typeof YTPlay !== 'undefined' && !!YTPlay.liveOpen && YTPlay.installMode() !== 'browser';
1359
1367
  }
1360
1368
  function liveKnown(url) {
1361
1369
  var k = (U.store.get(LIVE_KEY, {}) || {})[url];
1362
- return (k && Date.now() - k.at < LIVE_DAYS * 86400000) ? k : null;
1370
+ return (k && Date.now() - k.at < (k.mine ? LIVE_MINE_DAYS : LIVE_DAYS) * 86400000) ? k : null;
1363
1371
  }
1364
1372
  // The caption channels kept for a link: [{ ch: 'CC1', lang: 'en' }], or null (not known yet).
1365
1373
  function ccOf(k) {
1366
1374
  if (!k || !Array.isArray(k.cc)) { return null; }
1367
1375
  return k.cc.filter(function (c) { return c && /^CC[1-4]$/.test(c.ch) && (!c.lang || /^[a-z]{2,3}$/.test(c.lang)); }).slice(0, 4);
1368
1376
  }
1369
- function liveKeep(url, fix, cc) {
1370
- var all = U.store.get(LIVE_KEY, {}) || {};
1377
+ // hls: whether its sound can be repacked at all (HLS of plain MPEG-TS segments, or a raw MPEG-TS
1378
+ // stream: raw, with AAC sound, as the look found; not encrypted or fMP4 ones), kept with it,
1379
+ // with the look's version (lv: one kept by an older look is looked at again).
1380
+ var LIVE_LOOK = 2;
1381
+ function liveKeep(url, fix, cc, mine, hls, raw) {
1382
+ var all = U.store.get(LIVE_KEY, {}) || {}, prev = all[url];
1371
1383
  all[url] = { fix: fix ? 1 : 0, at: Date.now() };
1372
1384
  if (cc) { all[url].cc = cc; }
1385
+ if (mine || (prev && prev.mine && !!prev.fix === !!fix)) { all[url].mine = 1; } // (yours stays yours)
1386
+ if (hls !== undefined) { all[url].hls = hls ? 1 : 0; all[url].lv = LIVE_LOOK; if (raw) { all[url].raw = 1; } }
1387
+ else if (prev && prev.hls !== undefined) { all[url].hls = prev.hls; if (prev.lv) { all[url].lv = prev.lv; } if (prev.raw) { all[url].raw = 1; } }
1373
1388
  var keys = Object.keys(all);
1374
1389
  if (keys.length > LIVE_KEEP) {
1375
1390
  keys.sort(function (a, b) { return all[a].at - all[b].at; }).slice(0, keys.length - LIVE_KEEP).forEach(function (k) { delete all[k]; });
@@ -1386,11 +1401,42 @@ var PlayerParts = {};
1386
1401
  return cc.some(function (c) { return c.lang && langs.some(function (l) { return P.langMatches(l, c.lang); }); });
1387
1402
  }
1388
1403
  function ccIndex(cc, w) { for (var i = 0; i < cc.length; i++) { if (cc[i].ch === w.ch) { return i; } } return 0; }
1389
- function relayed(ctx, r, cc) {
1404
+ // fix: the sound repacked through it (not only captions).
1405
+ function relayed(ctx, r, cc, fix) {
1390
1406
  if (!r || typeof r.url !== 'string' || !/^http:\/\/localhost:\d+\/live\//.test(r.url)) { return false; }
1391
- ctx._relay = r.url; ctx._relayFor = ctx.url; ctx._relayCc = cc || null; ctx._ccOffer = cc ? null : ctx._ccOffer;
1407
+ ctx._relay = r.url; ctx._relayFor = ctx.url; ctx._relayCc = cc || null; ctx._ccOffer = cc ? null : ctx._ccOffer; ctx._relayFix = !!fix;
1392
1408
  return true;
1393
1409
  }
1410
+ // The audio menu's choice for a live channel (where its sound can be repacked: liveFixable):
1411
+ // null, or { repacked, mine }.
1412
+ // Only for a channel known to be repackable: an HLS link or format, or the look found HLS
1413
+ // segments (a raw MPEG-TS stream, an Xtream account's default, can't go through the relay).
1414
+ function liveSound() {
1415
+ var ctx = S.ctx;
1416
+ if (!S.active || !ctx || !liveFixable(ctx)) { return null; }
1417
+ var known = liveKnown(ctx.url);
1418
+ var hls = known && known.hls !== undefined ? known.hls === 1 : (HLS_LINK.test(ctx.url) || !!(ctx.formatInfo && ctx.formatInfo.container === 'hls'));
1419
+ if (!hls) { return null; }
1420
+ return { repacked: !!(ctx._relay && ctx._relayFix), mine: !!(known && known.mine) };
1421
+ }
1422
+ // Your choice: the channel again, its sound repacked by the service's relay or straight from
1423
+ // the server (captions through the relay stay), kept for it (liveKeep, mine).
1424
+ function setLiveSound(repack) {
1425
+ var ctx = S.ctx;
1426
+ if (!S.active || !ctx || !liveFixable(ctx)) { return; }
1427
+ var known = liveKnown(ctx.url), cc = ctx._relayCc || null, raw = !!(known && known.raw);
1428
+ liveKeep(ctx.url, repack, known ? ccOf(known) : null, true); // (its hls answer kept)
1429
+ U.log('player', 'Live sound ' + (repack ? 'repacked by StremioK\'s service' : 'straight from the server') + ': your choice for this channel');
1430
+ var msg = repack ? 'Repacking this channel’s sound…' : 'Playing the sound straight from the server…';
1431
+ if (!repack && !cc) { ctx._relay = null; ctx._relayFor = null; ctx._relayFix = false; reopen(msg); return; }
1432
+ function failed() { if (S.ctx === ctx && S.active) { U.toast('StremioK’s service didn’t answer: the sound stays as it was', 5000); } }
1433
+ YTPlay.liveOpen(ctx.url, ctx._headers, true, { fix: !!repack, cc: raw ? null : cc, raw: raw }).then(function (r) {
1434
+ if (S.ctx !== ctx || !S.active) { return; }
1435
+ if (!relayed(ctx, r, cc, repack)) { failed(); return; }
1436
+ reopen(msg);
1437
+ }, failed);
1438
+ }
1439
+ P.liveSound = liveSound; P.setLiveSound = setLiveSound;
1394
1440
  // HLS through StremioK's service (Settings › Playback › Seeking & buffering: 'off' | 'headers':
1395
1441
  // sources with their own User-Agent, Referer or Cookie | 'all'; or ctx.viaService, hold OK on a
1396
1442
  // source): the relay without the look, so every playlist and piece is fetched with the source's
@@ -1411,7 +1457,7 @@ var PlayerParts = {};
1411
1457
  var live = !!S.isLive, known = live && liveFixable(ctx) ? liveKnown(ctx.url) : null;
1412
1458
  YTPlay.liveOpen(ctx.url, ctx._headers, true, { fix: !!(known && known.fix), film: !live }).then(function (r) {
1413
1459
  if (S.ctx !== ctx || !S.active) { return; }
1414
- relayed(ctx, r, null);
1460
+ relayed(ctx, r, null, !!(known && known.fix));
1415
1461
  startAV(ctx.url, settle);
1416
1462
  }, function () { if (S.ctx === ctx && S.active) { startAV(ctx.url, settle); } });
1417
1463
  }
@@ -1422,9 +1468,9 @@ var PlayerParts = {};
1422
1468
  var withCc = ccWanted(ctx, cc) ? cc : null;
1423
1469
  if (cc) { ctx._liveChecked = true; } // (both answers in: not asked again)
1424
1470
  if (!known || (!known.fix && !withCc)) { startAV(ctx.url, settle); return; }
1425
- YTPlay.liveOpen(ctx.url, ctx._headers, true, { fix: !!known.fix, cc: withCc }).then(function (r) {
1471
+ YTPlay.liveOpen(ctx.url, ctx._headers, true, { fix: !!known.fix, cc: withCc, raw: !!known.raw }).then(function (r) {
1426
1472
  if (S.ctx !== ctx || !S.active) { return; }
1427
- relayed(ctx, r, withCc);
1473
+ relayed(ctx, r, withCc, !!known.fix);
1428
1474
  startAV(ctx.url, settle);
1429
1475
  }, function () { if (S.ctx === ctx && S.active) { startAV(ctx.url, settle); } });
1430
1476
  }
@@ -1439,7 +1485,7 @@ var PlayerParts = {};
1439
1485
  if (!ctx || ctx._liveChecked || !liveFixable(ctx)) { return; }
1440
1486
  ctx._liveChecked = true;
1441
1487
  var known = liveKnown(ctx.url);
1442
- if (known && ccOf(known)) { return; }
1488
+ if (known && ccOf(known) && known.lv === LIVE_LOOK) { return; } // (one kept by an older look: looked at again, once)
1443
1489
  var url = ctx.url;
1444
1490
  stopLiveLook();
1445
1491
  var look = _liveLook = U.cancelToken();
@@ -1447,11 +1493,12 @@ var PlayerParts = {};
1447
1493
  if (_liveLook === look) { _liveLook = null; }
1448
1494
  if (!r || !r.sure) { return; } // (couldn't tell: asked again next time)
1449
1495
  var cc = (r.ccSure || r.cc === undefined) ? (ccOf(r) || []) : null, fix = known ? !!known.fix : !!r.fix; // (captions with no text yet: asked again next time; the sound's answer: as first found)
1450
- liveKeep(url, fix, cc);
1496
+ var hls = !/not an HLS playlist|no variant|encrypted or fMP4|not MPEG-TS|no AAC sound|clock is on the sound/i.test(r.why || ''); // (repackable: its AAC sound reached)
1497
+ liveKeep(url, fix, cc, false, hls, !!r.raw);
1451
1498
  if (S.ctx !== ctx || !S.active || ctx.url !== url) { return; }
1452
1499
  if (cc && cc.length && !ctx._relayCc) { ctx._ccOffer = cc; }
1453
1500
  if (cc && cc.length && ccWanted(ctx, cc)) { ccOn(ctx, 'Adding this channel’s captions…'); return; }
1454
- if (known || !fix || ctx._relay || !relayed(ctx, r, null)) { return; } // (the sound: restarted for on its first look only)
1501
+ if (known || !fix || ctx._relay || !relayed(ctx, r, null, true)) { return; } // (the sound: restarted for on its first look only)
1455
1502
  U.log('player', 'Live sound repacked by StremioK\'s service (' + (r.why || '') + ')');
1456
1503
  reopen('Fixing this channel’s sound…');
1457
1504
  }, function () {});
@@ -1463,7 +1510,7 @@ var PlayerParts = {};
1463
1510
  var known = liveKnown(ctx.url), cc = ccOf(known) || ctx._ccOffer;
1464
1511
  if (!cc || !cc.length || !liveFixable(ctx)) { return Promise.resolve(false); }
1465
1512
  return YTPlay.liveOpen(ctx.url, ctx._headers, true, { fix: !!(known && known.fix), cc: cc }).then(function (r) {
1466
- if (S.ctx !== ctx || !S.active || !relayed(ctx, r, cc)) { return false; }
1513
+ if (S.ctx !== ctx || !S.active || !relayed(ctx, r, cc, !!(known && known.fix))) { return false; }
1467
1514
  var w = want || cc.filter(function (c) { return ccWanted(ctx, [c]); })[0] || null;
1468
1515
  U.log('player', 'Live captions through StremioK\'s service (' + cc.map(function (c) { return c.ch; }).join(', ') + ')');
1469
1516
  reopen(message);
@@ -1602,6 +1649,7 @@ var PlayerParts = {};
1602
1649
  shakaStop();
1603
1650
  try { S.videoEl.pause(); } catch (e3) {}
1604
1651
  S.videoEl.removeAttribute('src');
1652
+ try { S.videoEl.load(); } catch (e4) {} // (src removed alone doesn't release the file: it stayed loaded, playable behind the menus)
1605
1653
  S.videoEl.className = '';
1606
1654
  }
1607
1655
  useAV = hasAV; P.useAV = hasAV; // (the next playback the TV's player's, unless it's ClearKey too)
@@ -11,14 +11,16 @@
11
11
  var WATCHED_KEY = 'stremiok.watched';
12
12
  function watchedAll() { return U.store.get(WATCHED_KEY, {}) || {}; }
13
13
  // A mark made here: watched at (ms, > 0), or not watched at (−ms; false: an older "not
14
- // watched", at 0). Trakt's history (when connected) and your media servers' marks are weighed
15
- // against it by time: marked watched here: watched; marked not watched here: watched only if
16
- // Trakt or a server has it watched since (on another device); no mark here: as they have it.
14
+ // watched", at 0). Trakt's history (when connected), your Stremio account's and your media
15
+ // servers' marks are weighed against it by time: marked watched here: watched; marked not
16
+ // watched here: watched only if one of them has it watched since (on another device); no mark
17
+ // here: as they have it.
17
18
  // null: none knows it.
18
19
  function traktAt(type, id) {
19
20
  var t = (typeof Trakt !== 'undefined' && Trakt.isConnected && Trakt.isConnected() && Trakt.watchedAt) ? Trakt.watchedAt(type, id) : 0;
20
21
  var s = (typeof Jellyfin !== 'undefined' && Jellyfin.watchedAt) ? Jellyfin.watchedAt(type, id) : 0; // (Jellyfin, Emby and Plex: js/jellyfin.js)
21
- return Math.max(t || 0, s || 0);
22
+ var a = (typeof StremioSync !== 'undefined' && StremioSync.watchedAt) ? StremioSync.watchedAt(type, id) : 0; // (your Stremio account)
23
+ return Math.max(t || 0, s || 0, a || 0);
22
24
  }
23
25
  function watchedState(type, id) {
24
26
  var v = watchedAll()[type + ':' + id], t = traktAt(type, id);
@@ -43,12 +45,14 @@
43
45
  });
44
46
  return out;
45
47
  }
46
- // quiet: Trakt not told (it's been told another way: a finished scrobble)
48
+ // quiet: Trakt not told (it's been told another way: a finished scrobble); your Stremio
49
+ // account always is
47
50
  function setWatched(type, id, on, quiet) {
48
51
  var a = watchedAll();
49
52
  a[type + ':' + id] = on ? Date.now() : -Date.now();
50
53
  U.store.set(WATCHED_KEY, a);
51
54
  if (!quiet) { tellTrakt(type, [id], on); }
55
+ tellStremio(type, [id], on);
52
56
  }
53
57
  function setWatchedMany(type, ids, on) {
54
58
  var a = watchedAll();
@@ -56,7 +60,9 @@
56
60
  ids.forEach(function (id) { a[type + ':' + id] = value; });
57
61
  U.store.set(WATCHED_KEY, a);
58
62
  tellTrakt(type, ids, on);
63
+ tellStremio(type, ids, on);
59
64
  }
65
+ function tellStremio(type, ids, on) { if (typeof StremioSync !== 'undefined' && StremioSync.onMarked) { StremioSync.onMarked(type, ids, !!on); } }
60
66
  // A "not watched" Trakt has confirmed (and its copy shows): dropped here, so Trakt decides.
61
67
  function clearUnwatched(type, id) {
62
68
  var a = watchedAll(), k = type + ':' + id, v = a[k];
@@ -158,6 +164,7 @@
158
164
  if (all[k]) { all[k].added = true; }
159
165
  else { all[k] = { id: e.id, type: e.type, name: e.name, poster: e.poster, background: e.background, parent: e.parent, position: 0, duration: 0, updated: Date.now(), added: true }; }
160
166
  U.store.set(PROGRESS_KEY, all);
167
+ if (typeof StremioSync !== 'undefined' && StremioSync.onAdded) { StremioSync.onAdded(e); } // (your Stremio account's too, at its start)
161
168
  }
162
169
 
163
170
  function progressFor(type, id) { return progressAll()[type + ':' + id] || null; }
package/js/plex.js CHANGED
@@ -21,7 +21,7 @@ var Plex = (function () {
21
21
 
22
22
  var KEY = 'stremiok.plex.servers', DEV_KEY = 'stremiok.plex.device', LIBS_KEY = 'stremiok.plex.libs';
23
23
  var TV = 'https://clients.plex.tv', LINK = 'https://plex.tv/link';
24
- var PAGE = 100, INDEX_FRESH_MS = 30 * 60000, INDEX_RETRY_MS = 60000, LIBS_FRESH_MS = 86400000;
24
+ var PAGE = 100, INDEX_FRESH_MS = 30 * 60000, INDEX_RETRY_MS = 60000, INDEX_SLOW_MS = 30 * 60000, LIBS_FRESH_MS = 86400000;
25
25
  var PIN_EVERY = 3000, PIN_FOR = 10 * 60000, REPORT_EVERY = 60000, PIC_EVERY = 5000;
26
26
  var _changeFns = [];
27
27
  function onChange(fn) { _changeFns.push(fn); }
@@ -384,9 +384,16 @@ var Plex = (function () {
384
384
  var x = _index[srv.id];
385
385
  if (x && x.map && (x.p || Date.now() - x.at < INDEX_FRESH_MS)) { return Promise.resolve(x.map); }
386
386
  if (x && x.p) { return x.p; }
387
+ // (each library a page at a time, as Jellyfin's list: Jellyfin.shared.pages; one not all
388
+ // read, or not at all after its first page: __part, its titles looked up by name too)
389
+ var part = null;
387
390
  var p = Promise.all(libsOf(srv).map(function (lib) {
388
- return get(srv, '/library/sections/' + enc(lib.id) + '/all?type=' + (lib.type === 'movie' ? 1 : 2) + '&includeGuids=1', 16 * 1048576).then(function (r) {
389
- return U.listOf(mc(r).Metadata, 100000).map(function (it) { return { t: lib.type, it: it }; });
391
+ return share().pages(function (start) {
392
+ return get(srv, '/library/sections/' + enc(lib.id) + '/all?type=' + (lib.type === 'movie' ? 1 : 2) + '&includeGuids=1&sort=titleSort' +
393
+ '&X-Plex-Container-Start=' + start + '&X-Plex-Container-Size=' + share().INDEX_PAGE, 8 * 1048576).then(function (r) { return U.listOf(mc(r).Metadata, share().INDEX_PAGE); });
394
+ }).then(function (got) {
395
+ if (got.part) { part = part && part.e ? part : got.part; }
396
+ return got.items.map(function (it) { return { t: lib.type, it: it }; });
390
397
  });
391
398
  })).then(function (lists) {
392
399
  var map = { __ids: {}, __tm: {}, __played: [] }; // (__played: its watched films and shows)
@@ -399,12 +406,22 @@ var Plex = (function () {
399
406
  var played = e.t === 'movie' ? +it.viewCount > 0 : +it.leafCount > 0 && +it.viewedLeafCount >= +it.leafCount;
400
407
  if (played) { map.__played.push({ t: e.t, ids: titleIds(map, (e.t === 'movie' ? 'pxm.' : 'pxs.') + srv.id + '.', rk), at: (+it.lastViewedAt || 0) * 1000 }); }
401
408
  });
402
- if (_index[srv.id] && _index[srv.id].p === p) { _index[srv.id] = { at: Date.now(), map: map }; }
409
+ var at = Date.now();
410
+ if (part) {
411
+ map.__part = true;
412
+ if (part.e) {
413
+ U.log('plex', '“' + srv.name + '”: only some of its titles read (' + U.problem(part.e) + ')');
414
+ at -= INDEX_FRESH_MS - (/Timed out/i.test(part.e.message || '') ? INDEX_SLOW_MS : INDEX_RETRY_MS);
415
+ }
416
+ }
417
+ if (_index[srv.id] && _index[srv.id].p === p) { _index[srv.id] = { at: at, map: map }; }
403
418
  return map;
404
419
  }, function (e) {
405
420
  U.log('plex', '“' + srv.name + '”: its titles couldn’t be read (' + U.problem(e) + ')');
406
421
  var old = _index[srv.id], map = (old && old.map) || { __ids: {}, __tm: {}, __played: [], __err: true };
407
- if (old && old.p === p) { _index[srv.id] = { at: Date.now() - INDEX_FRESH_MS + INDEX_RETRY_MS, map: map }; }
422
+ // (asked again in a minute; one that timed out, after 30: titles looked up by name meanwhile, idsFor)
423
+ var slow = /Timed out/i.test((e && e.message) || '');
424
+ if (old && old.p === p) { _index[srv.id] = { at: Date.now() - INDEX_FRESH_MS + (slow ? INDEX_SLOW_MS : INDEX_RETRY_MS), map: map }; }
408
425
  return map;
409
426
  });
410
427
  _index[srv.id] = { at: x ? x.at : 0, map: x ? x.map : null, p: p };
@@ -438,7 +455,37 @@ var Plex = (function () {
438
455
  return sh.marksFrom(list);
439
456
  });
440
457
  }
441
- function copies(type, id) {
458
+ // A title the server's list can't give (never read, or not all of it: a library too big or slow):
459
+ // searched for by its name in each library of its kind, taken only when its IMDb or TMDB id is
460
+ // the one asked for (Jellyfin's way). Kept FOUND_MS (a failed search: asked again next time).
461
+ var FOUND_MS = 30 * 60000, _found = U.lru(300);
462
+ function lookup(srv, type, key, name) {
463
+ name = ('' + (name || '')).replace(/\s+/g, ' ').trim().slice(0, 100);
464
+ if (!name) { return Promise.resolve([]); }
465
+ var k = srv.id + '|' + type + '|' + key, had = _found.get(k);
466
+ if (had && had.p && Date.now() - had.at < FOUND_MS) { return had.p; }
467
+ var p = Promise.all(libsOf(srv).filter(function (l) { return l.type === type; }).map(function (lib) {
468
+ return get(srv, '/library/sections/' + enc(lib.id) + '/all?type=' + (type === 'movie' ? 1 : 2) + '&includeGuids=1&title=' + enc(name) +
469
+ '&X-Plex-Container-Start=0&X-Plex-Container-Size=40').then(function (r) {
470
+ return U.listOf(mc(r).Metadata, 40, function (it) { return it && it.ratingKey != null && (imdbOf(it) === key || (!!tmdbOf(it) && 'tmdb:' + tmdbOf(it) === key)); }).map(function (it) { return '' + it.ratingKey; });
471
+ });
472
+ })).then(flat, function (e) {
473
+ _found.set(k, null);
474
+ U.log('plex', '“' + srv.name + '”: “' + name + '” couldn’t be looked up (' + U.problem(e) + ')');
475
+ return [];
476
+ });
477
+ _found.set(k, { at: Date.now(), p: p });
478
+ return p;
479
+ }
480
+ // The server's items for a title: from its list; with no list yet, none to be had or not all of
481
+ // it, looked up by name meanwhile, the list's answer used when that finds none.
482
+ function idsFor(srv, type, key, name) {
483
+ var x = _index[srv.id];
484
+ var fromList = index(srv).then(function (map) { return map[type + '|' + key] || []; });
485
+ if (x && x.map && !x.map.__err && !x.map.__part) { return fromList; }
486
+ return lookup(srv, type, key, name).then(function (ids) { return ids.length ? ids : fromList; });
487
+ }
488
+ function copies(type, id, meta) {
442
489
  var key = '', season = null, episode = null;
443
490
  if (type === 'movie') { key = /^(tt\d+|tmdb:\d+)$/.test('' + id) ? '' + id : ''; }
444
491
  else if (type === 'series') {
@@ -446,9 +493,10 @@ var Plex = (function () {
446
493
  if (mm) { key = mm[1]; season = +mm[2]; episode = +mm[3]; }
447
494
  }
448
495
  if (!key) { return Promise.resolve([]); }
496
+ var name = meta && typeof meta.name === 'string' ? meta.name : '';
449
497
  return Promise.all(servers().map(function (srv) {
450
- return index(srv).then(function (map) {
451
- return Promise.all((map[type + '|' + key] || []).slice(0, 3).map(function (rk) {
498
+ return idsFor(srv, type, key, name).then(function (rks) {
499
+ return Promise.all(rks.slice(0, 3).map(function (rk) {
452
500
  return type === 'movie' ? item(srv, rk).then(function (it) { return sourcesOf(srv, it); }, none) : episodeSources(srv, rk, season, episode);
453
501
  }));
454
502
  }).then(flat, none);
@@ -527,14 +575,14 @@ var Plex = (function () {
527
575
  return e ? item(srv, e.it.ratingKey).then(function (it) { return sourcesOf(srv, it); }, none) : [];
528
576
  }, none);
529
577
  }
530
- function streams(type, id) {
578
+ function streams(type, id, meta) { // (meta: the title's details, for its name: lookup)
531
579
  var x = parseId(id);
532
580
  if (x) {
533
581
  if (!x.srv) { return Promise.resolve([]); }
534
582
  if (x.kind === 'm') { return item(x.srv, x.item).then(function (it) { return sourcesOf(x.srv, it); }, none); }
535
583
  return x.season != null ? episodeSources(x.srv, x.item, x.season, x.episode) : Promise.resolve([]);
536
584
  }
537
- return copies(type, id);
585
+ return copies(type, id, meta);
538
586
  }
539
587
  function isPlexId(id) { return /^px[ms]\./.test('' + id); }
540
588
 
@@ -4,6 +4,7 @@
4
4
  seconds, it then gives a sign-in key (start, wait). With it the account's addons are read
5
5
  (addons) and the key is given up at once (signOut): no password on the TV, nothing of the
6
6
  account kept, the account itself unchanged. StremioK has no key of Stremio's: none is needed.
7
+ Keeping your account in step (js/stremio-sync.js) signs in the same way and keeps the key.
7
8
  Global namespace: StremioAccount */
8
9
  var StremioAccount = (function () {
9
10
  'use strict';
@@ -35,24 +36,28 @@ var StremioAccount = (function () {
35
36
  setTimeout(ask, POLL_MS);
36
37
  });
37
38
  }
38
- // POST a request to Stremio's API: its result.
39
- function call(method, body) {
39
+ // POST a request to Stremio's API: its result (an answer over max, MAX_BYTES unless given,
40
+ // refused). A refusal's Error carries Stremio's code (1: the sign-in no longer works).
41
+ function call(method, body, max) {
42
+ max = max || MAX_BYTES;
40
43
  return new Promise(function (resolve, reject) {
41
44
  var xhr = new XMLHttpRequest(), done = false;
42
45
  try { xhr.open('POST', API + method, true); } catch (e) { reject(new Error('couldn’t reach Stremio')); return; }
43
46
  xhr.timeout = 20000;
44
47
  xhr.setRequestHeader('Content-Type', 'application/json');
45
48
  xhr.onprogress = function (ev) { // (an answer over MAX_BYTES: stopped as it arrives, as every other request is)
46
- if (!done && ev && ev.loaded > MAX_BYTES) { done = true; try { xhr.abort(); } catch (e) {} reject(new Error('too large an answer')); }
49
+ if (!done && ev && ev.loaded > max) { done = true; try { xhr.abort(); } catch (e) {} reject(new Error('too large an answer')); }
47
50
  };
48
51
  xhr.onreadystatechange = function () {
49
52
  if (xhr.readyState !== 4 || done) { return; }
50
53
  done = true;
51
54
  var text = '' + (xhr.responseText || ''), data = null;
52
- if (text.length > MAX_BYTES) { reject(new Error('too large an answer')); return; }
55
+ if (text.length > max) { reject(new Error('too large an answer')); return; }
53
56
  try { data = JSON.parse(text); } catch (e2) { data = null; }
54
57
  if (xhr.status >= 200 && xhr.status < 300 && data && data.result) { resolve(data.result); return; }
55
- reject(new Error((data && data.error && data.error.message) || ('HTTP ' + xhr.status)));
58
+ var err = new Error((data && data.error && data.error.message) || ('HTTP ' + xhr.status));
59
+ err.code = (data && data.error && typeof data.error.code === 'number') ? data.error.code : 0;
60
+ reject(err);
56
61
  };
57
62
  xhr.ontimeout = function () { if (!done) { done = true; reject(new Error('Stremio didn’t answer')); } };
58
63
  xhr.onerror = function () { if (!done) { done = true; reject(new Error('couldn’t reach Stremio')); } };
@@ -75,5 +80,5 @@ var StremioAccount = (function () {
75
80
  // The key given up (Stremio's own sign-out): whatever happens, nothing is kept here.
76
81
  function signOut(key) { return call('logout', { type: 'Logout', authKey: key }).then(function () {}, function () {}); }
77
82
 
78
- return { start: start, wait: wait, addons: addons, signOut: signOut };
83
+ return { start: start, wait: wait, addons: addons, signOut: signOut, call: call };
79
84
  })();