stremiok 2.2.7 → 2.2.9

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/ytplay.js CHANGED
@@ -50,6 +50,17 @@ var YTPlay = (function () {
50
50
  var t = (typeof LocalMedia !== 'undefined' && LocalMedia.serviceToken) ? LocalMedia.serviceToken() : Promise.resolve('');
51
51
  return t.then(function (tk) { return tk ? { q: '&token=' + encodeURIComponent(tk), h: null } : HEADER; }, function () { return HEADER; });
52
52
  }
53
+ // An export (a configuration file) given to the phone: a one-time page to copy or download it
54
+ // -> { url, token } (polled like an entry: { seen }; closed with entryClose). POSTed: the token,
55
+ // or the guide ticket (the page's POST carries an Origin the header alone doesn't pass).
56
+ function entryGive(text) {
57
+ if (MODE === 'browser') { return Promise.reject(new Error('no service')); }
58
+ return ensureService().then(entryAuth).then(function (a) {
59
+ return (a.q ? Promise.resolve(a.q) : ticketOf(a)).then(function (cred) {
60
+ return U.postJSON(PROXY + '/entry/give' + (cred ? '?' + cred.replace(/^&/, '') : ''), text, 10000, 65536, a.h);
61
+ });
62
+ });
63
+ }
53
64
  function entryOpen(what) {
54
65
  return entryAuth().then(function (a) { return U.getJSON(PROXY + '/entry/open?what=' + encodeURIComponent(what || 'link') + a.q, 8000, undefined, null, a.h); });
55
66
  }
@@ -57,6 +68,10 @@ var YTPlay = (function () {
57
68
  return entryAuth().then(function (a) { return U.getJSON(PROXY + '/entry/poll?t=' + encodeURIComponent(token) + a.q, 5000, undefined, null, a.h); })
58
69
  .then(function (r) { return (r && typeof r.text === 'string') ? r.text : null; });
59
70
  }
71
+ function entrySeen(token) { // (an export's page: kept open by asking, and whether the phone has opened it)
72
+ return entryAuth().then(function (a) { return U.getJSON(PROXY + '/entry/poll?t=' + encodeURIComponent(token) + a.q, 5000, undefined, null, a.h); })
73
+ .then(function (r) { return !!(r && r.seen); });
74
+ }
60
75
  function entryClose(token) {
61
76
  return entryAuth().then(function (a) { return U.getText(PROXY + '/entry/close?t=' + encodeURIComponent(token) + a.q, 4000, 4096, null, true, a.h); }).then(null, function () {});
62
77
  }
@@ -71,8 +86,8 @@ var YTPlay = (function () {
71
86
  if (MODE === 'browser') { return Promise.reject(new Error('no service')); }
72
87
  var cc = opts && opts.cc ? opts.cc.map(function (c) { return c.ch + (c.lang ? '-' + c.lang : ''); }).join(',') : '';
73
88
  return ensureService().then(entryAuth).then(function (a) {
74
- var q = '/live/open?u=' + encodeURIComponent(url) + (h && h.ua ? '&ua=' + encodeURIComponent(h.ua) : '') + (h && h.ref ? '&ref=' + encodeURIComponent(h.ref) : '') + (force ? '&force=1' : '') +
75
- (force && opts && opts.fix === false ? '&fix=0' : '') + (force && cc ? '&cc=' + encodeURIComponent(cc) : '');
89
+ var q = '/live/open?u=' + encodeURIComponent(url) + (h && h.ua ? '&ua=' + encodeURIComponent(h.ua) : '') + (h && h.ref ? '&ref=' + encodeURIComponent(h.ref) : '') + (h && h.cookie ? '&cookie=' + encodeURIComponent(h.cookie) : '') + (force ? '&force=1' : '') +
90
+ (force && opts && opts.fix === false ? '&fix=0' : '') + (force && cc ? '&cc=' + encodeURIComponent(cc) : '') + (force && opts && opts.film ? '&film=1' : '');
76
91
  return U.getJSON(PROXY + q + a.q, force ? 5000 : 30000, 65536, cancel || null, a.h);
77
92
  });
78
93
  }
@@ -81,7 +96,7 @@ var YTPlay = (function () {
81
96
  function hlsMaster(url, h) {
82
97
  if (MODE === 'browser') { return Promise.reject(new Error('no service')); }
83
98
  return ensureService().then(entryAuth).then(function (a) {
84
- var q = '/live/master?u=' + encodeURIComponent(url) + (h && h.ua ? '&ua=' + encodeURIComponent(h.ua) : '') + (h && h.ref ? '&ref=' + encodeURIComponent(h.ref) : '');
99
+ var q = '/live/master?u=' + encodeURIComponent(url) + (h && h.ua ? '&ua=' + encodeURIComponent(h.ua) : '') + (h && h.ref ? '&ref=' + encodeURIComponent(h.ref) : '') + (h && h.cookie ? '&cookie=' + encodeURIComponent(h.cookie) : '');
85
100
  return U.getText(PROXY + q + a.q, 12000, 524288, null, false, a.h);
86
101
  });
87
102
  }
@@ -170,6 +185,18 @@ var YTPlay = (function () {
170
185
  });
171
186
  });
172
187
  }
188
+ // A Widevine channel's license request (challenge: base64), posted by the service to its
189
+ // license server with the playlist's headers (see service/index.js, drmControl) -> { license:
190
+ // base64 } or { why }. b64: the server answers in base64 already.
191
+ function drmLicense(server, headers, challenge, b64) {
192
+ if (MODE === 'browser') { return Promise.reject(new Error('no service')); }
193
+ return ensureService().then(entryAuth).then(function (a) {
194
+ return (a.q ? Promise.resolve(a.q) : ticketOf(a)).then(function (cred) {
195
+ var body = JSON.stringify({ u: server, h: headers || {}, c: challenge, b64: !!b64 });
196
+ return U.postJSON(PROXY + '/drm/license' + (cred ? '?' + cred.replace(/^&/, '') : ''), body, 20000, 2 * 1048576, a.h);
197
+ });
198
+ });
199
+ }
173
200
  // Settings › Storage: the saved guides ({ count, bytes }), and deleting them all.
174
201
  function epgFiles() {
175
202
  if (MODE === 'browser') { return Promise.resolve(null); }
@@ -272,6 +299,6 @@ var YTPlay = (function () {
272
299
  return MODE === 'tizenbrew' ? 'TizenBrew module' : MODE === 'wgt' ? 'Sideloaded app (.wgt)' : 'Browser (development)';
273
300
  }
274
301
 
275
- return { ensureService: ensureService, resolverUrl: resolverUrl, infoUrl: infoUrl, canPlay: canPlay, liveOpen: liveOpen, hlsMaster: hlsMaster, aiomAddons: aiomAddons, stalkerList: stalkerList, stalkerVod: stalkerVod, stalkerPlayUrl: stalkerPlayUrl, stalkerGenres: stalkerGenres, stalkerLink: stalkerLink, xtvodAsk: xtvodAsk, epgLoad: epgLoad, epgGet: epgGet, epgFiles: epgFiles, epgClear: epgClear, entryOpen: entryOpen, entryPoll: entryPoll, entryClose: entryClose, subsUrl: subsUrl, audioLang: audioLang, setAudioLang: setAudioLang, installMode: function () { return MODE; },
302
+ return { ensureService: ensureService, resolverUrl: resolverUrl, infoUrl: infoUrl, canPlay: canPlay, liveOpen: liveOpen, hlsMaster: hlsMaster, aiomAddons: aiomAddons, stalkerList: stalkerList, stalkerVod: stalkerVod, drmLicense: drmLicense, stalkerPlayUrl: stalkerPlayUrl, stalkerGenres: stalkerGenres, stalkerLink: stalkerLink, xtvodAsk: xtvodAsk, epgLoad: epgLoad, epgGet: epgGet, epgFiles: epgFiles, epgClear: epgClear, entryOpen: entryOpen, entryGive: entryGive, entrySeen: entrySeen, entryPoll: entryPoll, entryClose: entryClose, subsUrl: subsUrl, audioLang: audioLang, setAudioLang: setAudioLang, installMode: function () { return MODE; },
276
303
  installLabel: installLabel, unavailableMessage: unavailableMessage, isRunning: isRunning, port: PORT };
277
304
  })();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "stremiok",
3
- "version": "2.2.7",
3
+ "version": "2.2.9",
4
4
  "description": "StremioK streaming client for Tizen 3.0+ Samsung TVs (TizenBrew app module).",
5
5
  "packageType": "app",
6
6
  "appName": "StremioK",
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,8 @@ 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; }
2006
+ if (who.range) { h.Range = who.range; } // (a film's piece that's part of a file: EXT-X-BYTERANGE)
1983
2007
  var opts = { hostname: pu.hostname, port: pu.port, path: pu.path, headers: h };
1984
2008
  if (pu.protocol === 'https:' && caList().length) { opts.ca = caList(); }
1985
2009
  var chunks = [], size = 0, done = false;
@@ -1998,7 +2022,8 @@ function liveGet(u, who, max, cb, part) {
1998
2022
  if (!gone) { get(urllib.resolve(url, resp.headers.location)); }
1999
2023
  return;
2000
2024
  }
2001
- if (sc !== 200) { resp.resume(); end(upError('HTTP ' + sc, sc >= 400 && sc < 600 ? sc : 502)); return; }
2025
+ if (who.range && sc === 200) { resp.resume(); end(upError('the server sent the whole file, not the part asked for', 502)); return; }
2026
+ if (sc !== 200 && !(sc === 206 && who.range)) { resp.resume(); end(upError('HTTP ' + sc, sc >= 400 && sc < 600 ? sc : 502)); return; }
2002
2027
  resp.on('data', function (c) {
2003
2028
  if (done) { return; }
2004
2029
  chunks.push(c); size += c.length; held += c.length; _liveHeld += c.length;
@@ -2466,31 +2491,57 @@ function ccList(s, text, base, k) {
2466
2491
  // A playlist with its links through the relay: a master's variants and renditions (m), a media
2467
2492
  // playlist's segments (s, numbered from its media sequence); encrypted or fMP4 segments, keys:
2468
2493
  // fetched directly (their absolute links).
2469
- function liveLink(s, url, kind, seq, ch) {
2470
- var key = kind + (ch !== undefined ? ch : '') + ' ' + url;
2494
+ // A film's relay (&film=1: HLS through StremioK's service) keeps every link (up to
2495
+ // LIVE_FILM_LINKS: seeking goes back to any of them), a live channel's its last LIVE_LINKS.
2496
+ // raw: a key, an init section or an encrypted / fMP4 piece, passed on as it is; range: a byte
2497
+ // range of its link ('bytes=a-b').
2498
+ var LIVE_FILM_LINKS = 30000, LIVE_FILM_IDLE_MS = 3 * 3600 * 1000;
2499
+ function liveLink(s, url, kind, seq, ch, raw, range) {
2500
+ var key = kind + (ch !== undefined ? ch : '') + (range ? '@' + range : '') + ' ' + url;
2471
2501
  if (s.at[key] !== undefined) { return s.at[key]; }
2472
- var n = s.next++;
2473
- s.links[n] = { url: url, kind: kind, seq: seq, ch: ch, key: key };
2502
+ var n = s.next++, keep = s.film ? LIVE_FILM_LINKS : LIVE_LINKS;
2503
+ s.links[n] = { url: url, kind: kind, seq: seq, ch: ch, key: key, raw: !!raw, range: range || '' };
2474
2504
  s.at[key] = n;
2475
- var old = s.links[n - LIVE_LINKS];
2476
- if (old) { delete s.at[old.key]; delete s.links[n - LIVE_LINKS]; }
2505
+ var old = s.links[n - keep];
2506
+ if (old) { delete s.at[old.key]; delete s.links[n - keep]; }
2477
2507
  return n;
2478
2508
  }
2509
+ // EXT-X-BYTERANGE's "<length>[@<offset>]" as a Range header, after the one before it (a piece
2510
+ // without an offset follows the last of the same link): { range, end } or null.
2511
+ function liveRange(v, last, url) {
2512
+ var m = /^\s*(\d+)(?:@(\d+))?\s*$/.exec(v || '');
2513
+ if (!m) { return null; }
2514
+ var len = +m[1], off = m[2] !== undefined ? +m[2] : (last && last.url === url ? last.end : 0);
2515
+ if (!(len > 0)) { return null; }
2516
+ return { range: 'bytes=' + off + '-' + (off + len - 1), end: off + len, url: url };
2517
+ }
2479
2518
  function liveBase(s) { return 'http://localhost:' + PORT + '/live/' + s.id + '/'; }
2480
2519
  function liveRewrite(s, text, base) {
2481
2520
  var master = /#EXT-X-STREAM-INF/.test(text), direct = !master && /#EXT-X-KEY:METHOD=(?!NONE)|#EXT-X-MAP/.test(text);
2482
2521
  var sq = /#EXT-X-MEDIA-SEQUENCE:\s*(\d+)/.exec(text), seq = sq ? +sq[1] : 0, pre = liveBase(s);
2522
+ var span = null, last = null; // (a film's: the byte range of the next piece, and of the one before)
2483
2523
  return String(text).split(/\r?\n/).map(function (ln) {
2484
2524
  var t = ln.trim();
2485
2525
  if (!t) { return ln; }
2486
2526
  if (t.charAt(0) === '#') {
2527
+ if (s.film && /^#EXT-X-BYTERANGE:/.test(t)) { span = t.slice(17); return ln; }
2487
2528
  return t.replace(/URI="([^"]*)"/, function (all, v) {
2488
2529
  var abs = urllib.resolve(base, v);
2489
- return 'URI="' + (/^#EXT-X-MEDIA:/.test(t) ? pre + 'm?n=' + liveLink(s, abs, 'm') : abs) + '"';
2530
+ if (/^#EXT-X-MEDIA:/.test(t)) { return 'URI="' + pre + 'm?n=' + liveLink(s, abs, 'm') + '"'; }
2531
+ if (s.film && /^#EXT-X-(KEY|MAP|SESSION-KEY):/.test(t)) { // (a film's key or init section: with its headers too)
2532
+ var br = /^#EXT-X-MAP:/.test(t) && /BYTERANGE="([^"]*)"/.exec(t), r = br ? liveRange(br[1], null, abs) : null;
2533
+ return 'URI="' + pre + 's?n=' + liveLink(s, abs, 's', -1, undefined, true, r ? r.range : '') + '"';
2534
+ }
2535
+ return 'URI="' + abs + '"';
2490
2536
  });
2491
2537
  }
2492
2538
  var abs = urllib.resolve(base, t);
2493
2539
  if (master) { return pre + 'm?n=' + liveLink(s, abs, 'm'); }
2540
+ if (s.film) {
2541
+ var rg = span !== null ? liveRange(span, last, abs) : null;
2542
+ span = null; last = rg;
2543
+ return pre + 's?n=' + liveLink(s, abs, 's', seq++, undefined, direct, rg ? rg.range : '');
2544
+ }
2494
2545
  if (direct) { seq++; return abs; }
2495
2546
  return pre + 's?n=' + liveLink(s, abs, 's', seq++);
2496
2547
  }).join('\n');
@@ -2502,15 +2553,15 @@ function liveSession(u, who, opts) {
2502
2553
  ids.sort(function (x, y) { return _live[x].last - _live[y].last; });
2503
2554
  delete _live[ids[0]];
2504
2555
  }
2505
- var s = { id: crypto.randomBytes(16).toString('hex'), ua: who.ua, ref: who.ref, links: {}, at: {}, next: 0, last: Date.now(), a: liveAudio(),
2506
- fix: opts.fix !== false, cc: opts.cc && opts.cc.length ? opts.cc : null, c: ccState(), got: Object.create(null) };
2556
+ 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(),
2557
+ fix: opts.fix !== false && !opts.film, cc: opts.cc && opts.cc.length && !opts.film ? opts.cc : null, film: !!opts.film, c: ccState(), got: Object.create(null) };
2507
2558
  _live[s.id] = s;
2508
2559
  s.top = liveLink(s, u, 'm');
2509
2560
  return s;
2510
2561
  }
2511
2562
  function livePurge() {
2512
2563
  var now = Date.now();
2513
- Object.keys(_live).forEach(function (id) { if (now - _live[id].last > LIVE_IDLE_MS) { delete _live[id]; } });
2564
+ Object.keys(_live).forEach(function (id) { if (now - _live[id].last > (_live[id].film ? LIVE_FILM_IDLE_MS : LIVE_IDLE_MS)) { delete _live[id]; } }); // (a film may be paused a while)
2514
2565
  }
2515
2566
  // The look: the playlist (a master's first variant), then the start of the segment a player
2516
2567
  // starts with (the third from the end); with captions in that start, the whole segment (up to
@@ -2546,30 +2597,32 @@ function liveProbe(u, who, cb, leaving) {
2546
2597
  }
2547
2598
  list(u);
2548
2599
  }
2549
- function liveHeader(v) { v = String(v || ''); return /^[\x20-\x7e]{1,300}$/.test(v) ? v : ''; }
2600
+ function liveHeader(v, max) { v = String(v || ''); return v.length <= (max || 300) && /^[\x20-\x7e]+$/.test(v) ? v : ''; }
2601
+ 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
2602
  function liveControl(req, res, path, query, leaving) {
2551
2603
  livePurge();
2552
2604
  var q = {};
2553
2605
  (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)
2606
+ 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
2607
  if (!entryAllowed(req, query)) { send(res, 403, 'text/plain', 'not allowed (token)'); return; }
2556
2608
  var mu = q.u || '';
2557
2609
  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) {
2610
+ leaving.push(liveGet(mu, liveWho(q), HLS_MASTER_MAX, function (err, buf) {
2559
2611
  if (err) { send(res, err.status || 502, 'text/plain', 'failed: ' + (err.message || 'unknown')); return; }
2560
2612
  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);
2613
+ var dash = /<MPD[\s>]/i.test(text.slice(0, 4000)); // (a DASH manifest: is it a film? see the player's manifestVod)
2614
+ if (text.replace(/^\s+/, '').indexOf('#EXTM3U') !== 0 && !dash) { send(res, 502, 'text/plain', 'not an HLS playlist'); return; }
2615
+ send(res, 200, dash ? 'application/dash+xml' : 'application/vnd.apple.mpegurl', text);
2563
2616
  }));
2564
2617
  return;
2565
2618
  }
2566
2619
  if (path === '/live/open') {
2567
2620
  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) };
2621
+ var u = q.u || '', who = liveWho(q);
2569
2622
  if (!/^https?:\/\/[^\s]+$/i.test(u) || u.length > 2000) { send(res, 400, 'text/plain', 'bad link'); return; }
2570
2623
  var cc = ccAsked(q.cc);
2571
2624
  if (q.force === '1') {
2572
- var sf = liveSession(u, who, { fix: q.fix !== '0', cc: cc });
2625
+ var sf = liveSession(u, who, { fix: q.fix !== '0', cc: cc, film: q.film === '1' });
2573
2626
  send(res, 200, 'application/json', JSON.stringify({ fix: true, sure: true, why: 'asked for', url: liveBase(sf) + 'm?n=' + sf.top }));
2574
2627
  return;
2575
2628
  }
@@ -2590,11 +2643,13 @@ function liveControl(req, res, path, query, leaving) {
2590
2643
  try { return ccSegment(s.c, body, link.seq); } catch (e) { log('live captions: ' + (e && e.message)); s.c = ccState(); return null; }
2591
2644
  }
2592
2645
  if (kind === 'v' && s.c.segs[link.seq]) { send(res, 200, 'text/vtt; charset=utf-8', ccVtt(s.c.segs[link.seq], link.ch)); return; }
2593
- leaving.push((seg && s.cc ? liveShared : liveGet)(link.url, s, seg ? LIVE_SEG_MAX : LIVE_LIST_MAX, function (err, body, at) {
2646
+ var who = link.range ? { ua: s.ua, ref: s.ref, cookie: s.cookie, range: link.range } : s; // (a byte range: asked as one)
2647
+ leaving.push((seg && s.cc ? liveShared : liveGet)(link.url, who, seg ? LIVE_SEG_MAX : LIVE_LIST_MAX, function (err, body, at) {
2594
2648
  if (err) { send(res, err.status || 502, 'text/plain', 'failed: ' + (err.message || 'unknown')); return; }
2595
2649
  if (kind === 'v') { var cs = captions(body); send(res, 200, 'text/vtt; charset=utf-8', cs ? ccVtt(cs, link.ch) : 'WEBVTT\n'); return; }
2596
2650
  if (kind === 'c') { send(res, 200, 'application/vnd.apple.mpegurl', ccList(s, body.toString('utf8'), at, link.ch)); return; }
2597
2651
  if (kind !== 's') { send(res, 200, 'application/vnd.apple.mpegurl', s.cc && kind === 'm' && +q.n === s.top ? ccMaster(s, body.toString('utf8'), at) : liveRewrite(s, body.toString('utf8'), at)); return; }
2652
+ if (link.raw) { send(res, 200, 'application/octet-stream', body); return; } // (a film's key, init section or encrypted piece: as it came)
2598
2653
  var out = body;
2599
2654
  if (s.cc) { captions(body); }
2600
2655
  if (s.fix) { try { out = liveFix(s, body, link.seq); } catch (e) { log('live: ' + (e && e.message)); s.a = liveAudio(); } }
@@ -3171,6 +3226,18 @@ function stalkerM3u(s, list, genres) {
3171
3226
  // episodes: a season's cmd and its episodes' numbers, or each episode's own cmd) and play (a film's
3172
3227
  // or an episode's link asked now, create_link, and sent there: what's saved to resume stays good).
3173
3228
  var STALKER_VOD_TAKE = 42, STALKER_VOD_PAGES = 4, STALKER_VOD_CATS_MS = 10 * 60000, STALKER_SEASONS = 60, STALKER_EPISODES = 500;
3229
+ // What a portal answered (a list from a position, a search, a series' seasons): kept
3230
+ // STALKER_VOD_KEEP_MS, the last STALKER_VOD_KEEP a portal, so a row or category shown again isn't
3231
+ // asked again (a portal may stop answering many quick asks); fresh=1 (Reload) lets it all go.
3232
+ // &keep=: the app's Stalker films and series setting, in minutes (0: not kept; up to 10).
3233
+ var STALKER_VOD_KEEP_MS = 10 * 60000, STALKER_VOD_KEEP = 40;
3234
+ function stalkerKeepMs(q) { var m = /^\d{1,2}$/.test(q.keep || '') ? +q.keep : 10; return Math.min(m, 10) * 60000; }
3235
+ function stalkerKept(s, key, ms) { var k = s.vodKept && s.vodKept[key]; return k && Date.now() - k.at < Math.min(ms, STALKER_VOD_KEEP_MS) ? k.v : null; }
3236
+ function stalkerKeepVod(s, key, v) {
3237
+ if (!s.vodKept) { s.vodKept = Object.create(null); s.vodOrder = []; }
3238
+ if (!s.vodKept[key]) { s.vodOrder.push(key); while (s.vodOrder.length > STALKER_VOD_KEEP) { delete s.vodKept[s.vodOrder.shift()]; } }
3239
+ s.vodKept[key] = { at: Date.now(), v: v };
3240
+ }
3174
3241
  function stalkerText(v, n) { return String(v == null ? '' : v).replace(/\s+/g, ' ').trim().slice(0, n); }
3175
3242
  function stalkerCmdOk(cmd) { return !!cmd && cmd.length <= 2000 && !/[\r\n]/.test(cmd); }
3176
3243
  function stalkerVodItem(s, o) {
@@ -3327,6 +3394,12 @@ function stalkerControl(req, res, path, query, leaving) {
3327
3394
  }
3328
3395
  if (path === '/stalker/vod') {
3329
3396
  var type = q.type === 'series' ? 'series' : 'movie', what = String(q.do || '');
3397
+ if (q.fresh === '1') { s.vodCats = null; s.vodKept = null; s.vodOrder = null; } // (Reload: all of it read again)
3398
+ 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('|') : '';
3399
+ var keepMs = stalkerKeepMs(q);
3400
+ if (!keepMs) { vkey = ''; } // (not kept: asked each time)
3401
+ var kept = vkey && stalkerKept(s, vkey, keepMs);
3402
+ if (kept) { json(kept); return; }
3330
3403
  stalkerWith(s, portal, mac, ctl, function (ss, done) {
3331
3404
  if (what === 'cats') { stalkerVodCats(ss, type, ctl, function (err, list) { done(err, { cats: list }); }); return; }
3332
3405
  if (what === 'list') {
@@ -3336,7 +3409,10 @@ function stalkerControl(req, res, path, query, leaving) {
3336
3409
  }
3337
3410
  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
3411
  done(upError('bad request', 400));
3339
- }, function (err, r) { json(err ? { why: err.message || 'failed' } : r); });
3412
+ }, function (err, r) {
3413
+ if (!err && vkey) { stalkerKeepVod(s, vkey, r); } // (an error isn't kept: asked again next time)
3414
+ json(err ? { why: err.message || 'failed' } : r);
3415
+ });
3340
3416
  return;
3341
3417
  }
3342
3418
  if (path === '/stalker/genres') {
@@ -3372,6 +3448,54 @@ function stalkerControl(req, res, path, query, leaving) {
3372
3448
  });
3373
3449
  }
3374
3450
 
3451
+ // ---- A DRM channel's license (/drm/license) ----
3452
+ // A Widevine channel's license request, posted to the license server its playlist names, with the
3453
+ // playlist's headers for it (a web page can't send a User-Agent, a Cookie…, and some servers refuse
3454
+ // its origin), its answer sent back in base64. The player hands over the request and installs the
3455
+ // answer (see js/player-core.js, drmSetup). POSTed: { u: the license server, h: { name: value },
3456
+ // c: the request, base64, b64: the answer is base64 already }; the token, or the guide ticket.
3457
+ var DRM_BODY_MAX = 65536, DRM_MS = 15000, DRM_MAX = 1048576;
3458
+ var DRM_NOT = /^(host|content-length|connection|transfer-encoding|keep-alive|upgrade|te|trailer|proxy-.*)$/i;
3459
+ function drmControl(req, res, query, body, leaving) {
3460
+ if (!entryAllowed(req, query) && !hasTicket(query)) { send(res, 403, 'text/plain', 'not allowed (token)'); return; }
3461
+ var o = null;
3462
+ try { o = JSON.parse(body); } catch (e) { o = null; }
3463
+ function json(x) { send(res, 200, 'application/json', JSON.stringify(x)); }
3464
+ var u = o && typeof o.u === 'string' ? o.u : '', c = o && typeof o.c === 'string' ? o.c : '', pu = null;
3465
+ try { pu = urllib.parse(u); } catch (e) { pu = null; }
3466
+ if (!pu || (pu.protocol !== 'http:' && pu.protocol !== 'https:') || u.length > 2000 || !dlHostOk(pu.hostname)) { json({ why: 'not a license server StremioK can reach' }); return; }
3467
+ if (!c || !/^[A-Za-z0-9+\/=]+$/.test(c)) { json({ why: 'no license request' }); return; }
3468
+ var data = HAS_BUFFER_FROM ? Buffer.from(c, 'base64') : new Buffer(c, 'base64'), h = { 'Content-Type': 'application/octet-stream', 'User-Agent': TV_UA, 'Accept': '*/*' };
3469
+ Object.keys((o.h && typeof o.h === 'object') ? o.h : {}).slice(0, 16).forEach(function (k) {
3470
+ var v = o.h[k];
3471
+ 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; }
3472
+ });
3473
+ h['Content-Length'] = data.length;
3474
+ var done = false, r = null, chunks = [], size = 0;
3475
+ var timer = setTimeout(function () { finish({ why: 'the license server didn\'t answer' }); }, DRM_MS);
3476
+ 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); }
3477
+ leaving.push(function () { done = true; clearTimeout(timer); try { if (r) { r.abort(); } } catch (e) {} });
3478
+ var opts = { hostname: pu.hostname, port: pu.port, path: pu.path, method: 'POST', headers: h };
3479
+ if (pu.protocol === 'https:' && caList().length) { opts.ca = caList(); }
3480
+ try {
3481
+ r = (pu.protocol === 'https:' ? https : http).request(opts, function (resp) {
3482
+ var sc = resp.statusCode;
3483
+ resp.on('data', function (b) { if (done) { return; } chunks.push(b); size += b.length; if (size > DRM_MAX) { finish({ why: 'too large an answer' }); } });
3484
+ resp.on('end', function () {
3485
+ if (done) { return; }
3486
+ var all = Buffer.concat(chunks, size);
3487
+ if (sc !== 200) { finish({ why: 'HTTP ' + sc + (all.length && all.length < 200 ? ': ' + all.toString('utf8').replace(/\s+/g, ' ').trim().slice(0, 120) : '') }); return; }
3488
+ if (!all.length) { finish({ why: 'an empty answer' }); return; }
3489
+ finish({ license: o.b64 ? all.toString('utf8').trim() : all.toString('base64') });
3490
+ });
3491
+ resp.on('error', function (e) { finish({ why: e.message || 'failed' }); });
3492
+ });
3493
+ r.on('error', function (e) { finish({ why: 'couldn\'t reach it (' + (e.code || e.message) + ')' }); });
3494
+ guardSelf(r, function () { finish({ why: 'an address it can\'t reach' }); });
3495
+ r.end(data);
3496
+ } catch (e) { finish({ why: e.message || 'failed' }); }
3497
+ }
3498
+
3375
3499
  // ---- TV guide (/epg/load, /epg/get) ----
3376
3500
  // A playlist's XMLTV guide, read for StremioK's channels only. The app sends their keys (epgKey:
3377
3501
  // "i:" and a tvg-id, "n:" and a name without capitals, accents, spaces or HD / FHD / 4K tags) as
@@ -3785,8 +3909,11 @@ function epgControl(req, res, path, query) {
3785
3909
  // minute. The port is open only while one is: ENTRY_CONNECTIONS at a time, each given
3786
3910
  // ENTRY_VISIT_MS (ENTRY_QUIET_MS of silence). It's plain HTTP: the page says so.
3787
3911
  var ENTRY_PORT = PORT + 10, ENTRY_MS = 5 * 60 * 1000, ENTRY_IDLE_MS = 30000, ENTRY_MAX = 8192;
3912
+ // A configuration file: pasted on the import's page (CONFIG_MAX, sent %-encoded: 3 times that), or
3913
+ // given by the TV to the export's page (GIVE_MAX, POSTed to /entry/give), shown to copy or download.
3914
+ var CONFIG_MAX = 262144, GIVE_MAX = 262144;
3788
3915
  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',
3916
+ 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
3917
  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
3918
  server: 'Your streaming server’s address for StremioK', mac: 'Your Stalker portal’s MAC address for StremioK' };
3792
3919
  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 +3953,22 @@ function entryIdle(token) {
3826
3953
  clearTimeout(e.idle);
3827
3954
  e.idle = setTimeout(function () { entryDrop(token); }, ENTRY_IDLE_MS);
3828
3955
  }
3829
- function entryControl(req, res, path, query) {
3830
- if (!entryAllowed(req, query)) { send(res, 403, 'text/plain', 'not allowed'); return; }
3956
+ function entryControl(req, res, path, query, body) {
3957
+ 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
3958
  var tm = /(?:^|&)t=([0-9a-f]{32})(?:&|$)/.exec(query || ''), token = tm ? tm[1] : '';
3832
- if (path === '/entry/open') {
3959
+ if (path === '/entry/open' || path === '/entry/give') {
3960
+ if (path === '/entry/give' && !String(body || '').trim()) { send(res, 400, 'text/plain', 'nothing to give'); return; }
3833
3961
  var now = Date.now();
3834
3962
  _entryOpened = _entryOpened.filter(function (x) { return now - x < 60000; });
3835
3963
  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';
3964
+ 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
3965
  var ip = lanAddress();
3838
3966
  if (!ip) { send(res, 503, 'text/plain', 'no home network address'); return; }
3839
3967
  _entryOpened.push(now);
3840
3968
  var open = Object.keys(_entries).sort(function (a, b) { return _entries[a].at - _entries[b].at; });
3841
3969
  while (open.length >= ENTRY_OPEN_MAX) { entryDrop(open.shift(), true); } // (the oldest goes)
3842
3970
  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 };
3971
+ _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
3972
  entryIdle(t);
3845
3973
  var opened = function () { send(res, 200, 'application/json', JSON.stringify({ url: 'http://' + ip + ':' + ENTRY_PORT + '/e/' + t, token: t, expires: ENTRY_MS })); };
3846
3974
  if (_entryServer) { opened(); return; }
@@ -3866,7 +3994,7 @@ function entryControl(req, res, path, query) {
3866
3994
  if (path === '/entry/poll') {
3867
3995
  var text = e.text;
3868
3996
  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 }));
3997
+ send(res, 200, 'application/json', JSON.stringify(e.give !== null ? { seen: e.seen } : { text: text })); // (an export: whether the phone has it)
3870
3998
  return;
3871
3999
  }
3872
4000
  if (path === '/entry/close') { entryDrop(token); send(res, 200, 'text/plain', 'closed'); return; }
@@ -3875,16 +4003,36 @@ function entryControl(req, res, path, query) {
3875
4003
  function entryHtml(title, body) {
3876
4004
  return '<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">' +
3877
4005
  '<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}' +
4006
+ '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
4007
  '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
4008
  '<h1>' + title + '</h1>' + body + '</body></html>';
3881
4009
  }
3882
4010
  function entryPage(req, res) {
3883
4011
  try {
3884
4012
  res.setHeader('Cache-Control', 'no-store');
3885
- var m = /^\/e\/([0-9a-f]{32})$/.exec(String(req.url || '')), e = m && _entries[m[1]];
4013
+ var m = /^\/e\/([0-9a-f]{32})(\/stremiok\.txt)?$/.exec(String(req.url || '')), e = m && _entries[m[1]];
3886
4014
  if (!e || e.sent) { send(res, 404, 'text/plain', 'Not here (it was used, or the TV closed it)'); return; }
3887
4015
  var title = ENTRY_TITLES[e.what];
4016
+ if (e.give !== null) { // (an export: the file to copy, or download)
4017
+ if (req.method !== 'GET') { send(res, 405, 'text/plain', 'GET only'); return; }
4018
+ e.seen = true;
4019
+ if (m[2]) { res.setHeader('Content-Disposition', 'attachment; filename="stremiok.txt"'); send(res, 200, 'text/plain; charset=utf-8', e.give); return; }
4020
+ var esc = e.give.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
4021
+ 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>' +
4022
+ '<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>' +
4023
+ '<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>'));
4024
+ return;
4025
+ }
4026
+ if (m[2]) { send(res, 404, 'text/plain', 'Not here'); return; }
4027
+ var config = e.what === 'config', max = config ? CONFIG_MAX * 3 : ENTRY_MAX; // (a pasted file: its lines kept, %-encoded as sent)
4028
+ if (req.method === 'GET' && config) { // (its link, as before; or the file itself, chosen from the phone's files or pasted)
4029
+ 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://…">' +
4030
+ '<p>Or the file itself (an export\'s stremiok.txt)</p><input id="pick" type="file" accept=".txt,.cfg,.conf,text/plain">' +
4031
+ '<textarea id="f" name="text" rows="8" autocomplete="off" placeholder="…or paste it here"></textarea>' +
4032
+ '<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>' +
4033
+ '<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>'));
4034
+ return;
4035
+ }
3888
4036
  if (req.method === 'GET') {
3889
4037
  var plain = ENTRY_TEXT[e.what];
3890
4038
  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 +4045,16 @@ function entryPage(req, res) {
3897
4045
  req.on('data', function (c) {
3898
4046
  if (done) { return; }
3899
4047
  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)
4048
+ if (size > max) { done = true; send(res, 413, 'text/plain', 'Too long'); return; } // (the rest read and dropped: the connection stays usable)
3901
4049
  body += c;
3902
4050
  });
3903
4051
  req.on('end', function () {
3904
4052
  if (done) { return; }
3905
4053
  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 = ''; }
4054
+ var tm = /(?:^|&)text=([^&]*)/.exec(body), lm = config && /(?:^|&)link=([^&]*)/.exec(body), text = '';
4055
+ try { text = tm ? decodeURIComponent(tm[1].replace(/\+/g, ' ')) : ''; } catch (e3) { text = ''; }
4056
+ if (!text.trim() && lm) { try { text = decodeURIComponent(lm[1].replace(/\+/g, ' ')); } catch (e4) { text = ''; } } // (a link to the file, as before)
4057
+ text = config ? text.replace(/\r\n?/g, '\n').trim().slice(0, CONFIG_MAX) : text.replace(/[\r\n\t]+/g, ' ').trim();
3908
4058
  if (!text || !_entries[m[1]] || e.sent) { send(res, 400, 'text/plain', 'Nothing sent'); return; }
3909
4059
  e.text = text; e.sent = true;
3910
4060
  send(res, 200, 'text/html; charset=utf-8', entryHtml(title, '<p>Sent to your TV.</p>'));