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/service/index.js CHANGED
@@ -40,6 +40,10 @@
40
40
  * only; /epg/get?u=<guide>&ids=<key>|<key>&from&to[&max] -> JSON { <key>:
41
41
  * [[start, stop, title, desc, picture?, about?]], _icons: { <key>: logo } }: their programs and
42
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
43
47
  * /epg/ticket -> JSON { ticket }: for guide POSTs from an app without the token (see hasTicket)
44
48
  * /epg/files -> JSON { count, bytes, xtv: { count, bytes } }: the saved guides, and Xtream lists;
45
49
  * /epg/clear (POST) -> { cleared }: all of them deleted
@@ -1794,12 +1798,14 @@ function handle(req, res) {
1794
1798
  // The app's own guide POSTs: a browser sends an Origin with every POST (the app's page is
1795
1799
  // file://: "null"); let through with the token, or the guide ticket (for an app that can't
1796
1800
  // read the token: see /epg/ticket), which no web page has (/epg/ only).
1797
- 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)
1798
1802
  if (who) { send(res, 403, 'text/plain', 'not allowed (' + who + ')'); return; }
1799
1803
  if (req.method === 'OPTIONS') { if (isFs) { send(res, 403, 'text/plain', 'not allowed'); return; } res.writeHead(200); res.end(); return; }
1800
1804
  var epgPost = req.method === 'POST' && /^\/epg\/(load|get|clear)$/.test(path); // (a guide's channels: in the body, see epgControl)
1801
- if (req.method !== 'GET' && !epgPost) { send(res, 405, 'text/plain', 'GET only'); return; } // (before any work)
1802
- 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)
1803
1809
  // (StremioK gave up on it — a screen left, the player closed: what it still waits for is
1804
1810
  // dropped; 'close' before the response finished means that on every Node)
1805
1811
  var leaving = [];
@@ -1810,6 +1816,14 @@ function handle(req, res) {
1810
1816
  res.on('close', function () { clearTimeout(deadline); if (!res.finished) { leaveAll(); } });
1811
1817
  }
1812
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
+ }
1813
1827
  if (/^\/entry\//.test(path)) { entryControl(req, res, path, parts[1]); return; }
1814
1828
  if (/^\/live\//.test(path)) { liveControl(req, res, path, parts[1], leaving); return; }
1815
1829
  if (epgPost) { // what's asked, in the body (to EPG_BODY_MAX), after the address's own (its token)
@@ -1820,6 +1834,14 @@ function handle(req, res) {
1820
1834
  req.on('end', function () { if (!over) { epgControl(req, res, path, (parts[1] ? parts[1] + '&' : '') + body); } });
1821
1835
  return;
1822
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
+ }
1823
1845
  if (/^\/epg\//.test(path)) { epgControl(req, res, path, parts[1]); return; } // (a playlist's TV guide: see epgControl)
1824
1846
  if (path === '/aiom/addons') { aiomControl(req, res, parts[1], leaving); return; }
1825
1847
  if (path === '/xtvod/list' || path === '/xtvod/find') { xtvControl(req, res, path, parts[1]); return; } // (an Xtream account's films and series: see xtvControl)
@@ -1980,6 +2002,7 @@ function liveGet(u, who, max, cb, part) {
1980
2002
  if ((pu.protocol !== 'http:' && pu.protocol !== 'https:') || !dlHostOk(pu.hostname)) { cb(upError('a link it can\'t follow', 400)); return; }
1981
2003
  var h = { 'User-Agent': who.ua || TV_UA };
1982
2004
  if (who.ref) { h.Referer = who.ref; }
2005
+ if (who.cookie) { h.Cookie = who.cookie; }
1983
2006
  var opts = { hostname: pu.hostname, port: pu.port, path: pu.path, headers: h };
1984
2007
  if (pu.protocol === 'https:' && caList().length) { opts.ca = caList(); }
1985
2008
  var chunks = [], size = 0, done = false;
@@ -2502,7 +2525,7 @@ function liveSession(u, who, opts) {
2502
2525
  ids.sort(function (x, y) { return _live[x].last - _live[y].last; });
2503
2526
  delete _live[ids[0]];
2504
2527
  }
2505
- 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(),
2506
2529
  fix: opts.fix !== false, cc: opts.cc && opts.cc.length ? opts.cc : null, c: ccState(), got: Object.create(null) };
2507
2530
  _live[s.id] = s;
2508
2531
  s.top = liveLink(s, u, 'm');
@@ -2546,26 +2569,28 @@ function liveProbe(u, who, cb, leaving) {
2546
2569
  }
2547
2570
  list(u);
2548
2571
  }
2549
- 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)
2550
2574
  function liveControl(req, res, path, query, leaving) {
2551
2575
  livePurge();
2552
2576
  var q = {};
2553
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) {} } });
2554
- 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)
2555
2579
  if (!entryAllowed(req, query)) { send(res, 403, 'text/plain', 'not allowed (token)'); return; }
2556
2580
  var mu = q.u || '';
2557
2581
  if (!/^https?:\/\/[^\s]+$/i.test(mu) || mu.length > 2000) { send(res, 400, 'text/plain', 'bad link'); return; }
2558
- 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) {
2559
2583
  if (err) { send(res, err.status || 502, 'text/plain', 'failed: ' + (err.message || 'unknown')); return; }
2560
2584
  var text = buf.toString('utf8').replace(/^\uFEFF/, '');
2561
- if (text.replace(/^\s+/, '').indexOf('#EXTM3U') !== 0) { send(res, 502, 'text/plain', 'not an HLS playlist'); return; }
2562
- 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);
2563
2588
  }));
2564
2589
  return;
2565
2590
  }
2566
2591
  if (path === '/live/open') {
2567
2592
  if (!entryAllowed(req, query)) { send(res, 403, 'text/plain', 'not allowed (token)'); return; }
2568
- var u = q.u || '', who = { ua: liveHeader(q.ua), ref: liveHeader(q.ref) };
2593
+ var u = q.u || '', who = liveWho(q);
2569
2594
  if (!/^https?:\/\/[^\s]+$/i.test(u) || u.length > 2000) { send(res, 400, 'text/plain', 'bad link'); return; }
2570
2595
  var cc = ccAsked(q.cc);
2571
2596
  if (q.force === '1') {
@@ -3171,6 +3196,16 @@ function stalkerM3u(s, list, genres) {
3171
3196
  // episodes: a season's cmd and its episodes' numbers, or each episode's own cmd) and play (a film's
3172
3197
  // or an episode's link asked now, create_link, and sent there: what's saved to resume stays good).
3173
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
+ }
3174
3209
  function stalkerText(v, n) { return String(v == null ? '' : v).replace(/\s+/g, ' ').trim().slice(0, n); }
3175
3210
  function stalkerCmdOk(cmd) { return !!cmd && cmd.length <= 2000 && !/[\r\n]/.test(cmd); }
3176
3211
  function stalkerVodItem(s, o) {
@@ -3327,6 +3362,10 @@ function stalkerControl(req, res, path, query, leaving) {
3327
3362
  }
3328
3363
  if (path === '/stalker/vod') {
3329
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; }
3330
3369
  stalkerWith(s, portal, mac, ctl, function (ss, done) {
3331
3370
  if (what === 'cats') { stalkerVodCats(ss, type, ctl, function (err, list) { done(err, { cats: list }); }); return; }
3332
3371
  if (what === 'list') {
@@ -3336,7 +3375,10 @@ function stalkerControl(req, res, path, query, leaving) {
3336
3375
  }
3337
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; }
3338
3377
  done(upError('bad request', 400));
3339
- }, function (err, r) { json(err ? { why: err.message || 'failed' } : r); });
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
+ });
3340
3382
  return;
3341
3383
  }
3342
3384
  if (path === '/stalker/genres') {
@@ -3372,6 +3414,54 @@ function stalkerControl(req, res, path, query, leaving) {
3372
3414
  });
3373
3415
  }
3374
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
+
3375
3465
  // ---- TV guide (/epg/load, /epg/get) ----
3376
3466
  // A playlist's XMLTV guide, read for StremioK's channels only. The app sends their keys (epgKey:
3377
3467
  // "i:" and a tvg-id, "n:" and a name without capitals, accents, spaces or HD / FHD / 4K tags) as
@@ -3785,8 +3875,11 @@ function epgControl(req, res, path, query) {
3785
3875
  // minute. The port is open only while one is: ENTRY_CONNECTIONS at a time, each given
3786
3876
  // ENTRY_VISIT_MS (ENTRY_QUIET_MS of silence). It's plain HTTP: the page says so.
3787
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;
3788
3881
  var ENTRY_OPEN_MAX = 2, ENTRY_OPENS = 12, ENTRY_CONNECTIONS = 8, ENTRY_VISIT_MS = 20000, ENTRY_QUIET_MS = 10000;
3789
- 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',
3790
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',
3791
3884
  server: 'Your streaming server’s address for StremioK', mac: 'Your Stalker portal’s MAC address for StremioK' };
3792
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)
@@ -3826,21 +3919,22 @@ function entryIdle(token) {
3826
3919
  clearTimeout(e.idle);
3827
3920
  e.idle = setTimeout(function () { entryDrop(token); }, ENTRY_IDLE_MS);
3828
3921
  }
3829
- function entryControl(req, res, path, query) {
3830
- 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)
3831
3924
  var tm = /(?:^|&)t=([0-9a-f]{32})(?:&|$)/.exec(query || ''), token = tm ? tm[1] : '';
3832
- 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; }
3833
3927
  var now = Date.now();
3834
3928
  _entryOpened = _entryOpened.filter(function (x) { return now - x < 60000; });
3835
3929
  if (_entryOpened.length >= ENTRY_OPENS) { send(res, 429, 'text/plain', 'too many, try again in a minute'); return; }
3836
- 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';
3837
3931
  var ip = lanAddress();
3838
3932
  if (!ip) { send(res, 503, 'text/plain', 'no home network address'); return; }
3839
3933
  _entryOpened.push(now);
3840
3934
  var open = Object.keys(_entries).sort(function (a, b) { return _entries[a].at - _entries[b].at; });
3841
3935
  while (open.length >= ENTRY_OPEN_MAX) { entryDrop(open.shift(), true); } // (the oldest goes)
3842
3936
  var t = crypto.randomBytes(16).toString('hex');
3843
- _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 };
3844
3938
  entryIdle(t);
3845
3939
  var opened = function () { send(res, 200, 'application/json', JSON.stringify({ url: 'http://' + ip + ':' + ENTRY_PORT + '/e/' + t, token: t, expires: ENTRY_MS })); };
3846
3940
  if (_entryServer) { opened(); return; }
@@ -3866,7 +3960,7 @@ function entryControl(req, res, path, query) {
3866
3960
  if (path === '/entry/poll') {
3867
3961
  var text = e.text;
3868
3962
  if (e.sent) { entryDrop(token); } else { entryIdle(token); } // (collected: the page and its code go)
3869
- 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)
3870
3964
  return;
3871
3965
  }
3872
3966
  if (path === '/entry/close') { entryDrop(token); send(res, 200, 'text/plain', 'closed'); return; }
@@ -3875,16 +3969,36 @@ function entryControl(req, res, path, query) {
3875
3969
  function entryHtml(title, body) {
3876
3970
  return '<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">' +
3877
3971
  '<title>' + title + '</title><style>body{font-family:-apple-system,Roboto,sans-serif;background:#0e1117;color:#e6e9ef;margin:0;padding:24px}' +
3878
- '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}' +
3879
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>' +
3880
3974
  '<h1>' + title + '</h1>' + body + '</body></html>';
3881
3975
  }
3882
3976
  function entryPage(req, res) {
3883
3977
  try {
3884
3978
  res.setHeader('Cache-Control', 'no-store');
3885
- 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]];
3886
3980
  if (!e || e.sent) { send(res, 404, 'text/plain', 'Not here (it was used, or the TV closed it)'); return; }
3887
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
+ }
3888
4002
  if (req.method === 'GET') {
3889
4003
  var plain = ENTRY_TEXT[e.what];
3890
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>' +
@@ -3897,14 +4011,16 @@ function entryPage(req, res) {
3897
4011
  req.on('data', function (c) {
3898
4012
  if (done) { return; }
3899
4013
  size += c.length;
3900
- 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)
3901
4015
  body += c;
3902
4016
  });
3903
4017
  req.on('end', function () {
3904
4018
  if (done) { return; }
3905
4019
  done = true;
3906
- var tm = /(?:^|&)text=([^&]*)/.exec(body), text = '';
3907
- 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();
3908
4024
  if (!text || !_entries[m[1]] || e.sent) { send(res, 400, 'text/plain', 'Nothing sent'); return; }
3909
4025
  e.text = text; e.sent = true;
3910
4026
  send(res, 200, 'text/html; charset=utf-8', entryHtml(title, '<p>Sent to your TV.</p>'));