stremiok 2.2.6 → 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/service/index.js CHANGED
@@ -30,12 +30,20 @@
30
30
  * why }: a Stalker portal's channels as an M3U playlist; /stalker/link?portal&mac
31
31
  * &u=<a channel's link in it> -> JSON { url } or { why }: its link to play now
32
32
  * (see stalkerControl); StremioK only (entryAllowed)
33
+ * /stalker/vod?portal&mac&type=movie|series&do=cats|list|seasons[&cat=][&q=][&skip=][&id=][&via=vod]
34
+ * -> JSON { cats } | { items, more } | { seasons } or { why }: its films and
35
+ * series; /stalker/play?portal&mac&cmd=[&ep=] -> 302 to a film's or episode's
36
+ * link, asked now (the player's: the token, or the guide ticket)
33
37
  * /epg/load?u=<guide>&k=<bitset>[&force=1] (or POSTed: the same in its body, as StremioK
34
38
  * asks) -> JSON { state, at, channels, programmes, partial,
35
39
  * error }: a playlist's TV guide (XMLTV) read for StremioK's channels
36
40
  * only; /epg/get?u=<guide>&ids=<key>|<key>&from&to[&max] -> JSON { <key>:
37
41
  * [[start, stop, title, desc, picture?, about?]], _icons: { <key>: logo } }: their programs and
38
42
  * the guide's logos for them (see epgControl)
43
+ * /entry/give (POSTed: a configuration file) -> JSON { url, token }: a one-time phone page to
44
+ * copy or download it (see entryControl); the token or the ticket
45
+ * /drm/license (POSTed: { u, h, c }) -> JSON { license } or { why }: a Widevine channel's license
46
+ * request posted to its license server (see drmControl); the token or the ticket
39
47
  * /epg/ticket -> JSON { ticket }: for guide POSTs from an app without the token (see hasTicket)
40
48
  * /epg/files -> JSON { count, bytes, xtv: { count, bytes } }: the saved guides, and Xtream lists;
41
49
  * /epg/clear (POST) -> { cleared }: all of them deleted
@@ -1790,12 +1798,14 @@ function handle(req, res) {
1790
1798
  // The app's own guide POSTs: a browser sends an Origin with every POST (the app's page is
1791
1799
  // file://: "null"); let through with the token, or the guide ticket (for an app that can't
1792
1800
  // read the token: see /epg/ticket), which no web page has (/epg/ only).
1793
- if (who === 'origin' && req.method === 'POST' && /^\/epg\/(load|get|clear)$/.test(path) && /^(null|file:\/\/)$/.test(String(req.headers.origin || '')) && (hasToken(parts[1]) || hasTicket(parts[1]))) { who = null; }
1801
+ if (who === 'origin' && req.method === 'POST' && /^\/(epg\/(load|get|clear)|drm\/license|entry\/give)$/.test(path) && /^(null|file:\/\/)$/.test(String(req.headers.origin || '')) && (hasToken(parts[1]) || hasTicket(parts[1]))) { who = null; } // (and a DRM license's: see drmControl)
1794
1802
  if (who) { send(res, 403, 'text/plain', 'not allowed (' + who + ')'); return; }
1795
1803
  if (req.method === 'OPTIONS') { if (isFs) { send(res, 403, 'text/plain', 'not allowed'); return; } res.writeHead(200); res.end(); return; }
1796
1804
  var epgPost = req.method === 'POST' && /^\/epg\/(load|get|clear)$/.test(path); // (a guide's channels: in the body, see epgControl)
1797
- if (req.method !== 'GET' && !epgPost) { send(res, 405, 'text/plain', 'GET only'); return; } // (before any work)
1798
- if (req.url.length > (/^\/epg\//.test(path) ? 32768 : /^\/fsdl\/add$/.test(path) ? 8192 : 2048)) { send(res, 414, 'text/plain', 'request too long'); return; } // (a download's link can be long; a guide's channels, a bitset)
1805
+ var drmPost = req.method === 'POST' && path === '/drm/license'; // (a Widevine license request: see drmControl)
1806
+ var givePost = req.method === 'POST' && path === '/entry/give'; // (a configuration file for the phone: see entryControl)
1807
+ if (req.method !== 'GET' && !epgPost && !drmPost && !givePost) { send(res, 405, 'text/plain', 'GET only'); return; } // (before any work)
1808
+ if (req.url.length > (/^\/epg\//.test(path) ? 32768 : /^\/(fsdl\/add|live\/(open|master))$/.test(path) ? 8192 : 2048)) { send(res, 414, 'text/plain', 'request too long'); return; } // (a download's link can be long; a guide's channels, a bitset)
1799
1809
  // (StremioK gave up on it — a screen left, the player closed: what it still waits for is
1800
1810
  // dropped; 'close' before the response finished means that on every Node)
1801
1811
  var leaving = [];
@@ -1806,6 +1816,14 @@ function handle(req, res) {
1806
1816
  res.on('close', function () { clearTimeout(deadline); if (!res.finished) { leaveAll(); } });
1807
1817
  }
1808
1818
 
1819
+ if (givePost) {
1820
+ if (+(req.headers['content-length'] || 0) > GIVE_MAX) { send(res, 413, 'text/plain', 'too much'); req.resume(); return; }
1821
+ var gbody = '', gover = false;
1822
+ req.setEncoding('utf8');
1823
+ req.on('data', function (c) { if (gover) { return; } gbody += c; if (gbody.length > GIVE_MAX) { gover = true; send(res, 413, 'text/plain', 'too much'); } });
1824
+ req.on('end', function () { if (!gover) { entryControl(req, res, path, parts[1], gbody); } });
1825
+ return;
1826
+ }
1809
1827
  if (/^\/entry\//.test(path)) { entryControl(req, res, path, parts[1]); return; }
1810
1828
  if (/^\/live\//.test(path)) { liveControl(req, res, path, parts[1], leaving); return; }
1811
1829
  if (epgPost) { // what's asked, in the body (to EPG_BODY_MAX), after the address's own (its token)
@@ -1816,10 +1834,18 @@ function handle(req, res) {
1816
1834
  req.on('end', function () { if (!over) { epgControl(req, res, path, (parts[1] ? parts[1] + '&' : '') + body); } });
1817
1835
  return;
1818
1836
  }
1837
+ if (drmPost) {
1838
+ if (+(req.headers['content-length'] || 0) > DRM_BODY_MAX) { send(res, 413, 'text/plain', 'too much asked'); req.resume(); return; }
1839
+ var dbody = '', dover = false;
1840
+ req.setEncoding('utf8');
1841
+ req.on('data', function (c) { if (dover) { return; } dbody += c; if (dbody.length > DRM_BODY_MAX) { dover = true; send(res, 413, 'text/plain', 'too much asked'); } });
1842
+ req.on('end', function () { if (!dover) { drmControl(req, res, parts[1], dbody, leaving); } });
1843
+ return;
1844
+ }
1819
1845
  if (/^\/epg\//.test(path)) { epgControl(req, res, path, parts[1]); return; } // (a playlist's TV guide: see epgControl)
1820
1846
  if (path === '/aiom/addons') { aiomControl(req, res, parts[1], leaving); return; }
1821
1847
  if (path === '/xtvod/list' || path === '/xtvod/find') { xtvControl(req, res, path, parts[1]); return; } // (an Xtream account's films and series: see xtvControl)
1822
- if (path === '/stalker/list' || path === '/stalker/link' || path === '/stalker/genres') { stalkerControl(req, res, path, parts[1], leaving); return; } // (a Stalker portal: see stalkerControl) // (AIOManager's addons: see aiomControl) // (a live channel's sound repacked: see liveControl) // (the phone's one-time page: see below)
1848
+ if (path === '/stalker/list' || path === '/stalker/link' || path === '/stalker/genres' || path === '/stalker/vod' || path === '/stalker/play') { stalkerControl(req, res, path, parts[1], leaving); return; } // (a Stalker portal: see stalkerControl) // (AIOManager's addons: see aiomControl) // (a live channel's sound repacked: see liveControl) // (the phone's one-time page: see below)
1823
1849
  if (path === '/fsfile') { // a USB file over HTTP, with Range: the player reads a big one from here (see fsfile in the header)
1824
1850
  var whyF = fsAllowed(req, parts[1]);
1825
1851
  if (whyF) { send(res, 403, 'text/plain', 'not allowed (' + whyF + ')'); return; }
@@ -1976,6 +2002,7 @@ function liveGet(u, who, max, cb, part) {
1976
2002
  if ((pu.protocol !== 'http:' && pu.protocol !== 'https:') || !dlHostOk(pu.hostname)) { cb(upError('a link it can\'t follow', 400)); return; }
1977
2003
  var h = { 'User-Agent': who.ua || TV_UA };
1978
2004
  if (who.ref) { h.Referer = who.ref; }
2005
+ if (who.cookie) { h.Cookie = who.cookie; }
1979
2006
  var opts = { hostname: pu.hostname, port: pu.port, path: pu.path, headers: h };
1980
2007
  if (pu.protocol === 'https:' && caList().length) { opts.ca = caList(); }
1981
2008
  var chunks = [], size = 0, done = false;
@@ -2498,7 +2525,7 @@ function liveSession(u, who, opts) {
2498
2525
  ids.sort(function (x, y) { return _live[x].last - _live[y].last; });
2499
2526
  delete _live[ids[0]];
2500
2527
  }
2501
- var s = { id: crypto.randomBytes(16).toString('hex'), ua: who.ua, ref: who.ref, links: {}, at: {}, next: 0, last: Date.now(), a: liveAudio(),
2528
+ var s = { id: crypto.randomBytes(16).toString('hex'), ua: who.ua, ref: who.ref, cookie: who.cookie || '', links: {}, at: {}, next: 0, last: Date.now(), a: liveAudio(),
2502
2529
  fix: opts.fix !== false, cc: opts.cc && opts.cc.length ? opts.cc : null, c: ccState(), got: Object.create(null) };
2503
2530
  _live[s.id] = s;
2504
2531
  s.top = liveLink(s, u, 'm');
@@ -2542,26 +2569,28 @@ function liveProbe(u, who, cb, leaving) {
2542
2569
  }
2543
2570
  list(u);
2544
2571
  }
2545
- function liveHeader(v) { v = String(v || ''); return /^[\x20-\x7e]{1,300}$/.test(v) ? v : ''; }
2572
+ function liveHeader(v, max) { v = String(v || ''); return v.length <= (max || 300) && /^[\x20-\x7e]+$/.test(v) ? v : ''; }
2573
+ function liveWho(q) { return { ua: liveHeader(q.ua), ref: liveHeader(q.ref), cookie: liveHeader(q.cookie, 4096) }; } // (a stream's own headers, as the app sends them)
2546
2574
  function liveControl(req, res, path, query, leaving) {
2547
2575
  livePurge();
2548
2576
  var q = {};
2549
2577
  (query || '').split('&').forEach(function (kv) { var i = kv.indexOf('='); if (i > 0) { try { q[kv.slice(0, i)] = decodeURIComponent(kv.slice(i + 1)); } catch (e) {} } });
2550
- if (path === '/live/master') { // an HLS stream's quality list, asked with its own User-Agent / Referer (which a web page can't send)
2578
+ if (path === '/live/master') { // an HLS stream's quality list (or a DASH manifest), asked with its own User-Agent / Referer (which a web page can't send)
2551
2579
  if (!entryAllowed(req, query)) { send(res, 403, 'text/plain', 'not allowed (token)'); return; }
2552
2580
  var mu = q.u || '';
2553
2581
  if (!/^https?:\/\/[^\s]+$/i.test(mu) || mu.length > 2000) { send(res, 400, 'text/plain', 'bad link'); return; }
2554
- leaving.push(liveGet(mu, { ua: liveHeader(q.ua), ref: liveHeader(q.ref) }, HLS_MASTER_MAX, function (err, buf) {
2582
+ leaving.push(liveGet(mu, liveWho(q), HLS_MASTER_MAX, function (err, buf) {
2555
2583
  if (err) { send(res, err.status || 502, 'text/plain', 'failed: ' + (err.message || 'unknown')); return; }
2556
2584
  var text = buf.toString('utf8').replace(/^\uFEFF/, '');
2557
- if (text.replace(/^\s+/, '').indexOf('#EXTM3U') !== 0) { send(res, 502, 'text/plain', 'not an HLS playlist'); return; }
2558
- send(res, 200, 'application/vnd.apple.mpegurl', text);
2585
+ var dash = /<MPD[\s>]/i.test(text.slice(0, 4000)); // (a DASH manifest: is it a film? see the player's manifestVod)
2586
+ if (text.replace(/^\s+/, '').indexOf('#EXTM3U') !== 0 && !dash) { send(res, 502, 'text/plain', 'not an HLS playlist'); return; }
2587
+ send(res, 200, dash ? 'application/dash+xml' : 'application/vnd.apple.mpegurl', text);
2559
2588
  }));
2560
2589
  return;
2561
2590
  }
2562
2591
  if (path === '/live/open') {
2563
2592
  if (!entryAllowed(req, query)) { send(res, 403, 'text/plain', 'not allowed (token)'); return; }
2564
- var u = q.u || '', who = { ua: liveHeader(q.ua), ref: liveHeader(q.ref) };
2593
+ var u = q.u || '', who = liveWho(q);
2565
2594
  if (!/^https?:\/\/[^\s]+$/i.test(u) || u.length > 2000) { send(res, 400, 'text/plain', 'bad link'); return; }
2566
2595
  var cc = ccAsked(q.cc);
2567
2596
  if (q.force === '1') {
@@ -2971,7 +3000,7 @@ function xtvControl(req, res, path, query) {
2971
3000
  answer();
2972
3001
  }
2973
3002
 
2974
- // ---- Stalker portals (/stalker/list, /stalker/link) ----
3003
+ // ---- Stalker portals (/stalker/list, /stalker/link, /stalker/genres; films and series below) ----
2975
3004
  // A Stalker (Ministra) portal, asked as a MAG box asks: its MAC address in a cookie, a MAG
2976
3005
  // User-Agent, a session token from a handshake (none of which a web page can send). Its API at
2977
3006
  // <address>/portal.php, else /server/load.php (the address's /c/ left out). list: its genres and
@@ -3158,8 +3187,148 @@ function stalkerM3u(s, list, genres) {
3158
3187
  s.cmds = cmds;
3159
3188
  return { m3u: out.join('\n') + '\n', count: n };
3160
3189
  }
3190
+
3191
+ // ---- A Stalker portal's films and series (/stalker/vod, /stalker/play) ----
3192
+ // Asked as they're shown, never read whole: cats (a type's categories: films type=vod, series
3193
+ // type=series, a portal without that module none), list (a category's titles, newest first, or
3194
+ // those a search finds: STALKER_VOD_TAKE from skip, STALKER_VOD_PAGES of the portal's pages at
3195
+ // most; a film that's a series, is_series, marked so), seasons (a series' seasons and their
3196
+ // episodes: a season's cmd and its episodes' numbers, or each episode's own cmd) and play (a film's
3197
+ // or an episode's link asked now, create_link, and sent there: what's saved to resume stays good).
3198
+ var STALKER_VOD_TAKE = 42, STALKER_VOD_PAGES = 4, STALKER_VOD_CATS_MS = 10 * 60000, STALKER_SEASONS = 60, STALKER_EPISODES = 500;
3199
+ // What a portal answered (a list from a position, a search, a series' seasons): kept
3200
+ // STALKER_VOD_KEEP_MS, the last STALKER_VOD_KEEP a portal, so a row or category shown again isn't
3201
+ // asked again (a portal may stop answering many quick asks); fresh=1 (Reload) lets it all go.
3202
+ var STALKER_VOD_KEEP_MS = 10 * 60000, STALKER_VOD_KEEP = 40;
3203
+ function stalkerKept(s, key) { var k = s.vodKept && s.vodKept[key]; return k && Date.now() - k.at < STALKER_VOD_KEEP_MS ? k.v : null; }
3204
+ function stalkerKeepVod(s, key, v) {
3205
+ if (!s.vodKept) { s.vodKept = Object.create(null); s.vodOrder = []; }
3206
+ if (!s.vodKept[key]) { s.vodOrder.push(key); while (s.vodOrder.length > STALKER_VOD_KEEP) { delete s.vodKept[s.vodOrder.shift()]; } }
3207
+ s.vodKept[key] = { at: Date.now(), v: v };
3208
+ }
3209
+ function stalkerText(v, n) { return String(v == null ? '' : v).replace(/\s+/g, ' ').trim().slice(0, n); }
3210
+ function stalkerCmdOk(cmd) { return !!cmd && cmd.length <= 2000 && !/[\r\n]/.test(cmd); }
3211
+ function stalkerVodItem(s, o) {
3212
+ if (!o || typeof o !== 'object' || o.id == null) { return null; }
3213
+ var id = String(o.id), name = stalkerText(o.name || o.o_name, 200);
3214
+ if (!/^[\w-]{1,40}$/.test(id) || !name) { return null; }
3215
+ var it = { id: id, name: name }, y = parseInt(o.year, 10), pic = String(o.screenshot_uri || o.cover || ''), r = parseFloat(o.rating_imdb) || parseFloat(o.rating_kinopoisk), t = parseInt(o.time, 10), cmd = String(o.cmd || '');
3216
+ if (y > 1880 && y < 2100) { it.year = y; }
3217
+ if (/^\//.test(pic)) { var b = urllib.parse(s.base); pic = b.protocol + '//' + b.host + pic; } // (a picture on the portal's own server)
3218
+ if (/^https?:\/\//i.test(pic) && pic.length < 600) { it.pic = pic; }
3219
+ if (r > 0 && r <= 10) { it.rating = Math.round(r * 10) / 10; }
3220
+ if (stalkerText(o.description, 1)) { it.desc = stalkerText(o.description, 2000); }
3221
+ if (stalkerText(o.director, 1)) { it.director = stalkerText(o.director, 200); }
3222
+ if (stalkerText(o.actors, 1)) { it.cast = stalkerText(o.actors, 400); }
3223
+ if (stalkerText(o.genres_str, 1)) { it.genres = stalkerText(o.genres_str, 200); }
3224
+ if (t > 0 && t < 1000) { it.mins = t; }
3225
+ if (stalkerCmdOk(cmd)) { it.cmd = cmd; }
3226
+ if (+o.is_series === 1 || o.is_series === true) { it.series = true; }
3227
+ return it;
3228
+ }
3229
+ function stalkerVodCats(s, type, ctl, cb) {
3230
+ var kept = s.vodCats && s.vodCats[type];
3231
+ if (kept && Date.now() - kept.at < STALKER_VOD_CATS_MS) { cb(null, kept.list); return; }
3232
+ stalkerAsk(s, 'type=' + (type === 'movie' ? 'vod' : 'series') + '&action=get_categories', ctl, function (err, js) {
3233
+ if (err && (err.auth || type === 'movie')) { cb(err); return; } // (no series module: no series)
3234
+ var list = (Array.isArray(js) ? js : []).filter(function (x) { return x && x.id != null && String(x.id) !== '*' && x.title; }).slice(0, STALKER_GENRES)
3235
+ .map(function (x) { return { id: String(x.id).slice(0, 40), title: stalkerText(x.title, 100) }; });
3236
+ s.vodCats = s.vodCats || {};
3237
+ s.vodCats[type] = { at: Date.now(), list: list };
3238
+ cb(null, list);
3239
+ });
3240
+ }
3241
+ // cb(err, { items, more }): from skip on, in the portal's pages (s.vodSize titles each, learned
3242
+ // from its first answer: a page asked for that first, once, when skip is past it).
3243
+ function stalkerVodList(s, type, cat, words, skip, ctl, cb) {
3244
+ var params = 'type=' + (type === 'movie' ? 'vod' : 'series') + '&action=get_ordered_list&category=' + encodeURIComponent(cat || '*') + '&genre=*&sortby=added&hd=0&not_ended=0&fav=0' +
3245
+ (words ? '&search=' + encodeURIComponent(words) : '');
3246
+ function page(p, done) {
3247
+ stalkerAsk(s, params + '&p=' + p, ctl, function (err, o) {
3248
+ if (err) { done(err); return; }
3249
+ var d = o && Array.isArray(o.data) ? o.data : [], total = +(o && o.total_items) || 0;
3250
+ if (!s.vodSize && d.length && total > d.length) { s.vodSize = d.length; }
3251
+ done(null, d, total);
3252
+ });
3253
+ }
3254
+ function from() {
3255
+ var size = s.vodSize || STALKER_VOD_TAKE, p = Math.floor(skip / size) + 1, drop = skip % size, out = [], asked = 0;
3256
+ (function more() {
3257
+ page(p, function (err, d, total) {
3258
+ if (err) { if (out.length) { cb(null, { items: out, more: true }); } else { cb(err); } return; }
3259
+ asked++;
3260
+ d.slice(drop).forEach(function (o) { var it = stalkerVodItem(s, o); if (it) { out.push(it); } });
3261
+ drop = 0;
3262
+ var left = d.length && (!total || p * (s.vodSize || d.length) < total);
3263
+ if (!left || out.length >= STALKER_VOD_TAKE || asked >= STALKER_VOD_PAGES) { cb(null, { items: out.slice(0, STALKER_VOD_TAKE * 2), more: !!left }); return; }
3264
+ p++;
3265
+ more();
3266
+ });
3267
+ })();
3268
+ }
3269
+ if (skip > 0 && !s.vodSize) {
3270
+ page(1, function (err, d) {
3271
+ if (err) { cb(err); return; }
3272
+ if (s.vodSize) { from(); return; }
3273
+ var out = []; // (one page held all there is)
3274
+ d.slice(skip).forEach(function (o) { var it = stalkerVodItem(s, o); if (it) { out.push(it); } });
3275
+ cb(null, { items: out, more: false });
3276
+ });
3277
+ return;
3278
+ }
3279
+ from();
3280
+ }
3281
+ // A series' seasons: { season, name, cmd, eps: [{ n, cmd?, name? }] }. viaVod: a film that's a
3282
+ // series (is_series), its seasons asked of the films (type=vod).
3283
+ function stalkerSeasonNo(o, at) {
3284
+ var n = parseInt(o.season_number, 10), m = /(\d+)/.exec(String(o.name || ''));
3285
+ return n >= 0 ? n : m ? +m[1] : at;
3286
+ }
3287
+ function stalkerSeasons(s, id, viaVod, ctl, cb) {
3288
+ var base = viaVod ? 'type=vod&action=get_ordered_list&movie_id=' + encodeURIComponent(id) : 'type=series&action=get_ordered_list&movie_id=' + encodeURIComponent(id) + '&season_id=0&episode_id=0';
3289
+ var out = [], p = 1;
3290
+ function all(params, each, done) { // (every page of an answer, 10 at most)
3291
+ var page = 1, got = 0;
3292
+ (function more() {
3293
+ stalkerAsk(s, params + '&p=' + page, ctl, function (err, o) {
3294
+ if (err) { done(err); return; }
3295
+ var d = o && Array.isArray(o.data) ? o.data : [], total = +(o && o.total_items) || 0;
3296
+ d.forEach(function (x, i) { each(x, got + i + 1); });
3297
+ got += d.length;
3298
+ if (d.length && page < 10 && total > got) { page++; more(); } else { done(null); }
3299
+ });
3300
+ })();
3301
+ }
3302
+ all(base, function (x, at) {
3303
+ if (!x || typeof x !== 'object' || out.length >= STALKER_SEASONS) { return; }
3304
+ var cmd = String(x.cmd || ''), eps = Array.isArray(x.series) ? x.series.map(function (n) { return parseInt(n, 10); }).filter(function (n) { return n >= 0; }).slice(0, STALKER_EPISODES) : null;
3305
+ out.push({ season: stalkerSeasonNo(x, at), name: stalkerText(x.name, 100), cmd: stalkerCmdOk(cmd) ? cmd : '', id: String(x.id == null ? '' : x.id).slice(0, 60), eps: eps ? eps.map(function (n) { return { n: n }; }) : null });
3306
+ }, function (err) {
3307
+ if (err && !out.length) { cb(err); return; }
3308
+ (function next(i) { // (seasons that don't list their episodes: asked for them, each with its own cmd)
3309
+ while (i < out.length && out[i].eps) { i++; }
3310
+ if (i >= out.length || viaVod) { cb(null, out.filter(function (x) { return x.eps && x.eps.length; }).map(function (x) { delete x.id; return x; })); return; }
3311
+ var se = out[i];
3312
+ se.eps = [];
3313
+ all('type=series&action=get_ordered_list&movie_id=' + encodeURIComponent(id) + '&season_id=' + encodeURIComponent(se.id) + '&episode_id=0', function (e, at) {
3314
+ var cmd = String((e && e.cmd) || '');
3315
+ if (!e || !stalkerCmdOk(cmd) || se.eps.length >= STALKER_EPISODES) { return; }
3316
+ var n = parseInt(e.series_number, 10), m = /(\d+)/.exec(String(e.name || ''));
3317
+ se.eps.push({ n: n >= 0 ? n : m ? +m[1] : at, cmd: cmd, name: stalkerText(e.name, 120) });
3318
+ }, function () { next(i + 1); });
3319
+ })(0);
3320
+ });
3321
+ }
3322
+ // A film's or an episode's link to play now: cmd (an episode of a season's cmd: ep, its number).
3323
+ function stalkerVodLink(s, cmd, ep, ctl, cb) {
3324
+ stalkerAsk(s, 'type=vod&action=create_link&cmd=' + encodeURIComponent(cmd) + '&series=' + (ep >= 0 ? ep : '') + '&forced_storage=undefined&disable_ad=0&download=0&force_ch_link_check=0', ctl, function (err, js) {
3325
+ if (err) { cb(err); return; }
3326
+ var m = /(https?:\/\/[^\s"]+)/i.exec(String((js && js.cmd) || ''));
3327
+ cb(m ? null : upError('the portal gave no link for this title', 502), m ? m[1] : null);
3328
+ });
3329
+ }
3161
3330
  function stalkerControl(req, res, path, query, leaving) {
3162
- if (!entryAllowed(req, query)) { send(res, 403, 'text/plain', 'not allowed (token)'); return; }
3331
+ if (!entryAllowed(req, query) && !(path === '/stalker/play' && hasTicket(query))) { send(res, 403, 'text/plain', 'not allowed (token)'); return; } // (play: the player asks, without the header)
3163
3332
  var q = {};
3164
3333
  (query || '').split('&').forEach(function (kv) { var i = kv.indexOf('='); if (i > 0) { try { q[kv.slice(0, i)] = decodeURIComponent(kv.slice(i + 1)); } catch (e) {} } });
3165
3334
  var portal = String(q.portal || '').trim(), mac = String(q.mac || '').toUpperCase();
@@ -3181,6 +3350,37 @@ function stalkerControl(req, res, path, query, leaving) {
3181
3350
  }, function (err, link) { json(err ? { why: err.message || 'failed' } : { url: link }); });
3182
3351
  return;
3183
3352
  }
3353
+ if (path === '/stalker/play') { // (a film's or episode's link: asked now, and sent there)
3354
+ var cmd = String(q.cmd || ''), ep = /^\d{1,4}$/.test(q.ep || '') ? +q.ep : -1;
3355
+ if (!stalkerCmdOk(cmd)) { send(res, 400, 'text/plain', 'bad title'); return; }
3356
+ stalkerWith(s, portal, mac, ctl, function (ss, done) { stalkerVodLink(ss, cmd, ep, ctl, done); }, function (err, link) {
3357
+ if (err) { log('Stalker: no link for a title (' + (err.message || 'failed') + ')'); send(res, 502, 'text/plain', err.message || 'failed'); return; }
3358
+ res.writeHead(302, { 'Location': link, 'Cache-Control': 'no-store' });
3359
+ res.end();
3360
+ });
3361
+ return;
3362
+ }
3363
+ if (path === '/stalker/vod') {
3364
+ var type = q.type === 'series' ? 'series' : 'movie', what = String(q.do || '');
3365
+ if (q.fresh === '1') { s.vodCats = null; s.vodKept = null; s.vodOrder = null; } // (Reload: all of it read again)
3366
+ var vkey = what === 'list' || what === 'seasons' ? [what, type, q.cat || '*', String(q.q || '').trim().slice(0, 120), parseInt(q.skip, 10) || 0, q.id || '', q.via || ''].join('|') : '';
3367
+ var kept = vkey && stalkerKept(s, vkey);
3368
+ if (kept) { json(kept); return; }
3369
+ stalkerWith(s, portal, mac, ctl, function (ss, done) {
3370
+ if (what === 'cats') { stalkerVodCats(ss, type, ctl, function (err, list) { done(err, { cats: list }); }); return; }
3371
+ if (what === 'list') {
3372
+ var cat = /^[\w.-]{1,40}$/.test(q.cat || '') ? q.cat : '*', words = String(q.q || '').trim().slice(0, 120), skip = Math.min(parseInt(q.skip, 10) || 0, 100000);
3373
+ stalkerVodList(ss, type, cat, words, skip, ctl, done);
3374
+ return;
3375
+ }
3376
+ if (what === 'seasons' && /^[\w-]{1,40}$/.test(q.id || '')) { stalkerSeasons(ss, q.id, q.via === 'vod', ctl, function (err, l) { done(err, { seasons: l }); }); return; }
3377
+ done(upError('bad request', 400));
3378
+ }, function (err, r) {
3379
+ if (!err && vkey) { stalkerKeepVod(s, vkey, r); } // (an error isn't kept: asked again next time)
3380
+ json(err ? { why: err.message || 'failed' } : r);
3381
+ });
3382
+ return;
3383
+ }
3184
3384
  if (path === '/stalker/genres') {
3185
3385
  stalkerWith(s, portal, mac, ctl, function (ss, done) { stalkerAsk(ss, 'type=itv&action=get_genres', ctl, done); }, function (err, js) {
3186
3386
  if (err) { json({ why: err.message || 'failed' }); return; }
@@ -3214,6 +3414,54 @@ function stalkerControl(req, res, path, query, leaving) {
3214
3414
  });
3215
3415
  }
3216
3416
 
3417
+ // ---- A DRM channel's license (/drm/license) ----
3418
+ // A Widevine channel's license request, posted to the license server its playlist names, with the
3419
+ // playlist's headers for it (a web page can't send a User-Agent, a Cookie…, and some servers refuse
3420
+ // its origin), its answer sent back in base64. The player hands over the request and installs the
3421
+ // answer (see js/player-core.js, drmSetup). POSTed: { u: the license server, h: { name: value },
3422
+ // c: the request, base64, b64: the answer is base64 already }; the token, or the guide ticket.
3423
+ var DRM_BODY_MAX = 65536, DRM_MS = 15000, DRM_MAX = 1048576;
3424
+ var DRM_NOT = /^(host|content-length|connection|transfer-encoding|keep-alive|upgrade|te|trailer|proxy-.*)$/i;
3425
+ function drmControl(req, res, query, body, leaving) {
3426
+ if (!entryAllowed(req, query) && !hasTicket(query)) { send(res, 403, 'text/plain', 'not allowed (token)'); return; }
3427
+ var o = null;
3428
+ try { o = JSON.parse(body); } catch (e) { o = null; }
3429
+ function json(x) { send(res, 200, 'application/json', JSON.stringify(x)); }
3430
+ var u = o && typeof o.u === 'string' ? o.u : '', c = o && typeof o.c === 'string' ? o.c : '', pu = null;
3431
+ try { pu = urllib.parse(u); } catch (e) { pu = null; }
3432
+ if (!pu || (pu.protocol !== 'http:' && pu.protocol !== 'https:') || u.length > 2000 || !dlHostOk(pu.hostname)) { json({ why: 'not a license server StremioK can reach' }); return; }
3433
+ if (!c || !/^[A-Za-z0-9+\/=]+$/.test(c)) { json({ why: 'no license request' }); return; }
3434
+ var data = HAS_BUFFER_FROM ? Buffer.from(c, 'base64') : new Buffer(c, 'base64'), h = { 'Content-Type': 'application/octet-stream', 'User-Agent': TV_UA, 'Accept': '*/*' };
3435
+ Object.keys((o.h && typeof o.h === 'object') ? o.h : {}).slice(0, 16).forEach(function (k) {
3436
+ var v = o.h[k];
3437
+ if (/^[A-Za-z0-9-]{1,40}$/.test(k) && !DRM_NOT.test(k) && typeof v === 'string' && v.length <= 1000 && !/[\r\n]/.test(v)) { h[k] = v; }
3438
+ });
3439
+ h['Content-Length'] = data.length;
3440
+ var done = false, r = null, chunks = [], size = 0;
3441
+ var timer = setTimeout(function () { finish({ why: 'the license server didn\'t answer' }); }, DRM_MS);
3442
+ function finish(x) { if (done) { return; } done = true; clearTimeout(timer); try { if (x.why && r) { r.abort(); } } catch (e) {} if (x.why) { log('DRM: no license (' + x.why + ')'); } json(x); }
3443
+ leaving.push(function () { done = true; clearTimeout(timer); try { if (r) { r.abort(); } } catch (e) {} });
3444
+ var opts = { hostname: pu.hostname, port: pu.port, path: pu.path, method: 'POST', headers: h };
3445
+ if (pu.protocol === 'https:' && caList().length) { opts.ca = caList(); }
3446
+ try {
3447
+ r = (pu.protocol === 'https:' ? https : http).request(opts, function (resp) {
3448
+ var sc = resp.statusCode;
3449
+ resp.on('data', function (b) { if (done) { return; } chunks.push(b); size += b.length; if (size > DRM_MAX) { finish({ why: 'too large an answer' }); } });
3450
+ resp.on('end', function () {
3451
+ if (done) { return; }
3452
+ var all = Buffer.concat(chunks, size);
3453
+ if (sc !== 200) { finish({ why: 'HTTP ' + sc + (all.length && all.length < 200 ? ': ' + all.toString('utf8').replace(/\s+/g, ' ').trim().slice(0, 120) : '') }); return; }
3454
+ if (!all.length) { finish({ why: 'an empty answer' }); return; }
3455
+ finish({ license: o.b64 ? all.toString('utf8').trim() : all.toString('base64') });
3456
+ });
3457
+ resp.on('error', function (e) { finish({ why: e.message || 'failed' }); });
3458
+ });
3459
+ r.on('error', function (e) { finish({ why: 'couldn\'t reach it (' + (e.code || e.message) + ')' }); });
3460
+ guardSelf(r, function () { finish({ why: 'an address it can\'t reach' }); });
3461
+ r.end(data);
3462
+ } catch (e) { finish({ why: e.message || 'failed' }); }
3463
+ }
3464
+
3217
3465
  // ---- TV guide (/epg/load, /epg/get) ----
3218
3466
  // A playlist's XMLTV guide, read for StremioK's channels only. The app sends their keys (epgKey:
3219
3467
  // "i:" and a tvg-id, "n:" and a name without capitals, accents, spaces or HD / FHD / 4K tags) as
@@ -3627,8 +3875,11 @@ function epgControl(req, res, path, query) {
3627
3875
  // minute. The port is open only while one is: ENTRY_CONNECTIONS at a time, each given
3628
3876
  // ENTRY_VISIT_MS (ENTRY_QUIET_MS of silence). It's plain HTTP: the page says so.
3629
3877
  var ENTRY_PORT = PORT + 10, ENTRY_MS = 5 * 60 * 1000, ENTRY_IDLE_MS = 30000, ENTRY_MAX = 8192;
3878
+ // A configuration file: pasted on the import's page (CONFIG_MAX, sent %-encoded: 3 times that), or
3879
+ // given by the TV to the export's page (GIVE_MAX, POSTed to /entry/give), shown to copy or download.
3880
+ var CONFIG_MAX = 262144, GIVE_MAX = 262144;
3630
3881
  var ENTRY_OPEN_MAX = 2, ENTRY_OPENS = 12, ENTRY_CONNECTIONS = 8, ENTRY_VISIT_MS = 20000, ENTRY_QUIET_MS = 10000;
3631
- var ENTRY_TITLES = { link: 'Play a link on StremioK', addon: 'Add an addon to StremioK', playlist: 'Add an IPTV playlist to StremioK', config: 'Import a configuration file into StremioK',
3882
+ var ENTRY_TITLES = { link: 'Play a link on StremioK', addon: 'Add an addon to StremioK', playlist: 'Add an IPTV playlist to StremioK', config: 'Import a configuration file into StremioK', give: 'Your StremioK configuration',
3632
3883
  search: 'Search on StremioK', youtube: 'Add a YouTube catalog to StremioK', aiom: 'Your AIOManager address for StremioK', aiomkey: 'Your AIOManager API key for StremioK',
3633
3884
  server: 'Your streaming server’s address for StremioK', mac: 'Your Stalker portal’s MAC address for StremioK' };
3634
3885
  var ENTRY_TEXT = { search: 'Words to search for', youtube: 'A channel, a playlist link, or words to search YouTube for', aiomkey: 'Your account API key', mac: 'Its MAC address (00:1A:79:…)' }; // (plain text, not a link)
@@ -3668,21 +3919,22 @@ function entryIdle(token) {
3668
3919
  clearTimeout(e.idle);
3669
3920
  e.idle = setTimeout(function () { entryDrop(token); }, ENTRY_IDLE_MS);
3670
3921
  }
3671
- function entryControl(req, res, path, query) {
3672
- if (!entryAllowed(req, query)) { send(res, 403, 'text/plain', 'not allowed'); return; }
3922
+ function entryControl(req, res, path, query, body) {
3923
+ if (!entryAllowed(req, query) && !(path === '/entry/give' && hasTicket(query))) { send(res, 403, 'text/plain', 'not allowed'); return; } // (the export's POST: the guide ticket too)
3673
3924
  var tm = /(?:^|&)t=([0-9a-f]{32})(?:&|$)/.exec(query || ''), token = tm ? tm[1] : '';
3674
- if (path === '/entry/open') {
3925
+ if (path === '/entry/open' || path === '/entry/give') {
3926
+ if (path === '/entry/give' && !String(body || '').trim()) { send(res, 400, 'text/plain', 'nothing to give'); return; }
3675
3927
  var now = Date.now();
3676
3928
  _entryOpened = _entryOpened.filter(function (x) { return now - x < 60000; });
3677
3929
  if (_entryOpened.length >= ENTRY_OPENS) { send(res, 429, 'text/plain', 'too many, try again in a minute'); return; }
3678
- var wm = /(?:^|&)what=([a-z]{1,12})(?:&|$)/.exec(query || ''), what = wm && ENTRY_TITLES[wm[1]] ? wm[1] : 'link';
3930
+ var wm = /(?:^|&)what=([a-z]{1,12})(?:&|$)/.exec(query || ''), what = path === '/entry/give' ? 'give' : wm && ENTRY_TITLES[wm[1]] && wm[1] !== 'give' ? wm[1] : 'link';
3679
3931
  var ip = lanAddress();
3680
3932
  if (!ip) { send(res, 503, 'text/plain', 'no home network address'); return; }
3681
3933
  _entryOpened.push(now);
3682
3934
  var open = Object.keys(_entries).sort(function (a, b) { return _entries[a].at - _entries[b].at; });
3683
3935
  while (open.length >= ENTRY_OPEN_MAX) { entryDrop(open.shift(), true); } // (the oldest goes)
3684
3936
  var t = crypto.randomBytes(16).toString('hex');
3685
- _entries[t] = { what: what, text: null, sent: false, at: now, timer: setTimeout(function () { entryDrop(t); }, ENTRY_MS), idle: null };
3937
+ _entries[t] = { what: what, text: null, sent: false, at: now, timer: setTimeout(function () { entryDrop(t); }, ENTRY_MS), idle: null, give: what === 'give' ? String(body) : null, seen: false };
3686
3938
  entryIdle(t);
3687
3939
  var opened = function () { send(res, 200, 'application/json', JSON.stringify({ url: 'http://' + ip + ':' + ENTRY_PORT + '/e/' + t, token: t, expires: ENTRY_MS })); };
3688
3940
  if (_entryServer) { opened(); return; }
@@ -3708,7 +3960,7 @@ function entryControl(req, res, path, query) {
3708
3960
  if (path === '/entry/poll') {
3709
3961
  var text = e.text;
3710
3962
  if (e.sent) { entryDrop(token); } else { entryIdle(token); } // (collected: the page and its code go)
3711
- send(res, 200, 'application/json', JSON.stringify({ text: text }));
3963
+ send(res, 200, 'application/json', JSON.stringify(e.give !== null ? { seen: e.seen } : { text: text })); // (an export: whether the phone has it)
3712
3964
  return;
3713
3965
  }
3714
3966
  if (path === '/entry/close') { entryDrop(token); send(res, 200, 'text/plain', 'closed'); return; }
@@ -3717,16 +3969,36 @@ function entryControl(req, res, path, query) {
3717
3969
  function entryHtml(title, body) {
3718
3970
  return '<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">' +
3719
3971
  '<title>' + title + '</title><style>body{font-family:-apple-system,Roboto,sans-serif;background:#0e1117;color:#e6e9ef;margin:0;padding:24px}' +
3720
- 'h1{font-size:22px;margin:0 0 16px}input{width:100%;box-sizing:border-box;font-size:17px;padding:12px;border-radius:10px;border:1px solid #2a3346;background:#161b26;color:#e6e9ef}' +
3972
+ 'h1{font-size:22px;margin:0 0 16px}input,textarea{width:100%;box-sizing:border-box;font-size:17px;padding:12px;border-radius:10px;border:1px solid #2a3346;background:#161b26;color:#e6e9ef}' +
3721
3973
  'button{margin-top:14px;width:100%;font-size:17px;padding:12px;border:0;border-radius:10px;background:#818cf8;color:#0e1117;font-weight:600}p{color:#9aa3b5;font-size:15px}</style></head><body>' +
3722
3974
  '<h1>' + title + '</h1>' + body + '</body></html>';
3723
3975
  }
3724
3976
  function entryPage(req, res) {
3725
3977
  try {
3726
3978
  res.setHeader('Cache-Control', 'no-store');
3727
- var m = /^\/e\/([0-9a-f]{32})$/.exec(String(req.url || '')), e = m && _entries[m[1]];
3979
+ var m = /^\/e\/([0-9a-f]{32})(\/stremiok\.txt)?$/.exec(String(req.url || '')), e = m && _entries[m[1]];
3728
3980
  if (!e || e.sent) { send(res, 404, 'text/plain', 'Not here (it was used, or the TV closed it)'); return; }
3729
3981
  var title = ENTRY_TITLES[e.what];
3982
+ if (e.give !== null) { // (an export: the file to copy, or download)
3983
+ if (req.method !== 'GET') { send(res, 405, 'text/plain', 'GET only'); return; }
3984
+ e.seen = true;
3985
+ if (m[2]) { res.setHeader('Content-Disposition', 'attachment; filename="stremiok.txt"'); send(res, 200, 'text/plain; charset=utf-8', e.give); return; }
3986
+ var esc = e.give.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
3987
+ send(res, 200, 'text/html; charset=utf-8', entryHtml(title, '<p>It holds your addon links, playlist logins, API keys and MAC addresses: keep it somewhere private. To restore it: Settings › Content › Import configuration file, ▣ From your phone, then choose this file there (or paste it).</p>' +
3988
+ '<textarea id="f" readonly rows="12">' + esc + '</textarea><button type="button" onclick="var f=document.getElementById(\'f\');f.focus();f.select();try{document.execCommand(\'copy\');this.textContent=\'Copied\';}catch(x){}">Copy</button>' +
3989
+ '<a href="/e/' + m[1] + '/stremiok.txt" download="stremiok.txt"><button type="button">Download</button></a><p>It came over your home network <b>unencrypted</b>. This page closes when the TV stops showing its code.</p>'));
3990
+ return;
3991
+ }
3992
+ if (m[2]) { send(res, 404, 'text/plain', 'Not here'); return; }
3993
+ var config = e.what === 'config', max = config ? CONFIG_MAX * 3 : ENTRY_MAX; // (a pasted file: its lines kept, %-encoded as sent)
3994
+ if (req.method === 'GET' && config) { // (its link, as before; or the file itself, chosen from the phone's files or pasted)
3995
+ send(res, 200, 'text/html; charset=utf-8', entryHtml(title, '<form method="post"><p>A link to the file</p><input name="link" type="url" autocomplete="off" placeholder="https://…">' +
3996
+ '<p>Or the file itself (an export\'s stremiok.txt)</p><input id="pick" type="file" accept=".txt,.cfg,.conf,text/plain">' +
3997
+ '<textarea id="f" name="text" rows="8" autocomplete="off" placeholder="…or paste it here"></textarea>' +
3998
+ '<button type="submit">Send to the TV</button></form><p>It goes straight to your TV over your home network, <b>unencrypted</b>: use this only on a network you trust (a configuration file holds your tokens, passwords and keys). This page stops working once it has been sent.</p>' +
3999
+ '<script>document.getElementById("pick").onchange=function(){var f=this.files&&this.files[0];if(!f){return;}var r=new FileReader();r.onload=function(){document.getElementById("f").value=r.result;};r.readAsText(f);};</script>'));
4000
+ return;
4001
+ }
3730
4002
  if (req.method === 'GET') {
3731
4003
  var plain = ENTRY_TEXT[e.what];
3732
4004
  send(res, 200, 'text/html; charset=utf-8', entryHtml(title, '<form method="post"><input name="text" type="' + (plain ? 'text' : 'url') + '" autofocus autocomplete="off" placeholder="' + (plain || 'https://…') + '" required>' +
@@ -3739,14 +4011,16 @@ function entryPage(req, res) {
3739
4011
  req.on('data', function (c) {
3740
4012
  if (done) { return; }
3741
4013
  size += c.length;
3742
- if (size > ENTRY_MAX) { done = true; send(res, 413, 'text/plain', 'Too long'); return; } // (the rest read and dropped: the connection stays usable)
4014
+ if (size > max) { done = true; send(res, 413, 'text/plain', 'Too long'); return; } // (the rest read and dropped: the connection stays usable)
3743
4015
  body += c;
3744
4016
  });
3745
4017
  req.on('end', function () {
3746
4018
  if (done) { return; }
3747
4019
  done = true;
3748
- var tm = /(?:^|&)text=([^&]*)/.exec(body), text = '';
3749
- try { text = tm ? decodeURIComponent(tm[1].replace(/\+/g, ' ')).replace(/[\r\n\t]+/g, ' ').trim() : ''; } catch (e3) { text = ''; }
4020
+ var tm = /(?:^|&)text=([^&]*)/.exec(body), lm = config && /(?:^|&)link=([^&]*)/.exec(body), text = '';
4021
+ try { text = tm ? decodeURIComponent(tm[1].replace(/\+/g, ' ')) : ''; } catch (e3) { text = ''; }
4022
+ if (!text.trim() && lm) { try { text = decodeURIComponent(lm[1].replace(/\+/g, ' ')); } catch (e4) { text = ''; } } // (a link to the file, as before)
4023
+ text = config ? text.replace(/\r\n?/g, '\n').trim().slice(0, CONFIG_MAX) : text.replace(/[\r\n\t]+/g, ' ').trim();
3750
4024
  if (!text || !_entries[m[1]] || e.sent) { send(res, 400, 'text/plain', 'Nothing sent'); return; }
3751
4025
  e.text = text; e.sent = true;
3752
4026
  send(res, 200, 'text/html; charset=utf-8', entryHtml(title, '<p>Sent to your TV.</p>'));