stremiok 2.2.7 → 2.2.8

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
@@ -48,7 +48,9 @@ var PlayerParts = {};
48
48
  function skipShown() { return P.skipShown.apply(null, arguments); } // controls
49
49
 
50
50
  var avplay = (window.webapis && webapis.avplay) ? webapis.avplay : null;
51
- var useAV = !!avplay;
51
+ // useAV: this playback is the TV's player's (everything but a ClearKey channel: see startShaka);
52
+ // the page's own <video> otherwise, and in a desktop browser. P.useAV says which, as it is now.
53
+ var hasAV = !!avplay, useAV = hasAV;
52
54
  P.avplay = avplay; P.useAV = useAV;
53
55
 
54
56
  // The playback session: read by every part, written here (and a few fields where noted).
@@ -434,6 +436,7 @@ var PlayerParts = {};
434
436
  S.active = true; S.cur = 0; S.dur = 0; _bg = null; S.actual = null;
435
437
  // Stremio "tv" and "radio" types are strong live hints; refined after prepare.
436
438
  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)
439
+ if (S.isLive) { vodCheck(ctx); } // (one whose manifest says it's a film: not live after all)
437
440
  formatStart(ctx);
438
441
  S.ctx.resumeSec = (ctx.trailer || ctx.fromStart) ? 0 : (ctx.resumeSec || getResume(ctx.type, ctx.id)); // (Play from start: 0:00)
439
442
 
@@ -455,6 +458,7 @@ var PlayerParts = {};
455
458
  renderOSD(); // show the NEW title immediately (not the previous item's)
456
459
  U.spinner(true, ctx.switching ? 'Switching source…' : ctx.initialQualityHeight ? 'Opening stream at ' + ctx.initialQualityHeight + 'p…' : 'Opening stream…');
457
460
 
461
+ engineFor(ctx); // (the TV's player, or a ClearKey channel's own: see startShaka)
458
462
  // (a TorrServer torrent that doesn't say which of its files: its file list asked for first)
459
463
  var go = function () { if (useAV) { startLive(ctx, settle); } else { startHTML5(ctx.url); } };
460
464
  if (ctx.stream && ctx.stream._pickFile && typeof Stremio !== 'undefined' && Stremio.torrentFile) {
@@ -580,8 +584,45 @@ var PlayerParts = {};
580
584
 
581
585
  // Decides live vs VOD from the reported duration (0 / non-finite = live).
582
586
  function markLiveFromDuration() {
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; }
587
+ if (S.ctx && !(S.ctx.stream && S.ctx.stream._vod) && !S.ctx._vodManifest && (S.ctx.type === 'tv' || S.ctx.type === 'radio' || /^iptv:/.test(S.ctx.id || ''))) { S.isLive = true; }
584
588
  if (!S.dur || S.dur <= 0 || !isFinite(S.dur)) { S.isLive = true; }
589
+ else if (S.ctx && S.ctx._vodManifest) { S.isLive = false; } // (its manifest said it's a film before it was ready: see vodCheck)
590
+ }
591
+
592
+ // A playlist's entry whose link isn't a file's may still be a film: its manifest says so (DASH
593
+ // type="static", or none; HLS #EXT-X-ENDLIST or PLAYLIST-TYPE:VOD, a master playlist's first
594
+ // variant's). Read as it opens (with the channel's headers, through the service when it has
595
+ // some), not for an Xtream /live/ link; once known, it plays as a film (seeking, no ● LIVE).
596
+ var MANIFEST_LINK = /\.(mpd|m3u8?)(?:[?#]|$)/i, XT_LIVE_PATH = /\/live\/[^\/?#]+\/[^\/?#]+\/[^\/?#]+$/i;
597
+ function manifestText(url, h) {
598
+ if (!/\.mpd(?:[?#]|$)/i.test(url) && P.hlsMasterText) { return P.hlsMasterText(url, h); } // (HLS: read once, with the quality list)
599
+ if (h && (h.ua || h.ref || h.cookie) && typeof YTPlay !== 'undefined' && YTPlay.hlsMaster) { return YTPlay.hlsMaster(url, h); }
600
+ return U.getText(url, 8000, 524288, null, true);
601
+ }
602
+ function linkFrom(base, ref) {
603
+ if (/^https?:\/\//i.test(ref)) { return ref; }
604
+ var m = /^(https?:\/\/[^\/?#]+)([^?#]*)/i.exec(base);
605
+ if (!m) { return ''; }
606
+ return ref.charAt(0) === '/' ? m[1] + ref : m[1] + m[2].replace(/[^\/]*$/, '') + ref;
607
+ }
608
+ function manifestVod(url, h, inner) {
609
+ return manifestText(url, h).then(function (t) {
610
+ t = '' + t;
611
+ if (/<MPD[\s>]/i.test(t)) { return !/<MPD\b[^>]*\btype\s*=\s*["']dynamic["']/i.test(t); }
612
+ if (/#EXT-X-ENDLIST|#EXT-X-PLAYLIST-TYPE:\s*VOD/i.test(t)) { return true; }
613
+ var v = /#EXT-X-STREAM-INF[^\n]*\n\s*([^#\s][^\r\n]*)/i.exec(t), next = v ? linkFrom(url, v[1].trim()) : '';
614
+ return next && !inner ? manifestVod(next, h, true) : false;
615
+ });
616
+ }
617
+ function vodCheck(ctx) {
618
+ if (!ctx || ctx.yt || ctx.trailer || (ctx.stream && ctx.stream._vod) || !/^iptv:/.test(ctx.id || '')) { return; }
619
+ var url = ctx.url || '';
620
+ if (!MANIFEST_LINK.test(url) || XT_LIVE_PATH.test(url.replace(/[?#].*$/, '').replace(/\.[a-z0-9]+$/i, ''))) { return; }
621
+ manifestVod(url, U.sanitizeHeaders(ctx._headers)).then(function (vod) {
622
+ if (!vod || S.ctx !== ctx) { return; }
623
+ ctx._vodManifest = true;
624
+ if (S.active && S.playStarted && S.dur > 0 && isFinite(S.dur) && S.isLive) { S.isLive = false; U.log('player', 'A playlist entry that\'s a film (its manifest): seeking on'); renderOSD(); }
625
+ }, function () {});
585
626
  }
586
627
 
587
628
  // settle: a re-open of what's playing (a quality switch, or its retry). This TV's player
@@ -611,8 +652,57 @@ var PlayerParts = {};
611
652
  }
612
653
  openAV(url, token);
613
654
  }
655
+ // A DRM channel (its playlist's #KODIPROP lines, see IPTV's drmInto): set once the stream is
656
+ // open, before it's prepared (Samsung's order). PlayReady: the player asks its license server
657
+ // itself, with the playlist's headers. Widevine: the player hands over its license request
658
+ // (ondrmevent's Challenge), posted by StremioK's service (drmEvent), and the answer given back;
659
+ // Tizen 5 and later take its session in one call, earlier ones in three. ClearKey: Shaka's (see
660
+ // startShaka); one whose keys can't be read, or another system: said so, not opened.
661
+ function tizenMajor() { try { return parseInt(tizen.systeminfo.getCapability('http://tizen.org/feature/platform.version'), 10) || 0; } catch (e) { return 0; } }
662
+ function drmSetup(drm) {
663
+ try {
664
+ if (drm.sys === 'playready') {
665
+ var o = { DeleteLicenseAfterUse: true, LicenseServer: drm.url }, h = drm.h || {}, rest = [];
666
+ Object.keys(h).forEach(function (k) {
667
+ if (/^user-agent$/i.test(k)) { o.UserAgent = h[k]; } else if (/^cookie$/i.test(k)) { o.Cookie = h[k]; } else { rest.push(k + ': ' + h[k]); }
668
+ });
669
+ if (rest.length) { o.HttpHeader = rest.join('\r\n'); }
670
+ avplay.setDrm('PLAYREADY', 'SetProperties', JSON.stringify(o));
671
+ return;
672
+ }
673
+ var session = 'stremiok-' + Date.now(), v = tizenMajor();
674
+ if (!v || v >= 5) {
675
+ try { avplay.setDrm('WIDEVINE_CDM', 'SetProperties', JSON.stringify({ AppSession: session, DataType: 'MPEG-DASH' })); return; } catch (e5) { if (v) { throw e5; } } // (not known: the older calls next)
676
+ }
677
+ avplay.setDrm('WIDEVINE_CDM', 'Initialize', '');
678
+ avplay.setDrm('WIDEVINE_CDM', 'widevine_app_session', session);
679
+ avplay.setDrm('WIDEVINE_CDM', 'widevine_data_type', 'MPEG-DASH');
680
+ } catch (e) { U.log('player', 'DRM not set up (' + (e && (e.name || e.message || e)) + ')'); }
681
+ }
682
+ function drmEvent(drm, data, token) {
683
+ if (!drm || drm.sys !== 'widevine' || !data || data.name !== 'Challenge' || !data.challenge) { return; }
684
+ var ctx = S.ctx;
685
+ if (typeof YTPlay === 'undefined' || !YTPlay.drmLicense) { ctx._drmWhy = 'StremioK’s service isn’t there'; return; }
686
+ YTPlay.drmLicense(drm.url, drm.h, data.challenge, drm.b64).then(function (r) {
687
+ if (!S.active || token !== _playToken) { return; }
688
+ if (!r || !r.license) { throw new Error((r && r.why) || 'no answer'); }
689
+ avplay.setDrm('WIDEVINE_CDM', 'widevine_license_data', data.session_id + 'PARAM_START_POSITION' + r.license + 'PARAM_START_POSITION');
690
+ }).then(null, function (e) {
691
+ if (S.ctx !== ctx) { return; }
692
+ ctx._drmWhy = U.problem(e);
693
+ U.log('player', 'DRM: no license for this channel (' + ctx._drmWhy + ')');
694
+ });
695
+ }
696
+ function drmName(d) { return { clearkey: 'ClearKey', widevine: 'Widevine', playready: 'PlayReady' }[d.sys] || 'its DRM'; }
614
697
  var BUFFERS = { more: [8, 10], most: [15, 20] };
615
698
  function openAV(url, token) {
699
+ var drm = S.ctx && S.ctx.stream && S.ctx.stream._drm;
700
+ if (drm && !drm.ok) { // (ClearKey, or a license StremioK can't ask for)
701
+ U.log('player', 'Not played: ' + drmName(drm) + (drm.sys === 'clearkey' ? '' : ' without a license server StremioK can use') + ' (' + where(url) + ')');
702
+ U.spinner(false);
703
+ failedStart(drm.sys === 'clearkey' ? 'This ClearKey channel’s keys can’t be read (its playlist’s #KODIPROP lines)' : 'This channel’s DRM can’t be played on the TV (' + drmName(drm) + ')');
704
+ return;
705
+ }
616
706
  try {
617
707
  avplay.open(url);
618
708
  // Best-effort per-stream HTTP headers (some IPTV channels need a UA / Referer).
@@ -621,6 +711,7 @@ var PlayerParts = {};
621
711
  var h = U.sanitizeHeaders(S.ctx && S.ctx._headers);
622
712
  if (h && h.ua) { avplay.setStreamingProperty('USER_AGENT', h.ua); }
623
713
  if (h && h.ref) { avplay.setStreamingProperty('CUSTOM_MESSAGE', 'Referer:' + h.ref); }
714
+ if (h && h.cookie) { avplay.setStreamingProperty('COOKIE', h.cookie); }
624
715
  } catch (eh) {}
625
716
  // A bigger buffer (Settings › Playback › Seeking & buffering): seconds loaded before it
626
717
  // starts, and before it goes on after running dry (the TV's own when Normal)
@@ -661,6 +752,10 @@ var PlayerParts = {};
661
752
  if (!S.active || token !== _playToken) { return; }
662
753
  showEmbeddedText(text, duration);
663
754
  },
755
+ ondrmevent: function (type, data) {
756
+ if (!S.active || token !== _playToken) { return; }
757
+ drmEvent(drm, data, token);
758
+ },
664
759
  onerror: function (err) {
665
760
  // stop()/close() may emit a late NOT_SUPPORTED_FORMAT for an HLS
666
761
  // session that played successfully. Ignore callbacks after exit or
@@ -688,6 +783,7 @@ var PlayerParts = {};
688
783
  exitLater();
689
784
  }
690
785
  });
786
+ if (drm) { drmSetup(drm); }
691
787
  try { avplay.setStreamingProperty('ADAPTIVE_INFO', adaptiveInfo()); } catch (e0) {}
692
788
  _openedAt = Date.now();
693
789
  setTimeout(startCheck, startMs() + 500);
@@ -723,7 +819,7 @@ var PlayerParts = {};
723
819
  if (tryFallback()) { return; }
724
820
  U.log('player', 'Could not open: ' + (err && (err.name || err.message || err)) + ' (' + where(url) + ')');
725
821
  reportStart(false, err && (err.name || err.message || err));
726
- failedStart('Could not open stream');
822
+ failedStart(S.ctx && S.ctx._drmWhy ? 'No license for this channel: ' + S.ctx._drmWhy : 'Could not open stream');
727
823
  });
728
824
  } catch (e) {
729
825
  U.log('player', 'AVPlay failed: ' + (e && e.message));
@@ -757,18 +853,71 @@ var PlayerParts = {};
757
853
 
758
854
  // The desktop's <video> has no start timeout of its own (AVPlay's prepare does): a
759
855
  // stream the browser never gets going would leave the spinner up for good.
856
+ // A ClearKey channel (its playlist's #KODIPROP lines with keys or a key server, see IPTV's
857
+ // drmShaka): the TV's player has no ClearKey, so it alone plays in the page's own <video>
858
+ // through Shaka Player (js/vendor, Apache 2.0), loaded the first time one plays. Every other
859
+ // playback stays with the TV's player (engineFor: chosen as each starts, and after one, back).
860
+ var SHAKA_SRC = 'js/vendor/shaka-player.compiled.js', SHAKA_START_MS = 40000;
861
+ var _shakaPl = null, _shakaGone = null, _shakaLoad = null;
862
+ function shakaDrm(ctx) { var d = ctx && ctx.stream && ctx.stream._drm; return d && d.sys === 'clearkey' && d.shaka ? d : null; }
863
+ function loadShaka() {
864
+ if (typeof shaka !== 'undefined') { return Promise.resolve(); }
865
+ if (!_shakaLoad) {
866
+ _shakaLoad = U.loadScript(SHAKA_SRC).then(function () { if (typeof shaka !== 'undefined' && shaka.polyfill) { shaka.polyfill.installAll(); } });
867
+ _shakaLoad.then(null, function () { _shakaLoad = null; });
868
+ }
869
+ return _shakaLoad;
870
+ }
871
+ function shakaStop() { // (its player let go: the <video> free for the next)
872
+ var pl = _shakaPl;
873
+ _shakaPl = null;
874
+ if (pl) { _shakaGone = (_shakaGone || Promise.resolve()).then(function () { return pl.destroy(); }).then(null, function () {}); }
875
+ return _shakaGone || Promise.resolve();
876
+ }
877
+ function engineFor(ctx) {
878
+ var av = hasAV && !shakaDrm(ctx);
879
+ if (av === useAV) { return; }
880
+ if (useAV) { try { avplay.stop(); } catch (e0) {} try { avplay.close(); } catch (e1) {} objEl.className = ''; } // (the TV's player shut, for the page's)
881
+ else { shakaStop(); try { S.videoEl.pause(); S.videoEl.removeAttribute('src'); } catch (e2) {} S.videoEl.className = ''; }
882
+ useAV = av; P.useAV = av;
883
+ }
884
+ function shakaLoadInto(url, drm, token, fail) {
885
+ loadShaka().then(function () {
886
+ if (!S.active || token !== _playToken) { return; }
887
+ if (typeof shaka === 'undefined' || !shaka.Player.isBrowserSupported()) { throw new Error('this TV’s browser can’t play it'); }
888
+ return shakaStop().then(function () {
889
+ if (!S.active || token !== _playToken) { return; }
890
+ var pl = _shakaPl = new shaka.Player(), cfg = { streaming: { bufferingGoal: 10 } };
891
+ cfg.drm = drm.keys ? { clearKeys: drm.keys } : { servers: { 'org.w3.clearkey': drm.url } };
892
+ pl.configure(cfg);
893
+ var h = drm.h || {};
894
+ if (!drm.keys && Object.keys(h).length) { // (the key server's own headers: those a page may send)
895
+ pl.getNetworkingEngine().registerRequestFilter(function (type, req) {
896
+ if (type === shaka.net.NetworkingEngine.RequestType.LICENSE) { Object.keys(h).forEach(function (k) { if (!/^(user-agent|referer|cookie|host|origin)$/i.test(k)) { req.headers[k] = h[k]; } }); }
897
+ });
898
+ }
899
+ pl.addEventListener('error', function (ev) { if (token === _playToken) { fail(shakaWhy(ev.detail)); } });
900
+ return pl.attach(S.videoEl).then(function () { return token === _playToken ? pl.load(url) : null; }).then(function () {
901
+ if (!S.active || token !== _playToken) { return; }
902
+ var p = S.videoEl.play();
903
+ if (p && p['catch']) { p['catch'](function () {}); }
904
+ });
905
+ });
906
+ }).then(null, function (e) { if (S.active && token === _playToken) { fail(shakaWhy(e)); } });
907
+ }
908
+ function shakaWhy(e) { return e && e.code ? 'Shaka error ' + e.code : (e && e.message) || 'it didn’t start'; }
760
909
  var HTML5_START_MS = 20000;
761
910
  function startHTML5(url) {
762
911
  url = opened(url);
763
- var token = ++_playToken, loaded = false;
912
+ var token = ++_playToken, loaded = false, drm = shakaDrm(S.ctx);
764
913
  S.videoEl.className = 'active';
765
- S.videoEl.src = url;
914
+ if (!drm) { S.videoEl.src = url; }
766
915
  setTimeout(function () {
767
916
  if (loaded || !S.active || token !== _playToken) { return; }
768
917
  reportStart(false, 'TIMEOUT');
769
918
  U.spinner(false);
770
919
  U.toast('This stream didn\'t start'); exitLater();
771
- }, HTML5_START_MS);
920
+ }, drm ? SHAKA_START_MS : HTML5_START_MS);
772
921
  S.videoEl.onloadedmetadata = function () {
773
922
  if (!S.active || token !== _playToken) { return; }
774
923
  loaded = true;
@@ -789,12 +938,21 @@ var PlayerParts = {};
789
938
  if (S.active && token === _playToken) { onEnded(); }
790
939
  };
791
940
  S.videoEl.onerror = function () {
792
- if (!S.active || token !== _playToken) { return; }
941
+ if (!S.active || token !== _playToken || drm) { return; } // (Shaka's own errors: see shakaLoadInto)
793
942
  reportStart(false, S.videoEl.error && S.videoEl.error.code === 2 ? 'NETWORK' : 'MEDIA_ERR');
794
943
  U.toast('Playback error'); exitLater();
795
944
  };
796
- var p = S.videoEl.play();
797
- if (p && p['catch']) { p['catch'](function () {}); }
945
+ if (drm) {
946
+ shakaLoadInto(url, drm, token, function (why) {
947
+ if (loaded) { U.log('player', 'ClearKey channel: ' + why); U.toast('Playback error: ' + why); exitLater(); return; }
948
+ U.log('player', 'ClearKey channel didn’t play (' + why + ')');
949
+ U.spinner(false);
950
+ failedStart('This ClearKey channel didn’t play (' + why + ')');
951
+ });
952
+ } else {
953
+ var p = S.videoEl.play();
954
+ if (p && p['catch']) { p['catch'](function () {}); }
955
+ }
798
956
  applyAspect(true);
799
957
  startTicker();
800
958
  }
@@ -1057,7 +1215,7 @@ var PlayerParts = {};
1057
1215
  // playback (the next sources aren't). Not a source that needs its own request headers.
1058
1216
  function convertOnFail() {
1059
1217
  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; }
1218
+ if (!c || !S.active || S.playing || S.isLive || c.trailer || c.yt || c.localFile || !c.stream || c._converted || c._headers || c.stream._drm) { return false; }
1061
1219
  var u = (typeof Stremio !== 'undefined' && Stremio.convertUrl) ? Stremio.convertUrl(c.url) : null;
1062
1220
  if (!u) { return false; }
1063
1221
  c._converted = true; c._convertedFrom = c.url; // (kept by what replaces it: Continue Watching saves its own link)
@@ -1150,7 +1308,7 @@ var PlayerParts = {};
1150
1308
  // needs repacking too.
1151
1309
  var LIVE_KEY = 'stremiok.livefix', LIVE_KEEP = 300, LIVE_DAYS = 14;
1152
1310
  function liveFixable(ctx) {
1153
- return useAV && S.isLive && !!ctx && !ctx.yt && !ctx.trailer && /^https?:\/\//i.test(ctx.url || '') &&
1311
+ return useAV && S.isLive && !!ctx && !ctx.yt && !ctx.trailer && !(ctx.stream && ctx.stream._drm) && /^https?:\/\//i.test(ctx.url || '') &&
1154
1312
  typeof YTPlay !== 'undefined' && !!YTPlay.liveOpen && YTPlay.installMode() !== 'browser';
1155
1313
  }
1156
1314
  function liveKnown(url) {
@@ -1369,10 +1527,12 @@ var PlayerParts = {};
1369
1527
  try { avplay.close(); } catch (e2) {}
1370
1528
  objEl.className = '';
1371
1529
  } else {
1530
+ shakaStop();
1372
1531
  try { S.videoEl.pause(); } catch (e3) {}
1373
1532
  S.videoEl.removeAttribute('src');
1374
1533
  S.videoEl.className = '';
1375
1534
  }
1535
+ useAV = hasAV; P.useAV = hasAV; // (the next playback the TV's player's, unless it's ClearKey too)
1376
1536
  document.body.style.background = '';
1377
1537
  U.byId('app').className = '';
1378
1538
  U.spinner(false);
@@ -4,7 +4,6 @@
4
4
  (function (P) {
5
5
  'use strict';
6
6
  var S = P.S;
7
- var useAV = P.useAV;
8
7
 
9
8
  // ----- from the other parts -----
10
9
  function startAV() { return P.startAV.apply(null, arguments); } // core
@@ -119,7 +118,7 @@
119
118
  var v = variantByBw(bw);
120
119
  S.ctx.url = YTPlay.resolverUrl(S.ctx.yt, v ? v.h : 0, true, S.ctx.ytLang);
121
120
  }
122
- if (useAV) { startAV(S.ctx.url, true); } else { startHTML5(S.ctx.url); }
121
+ if (P.useAV) { startAV(S.ctx.url, true); } else { startHTML5(S.ctx.url); }
123
122
  }
124
123
 
125
124
  // YouTube re-opens fail on the FIRST attempt but succeed on the next (an AVPlay
@@ -137,7 +136,7 @@
137
136
  // Right after a switch this retry is routine: keep saying "Switching to …"
138
137
  U.spinner(true, _switchNote || ((retryHeight ? retryHeight + 'p' : 'The stream') + ' didn\'t start — retrying…'));
139
138
  _switchNote = null;
140
- if (useAV) { startAV(S.ctx.url, true); } else { startHTML5(S.ctx.url); }
139
+ if (P.useAV) { startAV(S.ctx.url, true); } else { startHTML5(S.ctx.url); }
141
140
  return true;
142
141
  }
143
142
 
@@ -165,7 +164,7 @@
165
164
  if (S.ctx.yt && typeof YTPlay !== 'undefined') { S.ctx.url = YTPlay.resolverUrl(S.ctx.yt, 0, true, S.ctx.ytLang); }
166
165
  _startNote = wasAuto ? '' : 'Playing with Auto quality';
167
166
  U.spinner(true, wasAuto ? 'Stream didn\'t start — retrying…' : 'Retrying with Auto quality…');
168
- if (useAV) { startAV(S.ctx.url); } else { startHTML5(S.ctx.url); }
167
+ if (P.useAV) { startAV(S.ctx.url); } else { startHTML5(S.ctx.url); }
169
168
  return true;
170
169
  }
171
170
 
@@ -191,13 +190,20 @@
191
190
  }
192
191
  // h: the stream's own User-Agent / Referer ({ ua, ref }): the list is then read through
193
192
  // StremioK's service, which can send them (as the TV's player does); a web page can't.
193
+ // (kept MASTER_MS: the player's look at whether a playlist's entry is a film reads it too, see vodCheck)
194
+ var _masters = U.lru(6), MASTER_MS = 15000;
194
195
  function getHlsMaster(url, h) {
195
- var viaService = !!(h && (h.ua || h.ref) && typeof YTPlay !== 'undefined' && YTPlay.hlsMaster && YTPlay.installMode && YTPlay.installMode() !== 'browser');
196
- return (viaService ? YTPlay.hlsMaster(url, h) : U.getText(url, 8000, HLS_MASTER_MAX)).then(function (text) {
196
+ var k = url + '|' + JSON.stringify(h || {}), kept = _masters.get(k);
197
+ if (kept && Date.now() - kept.at < MASTER_MS) { return kept.p; }
198
+ var viaService = !!(h && (h.ua || h.ref || h.cookie) && typeof YTPlay !== 'undefined' && YTPlay.hlsMaster && YTPlay.installMode && YTPlay.installMode() !== 'browser');
199
+ var p = (viaService ? YTPlay.hlsMaster(url, h) : U.getText(url, 8000, HLS_MASTER_MAX)).then(function (text) {
197
200
  var t = ('' + (text || '')).replace(/^\uFEFF/, '').replace(/^\s+/, '');
198
201
  if (t.indexOf('#EXTM3U') !== 0) { throw new Error('not an HLS playlist'); }
199
202
  return t;
200
203
  });
204
+ _masters.set(k, { at: Date.now(), p: p });
205
+ p.then(null, function () { var x = _masters.get(k); if (x && x.p === p) { _masters.set(k, null); } });
206
+ return p;
201
207
  }
202
208
  var _variantsToken = 0;
203
209
  // url: the master to read (a ctx's variantUrl), or a stream to read it from only when
@@ -286,7 +292,7 @@
286
292
  _switchNote = 'Switching to ' + ytLangLabel(a) + '…';
287
293
  _startNote = 'Audio: ' + ytLangLabel(a);
288
294
  U.spinner(true, _switchNote);
289
- if (useAV) { startAV(S.ctx.url, true); } else { startHTML5(S.ctx.url); }
295
+ if (P.useAV) { startAV(S.ctx.url, true); } else { startHTML5(S.ctx.url); }
290
296
  }
291
297
  function ytLanguageMenu() {
292
298
  var cur = currentYtLanguage(), list = ytLanguages().slice();
@@ -321,7 +327,7 @@
321
327
  // ----- for the other parts (and js/player.js) -----
322
328
  P.resetQuality = resetQuality; P.qualityOnStart = qualityOnStart; P.clearStartNote = clearStartNote;
323
329
  P.qualityHeight = qualityHeight; P.qualityCount = qualityCount; P.hasQualities = hasQualities; P.qualityUnread = qualityUnread;
324
- P.adaptiveInfo = adaptiveInfo; P.tryFallback = tryFallback; P.switchSource = switchSource;
330
+ P.adaptiveInfo = adaptiveInfo; P.tryFallback = tryFallback; P.switchSource = switchSource; P.hlsMasterText = getHlsMaster;
325
331
  P.qualityLabel = qualityLabel; P.qualityMenu = qualityMenu;
326
332
  P.hasYtLanguages = hasYtLanguages; P.ytLanguageLabel = ytLanguageLabel; P.ytLanguageMenu = ytLanguageMenu;
327
333
  })(PlayerParts);
package/js/player-subs.js CHANGED
@@ -4,7 +4,7 @@
4
4
  (function (P) {
5
5
  'use strict';
6
6
  var S = P.S;
7
- var avplay = P.avplay, useAV = P.useAV;
7
+ var avplay = P.avplay; // (P.useAV: the TV's player's playback or the page's, as it is now: see player-core's engineFor)
8
8
 
9
9
  // ----- from the other parts -----
10
10
  function updateHint() { return P.updateHint.apply(null, arguments); } // core
@@ -426,7 +426,7 @@
426
426
  // StremioK draws it like an addon subtitle. Like audio, a track is only switched
427
427
  // once playback runs. Image-based tracks (PGS) produce no text and show nothing.
428
428
  function getTextTracks() {
429
- if (!useAV) { return []; }
429
+ if (!P.useAV) { return []; }
430
430
  try {
431
431
  var all = avplay.getTotalTrackInfo() || [], out = [];
432
432
  for (var i = 0; i < all.length; i++) { if (('' + all[i].type).toUpperCase() === 'TEXT') { out.push(all[i]); } }
package/js/stremio.js CHANGED
@@ -543,12 +543,97 @@ var Stremio = (function () {
543
543
  var t = p.host + path;
544
544
  return t.length > 64 ? t.slice(0, 61) + '…' : t;
545
545
  }
546
+ // ---- Export configuration (Settings › Content › Export configuration) ----
547
+ // The file import reads (parseSetupList): a line an addon link, playlist link or API key, what
548
+ // any StremioK imports, and #!stremiok <kind> <JSON> lines, comments to an older one: playlist
549
+ // (a playlist's name, guide link, off), stalker (a portal) and store (one of EXPORT_STORE, what
550
+ // you chose in Settings: not caches, history, progress or your Trakt sign-in; integrations
551
+ // without the three keys, which have their own lines, or Trakt's). Imported settings replace
552
+ // yours, only those in EXPORT_STORE.
553
+ var EXPORT_LINE = '#!stremiok ';
554
+ var EXPORT_STORE = ['stremiok.prefs', 'stremiok.feeds', 'stremiok.searchfeeds', 'stremiok.sourcefeeds', 'stremiok.ranking', 'stremiok.server', 'stremiok.formats',
555
+ 'stremiok.resblock', 'stremiok.subcfg', 'stremiok.audiocfg', 'stremiok.playercfg', 'stremiok.private', 'stremiok.youtube', 'stremiok.appshortcuts',
556
+ 'stremiok.appsallowed', 'stremiok.aiomanager', 'stremiok.iptv.stalkerall', 'stremiok.iptv.every', 'stremiok.local.matching', 'stremiok.local.hidden',
557
+ 'stremiok.addonsoff', 'stremiok.integrations'];
558
+ function plural(n, one) { return n + ' ' + one + (n === 1 ? '' : 's'); }
559
+ function iptvLists() { return (_hasIptv && IPTV.getPlaylists) ? IPTV.getPlaylists() : []; }
560
+ // What there is to export: [{ key, label }] (settings always).
561
+ function exportGroups() {
562
+ var lists = iptvLists(), integ = getIntegrations(), out = [], n = getAddonUrls().length;
563
+ var pl = lists.filter(function (p) { return !p.mac; }).length, st = lists.length - pl;
564
+ var keys = Object.keys(KEY_NAMES).filter(function (k) { return integ[k]; }).map(function (k) { return KEY_NAMES[k].replace(/ key$/, ''); });
565
+ if (n) { out.push({ key: 'addons', label: plural(n, 'addon') + ', in your order' }); }
566
+ if (pl) { out.push({ key: 'playlists', label: plural(pl, 'IPTV playlist') + ' (their logins too)' }); }
567
+ if (st) { out.push({ key: 'stalker', label: plural(st, 'Stalker portal') + ' (their MAC addresses)' }); }
568
+ if (keys.length) { out.push({ key: 'keys', label: 'API keys: ' + keys.join(', ') }); }
569
+ out.push({ key: 'settings', label: 'Your settings: look, Home, playback, subtitles, sources, streaming server, YouTube…' });
570
+ return out;
571
+ }
572
+ function settingsValue(key) {
573
+ var v = U.store.get(key, null);
574
+ if (key !== INTEG_KEY || !v || typeof v !== 'object') { return v; }
575
+ var o = {}, n = 0; // (integrations: the three keys have lines of their own; Trakt's aren't for another TV)
576
+ Object.keys(v).forEach(function (k) { if (!KEY_NAMES[k] && !/^trakt/.test(k) && v[k]) { o[k] = v[k]; n++; } });
577
+ return n ? o : null;
578
+ }
579
+ // The file, with what's in keys (exportGroups' keys).
580
+ function exportSetup(keys, version) {
581
+ var want = {}, out = [], integ = getIntegrations(), lists = iptvLists();
582
+ (keys || []).forEach(function (k) { want[k] = true; });
583
+ out.push('# StremioK configuration, exported ' + new Date(Date.now()).toISOString().slice(0, 10) + (version ? ' from StremioK ' + version : '') + '.');
584
+ out.push('# It holds your addon links, playlist logins, API keys and MAC addresses: keep it private.');
585
+ out.push('# To import it: Settings › Content › Import configuration file (▣ From your phone: choose this file, or paste it).');
586
+ if (want.addons) { out.push(''); getAddonUrls().forEach(function (u) { out.push(u); }); }
587
+ if (want.playlists) {
588
+ out.push('');
589
+ lists.filter(function (p) { return !p.mac; }).forEach(function (p) {
590
+ out.push(p.url);
591
+ var d = { url: p.url };
592
+ if (p.name) { d.name = p.name; }
593
+ if (p.guide) { d.guide = p.guide; }
594
+ if (p.off) { d.off = true; }
595
+ if (d.name || d.guide || d.off) { out.push(EXPORT_LINE + 'playlist ' + JSON.stringify(d)); }
596
+ });
597
+ }
598
+ if (want.stalker) {
599
+ out.push('');
600
+ lists.filter(function (p) { return p.mac; }).forEach(function (p) {
601
+ var d = { url: p.url, mac: p.mac };
602
+ ['name', 'guide', 'genres', 'off'].forEach(function (k) { if (p[k]) { d[k] = p[k]; } });
603
+ out.push(EXPORT_LINE + 'stalker ' + JSON.stringify(d));
604
+ });
605
+ }
606
+ if (want.keys) { out.push(''); Object.keys(KEY_NAMES).forEach(function (k) { if (integ[k]) { out.push(integ[k]); } }); }
607
+ if (want.settings) {
608
+ out.push('');
609
+ EXPORT_STORE.forEach(function (key) {
610
+ var v = settingsValue(key);
611
+ if (v !== null && v !== undefined) { out.push(EXPORT_LINE + 'store ' + JSON.stringify({ k: key.replace(/^stremiok\./, ''), v: v })); }
612
+ });
613
+ }
614
+ return out.join('\n') + '\n';
615
+ }
546
616
  function parseSetupList(text) {
547
617
  var out = { items: [], ignored: 0 }, seen = {}, mine = getAddonUrls(), integ = getIntegrations();
548
- var lists = (_hasIptv && IPTV.getPlaylists) ? IPTV.getPlaylists().map(function (x) { return x.url; }) : [];
618
+ var have = iptvLists(), lists = have.map(function (x) { return x.url; }), details = {}, store = [];
549
619
  function push(it) { var k = it.kind + ' ' + it.value; if (seen[k]) { return; } seen[k] = 1; out.items.push(it); }
620
+ function stremiokLine(rest) { // (an export's own lines: see exportSetup)
621
+ var m = /^([a-z]+)\s+(\{[\s\S]*\})$/.exec(rest), o = null;
622
+ try { o = m ? JSON.parse(m[2]) : null; } catch (e) { o = null; }
623
+ if (!o || typeof o !== 'object') { out.ignored++; return; }
624
+ if (m[1] === 'playlist' && typeof o.url === 'string') { details[o.url] = o; return; }
625
+ if (m[1] === 'stalker' && typeof o.url === 'string' && _hasIptv && IPTV.macOf && IPTV.macOf(o.mac)) {
626
+ var mac = IPTV.macOf(o.mac);
627
+ push({ kind: 'stalker', value: o.url + '|' + mac, info: o, label: 'Stalker portal · ' + (typeof o.name === 'string' && o.name ? o.name.slice(0, 60) : shortLink(o.url)),
628
+ have: have.some(function (p) { return p.url === o.url && p.mac === mac; }), note: '' });
629
+ return;
630
+ }
631
+ if (m[1] === 'store' && typeof o.k === 'string' && EXPORT_STORE.indexOf('stremiok.' + o.k) !== -1 && o.v !== undefined && o.v !== null) { store.push(o); return; }
632
+ out.ignored++;
633
+ }
550
634
  ('' + (text || '')).split(/\r?\n/).forEach(function (line) {
551
635
  var value = line.trim(), key = null;
636
+ if (value.indexOf(EXPORT_LINE) === 0) { stremiokLine(value.slice(EXPORT_LINE.length).trim()); return; }
552
637
  if (!value || value.charAt(0) === '#') { return; }
553
638
  if (/^[A-Za-z0-9]{8}$/.test(value)) { key = 'omdb'; }
554
639
  else if (/^[A-Za-z0-9]{32}$/.test(value)) { key = 'tmdb'; }
@@ -565,14 +650,44 @@ var Stremio = (function () {
565
650
  out.ignored++;
566
651
  }
567
652
  });
653
+ out.items.forEach(function (it) { // (a playlist's name, guide link, off: with it)
654
+ var d = it.kind === 'playlist' && details[it.value];
655
+ if (d) { it.info = d; if (typeof d.name === 'string' && d.name) { it.label = 'IPTV playlist · ' + d.name.slice(0, 60); } }
656
+ });
657
+ if (store.length) { push({ kind: 'settings', value: 'settings', entries: store, label: 'Your settings (' + plural(store.length, 'part') + ')', have: false, note: 'replaces yours' }); }
568
658
  return out;
569
659
  }
660
+ function playlistDetails(id, d) {
661
+ if (typeof d.name === 'string' && d.name.trim()) { iptvRenamePlaylist(id, d.name.trim()); }
662
+ if (typeof d.guide === 'string' && d.guide) { iptvSetPlaylistGuide(id, d.guide); }
663
+ if (d.off === true) { iptvSetPlaylistOff(id, true); }
664
+ }
570
665
  // Import the chosen lines (parseSetupList's items): what was added, as importSetupList says.
571
666
  function applySetupEntries(items) {
572
- var result = { addons: 0, playlists: 0, omdb: false, tmdb: false, mdblist: false, ignored: 0 };
667
+ var result = { addons: 0, playlists: 0, omdb: false, tmdb: false, mdblist: false, settings: false, ignored: 0 };
573
668
  (items || []).forEach(function (it) {
574
669
  if (KEY_NAMES[it.kind]) { setIntegration(it.kind, it.value); result[it.kind] = true; }
575
- else if (it.kind === 'playlist') { if (iptvAddPlaylist(it.value)) { result.playlists++; } else { result.ignored++; } }
670
+ else if (it.kind === 'playlist') {
671
+ var pid = iptvAddPlaylist(it.value);
672
+ if (pid) { result.playlists++; if (it.info) { playlistDetails(pid, it.info); } } else { result.ignored++; }
673
+ } else if (it.kind === 'stalker') {
674
+ var sid = iptvAddStalker(it.info.url, it.info.mac);
675
+ if (!sid) { result.ignored++; return; }
676
+ result.playlists++;
677
+ playlistDetails(sid, it.info);
678
+ if (Array.isArray(it.info.genres) && it.info.genres.length && IPTV.setStalkerGroups) { IPTV.setStalkerGroups(sid, it.info.genres.filter(function (g) { return /^[\w.-]{1,40}$/.test('' + g); }).map(String)); }
679
+ } else if (it.kind === 'settings') {
680
+ it.entries.forEach(function (o) {
681
+ var key = 'stremiok.' + o.k;
682
+ if (EXPORT_STORE.indexOf(key) === -1) { return; }
683
+ if (key === INTEG_KEY && typeof o.v === 'object') { // (merged: your keys stay, unless the file has its own lines for them)
684
+ var cur = U.store.get(INTEG_KEY, {}) || {};
685
+ Object.keys(o.v).forEach(function (k) { if (!KEY_NAMES[k] && !/^trakt/.test(k)) { cur[k] = o.v[k]; } });
686
+ U.store.set(INTEG_KEY, cur);
687
+ } else { U.store.set(key, o.v); }
688
+ });
689
+ result.settings = true;
690
+ }
576
691
  else if (it.kind === 'addon') {
577
692
  var added = addAddon(it.value);
578
693
  if (added) { result.addons++; if (!addonOrigin(added)) { setAddonOrigin(added, 'config'); } } else { result.ignored++; }
@@ -2252,7 +2367,7 @@ var Stremio = (function () {
2252
2367
  getIntroSegments: getIntroSegments,
2253
2368
  tmdbValidate: tmdbValidate, mdblistValidate: mdblistValidate, omdbValidate: omdbValidate,
2254
2369
  tmdbFindTvId: tmdbFindTvId, tmdbSeasonEpisodes: tmdbSeasonEpisodes, tmdbImg: tmdbImg,
2255
- tmdbTitleExtras: tmdbTitleExtras, tmdbExtrasById: tmdbExtrasById, tmdbEpisodeCast: tmdbEpisodeCast, tmdbEpisodeTrailer: tmdbEpisodeTrailer, setHideWords: setHideWords, hideWordHit: hideWordHit, normalizeAddonUrl: normalizeManifestUrl, debridOf: debridOf, addonOrigin: addonOrigin, setAddonOrigin: setAddonOrigin, parseSetupList: parseSetupList, applySetupEntries: applySetupEntries, sizeLimitHit: sizeLimitHit, setSizeLimit: setSizeLimit, gbText: gbText, runtimeMinutes: runtimeMinutes, tmdbPeople: tmdbPeople, tmdbPerson: tmdbPerson, tmdbBrowse: tmdbBrowse, tmdbTitleTrailers: tmdbTitleTrailers, tmdbProviders: tmdbProviders, tmdbProvidersKept: tmdbProvidersKept, tmdbGenres: tmdbGenres, tmdbWhereToWatch: tmdbWhereToWatch, watchRegion: watchRegion, autoWatchRegion: autoWatchRegion, tmdbImdbId: tmdbImdbId, findFilm: findFilm, hasTmdb: function () { return !!tmdbKey(); },
2370
+ tmdbTitleExtras: tmdbTitleExtras, tmdbExtrasById: tmdbExtrasById, tmdbEpisodeCast: tmdbEpisodeCast, tmdbEpisodeTrailer: tmdbEpisodeTrailer, setHideWords: setHideWords, hideWordHit: hideWordHit, normalizeAddonUrl: normalizeManifestUrl, debridOf: debridOf, addonOrigin: addonOrigin, setAddonOrigin: setAddonOrigin, parseSetupList: parseSetupList, applySetupEntries: applySetupEntries, exportGroups: exportGroups, exportSetup: exportSetup, sizeLimitHit: sizeLimitHit, setSizeLimit: setSizeLimit, gbText: gbText, runtimeMinutes: runtimeMinutes, tmdbPeople: tmdbPeople, tmdbPerson: tmdbPerson, tmdbBrowse: tmdbBrowse, tmdbTitleTrailers: tmdbTitleTrailers, tmdbProviders: tmdbProviders, tmdbProvidersKept: tmdbProvidersKept, tmdbGenres: tmdbGenres, tmdbWhereToWatch: tmdbWhereToWatch, watchRegion: watchRegion, autoWatchRegion: autoWatchRegion, tmdbImdbId: tmdbImdbId, findFilm: findFilm, hasTmdb: function () { return !!tmdbKey(); },
2256
2371
  mdblistRatings: mdblistRatings,
2257
2372
  omdbSeasonRatings: omdbSeasonRatings,
2258
2373
  loadAddons: loadAddons, listCatalogs: listCatalogs, getCatalog: getCatalog,
package/js/stvod.js CHANGED
@@ -65,7 +65,8 @@ var StVod = (function () {
65
65
  if ((c && Date.now() - c.at < (c.none ? CATS_RETRY_MS : CATS_FRESH_MS)) || _catsAsked[sk]) { return; }
66
66
  _catsAsked[sk] = true; // (once a launch: a portal that didn't answer is asked again at the next)
67
67
  function either(p) { return p.then(null, function (e) { return { failed: e }; }); }
68
- Promise.all([either(ask(acc, '&type=movie&do=cats')), either(ask(acc, '&type=series&do=cats'))]).then(function (r) {
68
+ var fresh = _reloaded[acc.id] ? '&fresh=1' : ''; // (Reload: the service's kept lists let go too)
69
+ Promise.all([either(ask(acc, '&type=movie&do=cats' + fresh)), either(ask(acc, '&type=series&do=cats' + fresh))]).then(function (r) {
69
70
  if (r[0].failed && r[1].failed) { U.log('iptv', 'Stalker “' + acc.label + '”: its films and series couldn’t be read (' + U.problem(r[0].failed) + ')'); return; }
70
71
  var all = catsAll(), keep = {}, o = { sig: sk, movie: catList(r[0]), series: catList(r[1]), at: Date.now() };
71
72
  if (!o.movie.length && !o.series.length) { o.none = true; U.log('iptv', 'Stalker “' + acc.label + '”: no films or series'); }
@@ -80,7 +81,8 @@ var StVod = (function () {
80
81
  });
81
82
  });
82
83
  }
83
- // Reload on a portal (Settings › Content › IPTV): its categories asked again now.
84
+ // Reload on a portal (Settings › Content › IPTV): its categories asked again now, and the
85
+ // service's kept lists of it let go (fresh=1).
84
86
  function reload(id) {
85
87
  var acc = account(id), all = catsAll();
86
88
  if (!acc) { return; }
package/js/util.js CHANGED
@@ -382,12 +382,12 @@ var U = (function () {
382
382
  return cut ? out.replace(/[ \t]{2,}/g, ' ').replace(/^[ \t]+|[ \t]+$/gm, '') : out;
383
383
  }
384
384
 
385
- /* Request headers a stream needs (IPTV's http-user-agent / http-referrer): only these
386
- two (the only ones the TV's player takes), as { ua, ref }. Each is kept to printable
387
- ASCII on one line (a line break would add a header of its own) and a sane length; a
388
- Referer must be an http(s) link. The names Stremio uses ("User-Agent", "Referer") are
389
- read too. Returns null when nothing usable is left. */
390
- var HEADER_MAX = { ua: 512, ref: 2048 };
385
+ /* Request headers a stream needs (IPTV's http-user-agent / http-referrer, a cookie): only
386
+ these three (the ones the TV's player takes), as { ua, ref, cookie }. Each is kept to
387
+ printable ASCII on one line (a line break would add a header of its own) and a sane length;
388
+ a Referer must be an http(s) link. The names Stremio uses ("User-Agent", "Referer",
389
+ "Cookie") are read too. Returns null when nothing usable is left. */
390
+ var HEADER_MAX = { ua: 512, ref: 2048, cookie: 3000 }; // (a cookie: within what a newer TV's service reads of a request, 8 KB)
391
391
  function headerValue(v, max) {
392
392
  if (typeof v !== 'string') { return ''; }
393
393
  v = v.trim();
@@ -397,11 +397,13 @@ var U = (function () {
397
397
  if (!h || typeof h !== 'object') { return null; }
398
398
  var ua = headerValue(h.ua != null ? h.ua : (h['User-Agent'] || h['user-agent']), HEADER_MAX.ua);
399
399
  var ref = headerValue(h.ref != null ? h.ref : (h.Referer || h.referer), HEADER_MAX.ref);
400
+ var cookie = headerValue(h.cookie != null ? h.cookie : (h.Cookie || h.COOKIE), HEADER_MAX.cookie);
400
401
  if (ref && !/^https?:\/\/[^\s]+$/i.test(ref)) { ref = ''; }
401
- if (!ua && !ref) { return null; }
402
+ if (!ua && !ref && !cookie) { return null; }
402
403
  var out = {};
403
404
  if (ua) { out.ua = ua; }
404
405
  if (ref) { out.ref = ref; }
406
+ if (cookie) { out.cookie = cookie; }
405
407
  return out;
406
408
  }
407
409