stremiok 2.2.1 → 2.2.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/iptv.js CHANGED
@@ -30,6 +30,7 @@ var IPTV = (function () {
30
30
  if (typeof p.name === 'string' && p.name.trim()) { o.name = p.name.trim().slice(0, NAME_MAX); }
31
31
  if (p.off === true) { o.off = true; }
32
32
  if (typeof p.guide === 'string' && U.parseUrl(p.guide)) { o.guide = p.guide; } // (its TV guide, yours: see EPG.guideUrl)
33
+ if (macOf(p.mac)) { o.mac = macOf(p.mac); } // (a Stalker portal: see addStalker)
33
34
  return o;
34
35
  });
35
36
  }
@@ -185,6 +186,45 @@ var IPTV = (function () {
185
186
  return id;
186
187
  }
187
188
 
189
+ // ---- A Stalker portal: its address and the MAC address your provider registered ----
190
+ // Read by StremioK's service, which asks as a MAG box does (YTPlay.stalkerList): its channels
191
+ // come as an M3U playlist, and a channel's link is asked for each time it plays (streams). Saved
192
+ // as a playlist with its MAC ({ url: the portal, mac }).
193
+ var STB_UA = 'Mozilla/5.0 (QtEmbedded; U; Linux; C) AppleWebKit/533.3 (KHTML, like Gecko) MAG200 stbapp ver: 2 rev: 250 Safari/533.3';
194
+ // A MAC address as typed (00:1A:79:12:34:56, with dashes, or none): 00:1A:79:12:34:56, or ''.
195
+ function macOf(v) {
196
+ var h = ('' + (v || '')).trim().toUpperCase().replace(/[:\-.\s]/g, '');
197
+ return /^[0-9A-F]{12}$/.test(h) ? h.match(/../g).join(':') : '';
198
+ }
199
+ // The portal as typed (http:// when it has no scheme): its address, or ''.
200
+ function stalkerPortal(v) {
201
+ var s = ('' + (v || '')).trim();
202
+ if (s && !/^[a-z][a-z0-9+.-]*:\/\//i.test(s)) { s = 'http://' + s.replace(/^\/+/, ''); }
203
+ return checkedUrl(s);
204
+ }
205
+ function isStalker(p) { return !!(p && p.mac); }
206
+ // Checked through the service (its channels read): { ok, count }, { refused, why },
207
+ // { unreachable, why } or { noService } (a desktop browser).
208
+ function stalkerCheck(portal, mac) {
209
+ if (typeof YTPlay === 'undefined' || !YTPlay.stalkerList) { return Promise.resolve({ noService: true }); }
210
+ return YTPlay.stalkerList(portal, mac).then(function (r) {
211
+ if (r && typeof r.m3u === 'string') { return { ok: true, count: r.count || 0 }; }
212
+ return r && r.refused ? { refused: true, why: '' + (r.why || '') } : { unreachable: true, why: '' + ((r && r.why) || '') };
213
+ }, function (e) { return /no service/.test((e && e.message) || '') ? { noService: true } : { unreachable: true, why: U.problem(e) }; });
214
+ }
215
+ // Added (named after its server: "Stalker · portal.example.com"), or the one already there with
216
+ // that portal and MAC. Its id.
217
+ function addStalker(portal, mac) {
218
+ portal = stalkerPortal(portal); mac = macOf(mac);
219
+ if (!portal || !mac) { return false; }
220
+ var list = getPlaylists();
221
+ for (var i = 0; i < list.length; i++) { if (list[i].url === portal && list[i].mac === mac) { return list[i].id; } }
222
+ var id = newId(), u = U.parseUrl(portal);
223
+ list.push({ id: id, url: portal, mac: mac, name: freeName('Stalker · ' + (u ? u.host : 'portal'), list) });
224
+ savePlaylists(list);
225
+ return id;
226
+ }
227
+
188
228
  function updatePlaylist(id, url) {
189
229
  url = checkedUrl(url);
190
230
  if (!url) { return false; }
@@ -249,6 +289,10 @@ var IPTV = (function () {
249
289
  if (n === 'user-agent') { c.ua = v; } else if (n === 'referer' || n === 'referrer') { c.ref = v; }
250
290
  }
251
291
 
292
+ // A link to a file, not a stream: a film or an episode (an Xtream account's /movie/… and
293
+ // /series/… links, or a video file's name), played as one (seeking; see Player's isLive).
294
+ var VOD_LINK = /\.(mkv|mp4|m4v|avi|mov|wmv|mpg|mpeg|webm)(?:[?#]|$)/i;
295
+ var XTREAM_VOD = /^https?:\/\/[^\/]+(?:\/[^?#]*)?\/(movie|series)\/[^\/?#]+\/[^\/?#]+\/\d+\.[a-z0-9]{2,4}(?:[?#]|$)/i;
252
296
  function truthy(v) { return /^(?:1|true|yes)$/i.test(('' + (v || '')).trim()); }
253
297
 
254
298
  function audioUrl(u) {
@@ -328,6 +372,7 @@ var IPTV = (function () {
328
372
  cur._yt =
329
373
  /^https?:\/\/(?:[^\/]+\.)?youtube\.com(?::\d+)?(?:\/|$)/i.test(u) ||
330
374
  /^https?:\/\/youtu\.be(?::\d+)?(?:\/|$)/i.test(u);
375
+ if (VOD_LINK.test(u) || XTREAM_VOD.test(u)) { cur.vod = true; } // (a film's file: played as one, see plainStreams)
331
376
  add(cur);
332
377
  }
333
378
  cur = null;
@@ -427,8 +472,9 @@ var IPTV = (function () {
427
472
  var st = { id: playlist.id, url: playlist.url, count: 0, groups: 0, error: '', uncached: false, title: '', fetchedAt: 0, stale: false };
428
473
  _status[playlist.id] = st;
429
474
  if (/^http:/i.test(playlist.url)) { // (Settings › Diagnostics › Logs)
430
- U.log('iptv', 'Playlist “' + label(playlist) + '” is downloaded over unencrypted http:// — anyone on the network path can see or change it (and any username / password in its link)');
475
+ U.log('iptv', 'Playlist “' + label(playlist) + '” is downloaded over unencrypted http:// — anyone on the network path can see or change it (and ' + (isStalker(playlist) ? 'its MAC address' : 'any username / password in its link') + ')');
431
476
  }
477
+ var src = playlist.url + (playlist.mac ? '#mac=' + playlist.mac : ''); // (its saved copy: this portal and MAC's)
432
478
 
433
479
  function finish(text, at) {
434
480
  st.fetchedAt = at || 0;
@@ -437,7 +483,13 @@ var IPTV = (function () {
437
483
  st.title = r.title || '';
438
484
  st.guides = r.guides || [];
439
485
  _sources = null;
440
- return counted(tagChannels(r.channels, playlist.id));
486
+ // An Xtream account's films and episodes: its Movies and Series (js/xtvod.js), not channels
487
+ var channels = r.channels;
488
+ if (isXtream(playlist.url) && typeof XtVod !== 'undefined' && XtVod.hidesVodLines && XtVod.hidesVodLines(playlist.id)) {
489
+ channels = channels.filter(function (c) { return !XTREAM_VOD.test(c.url); });
490
+ st.vodLines = r.channels.length - channels.length;
491
+ }
492
+ return counted(tagChannels(channels, playlist.id));
441
493
  });
442
494
  }
443
495
  function counted(channels) {
@@ -445,7 +497,7 @@ var IPTV = (function () {
445
497
  channels.forEach(function (c) { groups[c.type + '|' + c.group] = 1; });
446
498
  st.count = channels.length;
447
499
  st.groups = Object.keys(groups).length;
448
- if (!channels.length && !st.error) {
500
+ if (!channels.length && !st.error && !st.vodLines) {
449
501
  st.error = 'No channels parsed (is the URL returning the .m3u file?)';
450
502
  }
451
503
  return channels;
@@ -453,13 +505,23 @@ var IPTV = (function () {
453
505
 
454
506
  var saved = force ? Promise.resolve(null) : readPersist(playlist.id);
455
507
  return saved.then(function (p) {
456
- if (p && p.url === playlist.url && typeof p.text === 'string') { return finish(p.text, p.at); }
508
+ if (p && p.url === src && typeof p.text === 'string') { return finish(p.text, p.at); }
457
509
  return fetchIt();
458
510
  });
511
+ // A Stalker portal's channels, from the service (see stalkerCheck): its M3U text.
512
+ function stalkerText() {
513
+ if (typeof YTPlay === 'undefined' || !YTPlay.stalkerList) { return Promise.reject(new Error('Stalker portals are read by StremioK’s service (not in a desktop browser)')); }
514
+ return YTPlay.stalkerList(playlist.url, playlist.mac).then(function (r) {
515
+ if (r && typeof r.m3u === 'string') { return r.m3u; }
516
+ throw new Error((r && r.refused ? 'The portal refused it: ' : 'Couldn’t read the portal: ') + ((r && r.why) || 'no answer'));
517
+ }, function (e) {
518
+ throw new Error(/no service/.test((e && e.message) || '') ? 'Stalker portals are read by StremioK’s service (not in a desktop browser)' : 'Couldn’t reach StremioK’s service: ' + U.problem(e));
519
+ });
520
+ }
459
521
  function fetchIt() {
460
- return U.getText(playlist.url, 15000, PLAYLIST_MAX).then(function (text) {
522
+ return (isStalker(playlist) ? stalkerText() : U.getText(playlist.url, 15000, PLAYLIST_MAX)).then(function (text) {
461
523
  var at = Date.now();
462
- return writePersist(playlist.id, playlist.url, text, at).then(function (ok) {
524
+ return writePersist(playlist.id, src, text, at).then(function (ok) {
463
525
  st.uncached = !ok;
464
526
  return finish(text, at);
465
527
  });
@@ -467,14 +529,14 @@ var IPTV = (function () {
467
529
  var msg = (e && e.message) ? e.message : 'Could not fetch the playlist URL';
468
530
  // status 0 / network error on a URL that opens fine in a browser almost
469
531
  // always means the server sent no Access-Control-Allow-Origin header.
470
- if (/HTTP 0\b/.test(msg) || /Network error/i.test(msg)) {
532
+ if (!isStalker(playlist) && (/HTTP 0\b/.test(msg) || /Network error|^No answer/i.test(msg))) {
471
533
  msg += ' — the playlist server likely isn\'t sending an ' +
472
534
  'Access-Control-Allow-Origin header (CORS). Serve the .m3u with CORS enabled.';
473
535
  }
474
536
  st.error = msg;
475
537
  // Fall back to this playlist's saved copy so a failed refresh doesn't wipe it.
476
538
  return readPersist(playlist.id).then(function (prev) {
477
- if (!(prev && prev.url === playlist.url && typeof prev.text === 'string')) { return []; }
539
+ if (!(prev && prev.url === src && typeof prev.text === 'string')) { return []; }
478
540
  st.stale = true; // (the channels are the saved copy's)
479
541
  return finish(prev.text, prev.at);
480
542
  });
@@ -544,6 +606,19 @@ var IPTV = (function () {
544
606
  return d;
545
607
  });
546
608
  }
609
+ // Auto-refresh (Settings › Content › IPTV): every this many hours (0: Off), all playlists and
610
+ // their guides downloaded again, as Reload does (the Home ticker: see view-home's
611
+ // iptvRefreshTick). EVERY: the choices.
612
+ var EVERY_KEY = 'stremiok.iptv.every', EVERY = [0, 1, 3, 6, 12];
613
+ function refreshEvery() { var h = +U.store.get(EVERY_KEY, 0); return EVERY.indexOf(h) !== -1 ? h : 0; }
614
+ function setRefreshEvery(h) { h = +h; U.store.set(EVERY_KEY, EVERY.indexOf(h) !== -1 ? h : 0); }
615
+ // When the playlists switched on were last downloaded: the oldest of them (a saved copy's own
616
+ // date), 0 when one never was.
617
+ function readAt() {
618
+ var on = getPlaylists().filter(function (p) { return !p.off; }), t = Infinity;
619
+ on.forEach(function (p) { var st = _status[p.id]; t = Math.min(t, st && st.fetchedAt ? st.fetchedAt : 0); });
620
+ return on.length ? t : Infinity;
621
+ }
547
622
  function status(id) {
548
623
  if (id) { return _status[id] || { id: id, url: '', count: 0, groups: 0, error: '', title: '', fetchedAt: 0 }; }
549
624
  return _status;
@@ -616,6 +691,8 @@ var IPTV = (function () {
616
691
  if (c._yt) {
617
692
  return [{ url: c.url, _yt: true, ytPage: c.url, name: c.name, title: 'YouTube · ' + c.group }];
618
693
  }
694
+ var list = getPlaylists(), pl = list[find(list, c._playlistId)];
695
+ if (isStalker(pl)) { return stalkerStreams(c, pl); }
619
696
  return youTubeEnd(c.url).then(function (page) {
620
697
  if (page) { return [{ url: page, _yt: true, ytPage: page, name: c.name, title: 'YouTube · ' + c.group }]; }
621
698
  return plainStreams(c);
@@ -625,11 +702,31 @@ var IPTV = (function () {
625
702
  function plainStreams(c) {
626
703
  var from = sourceOf(c);
627
704
  var st = { url: c.url, name: c.name, title: 'IPTV · ' + c.group + (from ? ' · ' + from : '') };
705
+ if (c.vod) { st._vod = true; }
628
706
  var h = U.sanitizeHeaders({ ua: c.ua, ref: c.ref }); // (only what the player takes, checked)
629
707
  if (h) { st._headers = h; }
630
708
  return [st];
631
709
  }
632
710
 
711
+ // A Stalker portal's channel: its link asked for now (create_link: most portals' links work for
712
+ // a short while, or once), played with a MAG User-Agent. None given: the one in its playlist,
713
+ // unless that's a stand-in (http://localhost/ch/…), which plays nothing.
714
+ function stalkerStreams(c, pl) {
715
+ var asked = typeof YTPlay !== 'undefined' && YTPlay.stalkerLink ? YTPlay.stalkerLink(pl.url, pl.mac, c.url) : Promise.reject(new Error('no service'));
716
+ return asked.then(function (r) {
717
+ if (r && r.url) { return r.url; }
718
+ U.log('iptv', 'Stalker: no link for “' + c.name + '” (' + ((r && r.why) || 'no answer') + ')');
719
+ return '';
720
+ }, function (e) { U.log('iptv', 'Stalker: no link for “' + c.name + '” (' + U.problem(e) + ')'); return ''; }).then(function (url) {
721
+ if (!url && /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?\//i.test(c.url)) { return []; }
722
+ var st = plainStreams(c)[0];
723
+ st.url = url || c.url;
724
+ var h = U.sanitizeHeaders({ ua: STB_UA, ref: c.ref });
725
+ if (h) { st._headers = h; }
726
+ return [st];
727
+ });
728
+ }
729
+
633
730
  // A local addon object shaped like the HTTP addons in Stremio.loadAddons().
634
731
  // `__local` tells Stremio to route resource calls here instead of over HTTP.
635
732
  function synthAddon() {
@@ -648,8 +745,9 @@ var IPTV = (function () {
648
745
  getPlaylists: getPlaylists, addPlaylist: addPlaylist, updatePlaylist: updatePlaylist,
649
746
  removePlaylist: removePlaylist, renamePlaylist: renamePlaylist, setPlaylistOff: setPlaylistOff,
650
747
  movePlaylist: movePlaylist, setPlaylistGuide: setPlaylistGuide, label: labelOf,
748
+ macOf: macOf, stalkerPortal: stalkerPortal, stalkerCheck: stalkerCheck, addStalker: addStalker, isStalker: isStalker,
651
749
  xtreamParts: xtreamParts, xtreamUrl: xtreamUrl, xtreamCheck: xtreamCheck, addXtream: addXtream, xtreamFormat: xtreamFormat, setXtreamFormat: setXtreamFormat,
652
- isFavorite: isFavorite, setFavorite: setFavorite,
750
+ isFavorite: isFavorite, setFavorite: setFavorite, refreshEvery: refreshEvery, setRefreshEvery: setRefreshEvery, readAt: readAt,
653
751
  channels: function () { return _cache ? _cache.channels : []; }, channel: function (id) { return _cache ? _cache.byId[id] || null : null; }, isEnabled: isEnabled, reset: reset, status: status,
654
752
  load: load, reload: reload, catalog: catalog, meta: meta, streams: streams, synthAddon: synthAddon, isReady: isReady,
655
753
  onProgress: onProgress
package/js/player-core.js CHANGED
@@ -128,7 +128,7 @@ var PlayerParts = {};
128
128
  saveProgress();
129
129
  // (where you stopped to Trakt; past 80% nothing: Trakt takes no paused place there, and you
130
130
  // may come back)
131
- if (!S.isLive && !_creditsHandled && S.ctx && !S.ctx.trailer && !S.ctx.private && !isNotice() && S.cur > 60 && typeof Trakt !== 'undefined' && Trakt.onProgress &&
131
+ if (!S.isLive && !_creditsHandled && S.ctx && !S.ctx.trailer && !S.ctx.private && !isNotice() && !/^iptv:/.test(S.ctx.id || '') && S.cur > 60 && typeof Trakt !== 'undefined' && Trakt.onProgress &&
132
132
  !(S.dur > 0 && S.cur / S.dur >= 0.8)) {
133
133
  Trakt.onProgress(S.ctx.type, S.ctx.id, S.cur, S.dur, S.ctx.name);
134
134
  }
@@ -157,14 +157,14 @@ var PlayerParts = {};
157
157
 
158
158
  function isActive() { return S.active; }
159
159
 
160
- // fromTicker: the 5-second save while it plays: skipped when nothing moved since the last one
161
- // (paused); a stop, a leave or a jump always saves.
162
- var _savedSig = '';
160
+ // fromTicker: the save while it plays, at most every SAVE_EVERY_MS: skipped when nothing moved
161
+ // since the last one (paused); a stop, a leave or a jump always saves.
162
+ var _savedSig = '', _savedAt = 0, SAVE_EVERY_MS = 60000;
163
163
  function saveProgress(fromTicker) {
164
- if (!S.ctx || !S.dur || S.isLive || S.ctx.trailer || S.ctx.private || isNotice()) { return; } // (a notice clip, private viewing: nothing saved, nothing removed)
164
+ if (!S.ctx || !S.dur || S.isLive || S.ctx.trailer || S.ctx.private || isNotice() || /^iptv:/.test(S.ctx.id || '')) { return; } // (a notice clip, private viewing, a film in a playlist: nothing saved, nothing removed)
165
165
  var sig = progressKey(S.ctx) + '|' + Math.floor(S.cur) + '|' + Math.floor(S.dur);
166
- if (fromTicker && sig === _savedSig) { return; }
167
- _savedSig = sig;
166
+ if (fromTicker && (sig === _savedSig || Date.now() - _savedAt < SAVE_EVERY_MS)) { return; }
167
+ _savedSig = sig; _savedAt = Date.now();
168
168
  // Past the credits the episode is watched: its entry was removed and the next one
169
169
  // queued (handleCredits). Saving again would put it back next to the next episode.
170
170
  if (_creditsHandled) { return; }
@@ -178,12 +178,20 @@ var PlayerParts = {};
178
178
  } else {
179
179
  all[k] = { id: S.ctx.id, type: S.ctx.type, name: S.ctx.name, poster: S.ctx.poster, background: S.ctx.background, parent: S.ctx.parent,
180
180
  position: Math.floor(S.cur), duration: Math.floor(S.dur), updated: Date.now(),
181
- url: S.ctx.yt || S.ctx.url, headers: S.ctx._headers, // the exact stream, to resume it directly (YouTube: its page)
181
+ url: S.ctx.yt || savedUrl(S.ctx), headers: S.ctx._headers, // the exact stream, to resume it directly (YouTube: its page)
182
+ torrent: torrentOf(S.ctx.stream), // (through a streaming server: its link made again from the one set then)
182
183
  fileHints: (P.fileHints && P.fileHints(S.ctx.subExtra)) || undefined, // (its file, for subtitles made for it)
183
184
  added: added || undefined };
184
185
  }
185
186
  writeProgress(all);
186
187
  }
188
+ // What's saved to resume: a converted playback's own link (not the server's conversion), and a
189
+ // torrent's infoHash, file and trackers (its link depends on the server set when it resumes).
190
+ function savedUrl(ctx) { return (ctx._convertedFrom && /\/hlsv2\//.test(ctx.url || '')) ? ctx._convertedFrom : ctx.url; }
191
+ function torrentOf(st) {
192
+ if (!st || !st._torrent) { return undefined; }
193
+ return { infoHash: st.infoHash, fileIdx: st.fileIdx, sources: Array.isArray(st.sources) ? st.sources.slice(0, 20) : undefined };
194
+ }
187
195
 
188
196
  // ---------- OSD ----------
189
197
  // Subtitles move up above the progress bar while it's on screen (above the UP bar too,
@@ -400,7 +408,7 @@ var PlayerParts = {};
400
408
  ctx.localSubs = s.localSubs; ctx.localFile = s.localFile; ctx.subExtra = s.subExtra; ctx.sourceSubs = s.sourceSubs;
401
409
  ctx.formatInfo = (s.stream && typeof Stremio !== 'undefined' && Stremio.streamInfo) ? Stremio.streamInfo(s.stream) : undefined;
402
410
  ctx.stream = s.stream; // (the addon's source: ⬇ Download, player-controls)
403
- var learn = (old.learnFor && s.stream) ? old.learnFor(s.stream) : {};
411
+ var learn = (old.learnFor && s.stream) ? old.learnFor(s.stream, { converted: !!s.converted }) : {}; // (converted: not what the TV plays itself)
404
412
  ctx.onStarted = learn.onStarted; ctx.onFailed = learn.onFailed;
405
413
  ctx.resumeSec = keep ? old.resumeSec : (S.isLive ? 0 : S.cur);
406
414
  if (keep) { ctx.fromStart = old.fromStart; }
@@ -414,6 +422,8 @@ var PlayerParts = {};
414
422
  // Replacing a YouTube stream that's playing (CH+/CH− to the next channel): the TV's
415
423
  // player can freeze on an open straight after closing it, so settle first (startAV).
416
424
  var settle = !!(S.active && S.ctx && S.ctx.yt);
425
+ if (S.ctx !== ctx) { stopLiveLook(); } // (another channel: the look at the one before stopped)
426
+ stopFileLook();
417
427
  S.ctx = ctx; _onExit = onExit;
418
428
  // (private viewing, a link played as it is, or one started from a private playback —
419
429
  // a video followed from it, another source: nothing recorded, see player-store)
@@ -423,7 +433,7 @@ var PlayerParts = {};
423
433
  if (U.crumb) { U.crumb('play ' + (ctx.type || '') + ' ' + (ctx.private ? '(private)' : /^file:/i.test(ctx.url || '') ? 'file .' + ('' + ctx.url).split('.').pop() : ('' + (ctx.url || '')).replace(/^https?:\/\/([^\/?#]+).*$/i, '$1'))); } // (Diagnostics, after an unexpected close)
424
434
  S.active = true; S.cur = 0; S.dur = 0; _bg = null; S.actual = null;
425
435
  // Stremio "tv" and "radio" types are strong live hints; refined after prepare.
426
- S.isLive = (ctx.type === 'tv' || ctx.type === 'radio') || /^iptv:/.test(ctx.id || '') || !!ctx.isLive; // (an IPTV channel: live, a sports one too)
436
+ S.isLive = !(ctx.stream && ctx.stream._vod) && ((ctx.type === 'tv' || ctx.type === 'radio') || /^iptv:/.test(ctx.id || '') || !!ctx.isLive); // (an IPTV channel: live, a sports one too; a film in a playlist isn't)
427
437
  formatStart(ctx);
428
438
  S.ctx.resumeSec = (ctx.trailer || ctx.fromStart) ? 0 : (ctx.resumeSec || getResume(ctx.type, ctx.id)); // (Play from start: 0:00)
429
439
 
@@ -445,7 +455,27 @@ var PlayerParts = {};
445
455
  renderOSD(); // show the NEW title immediately (not the previous item's)
446
456
  U.spinner(true, ctx.switching ? 'Switching source…' : ctx.initialQualityHeight ? 'Opening stream at ' + ctx.initialQualityHeight + 'p…' : 'Opening stream…');
447
457
 
448
- if (useAV) { startLive(ctx, settle); } else { startHTML5(ctx.url); }
458
+ // (a TorrServer torrent that doesn't say which of its files: its file list asked for first)
459
+ var go = function () { if (useAV) { startLive(ctx, settle); } else { startHTML5(ctx.url); } };
460
+ if (ctx.stream && ctx.stream._pickFile && typeof Stremio !== 'undefined' && Stremio.torrentFile) {
461
+ // (the source before stopped first: its callbacks are about it, not this one)
462
+ ++_playToken; _openedAt = 0;
463
+ if (useAV) { try { avplay.stop(); } catch (e0) {} try { avplay.close(); } catch (e1) {} }
464
+ else if (S.videoEl) { try { S.videoEl.pause(); S.videoEl.removeAttribute('src'); } catch (e2) {} }
465
+ U.spinner(true, 'Asking your streaming server for the torrent’s files…');
466
+ var ep = /:(\d+):(\d+)$/.exec(ctx.id || ''), look = _fileLook = U.cancelToken();
467
+ Stremio.torrentFile(ctx.stream, ep ? +ep[1] : 0, ep ? +ep[2] : 0, look).then(function (url) {
468
+ if (look.cancelled || S.ctx !== ctx || !S.active) { return; }
469
+ _fileLook = null;
470
+ if (url) { ctx.url = url; go(); return; }
471
+ var why = 'The torrent has no file for S' + ep[1] + 'E' + ep[2]; // (another episode isn't played in its place)
472
+ U.log('player', why);
473
+ U.spinner(false);
474
+ if (nextSourceOnFail({ text: why })) { return; }
475
+ U.toast(why + '. Try another source.', 6000);
476
+ exitLater();
477
+ });
478
+ } else { go(); }
449
479
 
450
480
  // A YouTube video (not a live channel): its audio languages and its links (end screen,
451
481
  // cards) from the service, for the menu and the overlays (player-quality / -controls).
@@ -550,7 +580,7 @@ var PlayerParts = {};
550
580
 
551
581
  // Decides live vs VOD from the reported duration (0 / non-finite = live).
552
582
  function markLiveFromDuration() {
553
- if (S.ctx && (S.ctx.type === 'tv' || S.ctx.type === 'radio' || /^iptv:/.test(S.ctx.id || ''))) { S.isLive = true; }
583
+ if (S.ctx && !(S.ctx.stream && S.ctx.stream._vod) && (S.ctx.type === 'tv' || S.ctx.type === 'radio' || /^iptv:/.test(S.ctx.id || ''))) { S.isLive = true; }
554
584
  if (!S.dur || S.dur <= 0 || !isFinite(S.dur)) { S.isLive = true; }
555
585
  }
556
586
 
@@ -660,7 +690,7 @@ var PlayerParts = {};
660
690
  });
661
691
  try { avplay.setStreamingProperty('ADAPTIVE_INFO', adaptiveInfo()); } catch (e0) {}
662
692
  _openedAt = Date.now();
663
- setTimeout(startCheck, AV_START_MS + 500);
693
+ setTimeout(startCheck, startMs() + 500);
664
694
  avplay.prepareAsync(function () {
665
695
  if (!S.active || token !== _playToken) { return; }
666
696
  U.spinner(false);
@@ -1022,6 +1052,21 @@ var PlayerParts = {};
1022
1052
  U.spinner(true, msg); U.toast(msg, notice ? 7000 : 4000);
1023
1053
  return true;
1024
1054
  }
1055
+ // With Stremio's streaming server (Settings › Content › Streaming server, Convert on): a source
1056
+ // the TV refused is tried once more, converted by the server, before the next source. Once a
1057
+ // playback (the next sources aren't). Not a source that needs its own request headers.
1058
+ function convertOnFail() {
1059
+ var c = S.ctx;
1060
+ if (!c || !S.active || S.playing || S.isLive || c.trailer || c.yt || c.localFile || !c.stream || c._converted || c._headers) { return false; }
1061
+ var u = (typeof Stremio !== 'undefined' && Stremio.convertUrl) ? Stremio.convertUrl(c.url) : null;
1062
+ if (!u) { return false; }
1063
+ c._converted = true; c._convertedFrom = c.url; // (kept by what replaces it: Continue Watching saves its own link)
1064
+ var msg = 'Didn’t start: converting it on your streaming server…';
1065
+ U.log('player', 'Source didn’t start: converting it on the streaming server');
1066
+ replaceSource({ url: u, stream: c.stream, subExtra: c.subExtra, sourceSubs: c.sourceSubs, localSubs: c.localSubs, converted: true }, true);
1067
+ U.spinner(true, msg); U.toast(msg, 5000);
1068
+ return true;
1069
+ }
1025
1070
  // A start that failed: is the link a debrid addon's notice video (Torrentio's failed_access,
1026
1071
  // limits_exceeded…: noticeOf)? Then that's said, and for the account's ones the next source
1027
1072
  // skips the addon's links through that service; then the next source, or what's to say.
@@ -1033,6 +1078,7 @@ var PlayerParts = {};
1033
1078
  U.log('player', 'The source sent a notice: ' + notice.kind + (notice.service ? ' (' + notice.service + ')' : ''));
1034
1079
  if (notice.account && notice.tag) { c._avoid = (c._avoid || []).concat([{ addon: st._addon, tag: notice.tag }]); }
1035
1080
  }
1081
+ if (!notice && convertOnFail()) { return; }
1036
1082
  if (nextSourceOnFail(notice)) { return; }
1037
1083
  U.toast(notice ? notice.text : why, notice ? 8000 : undefined);
1038
1084
  exitLater();
@@ -1072,15 +1118,21 @@ var PlayerParts = {};
1072
1118
  return n;
1073
1119
  }
1074
1120
  // Not playing after AV_START_MS (no answer from the server, or opened and nothing shown): the
1075
- // next source when there's one; else it stops and says so (not while you've paused it).
1121
+ // next source when there's one; else it stops and says so (not while you've paused it). A
1122
+ // torrent through a streaming server has longer (Settings › Content › Streaming server: finding
1123
+ // people sharing it takes a while).
1124
+ function startMs() {
1125
+ var st = S.ctx && S.ctx.stream;
1126
+ return (st && st._torrent && typeof Stremio !== 'undefined' && Stremio.server) ? Stremio.server().wait * 1000 : AV_START_MS;
1127
+ }
1076
1128
  function startCheck() {
1077
- if (!S.active || S.playing || !useAV || !_openedAt || Date.now() - _openedAt < AV_START_MS) { return; }
1129
+ if (!S.active || S.playing || !useAV || !_openedAt || Date.now() - _openedAt < startMs()) { return; }
1078
1130
  if (_reco.tries) { liveDropped('Couldn’t reconnect'); return; } // (a reconnect's try: the next one)
1079
1131
  if (nextSourceOnFail()) { return; }
1080
1132
  if (S.playStarted && isPaused()) { return; }
1081
- U.log('player', 'Didn’t start: nothing played in ' + (AV_START_MS / 1000) + ' s (' + where(S.ctx && S.ctx.url) + ')');
1133
+ U.log('player', 'Didn’t start: nothing played in ' + (startMs() / 1000) + ' s (' + where(S.ctx && S.ctx.url) + ')');
1082
1134
  U.spinner(false);
1083
- U.toast('Didn’t start: nothing played in ' + (AV_START_MS / 1000) + ' seconds. Try another source.', 6000);
1135
+ U.toast('Didn’t start: nothing played in ' + (startMs() / 1000) + ' seconds. Try another source.', 6000);
1084
1136
  exitLater();
1085
1137
  }
1086
1138
  P.startCheck = startCheck;
@@ -1147,6 +1199,12 @@ var PlayerParts = {};
1147
1199
  startAV(ctx.url, settle);
1148
1200
  }, function () { if (S.ctx === ctx && S.active) { startAV(ctx.url, settle); } });
1149
1201
  }
1202
+ // The look under way (_liveLook, a cancel token): stopped when another channel starts or the
1203
+ // player closes (stopLiveLook), the service's downloads for it with it.
1204
+ var _fileLook = null; // (TorrServer's file list asked for: see play)
1205
+ function stopFileLook() { if (_fileLook) { _fileLook.cancel(); _fileLook = null; } }
1206
+ var _liveLook = null;
1207
+ function stopLiveLook() { if (_liveLook) { _liveLook.cancel(); _liveLook = null; } }
1150
1208
  function liveCheck() {
1151
1209
  var ctx = S.ctx;
1152
1210
  if (!ctx || ctx._liveChecked || !liveFixable(ctx)) { return; }
@@ -1154,7 +1212,10 @@ var PlayerParts = {};
1154
1212
  var known = liveKnown(ctx.url);
1155
1213
  if (known && ccOf(known)) { return; }
1156
1214
  var url = ctx.url;
1157
- YTPlay.liveOpen(url, ctx._headers, false).then(function (r) {
1215
+ stopLiveLook();
1216
+ var look = _liveLook = U.cancelToken();
1217
+ YTPlay.liveOpen(url, ctx._headers, false, null, look).then(function (r) {
1218
+ if (_liveLook === look) { _liveLook = null; }
1158
1219
  if (!r || !r.sure) { return; } // (couldn't tell: asked again next time)
1159
1220
  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)
1160
1221
  liveKeep(url, fix, cc);
@@ -1278,6 +1339,7 @@ var PlayerParts = {};
1278
1339
 
1279
1340
  function exit() {
1280
1341
  if (!S.active) { return; }
1342
+ stopLiveLook(); stopFileLook();
1281
1343
  if (U.crumb) { U.crumb('player closed'); }
1282
1344
  if (P.sleepClear) { P.sleepClear(); } // (the sleep timer: this playback's)
1283
1345
  saveProgress();
@@ -130,19 +130,19 @@
130
130
  var SIZE_PX = { small: 28, medium: 36, large: 46, xlarge: 58 };
131
131
  function styleSpan(span) {
132
132
  var cfg = getSubCfg();
133
- span.style.fontSize = (SIZE_PX[cfg.size] || 36) + 'px';
133
+ span.style.fontSize = (SIZE_PX[cfg.size] || 36) / U.zoom() + 'px'; // (their own size, whatever the zoom)
134
134
  span.style.fontFamily = subFontFamily(cfg.font);
135
135
  span.style.color = pick3(SUB_COLORS, cfg.color)[2];
136
136
  span.style.background = pick3(SUB_BGS, cfg.bg)[2];
137
137
  span.style.textShadow = pick3(SUB_EDGES, cfg.edge)[2];
138
138
  if (span.parentNode) { span.parentNode.style.bottom = Math.max(subsPosPx(), (P.S && P.S.subsLift) || 0) + 'px'; } // (raised over the progress bar: core's liftSubs)
139
139
  }
140
- function subsPosPx() { return pick3(SUB_POSITIONS, getSubCfg().pos)[2]; }
140
+ function subsPosPx() { return pick3(SUB_POSITIONS, getSubCfg().pos)[2] / U.zoom(); }
141
141
 
142
142
  // ---------- progress (Continue Watching) ----------
143
143
  function progressAll() { return U.store.get(PROGRESS_KEY, {}); }
144
144
  function progressKey(ctx) { return ctx.type + ':' + ctx.id; }
145
- function writeProgress(all) { U.store.set(PROGRESS_KEY, all); }
145
+ function writeProgress(all) { U.store.set(PROGRESS_KEY, all, true); }
146
146
 
147
147
  // "Add to Continue Watching": list a title there without playing it. Also how
148
148
  // a show's next episode is queued (credits, marking episodes watched): like an added
package/js/player-subs.js CHANGED
@@ -48,7 +48,7 @@
48
48
 
49
49
  // A new playback: no subtitles yet.
50
50
  function resetSubs() {
51
- _subGen++;
51
+ _subGen++; stopSubLoad();
52
52
  _subTracks = []; _cues = null; _subOn = false; _subLabel = ''; _subTrackUrl = '';
53
53
  _subDelay = 0; _subTrackId = null; _embSub = null; _embLang = ''; _embWant = null;
54
54
  _embDelay = 0; _embQueue = []; _embNudge = null;
@@ -285,12 +285,52 @@
285
285
  // Each choice (a track, Off, a built-in one) is a new one: a download still on its way
286
286
  // for an earlier choice is dropped when it comes, without a word (_subGen).
287
287
  var _subGen = 0;
288
+ // A subtitle file's time to arrive: some servers build it when asked (12 s, seen from an
289
+ // OpenSubtitles proxy); the video plays on meanwhile.
290
+ var SUB_FILE_MS = 20000;
291
+ // The download under way (_subLoad: { url, ctx, cancel, timer, done }): the same track picked
292
+ // again while it comes waits for it (it used to be asked for again, what was on its way
293
+ // dropped: slow servers took several picks); another choice stops it, its connection freed.
294
+ // The files downloaded (the last SUB_FILES_MAX, while StremioK runs) come back at once.
295
+ var _subLoad = null, SUB_FILES_MAX = 8, _subFiles = []; // ([{ url, text }], newest last)
296
+ function subFile(url) { for (var i = 0; i < _subFiles.length; i++) { if (_subFiles[i].url === url) { return _subFiles[i].text; } } return null; }
297
+ function keepSubFile(url, text) {
298
+ _subFiles = _subFiles.filter(function (f) { return f.url !== url; });
299
+ _subFiles.push({ url: url, text: text });
300
+ if (_subFiles.length > SUB_FILES_MAX) { _subFiles.shift(); }
301
+ }
302
+ function stopSubLoad() {
303
+ var l = _subLoad;
304
+ _subLoad = null;
305
+ if (l) { clearInterval(l.timer); l.cancel.cancel(); }
306
+ }
307
+ // A subtitle file: from those kept, else downloaded (the same one shared by whoever asks).
308
+ function subText(track, cancel) {
309
+ var kept = subFile(track.url);
310
+ if (kept !== null) { return Promise.resolve(kept); }
311
+ return U.getText(track.url, SUB_FILE_MS, undefined, cancel || null, false, track.headers || null).then(function (text) { keepSubFile(track.url, text); return text; }); // (a USB file's: the service's header where there's no token)
312
+ }
288
313
  function loadTrack(track, onDone) {
289
314
  if (!U.parseUrl(track.url)) { U.toast('That subtitle track has no usable link'); return; } // (http(s) only)
290
- U.toast('Loading subtitles…', 1500);
315
+ var l = _subLoad;
316
+ if (l && l.url === track.url && l.ctx === S.ctx) { // (still coming: waited for, not asked for again)
317
+ if (onDone) { l.done.push(onDone); }
318
+ U.toast('Still loading subtitles… ' + l.secs + ' s', 1500);
319
+ return;
320
+ }
321
+ stopSubLoad();
291
322
  var forCtx = S.ctx, gen = ++_subGen;
292
323
  function stale() { return !S.active || S.ctx !== forCtx || gen !== _subGen; } // (another playback, or another choice, meanwhile)
293
- U.getText(track.url, 15000, undefined, null, false, track.headers || null).then(function (text) { // (a USB file's: the service's header where there's no token)
324
+ var cancel = U.cancelToken(), mine = { url: track.url, ctx: forCtx, cancel: cancel, secs: 0, done: onDone ? [onDone] : [], timer: null };
325
+ if (subFile(track.url) === null) { // (a download: how long it's been, every second, till it's in)
326
+ _subLoad = mine;
327
+ U.toast('Loading subtitles…', 1500);
328
+ mine.timer = setInterval(function () { mine.secs++; if (_subLoad === mine) { U.toast('Loading subtitles… ' + mine.secs + ' s', 1500); } }, 1000);
329
+ }
330
+ function finished() { clearInterval(mine.timer); if (_subLoad === mine) { _subLoad = null; } }
331
+ onDone = function () { mine.done.forEach(function (f) { try { f(); } catch (e) {} }); };
332
+ subText(track, cancel).then(function (text) {
333
+ finished();
294
334
  if (stale()) { return; }
295
335
  var cues = parseCues(text);
296
336
  if (!cues.length) { U.toast('Could not parse subtitles'); return; }
@@ -299,8 +339,8 @@
299
339
  _subTrackId = (track.id != null) ? track.id : null; _subDelay = 0;
300
340
  renderSubs();
301
341
  U.toast('Subtitles: ' + (track.lang || 'on'));
302
- if (onDone) { onDone(); }
303
- }, function () { if (!stale()) { U.toast('Failed to download subtitles'); } });
342
+ onDone();
343
+ }, function () { finished(); if (!stale()) { U.toast('Failed to download subtitles'); } });
304
344
  }
305
345
 
306
346
  // ---------- the second subtitle ----------
@@ -323,7 +363,7 @@
323
363
  var track = _subTracks.filter(function (t) { return t.url && langMatches(want, t.lang); })[0];
324
364
  if (!track || (_cues2 && _sub2Label === track.url)) { if (!track) { secondOff(); } return; }
325
365
  var forCtx = S.ctx, gen = ++_sub2Gen;
326
- U.getText(track.url, 15000, undefined, null, false, track.headers || null).then(function (text) {
366
+ subText(track).then(function (text) {
327
367
  if (!S.active || S.ctx !== forCtx || gen !== _sub2Gen) { return; }
328
368
  var cues = parseCues(text);
329
369
  if (!cues.length) { return; }
@@ -374,7 +414,7 @@
374
414
  }
375
415
 
376
416
  function subsOff() {
377
- _subGen++;
417
+ _subGen++; stopSubLoad(); // (a download under way for a track: stopped)
378
418
  _subOn = false; _cues = null; _subLabel = ''; _subTrackUrl = ''; _subTrackId = null; _subDelay = 0;
379
419
  embOff();
380
420
  S.subsEl.className = 'hidden'; U.clear(S.subsEl);