stremiok 2.3.1 → 2.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/service/index.js CHANGED
@@ -63,6 +63,9 @@
63
63
  * are; ASS / SSA as SRT; Windows-1252 and UTF-16 files converted)
64
64
  * /fshash?path=<file> -> JSON { size, hash }: a video's OpenSubtitles hash (its size and the
65
65
  * first and last 64 KB), so subtitle addons can find ones made for it
66
+ * /dav/list?u=<folder>&p=<path>, /dav/walk?u=, /dav/sub?u=&p= (+ X-Dav-Auth, X-Dav-Cert) ->
67
+ * a network folder's (WebDAV) listing, every video and subtitle file under
68
+ * it, a subtitle file as UTF-8 (see davControl); the token or the header
66
69
  * /ytinfo?u=<page> -> JSON { audio: [{ lang, name, original }], links: [{ kind, id, title,
67
70
  * teaser, startMs, endMs }], details, chapters: [{ t, title }] }: the
68
71
  * audio languages, the end screen and cards, the video, its chapters
@@ -1789,7 +1792,7 @@ function handle(req, res) {
1789
1792
  if (!isFs) {
1790
1793
  res.setHeader('Access-Control-Allow-Origin', '*');
1791
1794
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
1792
- res.setHeader('Access-Control-Allow-Headers', 'X-StremioK, X-AIOM-Key, *'); // (named: older engines don't take *)
1795
+ res.setHeader('Access-Control-Allow-Headers', 'X-StremioK, X-AIOM-Key, X-Dav-Auth, X-Dav-Cert, *'); // (named: older engines don't take *)
1793
1796
  }
1794
1797
  res.setHeader('Cache-Control', 'no-store');
1795
1798
  res.setHeader('X-Content-Type-Options', 'nosniff');
@@ -1805,12 +1808,12 @@ function handle(req, res) {
1805
1808
  var drmPost = req.method === 'POST' && path === '/drm/license'; // (a Widevine license request: see drmControl)
1806
1809
  var givePost = req.method === 'POST' && path === '/entry/give'; // (a configuration file for the phone: see entryControl)
1807
1810
  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)
1811
+ if (req.url.length > (/^\/epg\//.test(path) ? 32768 : /^\/(fsdl\/add|live\/(open|master)|dav\/(list|walk|sub))$/.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)
1809
1812
  // (StremioK gave up on it — a screen left, the player closed: what it still waits for is
1810
1813
  // dropped; 'close' before the response finished means that on every Node)
1811
1814
  var leaving = [];
1812
1815
  function leaveAll() { var l = leaving; leaving = []; l.forEach(function (f) { try { f(); } catch (e) {} }); }
1813
- if (!isFs) {
1816
+ if (!isFs && path !== '/dav/walk' && !/^\/live\/[0-9a-f]{32}\/t$/.test(path)) { // (a folder's walk, a raw channel's stream: their own limits)
1814
1817
  var deadline = setTimeout(function () { if (!res.headersSent) { send(res, 504, 'text/plain', 'took too long'); } leaveAll(); }, REQ_MS);
1815
1818
  res.on('finish', function () { clearTimeout(deadline); });
1816
1819
  res.on('close', function () { clearTimeout(deadline); if (!res.finished) { leaveAll(); } });
@@ -1843,6 +1846,7 @@ function handle(req, res) {
1843
1846
  return;
1844
1847
  }
1845
1848
  if (/^\/epg\//.test(path)) { epgControl(req, res, path, parts[1]); return; } // (a playlist's TV guide: see epgControl)
1849
+ if (/^\/dav\//.test(path)) { davControl(req, res, path, parts[1], leaving); return; } // (a network folder: see davControl)
1846
1850
  if (path === '/aiom/addons') { aiomControl(req, res, parts[1], leaving); return; }
1847
1851
  if (path === '/xtvod/list' || path === '/xtvod/find') { xtvControl(req, res, path, parts[1]); return; } // (an Xtream account's films and series: see xtvControl)
1848
1852
  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)
@@ -1978,7 +1982,11 @@ function handle(req, res) {
1978
1982
  // whole ADTS frames per packet, each packet with its first frame's own time), everything else
1979
1983
  // as it was. &force=1: the relay without the look (StremioK already knows the channel); &fix=0
1980
1984
  // with it: the sound as it is. &cc=: the relay with closed captions too (see ccSegment).
1985
+ // A raw MPEG-TS channel (one endless stream, no playlist: an Xtream account's default) is looked
1986
+ // at the same way, its first LIVE_RAW_PROBE bytes (raw: true); its relay, /live/<id>/t, is the
1987
+ // stream as it comes, its sound repacked on the way (liveStream); &raw=1 asks for that one.
1981
1988
  var HLS_MASTER_MAX = 524288; // (an HLS quality list: /live/master)
1989
+ var LIVE_RAW_PROBE = 1048576, LIVE_RAW_CHUNK = 65536;
1982
1990
  var LIVE_MAX = 4, LIVE_IDLE_MS = 5 * 60 * 1000, LIVE_LINKS = 400, LIVE_LIST_MAX = 1048576, LIVE_SEG_MAX = 32 * 1048576, LIVE_PROBE = 1536 * 1024, LIVE_MS = 20000;
1983
1991
  var ADTS_RATES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
1984
1992
  var _live = Object.create(null); // (no prototype: whatever key it's asked for, nothing shared is reached)
@@ -2516,6 +2524,79 @@ function liveRange(v, last, url) {
2516
2524
  return { range: 'bytes=' + off + '-' + (off + len - 1), end: off + len, url: url };
2517
2525
  }
2518
2526
  function liveBase(s) { return 'http://localhost:' + PORT + '/live/' + s.id + '/'; }
2527
+ function liveEntry(s) { return liveBase(s) + (s.raw ? 't' : 'm?n=' + s.top); } // (the link the player opens)
2528
+ // Where an MPEG-TS stream's packets start (three in a row), or -1.
2529
+ function tsSync(b) {
2530
+ for (var i = 0; i < 188 && i + 376 < b.length; i++) { if (b[i] === 0x47 && b[i + 188] === 0x47 && b[i + 376] === 0x47) { return i; } }
2531
+ return -1;
2532
+ }
2533
+ // A raw channel's relay (/live/<id>/t): the stream fetched with its headers and passed on as it
2534
+ // comes, in whole TS packets, its sound repacked chunk by chunk (liveFix: each chunk the next one,
2535
+ // what's left of a frame going on in the next). One at a time per relay (the player opening it
2536
+ // again: the old one stops); the TV's player reading slowly holds the server back (no piling up).
2537
+ function liveStream(s, req, res) {
2538
+ if (s.stop) { s.stop(); }
2539
+ var r = null, gone = false, seq = 0, carry = null, started = false, hops = 0, synced = false;
2540
+ s.a = liveAudio();
2541
+ function stop() { gone = true; try { if (r) { r.abort(); } } catch (e) {} if (s.stop === stop) { s.stop = null; } }
2542
+ s.stop = stop;
2543
+ res.on('close', stop);
2544
+ function fail(code, why) { if (gone) { return; } if (!started) { send(res, code, 'text/plain', 'failed: ' + why); } else { try { res.end(); } catch (e) {} } stop(); }
2545
+ var timer = setTimeout(function () { if (!started) { fail(504, 'timed out'); } }, LIVE_MS);
2546
+ // A chunk's whole packets out, its sound repacked (what's after its last whole packet kept for
2547
+ // the next): false when the player has enough for now.
2548
+ function pass(b) {
2549
+ var whole = b.length - b.length % 188, out = b.slice(0, whole);
2550
+ carry = whole < b.length ? b.slice(whole) : null;
2551
+ if (!whole) { return true; }
2552
+ if (s.fix) { try { out = liveFix(s, out, seq); } catch (e) { log('live (raw): ' + (e && e.message)); s.a = liveAudio(); } }
2553
+ seq++;
2554
+ return res.write(out);
2555
+ }
2556
+ function get(url) {
2557
+ var pu;
2558
+ try { pu = urllib.parse(url); } catch (e) { fail(400, 'bad link'); return; }
2559
+ if ((pu.protocol !== 'http:' && pu.protocol !== 'https:') || !dlHostOk(pu.hostname)) { fail(400, 'a link it can\'t follow'); return; }
2560
+ var h = { 'User-Agent': s.ua || TV_UA };
2561
+ if (s.ref) { h.Referer = s.ref; }
2562
+ if (s.cookie) { h.Cookie = s.cookie; }
2563
+ var opts = { hostname: pu.hostname, port: pu.port, path: pu.path, headers: h };
2564
+ if (pu.protocol === 'https:' && caList().length) { opts.ca = caList(); }
2565
+ try {
2566
+ r = (pu.protocol === 'https:' ? https : http).get(opts, function (resp) {
2567
+ if (gone) { resp.resume(); return; }
2568
+ var sc = resp.statusCode;
2569
+ if (sc >= 300 && sc < 400 && resp.headers.location && hops < 5) { resp.resume(); hops++; get(urllib.resolve(url, resp.headers.location)); return; }
2570
+ if (sc !== 200) { resp.resume(); clearTimeout(timer); fail(sc >= 400 && sc < 600 ? sc : 502, 'HTTP ' + sc); return; }
2571
+ clearTimeout(timer);
2572
+ started = true;
2573
+ res.writeHead(200, { 'Content-Type': 'video/mp2t', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
2574
+ resp.on('data', function (c) {
2575
+ if (gone) { return; }
2576
+ s.last = Date.now();
2577
+ var b = carry ? Buffer.concat([carry, c]) : c;
2578
+ if (!synced) { // (the stream's first bytes: from its first packet)
2579
+ var at = tsSync(b);
2580
+ if (at < 0) { carry = b.length > 1024 ? b.slice(-376) : b; return; }
2581
+ b = b.slice(at); synced = true;
2582
+ }
2583
+ if (b.length < LIVE_RAW_CHUNK && !(seq === 0 && b.length >= 188 * 3)) { carry = b; return; } // (whole chunks: fewer, larger pieces to repack)
2584
+ if (!pass(b)) { resp.pause(); res.once('drain', function () { if (!gone) { resp.resume(); } }); }
2585
+ });
2586
+ resp.on('end', function () { // (what's held back goes too)
2587
+ if (gone) { return; }
2588
+ if (carry && synced) { pass(carry); }
2589
+ try { res.end(); } catch (e) {}
2590
+ stop();
2591
+ });
2592
+ resp.on('error', function () { fail(502, 'the stream broke off'); });
2593
+ });
2594
+ r.on('error', function (e) { fail(502, (e && (e.code || e.message)) || 'unknown'); });
2595
+ guardSelf(r, function () { fail(400, 'a link to the TV itself'); });
2596
+ } catch (e) { fail(502, (e && e.message) || 'unknown'); }
2597
+ }
2598
+ get(s.raw);
2599
+ }
2519
2600
  function liveRewrite(s, text, base) {
2520
2601
  var master = /#EXT-X-STREAM-INF/.test(text), direct = !master && /#EXT-X-KEY:METHOD=(?!NONE)|#EXT-X-MAP/.test(text);
2521
2602
  var sq = /#EXT-X-MEDIA-SEQUENCE:\s*(\d+)/.exec(text), seq = sq ? +sq[1] : 0, pre = liveBase(s);
@@ -2551,17 +2632,20 @@ function liveSession(u, who, opts) {
2551
2632
  var ids = Object.keys(_live);
2552
2633
  if (ids.length >= LIVE_MAX) { // (the one asked for longest ago goes)
2553
2634
  ids.sort(function (x, y) { return _live[x].last - _live[y].last; });
2635
+ if (_live[ids[0]].stop) { _live[ids[0]].stop(); } // (a raw stream it was relaying: stopped)
2554
2636
  delete _live[ids[0]];
2555
2637
  }
2638
+ var raw = !!opts.raw && !opts.film;
2556
2639
  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) };
2640
+ fix: opts.fix !== false && !opts.film, cc: opts.cc && opts.cc.length && !opts.film && !raw ? opts.cc : null, film: !!opts.film, c: ccState(), got: Object.create(null),
2641
+ raw: raw ? u : null };
2558
2642
  _live[s.id] = s;
2559
2643
  s.top = liveLink(s, u, 'm');
2560
2644
  return s;
2561
2645
  }
2562
2646
  function livePurge() {
2563
2647
  var now = Date.now();
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)
2648
+ Object.keys(_live).forEach(function (id) { if (now - _live[id].last > (_live[id].film ? LIVE_FILM_IDLE_MS : LIVE_IDLE_MS)) { if (_live[id].stop) { _live[id].stop(); } delete _live[id]; } }); // (a film may be paused a while)
2565
2649
  }
2566
2650
  // The look: the playlist (a master's first variant), then the start of the segment a player
2567
2651
  // starts with (the third from the end); with captions in that start, the whole segment (up to
@@ -2569,10 +2653,14 @@ function livePurge() {
2569
2653
  function liveProbe(u, who, cb, leaving) {
2570
2654
  var depth = 0;
2571
2655
  function list(url) {
2572
- leaving.push(liveGet(url, who, LIVE_LIST_MAX, function (err, body, at) {
2656
+ leaving.push(liveGet(url, who, depth ? LIVE_LIST_MAX : LIVE_RAW_PROBE, function (err, body, at) {
2573
2657
  if (err) { cb(err); return; }
2574
2658
  var text = body.toString('utf8');
2575
- if (!/^\s*#EXTM3U/.test(text)) { cb(null, { fix: false, sure: true, why: 'not an HLS playlist' }); return; }
2659
+ if (!/^\s*#EXTM3U/.test(text)) {
2660
+ var at0 = depth ? -1 : tsSync(body); // (a raw MPEG-TS stream, not a playlist: its first MB looked at)
2661
+ if (at0 >= 0) { var vr = liveCut(body.slice(at0)); vr.raw = true; vr.cc = []; vr.ccSure = true; cb(null, vr); return; }
2662
+ cb(null, { fix: false, sure: true, why: 'not an HLS playlist' }); return;
2663
+ }
2576
2664
  var uris = text.split(/\r?\n/).map(function (l) { return l.trim(); }).filter(function (l) { return l && l.charAt(0) !== '#'; });
2577
2665
  if (/#EXT-X-STREAM-INF/.test(text)) {
2578
2666
  if (!uris.length || ++depth > 2) { cb(null, { fix: false, sure: true, why: 'no variant' }); return; }
@@ -2593,7 +2681,7 @@ function liveProbe(u, who, cb, leaving) {
2593
2681
  cb(null, v);
2594
2682
  }, true));
2595
2683
  }, true));
2596
- }));
2684
+ }, !depth)); // (the first link: what it gives up to LIVE_RAW_PROBE, a raw stream never ending)
2597
2685
  }
2598
2686
  list(u);
2599
2687
  }
@@ -2622,19 +2710,27 @@ function liveControl(req, res, path, query, leaving) {
2622
2710
  if (!/^https?:\/\/[^\s]+$/i.test(u) || u.length > 2000) { send(res, 400, 'text/plain', 'bad link'); return; }
2623
2711
  var cc = ccAsked(q.cc);
2624
2712
  if (q.force === '1') {
2625
- var sf = liveSession(u, who, { fix: q.fix !== '0', cc: cc, film: q.film === '1' });
2626
- send(res, 200, 'application/json', JSON.stringify({ fix: true, sure: true, why: 'asked for', url: liveBase(sf) + 'm?n=' + sf.top }));
2713
+ var sf = liveSession(u, who, { fix: q.fix !== '0', cc: cc, film: q.film === '1', raw: q.raw === '1' });
2714
+ send(res, 200, 'application/json', JSON.stringify({ fix: true, sure: true, why: 'asked for', url: liveEntry(sf) }));
2627
2715
  return;
2628
2716
  }
2629
2717
  liveProbe(u, who, function (err, v) {
2630
2718
  if (err) { send(res, 200, 'application/json', JSON.stringify({ fix: false, sure: false, why: 'couldn\'t check: ' + (err.message || 'unknown') })); return; }
2631
- if (v.fix) { var s = liveSession(u, who, { fix: true, cc: cc }); v.url = liveBase(s) + 'm?n=' + s.top; }
2719
+ if (v.fix) { var s = liveSession(u, who, { fix: true, cc: cc, raw: v.raw }); v.url = liveEntry(s); }
2632
2720
  send(res, 200, 'application/json', JSON.stringify(v));
2633
2721
  }, leaving);
2634
2722
  return;
2635
2723
  }
2636
2724
  // (m: a playlist; p: the top one under its made-up quality list; s: a segment; c: a caption
2637
2725
  // track's playlist; v: a segment's captions)
2726
+ var rt = /^\/live\/([0-9a-f]{32})\/t$/.exec(path);
2727
+ if (rt) { // (a raw stream's relay: see liveStream)
2728
+ var rs = _live[rt[1]];
2729
+ if (!rs || !rs.raw) { send(res, 404, 'text/plain', 'not found'); return; }
2730
+ rs.last = Date.now();
2731
+ liveStream(rs, req, res);
2732
+ return;
2733
+ }
2638
2734
  var m = /^\/live\/([0-9a-f]{32})\/(m|p|s|c|v)$/.exec(path), s = m && _live[m[1]], link = s && /^\d+$/.test(q.n || '') ? s.links[+q.n] : null;
2639
2735
  if (!link || link.kind !== m[2]) { send(res, 404, 'text/plain', 'not found'); return; }
2640
2736
  s.last = Date.now();
@@ -2739,6 +2835,251 @@ function aiomControl(req, res, query, leaving) {
2739
2835
  }));
2740
2836
  }
2741
2837
 
2838
+ // ---- Network folders (WebDAV: /dav/list, /dav/walk, /dav/sub) ----
2839
+ // A folder a NAS or computer shares over WebDAV, for the Local tab. Each request names the
2840
+ // folder's address (?u=, no sign-in in it) and a path under it (&p=), and carries its sign-in
2841
+ // (X-Dav-Auth: base64 "user:password", sent on as Basic) and a certificate the user trusted
2842
+ // (X-Dav-Cert: its base64 DER) in headers, never in a link: nothing is kept here. Requests go
2843
+ // to that server only, below that address (redirects: the same server, still below it), never
2844
+ // to the TV itself. An https certificate no known authority signed is sent back (why:
2845
+ // 'untrusted') for the app to ask about; trusted, it's the only one accepted for that folder
2846
+ // (its name not checked: that certificate or nothing). What the user can fix is answered 200
2847
+ // { why, message } (the app reads it); a malformed request, 400.
2848
+ var DAV_MS = 20000, DAV_LIST_MAX = 2 * 1048576, DAV_ENTRIES = 2000;
2849
+ var DAV_WALK_DIRS = 2000, DAV_WALK_FILES = 20000, DAV_WALK_DEPTH = 12, DAV_WALK_PAR = 4, DAV_WALK_MS = 90000;
2850
+ var DAV_PROPS = '<?xml version="1.0" encoding="utf-8"?><D:propfind xmlns:D="DAV:"><D:prop><D:resourcetype/><D:getcontentlength/></D:prop></D:propfind>';
2851
+ var _davWalking = null;
2852
+ function davQ(query) {
2853
+ var q = {};
2854
+ String(query || '').split('&').forEach(function (kv) { var i = kv.indexOf('='); if (i > 0) { try { q[kv.slice(0, i)] = decodeURIComponent(kv.slice(i + 1).replace(/\+/g, ' ')); } catch (e) {} } });
2855
+ return q;
2856
+ }
2857
+ function davWhy(why, message) { return Object.assign(new Error(message), { why: why }); }
2858
+ // The folder a request names: { base (its address, ending in /), pu, auth, cert } or null.
2859
+ function davFolder(req, q) {
2860
+ var u = String(q.u || '').trim(), pu;
2861
+ if (!/^https?:\/\/[^\s]+$/i.test(u) || u.length > 1000) { return null; }
2862
+ try { pu = urllib.parse(u); } catch (e) { return null; }
2863
+ if (!pu.hostname || pu.auth || pu.search || pu.hash || !dlHostOk(pu.hostname)) { return null; }
2864
+ var base = pu.protocol + '//' + pu.host + String(pu.pathname || '/').replace(/\/*$/, '/');
2865
+ var a = String((req.headers && req.headers['x-dav-auth']) || ''), c = String((req.headers && req.headers['x-dav-cert']) || '');
2866
+ if (a && !/^[A-Za-z0-9+\/=]{4,1400}$/.test(a)) { return null; }
2867
+ if (c && !/^[A-Za-z0-9+\/=]{200,5000}$/.test(c)) { return null; }
2868
+ var pem = c ? '-----BEGIN CERTIFICATE-----\n' + c.replace(/(.{64})/g, '$1\n').replace(/\n$/, '') + '\n-----END CERTIFICATE-----\n' : '';
2869
+ return { base: base, pu: urllib.parse(base), auth: a ? 'Basic ' + a : '', cert: pem };
2870
+ }
2871
+ // A path under the folder (each part %-escaped; '', '.' and '..' refused), or null.
2872
+ function davUrl(f, rel, dir) {
2873
+ rel = String(rel || '').replace(/^\/+|\/+$/g, '');
2874
+ if (!rel) { return f.base; }
2875
+ if (rel.length > 1024 || rel.indexOf('\0') !== -1) { return null; }
2876
+ var segs = rel.split('/');
2877
+ if (segs.some(function (s) { return !s || s === '.' || s === '..'; })) { return null; }
2878
+ return f.base + segs.map(encodeURIComponent).join('/') + (dir ? '/' : '');
2879
+ }
2880
+ function davUnder(f, pu) { return sameServerRedirect(f.pu, pu) && String(pu.pathname || '').indexOf(String(f.pu.pathname || '/')) === 0; }
2881
+ function davCertProblem(e) { return /CERT|SELF_SIGNED|UNABLE_TO_VERIFY|UNABLE_TO_GET_ISSUER|Hostname\/IP|altnames|ERR_TLS/i.test(String((e && e.code) || '') + ' ' + String((e && e.message) || '')); }
2882
+ // One request to the folder's server (with its redirects): one deadline for the whole chain; the
2883
+ // abort it returns stops it. cb(err, status, body (a 2xx's), final address).
2884
+ function davReq(f, method, url, headers, body, max, cb) {
2885
+ cb = once(cb);
2886
+ var ctl = { r: null, done: false };
2887
+ var timer = setTimeout(function () { finish(davWhy('unreachable', 'no answer in ' + (DAV_MS / 1000) + ' s')); }, DAV_MS);
2888
+ function finish(err, sc, buf, at) { if (ctl.done) { return; } ctl.done = true; clearTimeout(timer); try { if (ctl.r) { ctl.r.abort(); } } catch (e) {} cb(err, sc, buf, at); }
2889
+ function go(u, hops) {
2890
+ var pu;
2891
+ try { pu = urllib.parse(u); } catch (e) { finish(upError('bad address', 400)); return; }
2892
+ if ((pu.protocol !== 'http:' && pu.protocol !== 'https:') || !dlHostOk(pu.hostname)) { finish(upError('an address it can\'t reach', 400)); return; }
2893
+ var h = { 'User-Agent': 'StremioK', 'Accept': '*/*' }, data = body ? toBuffer(body) : null;
2894
+ Object.keys(headers || {}).forEach(function (k) { h[k] = headers[k]; });
2895
+ if (f.auth) { h.Authorization = f.auth; }
2896
+ if (data) { h['Content-Length'] = data.length; }
2897
+ var opts = { hostname: pu.hostname, port: pu.port, path: pu.path, method: method, headers: h };
2898
+ if (pu.protocol === 'https:') {
2899
+ if (f.cert) { opts.ca = [f.cert]; opts.checkServerIdentity = function () { return undefined; }; opts.agent = false; }
2900
+ else if (caList().length) { opts.ca = caList(); }
2901
+ }
2902
+ var chunks = [], size = 0;
2903
+ try {
2904
+ var r = ctl.r = (pu.protocol === 'https:' ? https : http).request(opts, function (resp) {
2905
+ if (ctl.done || ctl.r !== r) { resp.resume(); return; }
2906
+ var sc = resp.statusCode;
2907
+ if (sc >= 300 && sc < 400 && sc !== 304 && resp.headers.location && hops < 4) {
2908
+ resp.resume();
2909
+ var np = null;
2910
+ try { np = urllib.parse(urllib.resolve(u, String(resp.headers.location))); } catch (e) { np = null; }
2911
+ if (!np || !davUnder(f, np)) { finish(davWhy('elsewhere', 'it sent StremioK to another address: not followed (the sign-in stays with it)')); return; }
2912
+ go(urllib.format(np), hops + 1);
2913
+ return;
2914
+ }
2915
+ if (sc < 200 || sc >= 300) { resp.resume(); finish(null, sc, null, u); return; }
2916
+ resp.on('data', function (c) { if (ctl.done) { return; } chunks.push(c); size += c.length; if (size > max) { finish(davWhy('toolarge', 'its answer is over ' + Math.round(max / 1048576) + ' MB')); } });
2917
+ resp.on('end', function () { finish(null, sc, Buffer.concat(chunks, size), u); });
2918
+ resp.on('error', function (e) { finish(e); });
2919
+ });
2920
+ r.on('error', function (e) { if (ctl.r === r) { finish(e); } });
2921
+ guardSelf(r, function () { finish(upError('an address it can\'t reach', 400)); });
2922
+ if (data) { r.write(data); }
2923
+ r.end();
2924
+ } catch (e) { finish(e); }
2925
+ }
2926
+ go(url, 0);
2927
+ return function () { if (!ctl.done) { ctl.done = true; clearTimeout(timer); try { if (ctl.r) { ctl.r.abort(); } } catch (e) {} } };
2928
+ }
2929
+ // The certificate an https folder shows (not trusted): { cert (base64 DER), fp (SHA-256), name,
2930
+ // until }, or null. Only the handshake: nothing is sent. Checking is off for this one connection
2931
+ // on purpose (a certificate that fails it can't be read otherwise: Node gives none after the
2932
+ // failure); it's only shown to you to trust or not, and every request is checked (davReq: the
2933
+ // bundled authorities, or the one certificate you trusted).
2934
+ function davCertOf(f, cb) {
2935
+ cb = once(cb);
2936
+ var pu = f.pu, sock = null, timer = setTimeout(function () { done(null); }, 10000);
2937
+ function done(r) { clearTimeout(timer); try { if (sock) { sock.destroy(); } } catch (e) {} cb(r); }
2938
+ try {
2939
+ var o = { host: pu.hostname, port: +(pu.port || 443), rejectUnauthorized: false };
2940
+ if (!/^[\d.]+$/.test(pu.hostname) && String(pu.hostname).indexOf(':') === -1) { o.servername = pu.hostname; }
2941
+ sock = tls.connect(o, function () {
2942
+ if (isSelfAddr(sock.remoteAddress)) { done(null); return; }
2943
+ var c = null;
2944
+ try { c = sock.getPeerCertificate(); } catch (e) { c = null; }
2945
+ if (!c || !c.raw) { done(null); return; }
2946
+ var fp = crypto.createHash('sha256').update(c.raw).digest('hex').toUpperCase().replace(/(..)(?!$)/g, '$1:');
2947
+ done({ cert: c.raw.toString('base64'), fp: fp, name: String((c.subject && c.subject.CN) || '').slice(0, 200), until: String(c.valid_to || '').slice(0, 60) });
2948
+ });
2949
+ sock.on('error', function () { done(null); });
2950
+ } catch (e) { done(null); }
2951
+ }
2952
+ // What went wrong, as the app shows it: { why, message[, cert, fp, name, until] }.
2953
+ function davProblem(f, err, cb) {
2954
+ if (err && err.why) { cb({ why: err.why, message: err.message }); return; }
2955
+ if (f.pu.protocol === 'https:' && davCertProblem(err)) {
2956
+ davCertOf(f, function (c) {
2957
+ var p = { why: 'untrusted', message: 'its certificate isn\'t from a known authority (' + String((err && (err.code || err.message)) || '') + ')' };
2958
+ if (c) { p.cert = c.cert; p.fp = c.fp; p.name = c.name; p.until = c.until; }
2959
+ cb(p);
2960
+ });
2961
+ return;
2962
+ }
2963
+ var code = String((err && (err.code || err.message)) || 'unknown');
2964
+ cb({ why: /ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ENETUNREACH|ETIMEDOUT|ECONNRESET|EAI_AGAIN/.test(code) ? 'unreachable' : 'failed', message: 'couldn\'t reach it (' + code + ')' });
2965
+ }
2966
+ function xmlText(s) {
2967
+ return String(s).replace(/&#x([0-9a-f]+);/gi, function (m, h) { return String.fromCharCode(parseInt(h, 16)); }).replace(/&#(\d+);/g, function (m, d) { return String.fromCharCode(+d); })
2968
+ .replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&apos;/g, '\'').replace(/&amp;/g, '&');
2969
+ }
2970
+ function davNorm(p) { return String(p || '').replace(/\/+$/, ''); }
2971
+ // A PROPFIND answer's entries directly in the folder (dirPath: its path, decoded): [{ name, dir,
2972
+ // size }], the folder itself left out. Any namespace prefix (D:, d:, lp1:, none).
2973
+ function davEntries(xml, dirPath) {
2974
+ var out = [], self = davNorm(dirPath), seen = {};
2975
+ var parts = String(xml).split(/<(?:[\w.-]+:)?response(?:\s[^>]*)?>/i).slice(1);
2976
+ for (var i = 0; i < parts.length && out.length < DAV_ENTRIES; i++) {
2977
+ var x = parts[i], hm = /<(?:[\w.-]+:)?href(?:\s[^>]*)?>([^<]*)</i.exec(x);
2978
+ if (!hm) { continue; }
2979
+ var href = xmlText(hm[1]).trim(), p;
2980
+ try { p = /^https?:\/\//i.test(href) ? String(urllib.parse(href).pathname || '/') : href.split('?')[0]; } catch (e) { continue; }
2981
+ try { p = decodeURIComponent(p); } catch (e) {}
2982
+ var n = davNorm(p), name;
2983
+ if (n === self) { continue; }
2984
+ if (n.indexOf(self + '/') === 0) { name = n.slice(self.length + 1); if (name.indexOf('/') !== -1) { continue; } }
2985
+ else { name = n.split('/').pop(); }
2986
+ if (!name || name.length > 255 || name.indexOf('\0') !== -1 || name === '.' || name === '..' || seen[name]) { continue; }
2987
+ seen[name] = 1;
2988
+ var dir = /<(?:[\w.-]+:)?collection\s*\/?>/i.test(x);
2989
+ var sm = /<(?:[\w.-]+:)?getcontentlength(?:\s[^>]*)?>\s*(\d+)\s*</i.exec(x);
2990
+ out.push({ name: name, dir: dir, size: dir ? 0 : (sm ? +sm[1] : 0) });
2991
+ }
2992
+ return out;
2993
+ }
2994
+ // A folder's listing (one level): cb(err, { entries }).
2995
+ function davList(f, rel, cb) {
2996
+ cb = once(cb);
2997
+ var url = davUrl(f, rel, true);
2998
+ if (!url) { cb(upError('not a path in the folder', 400)); return noop; }
2999
+ return davReq(f, 'PROPFIND', url, { Depth: '1', 'Content-Type': 'application/xml; charset=utf-8' }, DAV_PROPS, DAV_LIST_MAX, function (err, sc, buf, at) {
3000
+ if (err) { cb(err); return; }
3001
+ if (sc === 401 || sc === 403) { cb(davWhy('auth', 'it refused the user name or password (HTTP ' + sc + ')')); return; }
3002
+ if (sc === 404) { cb(davWhy('missing', 'no such folder there (HTTP 404)')); return; }
3003
+ var text = buf ? buf.toString('utf8') : '';
3004
+ if (sc !== 207 || !/multistatus/i.test(text)) { cb(davWhy('notdav', 'not a WebDAV folder (HTTP ' + sc + ')')); return; }
3005
+ var dirPath = '/';
3006
+ try { dirPath = String(urllib.parse(at).pathname || '/'); dirPath = decodeURIComponent(dirPath); } catch (e) {}
3007
+ cb(null, { entries: davEntries(text, dirPath) });
3008
+ });
3009
+ }
3010
+ // Every video and subtitle file under the folder (the index): cb(err, { files: [{ p, size }],
3011
+ // dirs, truncated }). Bounded (DAV_WALK_*); a subfolder it can't read is left out (truncated).
3012
+ function davWalk(f, st, cb) {
3013
+ cb = once(cb);
3014
+ var files = [], queue = [{ rel: '', depth: 0 }], active = 0, dirs = 0, truncated = false, started = Date.now();
3015
+ function end() { if (!active && !queue.length) { cb(null, { files: files, dirs: dirs, truncated: truncated }); } }
3016
+ function pump() {
3017
+ while (!st.cancelled && active < DAV_WALK_PAR && queue.length) {
3018
+ if (dirs >= DAV_WALK_DIRS || files.length >= DAV_WALK_FILES || Date.now() - started > DAV_WALK_MS) { truncated = true; queue = []; break; }
3019
+ var d = queue.shift();
3020
+ dirs++; active++;
3021
+ st.aborts.push(davList(f, d.rel, (function (d) {
3022
+ return function (err, r) {
3023
+ active--;
3024
+ if (st.cancelled) { return; }
3025
+ if (err) {
3026
+ if (!d.rel) { st.cancelled = true; cb(err); return; } // (the folder itself)
3027
+ truncated = true;
3028
+ } else {
3029
+ r.entries.forEach(function (e) {
3030
+ if (HIDDEN_NAME.test(e.name)) { return; }
3031
+ var p = d.rel ? d.rel + '/' + e.name : e.name;
3032
+ if (e.dir) { if (d.depth < DAV_WALK_DEPTH) { queue.push({ rel: p, depth: d.depth + 1 }); } else { truncated = true; } }
3033
+ else if ((VIDEO_EXT.test(e.name) || SUB_EXT.test(e.name)) && files.length < DAV_WALK_FILES) { files.push({ p: p, size: e.size || 0 }); }
3034
+ });
3035
+ }
3036
+ pump();
3037
+ };
3038
+ })(d)));
3039
+ }
3040
+ end();
3041
+ }
3042
+ pump();
3043
+ }
3044
+ // A subtitle file in the folder, as UTF-8 text (as /fssub: ASS / SSA as SRT).
3045
+ function davSub(f, rel, cb) {
3046
+ cb = once(cb);
3047
+ var url = davUrl(f, rel, false);
3048
+ if (!url || !SUB_EXT.test(String(rel))) { cb(upError('not a subtitle file in the folder', 400)); return noop; }
3049
+ return davReq(f, 'GET', url, null, null, FS_SUB_MAX, function (err, sc, buf) {
3050
+ if (err) { cb(err); return; }
3051
+ if (sc !== 200 || !buf) { cb(upError('HTTP ' + sc, 502)); return; }
3052
+ var text = decodeText(buf);
3053
+ cb(null, /\.(ass|ssa)$/i.test(String(rel)) ? assToSrt(text) : text);
3054
+ });
3055
+ }
3056
+ function davControl(req, res, path, query, leaving) {
3057
+ if (!entryAllowed(req, query)) { send(res, 403, 'text/plain', 'not allowed (token)'); return; }
3058
+ var q = davQ(query), f = davFolder(req, q);
3059
+ if (!f) { send(res, 400, 'text/plain', 'bad folder'); return; }
3060
+ function answer(err, r) {
3061
+ if (!err) { send(res, 200, 'application/json', JSON.stringify(r)); return; }
3062
+ if (err.status === 400) { send(res, 400, 'text/plain', err.message); return; }
3063
+ davProblem(f, err, function (p) { send(res, 200, 'application/json', JSON.stringify(p)); });
3064
+ }
3065
+ if (path === '/dav/list') { leaving.push(davList(f, q.p, answer)); return; }
3066
+ if (path === '/dav/sub') {
3067
+ leaving.push(davSub(f, q.p, function (err, text) {
3068
+ if (err) { send(res, err.status === 400 ? 400 : 502, 'text/plain', 'failed: ' + (err.message || 'unknown')); return; }
3069
+ send(res, 200, 'text/plain; charset=utf-8', text);
3070
+ }));
3071
+ return;
3072
+ }
3073
+ if (path === '/dav/walk') {
3074
+ if (_davWalking) { send(res, 200, 'application/json', JSON.stringify({ why: 'busy', message: 'another folder is being indexed' })); return; }
3075
+ var st = _davWalking = { cancelled: false, aborts: [] };
3076
+ leaving.push(function () { st.cancelled = true; st.aborts.forEach(function (a) { try { a(); } catch (e) {} }); if (_davWalking === st) { _davWalking = null; } });
3077
+ davWalk(f, st, function (err, r) { if (_davWalking === st) { _davWalking = null; } answer(err, r); });
3078
+ return;
3079
+ }
3080
+ send(res, 404, 'text/plain', 'not found');
3081
+ }
3082
+
2742
3083
  // ---- Xtream films and series (/xtvod/list, /xtvod/find) ----
2743
3084
  // An Xtream account's whole list of films (get_vod_streams) and series (get_series), read a piece
2744
3085
  // at a time (xtvItems: one title parsed at a time, never the whole answer) into a small record each
@@ -3915,7 +4256,7 @@ var CONFIG_MAX = 262144, GIVE_MAX = 262144;
3915
4256
  var ENTRY_OPEN_MAX = 2, ENTRY_OPENS = 12, ENTRY_CONNECTIONS = 8, ENTRY_VISIT_MS = 20000, ENTRY_QUIET_MS = 10000;
3916
4257
  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',
3917
4258
  search: 'Search on StremioK', youtube: 'Add a YouTube catalog to StremioK', aiom: 'Your AIOManager address for StremioK', aiomkey: 'Your AIOManager API key for StremioK',
3918
- server: 'Your streaming server’s address for StremioK', mac: 'Your Stalker portal’s MAC address for StremioK' };
4259
+ server: 'Your streaming server’s address for StremioK', mac: 'Your Stalker portal’s MAC address for StremioK', webdav: 'Your network folder’s address for StremioK' };
3919
4260
  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)
3920
4261
  var _entries = Object.create(null), _entryServer = null, _entrySockets = [], _entryOpened = [];
3921
4262
  function lanAddress() {
package/tizenbrew.html ADDED
@@ -0,0 +1,20 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>StremioK</title>
6
+ <script>
7
+ // TizenBrew's start page (package.json's appPath). TizenBrew reads each file from jsDelivr at
8
+ // an address with no version, which jsDelivr keeps per file for hours after a release: an
9
+ // old file, or a mix of two versions. This page names no other file, so nothing is fetched
10
+ // from there: it opens this version's own copy (npm/stremiok@<version>/index.html), whose
11
+ // files all come from that address. build.sh stamps the ?v= below.
12
+ (function () {
13
+ var v = '?v=2.3.3'.slice(3), l = location, rest = (l.search || '') + (l.hash || '');
14
+ var m = /^(\/module\/npm%2F[^\/%@]+)\//i.exec(l.pathname || '');
15
+ l.replace(m ? m[1] + '%40' + v + '/index.html' + rest : 'index.html' + rest);
16
+ })();
17
+ </script>
18
+ </head>
19
+ <body style="background:#000"></body>
20
+ </html>