stremiok 2.3.2 → 2.3.4

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/local.js CHANGED
@@ -8,7 +8,10 @@
8
8
  opens, and a drive is indexed (StremioK's service walks it: which videos and subtitle
9
9
  files it has, so title pages know what's on it) only when you ask; the last index is kept.
10
10
  - Subtitle files next to a video (Film.srt, Film.en.srt…) are its subtitles, read through the
11
- service; with a match, subtitle addons are asked with the file's OpenSubtitles hash too. */
11
+ service; with a match, subtitle addons are asked with the file's OpenSubtitles hash too.
12
+ - A network folder (NetFolders: WebDAV) is a drive too ({ label, root: 'dav:<id>', dav }):
13
+ listed and indexed through the service, its files played from their links (openUrl adds
14
+ its sign-in), its subtitle files read by the service; no downloads or file hash. */
12
15
  var LocalMedia = (function () {
13
16
  'use strict';
14
17
 
@@ -21,7 +24,7 @@ var LocalMedia = (function () {
21
24
  var FIX_KEY = 'stremiok.local.fixes'; // a file (or a show) -> your own match | { none }
22
25
  var INDEX_KEY = 'stremiok.local.index.'; // + a drive's root (the TV's database): { label, at, files, subs }, one per drive
23
26
  var INDEXES_KEY = 'stremiok.local.indexes'; // the drives with one kept: root -> when (the INDEXES_MAX latest)
24
- var INDEXES_MAX = 4;
27
+ var INDEXES_MAX = 8; // (USB drives and network folders)
25
28
  var HIDDEN_KEY = 'stremiok.local.hidden';
26
29
  var MATCHES_MAX = 3000, FIXES_MAX = 2000, NONE_RETRY_MS = 7 * 86400000;
27
30
  var LIST_MAX = 3000, FS_WAIT = 10000, WALK_WAIT = 150000;
@@ -79,20 +82,27 @@ var LocalMedia = (function () {
79
82
  // Where the token can't be read (Tizen 6: the service keeps it in a folder of its own), the
80
83
  // service takes StremioK's X-StremioK header instead (a web page can't send one).
81
84
  var NO_TOKEN = { 'X-StremioK': '1' };
82
- function svcHeaders(token) { return token ? null : NO_TOKEN; }
85
+ function svcHeaders(token, extra) {
86
+ if (!extra) { return token ? null : NO_TOKEN; }
87
+ var h = {};
88
+ Object.keys(extra).forEach(function (k) { h[k] = extra[k]; });
89
+ if (!token) { h['X-StremioK'] = '1'; }
90
+ return h;
91
+ }
83
92
  // The service running and its token read (for the subtitle files' links): resolves either way.
84
93
  function ready() {
85
94
  if (!service()) { return Promise.resolve(false); }
86
95
  return YTPlay.ensureService().then(function () { return readToken(); }).then(function () { return true; }, function () { return false; }); // (no token: its header)
87
96
  }
88
- function askService(path, timeout, max, cancel) {
97
+ // extra: headers of its own (a network folder's sign-in: NetFolders).
98
+ function askService(path, timeout, max, cancel, extra) {
89
99
  if (!service()) { return Promise.reject(new Error('no StremioK service here')); }
90
100
  return YTPlay.ensureService().then(function () { return readToken(); }).then(function (t) {
91
- return U.getJSON(svcUrl(path, t), timeout, max, cancel, svcHeaders(t)).then(null, function (e) {
101
+ return U.getJSON(svcUrl(path, t), timeout, max, cancel, svcHeaders(t, extra)).then(null, function (e) {
92
102
  if (!/HTTP 403\b/.test((e && e.message) || '')) { throw e; }
93
103
  return readToken(true).then(function (t2) {
94
104
  if (!t2 || t2 === t) { throw e; }
95
- return U.getJSON(svcUrl(path, t2), timeout, max, cancel, svcHeaders(t2));
105
+ return U.getJSON(svcUrl(path, t2), timeout, max, cancel, svcHeaders(t2, extra));
96
106
  });
97
107
  });
98
108
  });
@@ -146,8 +156,11 @@ var LocalMedia = (function () {
146
156
  return _drivesP;
147
157
  }
148
158
  function drives() { return _drives ? Promise.resolve(_drives) : refreshDrives(); }
149
- function knownDrives() { return _drives || []; }
150
- function hasDrive() { return !!(_drives && _drives.length); }
159
+ function netDrives() { return typeof NetFolders !== 'undefined' ? NetFolders.drives() : []; }
160
+ function isNet(d) { return !!(d && d.dav); }
161
+ // The USB drives read, then the network folders that are on.
162
+ function knownDrives() { return (_drives || []).concat(netDrives()); }
163
+ function hasDrive() { return knownDrives().length > 0; }
151
164
  function driveOf(abs) {
152
165
  var ds = knownDrives();
153
166
  for (var i = 0; i < ds.length; i++) { if (abs === ds[i].root || abs.indexOf(ds[i].root + '/') === 0) { return ds[i]; } }
@@ -173,17 +186,39 @@ var LocalMedia = (function () {
173
186
  U.crumb('usb: plugged in?');
174
187
  usbStorages().then(function (l) { _present = l.length; listen(); if (_present) { emit('drives'); } }, function () { listen(); });
175
188
  }
176
- function present() { return _present > 0; }
189
+ function present() { return _present > 0 || netDrives().length > 0; }
190
+ // Resolves every drive (USB ones, then network folders), each one's saved index loaded.
177
191
  function ensure() {
178
- if (!fsApi()) { return Promise.resolve([]); }
179
192
  if (_ensured) { return _ensured; }
180
- _ensured = refreshDrives().then(function (ds) {
193
+ var usb = !fsApi() ? Promise.resolve([]) : refreshDrives().then(function (ds) {
181
194
  listen();
182
195
  if (service() && ds.length) { YTPlay.ensureService().then(function () { return readToken(); }).then(null, function () {}); } // (for a big file's link: openUrl)
183
- return Promise.all(ds.map(loadIndex)).then(function () { _read = true; emit('drives'); return ds; });
196
+ return ds;
197
+ });
198
+ _ensured = usb.then(function () {
199
+ var all = knownDrives();
200
+ return Promise.all(all.map(loadIndex)).then(function () { _read = true; emit('drives'); return all; });
184
201
  });
185
202
  return _ensured;
186
203
  }
204
+ // A network folder added, removed, turned on or off: its index loaded (or set aside), the
205
+ // titles' sources made again.
206
+ function netChanged() {
207
+ var ds = netDrives();
208
+ Promise.all(ds.map(loadIndex)).then(function () { rebuild(); emit('drives'); emit('index'); });
209
+ }
210
+ // A network folder removed: its index deleted (here and kept on the TV).
211
+ function forgetDrive(root) {
212
+ if (!/^dav:/.test(root)) { return; }
213
+ _gen[root] = (_gen[root] || 0) + 1;
214
+ if (_cancel[root]) { _cancel[root].cancel(); delete _cancel[root]; }
215
+ delete _scanning[root]; delete _status[root]; delete _index[root];
216
+ if (U.bigStore) { U.bigStore.remove(INDEX_KEY + root); }
217
+ var kept = U.store.get(INDEXES_KEY, {}) || {};
218
+ if (kept[root]) { delete kept[root]; U.store.set(INDEXES_KEY, kept); }
219
+ rebuild();
220
+ emit('index'); emit('status');
221
+ }
187
222
  function isRead() { return _read; }
188
223
  function listen() {
189
224
  if (_listening) { return; }
@@ -196,7 +231,7 @@ var LocalMedia = (function () {
196
231
  }
197
232
  _drives = null;
198
233
  refreshDrives().then(function (ds) {
199
- Object.keys(_index).forEach(function (root) { if (!ds.some(function (d) { return d.root === root; })) { delete _index[root]; } });
234
+ Object.keys(_index).forEach(function (root) { if (!/^dav:/.test(root) && !ds.some(function (d) { return d.root === root; })) { delete _index[root]; } });
200
235
  return Promise.all(ds.map(loadIndex));
201
236
  }).then(function () {
202
237
  rebuild();
@@ -233,6 +268,7 @@ var LocalMedia = (function () {
233
268
  // A folder of a drive (rel '' its top): { entries: [{ name, dir, size, rel, abs, uri, bad? }],
234
269
  // via? 'service' } — the TV's own listing, else (Tizen 3 failing a whole folder) the service's.
235
270
  function list(drive, rel) {
271
+ if (isNet(drive)) { return NetFolders.list(drive.dav, rel); }
236
272
  rel = (rel || '').replace(/^\/+|\/+$/g, '');
237
273
  var vpath = drive.label + (rel ? '/' + rel : ''), abs = drive.root + (rel ? '/' + rel : '');
238
274
  function viaService(why) {
@@ -430,17 +466,22 @@ var LocalMedia = (function () {
430
466
  }
431
467
  // Forget the drives' indexes (here and kept on the TV): title pages stop offering their files
432
468
  // until a drive is indexed again.
469
+ // (the USB drives' only: a network folder keeps its own, see forgetDrive)
433
470
  function clearIndex() {
434
- Object.keys(_scanning).forEach(function (root) { _gen[root] = (_gen[root] || 0) + 1; }); // (indexing now: stopped, nothing saved)
435
- Object.keys(_cancel).forEach(function (root) { _cancel[root].cancel(); });
436
- _scanning = {}; _cancel = {};
437
- _index = {}; _status = {};
471
+ function usb(root) { return !/^dav:/.test(root); }
472
+ Object.keys(_scanning).filter(usb).forEach(function (root) { _gen[root] = (_gen[root] || 0) + 1; }); // (indexing now: stopped, nothing saved)
473
+ Object.keys(_cancel).filter(usb).forEach(function (root) { _cancel[root].cancel(); delete _cancel[root]; });
474
+ Object.keys(_scanning).filter(usb).forEach(function (root) { delete _scanning[root]; });
475
+ Object.keys(_index).filter(usb).forEach(function (root) { delete _index[root]; });
476
+ Object.keys(_status).filter(usb).forEach(function (root) { delete _status[root]; });
438
477
  rebuild();
478
+ var kept = U.store.get(INDEXES_KEY, {}) || {};
439
479
  if (U.bigStore) {
440
- Object.keys(U.store.get(INDEXES_KEY, {}) || {}).forEach(function (root) { U.bigStore.remove(INDEX_KEY + root); });
480
+ Object.keys(kept).filter(usb).forEach(function (root) { U.bigStore.remove(INDEX_KEY + root); });
441
481
  U.bigStore.remove('stremiok.local.index'); // (1.9.0–1.9.3 kept every drive's in one)
442
482
  }
443
- U.store.remove(INDEXES_KEY);
483
+ Object.keys(kept).filter(usb).forEach(function (root) { delete kept[root]; });
484
+ if (Object.keys(kept).length) { U.store.set(INDEXES_KEY, kept); } else { U.store.remove(INDEXES_KEY); }
444
485
  emit('index'); emit('status');
445
486
  }
446
487
  function forgetMatches() { U.store.remove(MATCH_KEY); U.store.remove(FIX_KEY); rebuild(); emit('matches'); }
@@ -520,6 +561,7 @@ var LocalMedia = (function () {
520
561
  // Walk a drive: the service in one go (its own file access), else folder by folder here.
521
562
  // cancel: stopping it (Stop, Clear) closes the request, and the service stops walking.
522
563
  function walk(drive, cancel) {
564
+ if (isNet(drive)) { return NetFolders.walk(drive.dav, cancel); }
523
565
  return askService('/fswalk?path=' + encodeURIComponent(drive.root), WALK_WAIT, 8 * 1024 * 1024, cancel).then(function (r) {
524
566
  return { files: U.listOf(r && r.files, 20000, function (f) { return f && typeof f.p === 'string'; }), truncated: !!(r && r.truncated) };
525
567
  }, function (e) {
@@ -711,11 +753,12 @@ var LocalMedia = (function () {
711
753
  });
712
754
  }
713
755
  function subTrack(drive, s, lang, label) {
714
- var subPath = '/fssub?path=' + encodeURIComponent(drive.root + '/' + s);
715
- var track = { id: 'file:' + s, lang: lang, _addon: label, _file: nameOf(s) };
756
+ var net = isNet(drive) ? drive.dav : null;
757
+ var subPath = net ? NetFolders.subPath(net, s) : '/fssub?path=' + encodeURIComponent(drive.root + '/' + s);
758
+ var track = { id: (net ? 'dav:' + net.id + ':' : 'file:') + s, lang: lang, _addon: label, _file: nameOf(s) };
716
759
  // (its link with the token as it is when used: read once the service is up)
717
760
  Object.defineProperty(track, 'url', { enumerable: true, get: function () { return svcUrl(subPath, _token); } });
718
- Object.defineProperty(track, 'headers', { enumerable: false, get: function () { return svcHeaders(_token); } }); // (no token: its header)
761
+ Object.defineProperty(track, 'headers', { enumerable: false, get: function () { return svcHeaders(_token, net ? NetFolders.headers(net) : null); } }); // (no token: its header; a folder's sign-in)
719
762
  return track;
720
763
  }
721
764
  // A subtitle file of its own: its language when its name says one StremioK knows (after its
@@ -740,11 +783,14 @@ var LocalMedia = (function () {
740
783
  }
741
784
  var _recent = U.lru(200); // url -> a source made here lately (Continue Watching's resume finds it)
742
785
  function makeStream(drive, file, subs, uri) {
743
- var abs = drive.root + '/' + file.p, name = nameOf(file.p), url = uri || fileUri(abs);
744
- var st = { name: '💾 USB drive', title: name + (file.size ? '\n💾 ' + humanSize(file.size) : ''), url: url,
786
+ var net = isNet(drive) ? drive.dav : null;
787
+ var abs = net ? NetFolders.fileUrl(net, file.p) : drive.root + '/' + file.p, name = nameOf(file.p), url = net ? abs : (uri || fileUri(abs));
788
+ var icon = net ? '🌐' : '💾';
789
+ var st = { name: icon + (net ? ' Network folder' : ' USB drive'), title: name + (file.size ? '\n' + icon + ' ' + humanSize(file.size) : ''), url: url,
745
790
  behaviorHints: { filename: name, videoSize: file.size || undefined, bingeGroup: 'stremiok-local' },
746
- _addon: 'Your USB drive', _local: MARK, _localSubs: subs || subsInIndex(drive, file.p),
791
+ _addon: net ? 'Your network folder' : 'Your USB drive', _local: MARK, _localSubs: subs || subsInIndex(drive, file.p),
747
792
  _localFile: { abs: abs, rel: file.p, size: file.size || 0, name: name } };
793
+ if (net) { st._localFile.dav = net.id; }
748
794
  _recent.set(url, st);
749
795
  return st;
750
796
  }
@@ -753,14 +799,17 @@ var LocalMedia = (function () {
753
799
  // read past 2 GB of a file straight from the drive (playing from the start goes, every jump
754
800
  // stalls) —, else the file itself. The source's own link stays the file's (its identity).
755
801
  var BIG = 2147483647;
802
+ // A network folder's file: its link with the folder's sign-in (NetFolders.playUrl).
756
803
  function openUrl(url, size) {
804
+ if (typeof NetFolders !== 'undefined' && /^https?:/i.test(url || '')) { var nu = NetFolders.playUrl(url); if (nu) { return nu; } }
757
805
  if (!/^file:\/\/\/opt\/media\//i.test(url || '')) { return url; }
758
806
  var abs = realPath(url);
759
807
  if (!size) { var hit = _recent.get(url); size = hit && hit._localFile ? hit._localFile.size : 0; }
760
808
  if (!(size > BIG) || !_token || !service()) { return url; }
761
809
  return svcUrl('/fsfile?path=' + encodeURIComponent(abs), _token);
762
810
  }
763
- function isLocalStream(s) { return !!(s && s._local === MARK && typeof s.url === 'string' && /^file:\/\/\/opt\/media\//i.test(s.url)); }
811
+ function isFolderUrl(url) { return typeof NetFolders !== 'undefined' && !!NetFolders.folderOfUrl(url); }
812
+ function isLocalStream(s) { return !!(s && s._local === MARK && typeof s.url === 'string' && (/^file:\/\/\/opt\/media\//i.test(s.url) || isFolderUrl(s.url))); }
764
813
  // The files on your drives for a movie (tt…) or an episode (tt…:1:2), as sources.
765
814
  function streamsFor(type, id) {
766
815
  if ((type !== 'movie' && type !== 'series') || !/^tt\d+(:\d+:\d+)?$/.test('' + id)) { return []; }
@@ -775,20 +824,26 @@ var LocalMedia = (function () {
775
824
  subsInIndex(x.drive, x.file.p).forEach(function (t) {
776
825
  if (seen[t.id]) { return; }
777
826
  seen[t.id] = 1;
778
- t._addon = 'Your USB drive';
827
+ t._addon = isNet(x.drive) ? 'Your network folder' : 'Your USB drive';
779
828
  out.push(t);
780
829
  });
781
830
  });
782
831
  (_subsById[id] || []).forEach(function (x) { // (subtitle files of their own, matched to it)
783
832
  if (seen['file:' + x.rel]) { return; }
784
833
  seen['file:' + x.rel] = 1;
785
- out.push(subTrack(x.drive, x.rel, langOfName(x.rel), 'Your USB drive'));
834
+ out.push(subTrack(x.drive, x.rel, langOfName(x.rel), isNet(x.drive) ? 'Your network folder' : 'Your USB drive'));
786
835
  });
787
836
  return out;
788
837
  }
789
838
  // A local file's source again from its link (Continue Watching), on whichever drive has it now.
790
839
  function streamForUrl(url) {
791
840
  if (_recent.get(url)) { return _recent.get(url); }
841
+ var nf = typeof NetFolders !== 'undefined' ? NetFolders.folderOfUrl(url) : null;
842
+ if (nf) { // (a network folder's file: its index's size, where it has it)
843
+ var nd = NetFolders.driveOf(nf), nrel = NetFolders.relOf(nf, url), nx = _index[nd.root];
844
+ var nfile = (nx && nx.files.filter(function (y) { return y.p === nrel; })[0]) || { p: nrel, size: 0 };
845
+ return makeStream(nd, nfile);
846
+ }
792
847
  var abs = realPath(url), d = driveOf(abs);
793
848
  if (!/^\/opt\/media\//.test(abs)) { return null; }
794
849
  var rel = d ? abs.slice(d.root.length + 1) : abs.replace(/^\/opt\/media\/[^\/]+\//, '');
@@ -807,6 +862,7 @@ var LocalMedia = (function () {
807
862
  function subtitleExtra(localFile) {
808
863
  if (!localFile || !localFile.abs) { return Promise.resolve(null); }
809
864
  var base = { videoSize: localFile.size || undefined, filename: localFile.name };
865
+ if (localFile.dav) { return Promise.resolve(base); } // (a network folder's: no hash)
810
866
  if (!_hashes[localFile.abs]) {
811
867
  _hashes[localFile.abs] = within(askService('/fshash?path=' + encodeURIComponent(localFile.abs), 8000, 4096), 9000, 'hash').then(function (r) {
812
868
  return r && /^[0-9a-f]{16}$/.test(r.hash) ? r : null;
@@ -843,15 +899,25 @@ var LocalMedia = (function () {
843
899
  return m ? { size: +m[1], rel: m[2] } : { size: 0, rel: ('' + id).replace(/^local:/, '') }; // ('local:<path>': 1.9.0–1.9.2)
844
900
  }
845
901
  // fromStart: Play from start (Continue Watching), from 0:00.
902
+ // (a network folder's file: "@dav:<folder>/<path>" as its path, see resumePlain)
903
+ function plainRel(f) { return f.dav ? '@dav:' + f.dav + '/' + f.rel : f.rel; }
846
904
  function playPlain(st, onExit, id, fromStart) {
847
905
  var f = st._localFile;
848
- Player.play({ url: st.url, type: 'movie', id: id || plainId(f.rel, f.size), name: f.name, streams: [], localSubs: st._localSubs, localFile: f, fromStart: !!fromStart || undefined }, onExit || function () {});
906
+ Player.play({ url: st.url, type: 'movie', id: id || plainId(plainRel(f), f.size), name: f.name, streams: [], localSubs: st._localSubs, localFile: f, fromStart: !!fromStart || undefined }, onExit || function () {});
849
907
  }
850
908
  // A plain file's Continue Watching card: on whichever drive has that file (that path, that
851
909
  // size) now.
852
910
  function resumePlain(e, onExit, fromStart) {
853
- var want = parsePlainId(e.id), rel = want.rel;
911
+ var want = parsePlainId(e.id), rel = want.rel, dm = /^@dav:([a-z0-9]+)\/(.+)$/.exec(rel);
912
+ if (dm) { // a network folder's file
913
+ var nf = typeof NetFolders !== 'undefined' ? NetFolders.get(dm[1]) : null;
914
+ if (!nf) { U.toast('The network folder with “' + nameOf(dm[2]) + '” was removed', 4000); return Promise.resolve(false); }
915
+ if (nf.off) { U.toast('“' + nf.name + '” is off: Settings › Content › Network folders', 4000); return Promise.resolve(false); }
916
+ playPlain(makeStream(NetFolders.driveOf(nf), { p: dm[2], size: want.size }), onExit, e.id, fromStart);
917
+ return Promise.resolve(true);
918
+ }
854
919
  return ensure().then(function (ds) {
920
+ ds = ds.filter(function (x) { return !isNet(x); }); // (a USB drive's file)
855
921
  if (!ds.length) { U.toast('Plug in the USB drive with “' + nameOf(rel) + '”', 4000); return false; }
856
922
  var d = null, f = null;
857
923
  ds.forEach(function (x) {
@@ -877,8 +943,10 @@ var LocalMedia = (function () {
877
943
  return (entries || []).some(function (x) { return !x.dir && isVideo(x.name) && !matchOf(x.rel, x.size) && !!parsedOf(x.rel); });
878
944
  }
879
945
 
946
+ if (typeof NetFolders !== 'undefined') { NetFolders.onChange(netChanged); } // (netfolders.js loads first)
947
+
880
948
  return {
881
- available: available, ready: ready, watch: watch, present: present, ensure: ensure, isRead: isRead, onChange: onChange, drives: drives, knownDrives: knownDrives, hasDrive: hasDrive, refreshDrives: refreshDrives,
949
+ available: available, ready: ready, watch: watch, present: present, ensure: ensure, forgetDrive: forgetDrive, isNet: isNet, isFolderUrl: isFolderUrl, isRead: isRead, onChange: onChange, drives: drives, knownDrives: knownDrives, hasDrive: hasDrive, refreshDrives: refreshDrives,
882
950
  serviceToken: function () { return readToken(); }, askService: askService, addDownloaded: addDownloaded, openUrl: openUrl, list: list, isVideo: isVideo, isSub: isSub, isHidden: isHidden, showHidden: showHidden, setShowHidden: setShowHidden, humanSize: humanSize,
883
951
  parseName: parseName, choose: choose, matchOf: matchOf, lookup: lookup, matchFolder: matchFolder, parsedOf: parsedOf, setMatch: setMatch, forgetMatches: forgetMatches, searchTitles: searchTitles,
884
952
  scan: scan, stopScan: stopScan, continueMatching: continueMatching, status: status, clearIndex: clearIndex, streamsFor: streamsFor, subsForTitle: subsForTitle, isStandaloneSub: isStandaloneSub, streamForUrl: streamForUrl, isLocalStream: isLocalStream, subtitleExtra: subtitleExtra,
@@ -0,0 +1,157 @@
1
+ /* Network folders: folders a NAS or computer shares over WebDAV, in the Local tab beside USB
2
+ drives. Global namespace: NetFolders
3
+ - Kept here: each folder's address, user name, password and a certificate you trusted
4
+ (Settings › Content › Network folders). Nothing else knows the password: the service is
5
+ handed it with each request (a header, never in a link), and the player gets it in the
6
+ file's link only as it starts (playUrl).
7
+ - Listed through StremioK's service (/dav/list, /dav/walk, /dav/sub): no CORS rules to stop
8
+ it, and an https certificate the folder made itself can be trusted (that one only).
9
+ - As a USB drive otherwise (LocalMedia): a folder is a drive { label, root: 'dav:<id>', dav },
10
+ its files matched, indexed and offered as sources ("On your network folder"). */
11
+ var NetFolders = (function () {
12
+ 'use strict';
13
+
14
+ var KEY = 'stremiok.netfolders', MAX = 8;
15
+ var _listeners = [];
16
+ function onChange(fn) { _listeners.push(fn); }
17
+ function emit() { _listeners.slice().forEach(function (fn) { try { fn(); } catch (e) {} }); }
18
+
19
+ function valid(f) { return !!f && typeof f.id === 'string' && /^[a-z0-9]{4,16}$/.test(f.id) && typeof f.url === 'string' && /^https?:\/\/[^\s@]+\/$/i.test(f.url); }
20
+ function all() { return U.listOf(U.store.get(KEY, []), MAX, valid); }
21
+ function save(list) { U.store.set(KEY, list); emit(); }
22
+ function folders() { return all().filter(function (f) { return !f.off; }); }
23
+ function get(id) { return all().filter(function (f) { return f.id === id; })[0] || null; }
24
+ function driveOf(f) { return { label: f.name, root: 'dav:' + f.id, dav: f }; }
25
+ function drives() { return folders().map(driveOf); }
26
+
27
+ // A folder's address as kept: http(s), a real host, no user:password@, no ?query or #, ending
28
+ // in "/". addressProblem: why one typed can't be used, else null.
29
+ function addressProblem(v) {
30
+ var s = ('' + (v || '')).trim();
31
+ var p = U.urlProblem(s);
32
+ if (p) { return p; }
33
+ if (/[?#]/.test(s)) { return 'The folder’s address, without ? or #'; }
34
+ return null;
35
+ }
36
+ function baseOf(v) { return ('' + v).trim().replace(/\/*$/, '/'); }
37
+ // A name to show: its last folder, and its server ("media on 192.168.0.50").
38
+ function nameOf(url) {
39
+ var m = /^https?:\/\/([^\/:]+)(?::\d+)?(\/.*)?$/i.exec(url) || [], segs = (m[2] || '/').split('/').filter(Boolean), last = segs.length ? segs[segs.length - 1] : '';
40
+ try { last = decodeURIComponent(last); } catch (e) {}
41
+ return (last ? last + ' on ' : '') + (m[1] || url);
42
+ }
43
+
44
+ // ---- through StremioK's service ----
45
+ function b64(s) { return btoa(unescape(encodeURIComponent(s))); }
46
+ function headers(f) {
47
+ var h = {};
48
+ if (f.user || f.pass) { h['X-Dav-Auth'] = b64((f.user || '') + ':' + (f.pass || '')); }
49
+ if (f.cert) { h['X-Dav-Cert'] = f.cert; }
50
+ return h;
51
+ }
52
+ function query(f, rel) { return '?u=' + encodeURIComponent(f.url) + (rel != null ? '&p=' + encodeURIComponent(rel) : ''); }
53
+ var WHY = {
54
+ auth: 'It refused the user name or password',
55
+ untrusted: 'Its certificate isn’t from a known authority',
56
+ unreachable: 'Couldn’t reach it',
57
+ notdav: 'Not a WebDAV folder',
58
+ missing: 'No such folder there',
59
+ elsewhere: 'It sent StremioK to another address (not followed)',
60
+ toolarge: 'Its answer was too large',
61
+ busy: 'Another folder is being indexed: try again when it’s done'
62
+ };
63
+ // The service's answer, or what went wrong: an Error with why (and, untrusted, the
64
+ // certificate: cert, fp, name, until).
65
+ function ask(f, path, rel, timeout, max, cancel) {
66
+ if (typeof LocalMedia === 'undefined' || !LocalMedia.askService) { return Promise.reject(new Error('no StremioK service here')); }
67
+ return LocalMedia.askService('/dav/' + path + query(f, rel), timeout, max, cancel, headers(f)).then(function (r) {
68
+ if (!r || typeof r !== 'object') { throw new Error('No answer from StremioK’s service'); }
69
+ if (r.why) {
70
+ var e = new Error((WHY[r.why] || 'It failed') + (r.message && r.why !== 'auth' && r.why !== 'busy' ? ' (' + r.message + ')' : ''));
71
+ e.why = r.why;
72
+ if (r.why === 'untrusted' && typeof r.cert === 'string') { e.cert = r.cert; e.fp = '' + (r.fp || ''); e.name = '' + (r.name || ''); e.until = '' + (r.until || ''); }
73
+ throw e;
74
+ }
75
+ return r;
76
+ });
77
+ }
78
+ // A file's link (its identity: a source's, Continue Watching's), without the sign-in.
79
+ function fileUrl(f, rel) { return f.url + ('' + rel).split('/').map(encodeURIComponent).join('/'); }
80
+ function entryOf(f, rel, x) {
81
+ var name = '' + x.name, r = rel ? rel + '/' + name : name;
82
+ return { name: name, dir: !!x.dir, size: +x.size || 0, rel: r, abs: fileUrl(f, r), uri: fileUrl(f, r) };
83
+ }
84
+ // A folder's listing, as LocalMedia.list gives a drive's: { entries }.
85
+ function list(f, rel) {
86
+ rel = ('' + (rel || '')).replace(/^\/+|\/+$/g, '');
87
+ return ask(f, 'list', rel, 30000, 4 * 1048576).then(function (r) {
88
+ return { entries: U.listOf(r.entries, 3000, function (x) { return x && typeof x.name === 'string' && x.name && x.name.indexOf('/') === -1; }).map(function (x) { return entryOf(f, rel, x); }) };
89
+ });
90
+ }
91
+ // Every video and subtitle file under it (the index): { files: [{ p, size }], truncated }.
92
+ function walk(f, cancel) {
93
+ return ask(f, 'walk', null, 150000, 8 * 1048576, cancel).then(function (r) {
94
+ return { files: U.listOf(r.files, 20000, function (x) { return x && typeof x.p === 'string'; }), truncated: !!r.truncated };
95
+ });
96
+ }
97
+ function subPath(f, rel) { return '/dav/sub' + query(f, rel); }
98
+
99
+ // ---- links ----
100
+ // The folder a link is in (its address a prefix of the link), or null.
101
+ function folderOfUrl(url) {
102
+ url = '' + (url || '');
103
+ var l = all();
104
+ for (var i = 0; i < l.length; i++) { if (url.indexOf(l[i].url) === 0 && url.length > l[i].url.length) { return l[i]; } }
105
+ return null;
106
+ }
107
+ function relOf(f, url) {
108
+ return ('' + url).slice(f.url.length).split('/').map(function (s) { try { return decodeURIComponent(s); } catch (e) { return s; } }).join('/');
109
+ }
110
+ // The link the player opens: the file's, with the folder's user name and password in it
111
+ // (http://user:password@host/…, which the TV's player sends as its sign-in). Not a folder's
112
+ // file: null.
113
+ function playUrl(url) {
114
+ var f = folderOfUrl(url);
115
+ if (!f) { return null; }
116
+ if (!f.user && !f.pass) { return '' + url; }
117
+ return ('' + url).replace(/^(https?:\/\/)/i, '$1' + encodeURIComponent(f.user || '') + ':' + encodeURIComponent(f.pass || '') + '@');
118
+ }
119
+
120
+ // ---- adding, on and off ----
121
+ function newId() { var s = ''; while (s.length < 8) { s += Math.floor(Math.random() * 36).toString(36); } return s; }
122
+ // Ask the folder (its top's listing) with this sign-in: resolves the folder to keep, or
123
+ // rejects as ask does (untrusted: the certificate to ask about, then probe again with it).
124
+ function probe(url, user, pass, cert) {
125
+ var f = { id: 'probe', url: baseOf(url), user: '' + (user || ''), pass: '' + (pass || ''), cert: cert || '' };
126
+ return list(f, '').then(function (r) { return { url: f.url, user: f.user, pass: f.pass, cert: f.cert, name: nameOf(f.url), entries: r.entries.length }; });
127
+ }
128
+ // Keep a folder probe() found (the same address again: replaced).
129
+ function add(p) {
130
+ var l = all().filter(function (f) { return f.url !== p.url; });
131
+ if (l.length >= MAX) { throw new Error('Up to ' + MAX + ' network folders'); }
132
+ var f = { id: newId(), name: p.name || nameOf(p.url), url: p.url, user: p.user || '', pass: p.pass || '', cert: p.cert || '', at: Date.now() };
133
+ l.push(f);
134
+ save(l);
135
+ U.log('local', 'Network folder “' + f.name + '” added' + (f.cert ? ' (its certificate trusted)' : ''));
136
+ return f;
137
+ }
138
+ function setOn(id, on) {
139
+ save(all().map(function (f) {
140
+ if (f.id !== id) { return f; }
141
+ var g = Object.assign({}, f);
142
+ if (on) { delete g.off; } else { g.off = true; }
143
+ return g;
144
+ }));
145
+ }
146
+ function remove(id) {
147
+ var f = get(id);
148
+ save(all().filter(function (x) { return x.id !== id; }));
149
+ if (f && typeof LocalMedia !== 'undefined' && LocalMedia.forgetDrive) { LocalMedia.forgetDrive('dav:' + id); }
150
+ }
151
+
152
+ return {
153
+ all: all, folders: folders, get: get, drives: drives, driveOf: driveOf, onChange: onChange,
154
+ addressProblem: addressProblem, nameOf: nameOf, probe: probe, add: add, setOn: setOn, remove: remove,
155
+ list: list, walk: walk, headers: headers, subPath: subPath, fileUrl: fileUrl, folderOfUrl: folderOfUrl, relOf: relOf, playUrl: playUrl
156
+ };
157
+ })();
@@ -303,6 +303,15 @@
303
303
  } catch (e) { return '(unreadable: ' + trackError(e) + ')'; }
304
304
  }
305
305
 
306
+ // No TV player (TizenBrew: the TV gives it only to installed apps; a desktop browser): the
307
+ // page's <video> plays a file's first audio track whatever is chosen (the TV's engine ignores
308
+ // its audioTracks; checked on the Tizen 6 TV, issue 17), so the menu says so instead.
309
+ function cantSwitch() { return !avplay; }
310
+ function cantSwitchText() {
311
+ return (typeof YTPlay !== 'undefined' && YTPlay.installMode && YTPlay.installMode() === 'tizenbrew')
312
+ ? 'Under TizenBrew only a file’s first audio track plays: the TV gives its own player only to installed apps. The sideloaded app can switch.'
313
+ : 'Here only a file’s first audio track plays (no TV player).';
314
+ }
306
315
  // Tracks sorted by language (preferred languages first) and named in full, so the
307
316
  // same language's tracks sit together.
308
317
  function audioMenu() {
@@ -314,12 +323,13 @@
314
323
  var na = langName(a.k), nb = langName(b.k);
315
324
  return na !== nb ? (na < nb ? -1 : 1) : a.n - b.n;
316
325
  });
317
- var idx = 0;
326
+ var idx = 0, stuck = cantSwitch() && tracks.length > 1;
318
327
  var items = tracks.map(function (x, i) {
319
328
  var tr = x.tr;
320
329
  if (tr.index === _audioIdx) { idx = i; }
321
330
  return { label: audioMenuLabel(tr, x.n), sel: (tr.index === _audioIdx),
322
331
  run: function () {
332
+ if (stuck) { closeMenu(); U.toast(cantSwitchText(), 6000); return; }
323
333
  // re-picking the checked track re-applies it (see selectAudio)
324
334
  selectAudio(tr.index, 'Audio: ' + audioLabel(tr, x.n), tr.index === _audioIdx);
325
335
  var info = trackInfo(tr);
@@ -329,6 +339,20 @@
329
339
  closeMenu();
330
340
  } };
331
341
  });
342
+ // A live channel: its sound straight from the server, or repacked by StremioK's service
343
+ // (player-core's setLiveSound), after its tracks.
344
+ var ls = P.liveSound ? P.liveSound() : null;
345
+ if (ls) {
346
+ [[false, 'Sound: straight from the server'], [true, 'Sound: repacked by StremioK’s service']].forEach(function (o) {
347
+ var on = o[0] === ls.repacked;
348
+ items.push({ label: o[1], sel: on, detail: on && ls.mine ? 'your choice' : '', run: function () {
349
+ closeMenu();
350
+ if (on) { U.toast(o[1].replace('Sound: ', 'Already ') + '', 2500); return; }
351
+ P.setLiveSound(o[0]);
352
+ } });
353
+ });
354
+ }
355
+ if (stuck) { return { title: 'Audio track', items: items, idx: idx, wide: true, node: U.el('div', 'sm-detail', cantSwitchText()) }; }
332
356
  return { title: 'Audio track', items: items, idx: idx };
333
357
  }
334
358
 
@@ -645,7 +645,7 @@
645
645
  // Order per spec: Subtitles, Audio Track, Select Source, Playback
646
646
  var items = [];
647
647
  items.push({ label: 'Subtitles', run: function () { pushMenu(subConfigMenu()); } });
648
- if (getAudioTracks().length > 1) {
648
+ if (getAudioTracks().length > 1 || (P.liveSound && P.liveSound())) { // (a live channel: its sound's choice too)
649
649
  items.push({ label: 'Audio track', run: function () { pushMenu(audioMenu()); } });
650
650
  }
651
651
  if (hasYtLanguages()) { // (a YouTube video with dubs: each is a stream of its own)
@@ -851,6 +851,7 @@
851
851
  var c = S.ctx;
852
852
  if (c.yt) { return 'Through YouTube’s service (on the TV)'; }
853
853
  if (c._relay) { return 'Through StremioK’s service: the sound repacked'; }
854
+ if (c.localFile && c.localFile.dav) { return 'From your network folder'; }
854
855
  if (c.localFile) { return /^http:\/\/localhost/.test(typeof LocalMedia !== 'undefined' && LocalMedia.openUrl ? LocalMedia.openUrl(c.url, c.localFile.size) : '') ? 'From the USB drive, through StremioK’s service (over 2 GB)' : 'From the USB drive'; }
855
856
  return 'Straight from the server';
856
857
  }
@@ -932,7 +933,7 @@
932
933
  if (_menuOpen && _menuStack[0] && _menuStack[0].color === key) { closeMenu(); return; }
933
934
  var m = null;
934
935
  if (key === 'RED') {
935
- if (getAudioTracks().length > 1) { m = audioMenu(); }
936
+ if (getAudioTracks().length > 1 || (P.liveSound && P.liveSound())) { m = audioMenu(); }
936
937
  else if (hasYtLanguages()) { m = ytLanguageMenu(); }
937
938
  else { U.toast('Only one audio track', 1800); return; }
938
939
  } else if (key === 'GREEN') {