stremiok 2.3.3 → 2.3.5

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.
Files changed (57) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +6 -5
  3. package/config.xml +1 -1
  4. package/css/style.css +5 -0
  5. package/index.html +42 -39
  6. package/js/app.js +7 -3
  7. package/js/downloads.js +16 -16
  8. package/js/epg.js +2 -3
  9. package/js/hubpreview.js +1 -1
  10. package/js/i18n.js +108 -0
  11. package/js/iptv.js +13 -13
  12. package/js/jellyfin.js +62 -29
  13. package/js/lang/ar.js +1941 -0
  14. package/js/lang/de.js +1941 -0
  15. package/js/lang/es.js +1941 -0
  16. package/js/lang/fi.js +1941 -0
  17. package/js/lang/fr.js +1941 -0
  18. package/js/lang/he.js +1941 -0
  19. package/js/lang/hi.js +1941 -0
  20. package/js/lang/it.js +1941 -0
  21. package/js/lang/ja.js +1941 -0
  22. package/js/lang/ko.js +1941 -0
  23. package/js/lang/languages.js +21 -0
  24. package/js/lang/pl.js +1941 -0
  25. package/js/lang/pt-BR.js +1941 -0
  26. package/js/lang/ru.js +1941 -0
  27. package/js/lang/tr.js +1941 -0
  28. package/js/lang/zh-CN.js +1941 -0
  29. package/js/local.js +9 -9
  30. package/js/netfolders.js +13 -13
  31. package/js/player-audio.js +17 -17
  32. package/js/player-controls.js +100 -100
  33. package/js/player-core.js +60 -57
  34. package/js/player-lang.js +22 -22
  35. package/js/player-quality.js +15 -15
  36. package/js/player-store.js +25 -18
  37. package/js/player-subs.js +69 -69
  38. package/js/plex.js +69 -21
  39. package/js/stremio-account.js +17 -12
  40. package/js/stremio-sync.js +641 -0
  41. package/js/stremio.js +79 -76
  42. package/js/stvod.js +4 -4
  43. package/js/trakt.js +23 -23
  44. package/js/tvapps.js +4 -4
  45. package/js/util.js +39 -27
  46. package/js/view-core.js +109 -92
  47. package/js/view-detail.js +135 -126
  48. package/js/view-discover.js +27 -27
  49. package/js/view-guide.js +13 -13
  50. package/js/view-home.js +148 -120
  51. package/js/view-search.js +25 -25
  52. package/js/view-settings.js +735 -643
  53. package/js/xtvod.js +2 -2
  54. package/js/youtube.js +17 -17
  55. package/js/ytplay.js +11 -6
  56. package/package.json +1 -1
  57. package/tizenbrew.html +1 -1
@@ -0,0 +1,641 @@
1
+ /* Your Stremio account kept in step with StremioK (Settings › Content › Integrations › Stremio
2
+ account): its Continue Watching, watched marks and Library, both ways. Signing in is the
3
+ import's (js/stremio-account.js: a code approved on your phone); here the sign-in key is kept.
4
+
5
+ Stremio keeps one record a title (a "library item", as its own apps keep it: stremio-core):
6
+ where you stopped (one episode a show), how often it's been watched, the episodes watched (a
7
+ packed list of bits in the show's episode order), and whether it's in your Library or was only
8
+ watched. Each has the time it last changed: the newest wins, both ways, as Stremio's own apps
9
+ sync (datastoreMeta: every record's time; datastoreGet the ones newer there; datastorePut the
10
+ ones newer here). What you do here changes the copy kept on the TV at once (its time now), and
11
+ is sent a few seconds later (where you stopped while playing: at most every 3 minutes, as
12
+ Stremio's player does); anything not sent goes with the next sync (launch, every 15 minutes).
13
+
14
+ Only films and series are kept, and only titles with an addon's id (IMDb, TMDB, Kitsu…): never
15
+ a USB file, a media server's own item, YouTube or a channel. A show's watched episodes are read
16
+ with its details (its episodes in Stremio's order); written only where the list read here
17
+ matches the one in the account (its last watched episode found in it), never over it.
18
+ Global namespace: StremioSync */
19
+ var StremioSync = (function () {
20
+ 'use strict';
21
+
22
+ var KEY = 'stremiok.stremio'; // { key, user, at }: the sign-in (not in a configuration export)
23
+ var STATE_KEY = 'stremiok.stremio.sync'; // { last, reconnect, err, fails }
24
+ var DATA_KEY = 'stremiok.stremio.items'; // (the TV's database) { items: { id: record }, rm: { id: its time in the account, ms }, eps: { id: { m, v: [video ids] } }, marks: { id: { videoId: 1 | 0 } } }
25
+ var COLLECTION = 'libraryItem';
26
+ var ITEMS_MAX = 4000, GET_CHUNK = 100, PUT_CHUNK = 50, META_MAX = 4 * 1048576, GET_MAX = 4 * 1048576;
27
+ var SEND_MS = 5000, PLAYING_EVERY_MS = 180000, EVERY_MS = 15 * 60 * 1000, EPS_PER_SYNC = 30;
28
+ var ID_OK = /^(tt\d{1,12}|(tmdb|tvdb|kitsu|mal|anilist|anidb|imdb):[\w.-]{1,40})(:\d{1,5}:\d{1,6})?$/;
29
+
30
+ // ---------- the sign-in ----------
31
+ function auth() { var a = U.store.get(KEY, null); return (a && typeof a.key === 'string' && a.key) ? a : null; }
32
+ function isConnected() { return !!auth(); }
33
+ function authKey() { var a = auth(); return a ? a.key : ''; }
34
+ function state() { var s = U.store.get(STATE_KEY, null); return (s && typeof s === 'object') ? s : {}; }
35
+ function setState(patch) { var s = state(); Object.keys(patch).forEach(function (k) { s[k] = patch[k]; }); U.store.set(STATE_KEY, s); }
36
+ var _gen = 0; // (disconnecting starts a new one: work under way for the old one changes nothing)
37
+
38
+ // Signed in (the key from StremioAccount.wait): the account's email, then a first sync.
39
+ function connect(key) {
40
+ var g = ++_gen;
41
+ return StremioAccount.call('getUser', { type: 'GetUser', authKey: key }).then(function (r) { return r; }, function () { return null; }).then(function (u) {
42
+ if (g !== _gen) { return ''; }
43
+ var user = (u && typeof u.email === 'string') ? U.drawable(u.email).slice(0, 120) : '';
44
+ return _ready.then(function () {
45
+ if (g !== _gen) { return ''; }
46
+ U.store.set(KEY, { key: key, user: user, at: Date.now() });
47
+ U.store.remove(STATE_KEY);
48
+ _data = blank(); dirty(); save();
49
+ sync();
50
+ return user;
51
+ });
52
+ });
53
+ }
54
+ function disconnect() {
55
+ _gen++;
56
+ var k = authKey();
57
+ if (k) { StremioAccount.signOut(k); }
58
+ U.store.remove(KEY); U.store.remove(STATE_KEY);
59
+ if (_timer) { clearTimeout(_timer); _timer = null; }
60
+ if (_every) { clearInterval(_every); _every = null; }
61
+ _syncing = null; _data = blank();
62
+ if (U.bigStore) { U.bigStore.remove(DATA_KEY); } else { U.store.remove(DATA_KEY); }
63
+ changed();
64
+ }
65
+ // A key Stremio no longer takes: nothing more sent until you connect again.
66
+ var _told = false;
67
+ function lostSignIn() {
68
+ if (!isConnected()) { return; }
69
+ setState({ reconnect: true });
70
+ if (!_told) { _told = true; U.toast(U.t('Your Stremio account needs connecting again: Settings › Content › Integrations'), 6000); U.log('stremio', 'Stremio sign-in no longer works: connect again in Settings'); }
71
+ }
72
+ function connectStatus() {
73
+ var a = auth() || {}, s = state();
74
+ return { connected: !!a.key, user: a.user || '', reconnect: !!s.reconnect, lastSync: s.last || 0, pending: pending().length, err: s.err || '' };
75
+ }
76
+
77
+ // ---------- the copy kept on the TV ----------
78
+ function blank() { return { items: {}, rm: {}, eps: {}, marks: {} }; }
79
+ var _data = blank(), _loaded = false;
80
+ var _ready = (U.bigStore ? U.bigStore.get(DATA_KEY) : Promise.resolve(U.store.get(DATA_KEY, null, true))).then(function (d) {
81
+ if (!d || typeof d !== 'object') { d = U.store.get(DATA_KEY, null, true); }
82
+ if (isConnected() && d && typeof d === 'object' && d.items && typeof d.items === 'object') {
83
+ ['rm', 'eps', 'marks'].forEach(function (k) { if (!d[k] || typeof d[k] !== 'object') { d[k] = {}; } });
84
+ _data = d;
85
+ }
86
+ _loaded = true;
87
+ }, function () { _loaded = true; });
88
+ var _saveTimer = null;
89
+ function save() {
90
+ if (_saveTimer) { return; }
91
+ _saveTimer = setTimeout(function () {
92
+ _saveTimer = null;
93
+ if (!isConnected()) { return; }
94
+ if (!U.bigStore) { U.store.set(DATA_KEY, _data); return; }
95
+ U.bigStore.set(DATA_KEY, _data).then(function (ok) {
96
+ if (ok) { return; }
97
+ U.bigStore.remove(DATA_KEY, true);
98
+ if (U.store.set(DATA_KEY, _data)) { U.log('storage', 'Your Stremio library is kept in the settings storage instead'); }
99
+ });
100
+ }, 1000);
101
+ }
102
+ function changed() {
103
+ if (typeof Stremio !== 'undefined' && Stremio.addonsChanged) { Stremio.addonsChanged(); }
104
+ if (typeof ViewParts !== 'undefined' && ViewParts.refreshAddonRows) { ViewParts.refreshAddonRows('local:stremio'); }
105
+ }
106
+
107
+ // ---------- reading what Stremio sends ----------
108
+ function iso(ms) { return new Date(ms).toISOString(); }
109
+ function ms(x) { var t = typeof x === 'number' ? x : Date.parse(typeof x === 'string' ? x : ''); return t > 0 ? t : 0; }
110
+ function sec(t) { return Math.floor((t || 0) / 1000); }
111
+ function n(x) { return (typeof x === 'number' && isFinite(x) && x >= 0) ? Math.floor(x) : 0; }
112
+ // A record worth keeping: a film or series with an id and a time; its state's numbers checked.
113
+ function usable(it) {
114
+ if (!it || typeof it !== 'object' || typeof it._id !== 'string' || it._id.length > 200 || (it.type !== 'movie' && it.type !== 'series') || !ms(it._mtime)) { return false; }
115
+ if (!it.state || typeof it.state !== 'object') { it.state = {}; }
116
+ var s = it.state;
117
+ ['timeOffset', 'timeWatched', 'overallTimeWatched', 'timesWatched', 'flaggedWatched', 'duration'].forEach(function (k) { s[k] = n(s[k]); });
118
+ if (typeof s.video_id !== 'string' || s.video_id.length > 300) { s.video_id = null; }
119
+ if (typeof s.watched !== 'string' || s.watched.length > 20000) { s.watched = null; }
120
+ it.removed = it.removed === true; it.temp = it.temp === true;
121
+ return true;
122
+ }
123
+ function mtime(it) { return ms(it && it._mtime); }
124
+ function nameOf(it) { return U.drawable('' + (it.name || '')).slice(0, 200); }
125
+ function posterOf(it) {
126
+ var p = typeof it.poster === 'string' ? it.poster : '';
127
+ return /^https?:\/\//.test(p) ? p : (/^tt\d+$/.test(it._id) ? 'https://images.metahub.space/poster/small/' + it._id + '/img' : '');
128
+ }
129
+
130
+ // ---------- Stremio's watched episodes: a packed list of bits ----------
131
+ // "{last watched video id}:{its place + 1}:{base64 of the zlib-packed bytes}", bit i (low bit
132
+ // first) for the i-th video in the show's order: season, then episode, then release date.
133
+ function videoOrder(meta) {
134
+ var vids = ((meta && meta.videos) || []).filter(function (v) { return v && typeof v.id === 'string'; }).map(function (v, i) {
135
+ var s = typeof v.season === 'number' ? v.season : -Infinity, e = typeof v.episode === 'number' ? v.episode : (typeof v.number === 'number' ? v.number : -Infinity);
136
+ return { id: v.id, s: s, e: e, r: ms(v.released) || -Infinity, i: i, released: v.released };
137
+ });
138
+ vids.sort(function (a, b) { return (a.s - b.s) || (a.e - b.e) || ((a.r === b.r) ? 0 : (a.r < b.r ? -1 : 1)) || (a.i - b.i); }); // (the place in the list last: a stable order)
139
+ return vids;
140
+ }
141
+ // The bits as the account has them, laid on this list of videos (moved by where the last
142
+ // watched one is now); null: that one isn't in the list (a different list: not ours to read).
143
+ function readBits(field, ids) {
144
+ var bits = [], i;
145
+ for (i = 0; i < ids.length; i++) { bits.push(false); }
146
+ if (!field) { return bits; }
147
+ var parts = ('' + field).split(':');
148
+ if (parts.length < 3) { return null; }
149
+ var packed = parts.pop(), len = parseInt(parts.pop(), 10), anchor = parts.join(':'), bytes = unpack(packed);
150
+ if (!bytes || isNaN(len)) { return null; }
151
+ var at = ids.indexOf(anchor);
152
+ if (at === -1) { return anchor === 'undefined' ? bits : null; }
153
+ var offset = len - at - 1;
154
+ for (i = 0; i < ids.length; i++) {
155
+ var j = i + offset;
156
+ if (j >= 0 && j < bytes.length * 8) { bits[i] = ((bytes[j >> 3] >> (j & 7)) & 1) === 1; }
157
+ }
158
+ return bits;
159
+ }
160
+ function writeBits(bits, ids) {
161
+ var bytes = [], last = -1, i;
162
+ for (i = 0; i < Math.ceil(ids.length / 8); i++) { bytes.push(0); }
163
+ for (i = 0; i < bits.length; i++) { if (bits[i]) { bytes[i >> 3] |= 1 << (i & 7); last = i; } }
164
+ return (last >= 0 ? ids[last] : (ids.length ? ids[0] : 'undefined')) + ':' + (Math.max(last, 0) + 1) + ':' + pack(bytes);
165
+ }
166
+ function pack(bytes) { // (zlib, stored as is: tiny, and any zlib reader takes it)
167
+ var out = [0x78, 0x01], a = 1, b = 0, i, at = 0;
168
+ do {
169
+ var len = Math.min(65535, bytes.length - at), last = at + len >= bytes.length;
170
+ out.push(last ? 1 : 0, len & 255, len >> 8, ~len & 255, (~len >> 8) & 255);
171
+ for (i = at; i < at + len; i++) { out.push(bytes[i]); }
172
+ at += len;
173
+ } while (at < bytes.length);
174
+ for (i = 0; i < bytes.length; i++) { a = (a + bytes[i]) % 65521; b = (b + a) % 65521; }
175
+ out.push((b >> 8) & 255, b & 255, (a >> 8) & 255, a & 255);
176
+ var s = '';
177
+ for (i = 0; i < out.length; i++) { s += String.fromCharCode(out[i]); }
178
+ return btoa(s);
179
+ }
180
+ function unpack(b64) {
181
+ var s;
182
+ try { s = atob(b64); } catch (e) { return null; }
183
+ var bytes = [];
184
+ for (var i = 0; i < s.length; i++) { bytes.push(s.charCodeAt(i) & 255); }
185
+ try { return inflate(bytes); } catch (e2) { return null; }
186
+ }
187
+ // zlib's inflate (stored, fixed and dynamic blocks), for these few bytes: at most OUT_MAX out.
188
+ var OUT_MAX = 65536;
189
+ var LBASE = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258];
190
+ var LEXT = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0];
191
+ var DBASE = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577];
192
+ var DEXT = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13];
193
+ var CLORDER = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
194
+ function inflate(src) {
195
+ if (src.length < 6 || (src[0] & 15) !== 8 || ((src[0] << 8) | src[1]) % 31 || (src[1] & 32)) { throw new Error('not zlib'); }
196
+ var pos = 2, bit = 0, out = [];
197
+ function bits(k) {
198
+ var v = 0;
199
+ for (var i = 0; i < k; i++) {
200
+ if (pos >= src.length) { throw new Error('short'); }
201
+ v |= ((src[pos] >> bit) & 1) << i;
202
+ if (++bit === 8) { bit = 0; pos++; }
203
+ }
204
+ return v;
205
+ }
206
+ function table(lengths) {
207
+ var count = [], offs = [0, 0], sym = [], i;
208
+ for (i = 0; i <= 15; i++) { count[i] = 0; }
209
+ for (i = 0; i < lengths.length; i++) { count[lengths[i]]++; }
210
+ count[0] = 0;
211
+ for (i = 1; i < 15; i++) { offs[i + 1] = offs[i] + count[i]; }
212
+ for (i = 0; i < lengths.length; i++) { if (lengths[i]) { sym[offs[lengths[i]]++] = i; } }
213
+ return { count: count, sym: sym };
214
+ }
215
+ function decode(h) {
216
+ var code = 0, first = 0, index = 0;
217
+ for (var len = 1; len <= 15; len++) {
218
+ code |= bits(1);
219
+ var c = h.count[len];
220
+ if (code - c < first) { return h.sym[index + (code - first)]; }
221
+ index += c; first += c; first <<= 1; code <<= 1;
222
+ }
223
+ throw new Error('bad code');
224
+ }
225
+ function put(x) { if (out.length >= OUT_MAX) { throw new Error('too long'); } out.push(x); }
226
+ function codes(lit, dist) {
227
+ for (;;) {
228
+ var s = decode(lit);
229
+ if (s < 256) { put(s); continue; }
230
+ if (s === 256) { return; }
231
+ s -= 257;
232
+ if (s >= 29) { throw new Error('bad length'); }
233
+ var len = LBASE[s] + bits(LEXT[s]), d = decode(dist);
234
+ if (d >= 30) { throw new Error('bad distance'); }
235
+ var back = DBASE[d] + bits(DEXT[d]);
236
+ if (back > out.length) { throw new Error('too far'); }
237
+ for (var k = 0; k < len; k++) { put(out[out.length - back]); }
238
+ }
239
+ }
240
+ var fixedLit = null, fixedDist = null, last;
241
+ do {
242
+ last = bits(1);
243
+ var type = bits(2), i;
244
+ if (type === 0) {
245
+ if (bit) { bit = 0; pos++; }
246
+ if (pos + 4 > src.length) { throw new Error('short'); }
247
+ var len = src[pos] | (src[pos + 1] << 8), nlen = src[pos + 2] | (src[pos + 3] << 8);
248
+ if ((len ^ 0xffff) !== nlen || pos + 4 + len > src.length) { throw new Error('bad stored'); }
249
+ for (i = 0; i < len; i++) { put(src[pos + 4 + i]); }
250
+ pos += 4 + len;
251
+ } else if (type === 1) {
252
+ if (!fixedLit) {
253
+ var l = [];
254
+ for (i = 0; i < 288; i++) { l.push(i < 144 ? 8 : i < 256 ? 9 : i < 280 ? 7 : 8); }
255
+ fixedLit = table(l);
256
+ var dl = [];
257
+ for (i = 0; i < 30; i++) { dl.push(5); }
258
+ fixedDist = table(dl);
259
+ }
260
+ codes(fixedLit, fixedDist);
261
+ } else if (type === 2) {
262
+ var nlit = bits(5) + 257, ndist = bits(5) + 1, ncode = bits(4) + 4, cl = [], lens = [];
263
+ for (i = 0; i < 19; i++) { cl.push(0); }
264
+ for (i = 0; i < ncode; i++) { cl[CLORDER[i]] = bits(3); }
265
+ var clt = table(cl);
266
+ while (lens.length < nlit + ndist) {
267
+ var sym = decode(clt), rep = 0, val = 0;
268
+ if (sym < 16) { lens.push(sym); continue; }
269
+ if (sym === 16) { if (!lens.length) { throw new Error('bad repeat'); } val = lens[lens.length - 1]; rep = 3 + bits(2); }
270
+ else if (sym === 17) { rep = 3 + bits(3); }
271
+ else { rep = 11 + bits(7); }
272
+ if (lens.length + rep > nlit + ndist) { throw new Error('too many lengths'); }
273
+ while (rep--) { lens.push(val); }
274
+ }
275
+ codes(table(lens.slice(0, nlit)), table(lens.slice(nlit)));
276
+ } else { throw new Error('bad block'); }
277
+ } while (!last);
278
+ return out;
279
+ }
280
+
281
+ // ---------- what StremioK reads from it ----------
282
+ function idOk(id) { return ID_OK.test('' + id); }
283
+ function showOf(type, id) { return type === 'series' ? ('' + id).replace(/:\d+:\d+$/, '') : '' + id; }
284
+ function item(type, id) { var it = _data.items[showOf(type, id)]; return (it && it.type === type) ? it : null; }
285
+ function seOf(vid) { var p = /:(\d+):(\d+)$/.exec('' + vid); return p ? [+p[1], +p[2]] : null; }
286
+ function further(a, b) { var x = seOf(a), y = seOf(b); return !!(x && y && (x[0] > y[0] || (x[0] === y[0] && x[1] > y[1]))); }
287
+ // When the account has it watched (ms), 0: not watched (or not known).
288
+ var _watchedIdx = null;
289
+ function watchedIdx() {
290
+ if (_watchedIdx) { return _watchedIdx; }
291
+ var m = {};
292
+ Object.keys(_data.items).forEach(function (id) {
293
+ var it = _data.items[id], at = ms(it.state.lastWatched) || mtime(it);
294
+ if (it.type === 'movie' && (it.state.timesWatched > 0 || it.state.flaggedWatched > 0)) { m['movie:' + id] = at; }
295
+ var e = _data.eps[id];
296
+ if (it.type === 'series' && e) { (e.v || []).forEach(function (v) { m['series:' + v] = at; }); } // (an older read until it's read again)
297
+ });
298
+ _watchedIdx = m;
299
+ return m;
300
+ }
301
+ function dirty() { _watchedIdx = null; }
302
+ function watchedAt(type, id) { return isConnected() ? (watchedIdx()[type + ':' + id] || 0) : 0; }
303
+ // Continue Watching as the account has it: what's been started (or queued: an episode at the
304
+ // start), a show at its episode. Records it calls removed only once watched (as Stremio's do).
305
+ function continueList() {
306
+ if (!isConnected()) { return []; }
307
+ var out = [];
308
+ Object.keys(_data.items).forEach(function (id) {
309
+ var it = _data.items[id], s = it.state;
310
+ if ((it.removed && !it.temp) || !s.timeOffset || !idOk(id)) { return; }
311
+ var vid = it.type === 'series' ? s.video_id : id;
312
+ if (it.type === 'series' && (!vid || !seOf(vid))) { return; }
313
+ var se = seOf(vid);
314
+ out.push({ id: vid, type: it.type, parent: id, name: nameOf(it) + (it.type === 'series' ? ' S' + se[0] + 'E' + se[1] : ''), poster: posterOf(it),
315
+ position: s.timeOffset > 1000 ? Math.floor(s.timeOffset / 1000) : 0, duration: Math.floor(s.duration / 1000), updated: ms(s.lastWatched) || mtime(it), _stremio: true });
316
+ });
317
+ return out;
318
+ }
319
+ // A place kept on this TV that the account has you past since: a film watched since, a show
320
+ // moved on to a later episode (or this one watched).
321
+ function watchedPast(e) {
322
+ if (!isConnected() || !e || !e.updated) { return false; }
323
+ var it = item(e.type, e.parent || e.id);
324
+ if (!it || (ms(it.state.lastWatched) || mtime(it)) <= e.updated) { return false; }
325
+ if (e.type === 'movie') { return it.state.timesWatched > 0 && !it.state.timeOffset; }
326
+ return further(it.state.video_id, e.id) || watchedAt('series', e.id) > e.updated;
327
+ }
328
+ function inLibrary(type, id) { var it = item(type, id); return !!(it && !it.removed && !it.temp); }
329
+ // The Library as Home rows (Movies, Series) and in Discover: the latest added first.
330
+ function synthCatalog(catId, extra) {
331
+ var type = catId === 'stremio_library_movies' ? 'movie' : 'series', skip = (extra && +extra.skip) || 0;
332
+ return _ready.then(function () {
333
+ var list = Object.keys(_data.items).map(function (id) { return _data.items[id]; }).filter(function (it) { return it.type === type && !it.removed && !it.temp && idOk(it._id); });
334
+ list.sort(function (a, b) { return (ms(b._ctime) || mtime(b)) - (ms(a._ctime) || mtime(a)); });
335
+ return list.slice(skip, skip + 100).map(function (it) { return { id: it._id, type: it.type, name: nameOf(it) || it._id, poster: posterOf(it), posterShape: 'poster' }; });
336
+ });
337
+ }
338
+ function synthAddon() {
339
+ return {
340
+ __local: true, __impl: { catalog: synthCatalog }, url: 'local:stremio', base: 'local:stremio',
341
+ manifest: { id: 'org.stremiok.stremio-library', name: U.t('Stremio Library'), version: '1.0.0', types: ['movie', 'series'], resources: ['catalog'],
342
+ catalogs: [{ type: 'movie', id: 'stremio_library_movies', name: U.t('Stremio Library'), extra: [{ name: 'skip' }] },
343
+ { type: 'series', id: 'stremio_library_shows', name: U.t('Stremio Library'), extra: [{ name: 'skip' }] }] }
344
+ };
345
+ }
346
+
347
+ // ---------- what StremioK changes ----------
348
+ // The record for a title (a new one as Stremio makes it: only watched, not in the Library);
349
+ // null: not one for the account. m: { name, poster } when it's new.
350
+ function record(type, show, m) {
351
+ if ((type !== 'movie' && type !== 'series') || !idOk(show)) { return null; }
352
+ var it = _data.items[show];
353
+ if (it && it.type === type) { return it; }
354
+ var kept = (typeof Stremio !== 'undefined' && Stremio.metaKept) ? Stremio.metaKept(type, show) : null;
355
+ m = m || {};
356
+ var now = iso(Date.now());
357
+ it = { _id: show, name: ('' + ((kept && kept.name) || m.name || '')).replace(/\s+S\d+E\d+$/, '').slice(0, 200), type: type,
358
+ poster: (kept && kept.poster) || m.poster || '', posterShape: 'poster', removed: true, temp: true, _ctime: now, _mtime: now,
359
+ state: { lastWatched: now, timeWatched: 0, timeOffset: 0, overallTimeWatched: 0, timesWatched: 0, flaggedWatched: 0, duration: 0, video_id: null, watched: null, noNotif: false },
360
+ behaviorHints: { defaultVideoId: null, featuredVideoId: null, hasScheduledVideos: false } };
361
+ _data.items[show] = it;
362
+ return it;
363
+ }
364
+ function touched(it) { it._mtime = iso(Math.max(Date.now(), mtime(it) + 1000)); dirty(); save(); }
365
+ function when(fn) { if (!isConnected()) { return; } if (_loaded) { fn(); } else { _ready.then(function () { if (isConnected()) { fn(); } }); } }
366
+
367
+ // A playback's place (Player's own saves: while it plays, and on stopping). final: stopped or
368
+ // left (sent soon); otherwise at most every PLAYING_EVERY_MS.
369
+ var _last = { key: '', cur: 0, at: 0, sent: 0 };
370
+ function onProgress(ctx, cur, dur, final) {
371
+ if (!ctx || ctx.addonType || !dur || cur < 5) { return; }
372
+ when(function () {
373
+ var type = ctx.type, vid = '' + ctx.id, show = type === 'series' ? (ctx.parent || showOf(type, vid)) : vid;
374
+ if (type === 'series' && !seOf(vid)) { return; }
375
+ var it = record(type, show, { name: ctx.name, poster: ctx.poster });
376
+ if (!it) { return; }
377
+ var s = it.state, key = show + '|' + vid, now = Date.now(), video = type === 'series' ? vid : show;
378
+ if (s.video_id !== video) {
379
+ s.overallTimeWatched += s.timeWatched; s.timeWatched = 0; s.flaggedWatched = 0; s.video_id = video;
380
+ } else if (_last.key === key) {
381
+ var moved = (cur - _last.cur) * 1000; // (watched since the last save: at most the time that's passed)
382
+ if (moved > 0) { moved = Math.min(moved, now - _last.at + 1000); s.timeWatched += moved; s.overallTimeWatched += moved; }
383
+ }
384
+ s.timeOffset = Math.max(1, Math.floor(cur * 1000)); s.duration = Math.floor(dur * 1000); s.lastWatched = iso(now);
385
+ if (it.temp && !s.timesWatched) { it.removed = true; }
386
+ if (it.removed) { it.temp = true; }
387
+ _last = { key: key, cur: cur, at: now, sent: _last.key === key ? _last.sent : 0 };
388
+ touched(it);
389
+ if (final || now - _last.sent >= PLAYING_EVERY_MS) { _last.sent = now; sendSoon(); }
390
+ });
391
+ }
392
+ // Watched / not watched (however it's marked here): a film's count; an episode's bit (set when
393
+ // its show's episodes are read, before it's sent). A finished episode or film leaves Continue
394
+ // Watching there too.
395
+ function onMarked(type, ids, on) {
396
+ when(function () {
397
+ var shows = {};
398
+ (ids || []).forEach(function (id) {
399
+ id = '' + id;
400
+ if (type === 'movie') {
401
+ var it = on ? record('movie', id, null) : item('movie', id);
402
+ if (!it) { return; }
403
+ if (on) { it.state.timesWatched += 1; it.state.flaggedWatched = 1; it.state.lastWatched = iso(Date.now()); it.state.timeOffset = 0; }
404
+ else { it.state.timesWatched = 0; it.state.flaggedWatched = 0; }
405
+ touched(it);
406
+ } else if (type === 'series' && seOf(id)) {
407
+ var show = showOf('series', id), r = on ? record('series', show, null) : item('series', show);
408
+ if (!r) { return; }
409
+ (_data.marks[show] = _data.marks[show] || {})[id] = on ? 1 : 0;
410
+ if (on && r.state.video_id === id) { r.state.timeOffset = 0; }
411
+ shows[show] = r;
412
+ }
413
+ });
414
+ Object.keys(shows).forEach(function (k) { touched(shows[k]); });
415
+ sendSoon();
416
+ });
417
+ }
418
+ // Put in Continue Watching here (the next episode queued, or "Add to Continue Watching"): there
419
+ // too, at its start, as Stremio's own player queues the next episode.
420
+ function onAdded(e) {
421
+ if (!e) { return; }
422
+ when(function () {
423
+ var vid = '' + e.id, show = e.type === 'series' ? (e.parent || showOf('series', vid)) : vid;
424
+ if (e.type === 'series' && !seOf(vid)) { return; }
425
+ var it = record(e.type, show, e);
426
+ if (!it) { return; }
427
+ var s = it.state, video = e.type === 'series' ? vid : show;
428
+ if (s.video_id !== video) { s.overallTimeWatched += s.timeWatched; s.timeWatched = 0; s.flaggedWatched = 0; s.video_id = video; s.timeOffset = 1; }
429
+ else { s.timeOffset = Math.max(1, s.timeOffset); }
430
+ s.lastWatched = iso(Date.now());
431
+ touched(it);
432
+ sendSoon();
433
+ });
434
+ }
435
+ // Off Continue Watching (Remove): there too (Stremio's "rewind": its place cleared).
436
+ function dismiss(type, id) {
437
+ when(function () {
438
+ var it = item(type, id);
439
+ if (!it || !it.state.timeOffset) { return; }
440
+ if (type === 'series' && seOf(id) && it.state.video_id && it.state.video_id !== '' + id && further(it.state.video_id, id)) { return; } // (the account has it at a later episode)
441
+ it.state.timeOffset = 0;
442
+ touched(it);
443
+ sendSoon();
444
+ });
445
+ }
446
+ function setInLibrary(type, meta, on) {
447
+ when(function () {
448
+ var it = on ? record(type, meta.id, meta) : item(type, meta.id);
449
+ if (!it) { return; }
450
+ if (on) { if (meta.name) { it.name = ('' + meta.name).slice(0, 200); } if (meta.poster) { it.poster = meta.poster; } }
451
+ it.removed = !on; it.temp = false;
452
+ touched(it);
453
+ changed();
454
+ sendSoon();
455
+ });
456
+ }
457
+
458
+ // ---------- talking to the account ----------
459
+ function call(method, body, max) {
460
+ var g = _gen;
461
+ body.authKey = authKey();
462
+ return StremioAccount.call(method, body, max).then(function (r) { if (g !== _gen) { throw { stale: true }; } return r; }, function (e) {
463
+ if (g === _gen && e && (e.code === 1 || /session|auth/i.test(e.message || ''))) { lostSignIn(); }
464
+ throw e;
465
+ });
466
+ }
467
+ function pending() {
468
+ return Object.keys(_data.items).filter(function (id) {
469
+ var it = _data.items[id];
470
+ return idOk(id) && sec(mtime(it)) > sec(_data.rm[id] || 0) && !(it.removed && mtime(it) < Date.now() - 365 * 86400000);
471
+ });
472
+ }
473
+ // Episode marks made here, laid on the account's bits (the show's episodes read first).
474
+ function applyMarks() {
475
+ var shows = Object.keys(_data.marks);
476
+ return shows.reduce(function (p, show) {
477
+ return p.then(function () {
478
+ var it = _data.items[show], marks = _data.marks[show];
479
+ if (!it || it.type !== 'series') { delete _data.marks[show]; return; }
480
+ return Stremio.getMeta('series', show).then(function (meta) {
481
+ var vids = videoOrder(meta), ids = vids.map(function (v) { return v.id; }), bits = readBits(it.state.watched, ids);
482
+ delete _data.marks[show];
483
+ if (!bits || !ids.length) { U.log('stremio', 'Watched episodes of ' + (nameOf(it) || show) + ' not sent: its episode list differs from your Stremio account’s'); return; }
484
+ var newest = ms(it.state.lastWatched);
485
+ Object.keys(marks).forEach(function (vid) {
486
+ var at = ids.indexOf(vid);
487
+ if (at === -1) { return; }
488
+ bits[at] = marks[vid] === 1;
489
+ if (marks[vid] === 1 && ms(vids[at].released) > newest) { newest = ms(vids[at].released); }
490
+ });
491
+ it.state.watched = writeBits(bits, ids);
492
+ if (newest) { it.state.lastWatched = iso(Math.min(newest, Date.now())); }
493
+ touched(it);
494
+ _data.eps[show] = { m: mtime(it), v: ids.filter(function (x, i) { return bits[i]; }) };
495
+ }, function () {}); // (its details not read now: kept for the next sync)
496
+ });
497
+ }, Promise.resolve());
498
+ }
499
+ function push(ids) {
500
+ var chunks = [];
501
+ for (var i = 0; i < ids.length; i += PUT_CHUNK) { chunks.push(ids.slice(i, i + PUT_CHUNK)); }
502
+ return chunks.reduce(function (p, chunk) {
503
+ return p.then(function () {
504
+ var items = chunk.map(function (id) { return _data.items[id]; }).filter(Boolean);
505
+ var times = items.map(function (it) { return mtime(it); }); // (as sent: a change made while it's under way is newer, and goes next)
506
+ return call('datastorePut', { collection: COLLECTION, changes: items }).then(function () {
507
+ items.forEach(function (it, i) { _data.rm[it._id] = Math.max(_data.rm[it._id] || 0, times[i]); });
508
+ save();
509
+ });
510
+ });
511
+ }, Promise.resolve());
512
+ }
513
+ function pull(ids) {
514
+ var chunks = [];
515
+ for (var i = 0; i < ids.length; i += GET_CHUNK) { chunks.push(ids.slice(i, i + GET_CHUNK)); }
516
+ return chunks.reduce(function (p, chunk) {
517
+ return p.then(function () {
518
+ return call('datastoreGet', { collection: COLLECTION, ids: chunk, all: false }, GET_MAX).then(function (list) {
519
+ (Array.isArray(list) ? list : []).forEach(function (it) {
520
+ if (!it || typeof it._id !== 'string') { return; }
521
+ var t = ms(it._mtime), mine = _data.items[it._id];
522
+ if (usable(it) && mine && !_data.rm[it._id]) { _data.items[it._id] = merged(it, mine); } // (made here before the account's was read)
523
+ else if (usable(it) && t >= mtime(mine)) { _data.items[it._id] = it; }
524
+ if (t) { _data.rm[it._id] = Math.max(_data.rm[it._id] || 0, t); }
525
+ });
526
+ dirty(); save();
527
+ });
528
+ });
529
+ }, Promise.resolve());
530
+ }
531
+ // A record made here (never sent) for a title the account has a record of: the account's, with
532
+ // what was done here laid on (its place when newer, watched counts, in the Library); episode
533
+ // marks are kept apart and laid on its watched episodes when sent. Newer than both: it's sent.
534
+ function merged(theirs, mine) {
535
+ var a = theirs.state, b = mine.state;
536
+ if (ms(b.lastWatched) > ms(a.lastWatched) && b.timeOffset) {
537
+ ['video_id', 'timeOffset', 'duration', 'timeWatched', 'lastWatched'].forEach(function (k) { a[k] = b[k]; });
538
+ }
539
+ a.timesWatched = Math.max(a.timesWatched, b.timesWatched); a.flaggedWatched = Math.max(a.flaggedWatched, b.flaggedWatched);
540
+ if (b.flaggedWatched && !b.timeOffset && (mine.type === 'movie' || a.video_id === b.video_id)) { a.timeOffset = 0; } // (finished here)
541
+ if (!mine.removed) { theirs.removed = false; theirs.temp = false; }
542
+ theirs._mtime = iso(Math.max(Date.now(), mtime(theirs) + 1000, mtime(mine)));
543
+ return theirs;
544
+ }
545
+ // A show's watched episodes read (its details: the episode order), for the ones that changed.
546
+ function readEpisodes() {
547
+ var todo = Object.keys(_data.items).filter(function (id) {
548
+ var it = _data.items[id], e = _data.eps[id];
549
+ return it.type === 'series' && it.state.watched && !_data.marks[id] && (!e || e.m !== mtime(it)) && idOk(id);
550
+ }).slice(0, EPS_PER_SYNC);
551
+ return todo.reduce(function (p, id) {
552
+ return p.then(function () {
553
+ return Stremio.getMeta('series', id).then(function (meta) {
554
+ var it = _data.items[id];
555
+ if (!it) { return; }
556
+ var ids = videoOrder(meta).map(function (v) { return v.id; }), bits = readBits(it.state.watched, ids);
557
+ _data.eps[id] = { m: mtime(it), v: bits ? ids.filter(function (x, i) { return bits[i]; }) : [] };
558
+ dirty(); save();
559
+ }, function () {});
560
+ });
561
+ }, Promise.resolve());
562
+ }
563
+ // Only so many records kept: the oldest go (not ones waiting to be sent).
564
+ function trim() {
565
+ var ids = Object.keys(_data.items);
566
+ if (ids.length <= ITEMS_MAX) { return; }
567
+ var wait = {};
568
+ pending().forEach(function (id) { wait[id] = 1; });
569
+ ids.sort(function (a, b) { return mtime(_data.items[b]) - mtime(_data.items[a]); });
570
+ ids.slice(ITEMS_MAX).forEach(function (id) { if (!wait[id]) { delete _data.items[id]; delete _data.eps[id]; } });
571
+ }
572
+
573
+ // Both ways: what's newer there read, the episode marks made here laid on, what's newer here
574
+ // sent, then the shows' watched episodes read. sendOnly: only the sending (a change made here).
575
+ // One at a time (one under way is shared, and a send asked meanwhile follows it); a failure
576
+ // waits for the next.
577
+ var _syncing = null, _again = false;
578
+ function sync(sendOnly) {
579
+ if (!isConnected() || state().reconnect) { return Promise.resolve(); }
580
+ if (_syncing) { if (sendOnly) { _again = true; } return _syncing; }
581
+ startEvery();
582
+ var g = _gen, p = _ready.then(function () {
583
+ if (sendOnly) { return null; }
584
+ return call('datastoreMeta', { collection: COLLECTION }, META_MAX).then(compare);
585
+ }).then(applyMarks).then(function () { return push(pending()); }).then(function () {
586
+ if (sendOnly) { return; }
587
+ trim();
588
+ return readEpisodes();
589
+ }).then(function () {
590
+ if (g !== _gen) { return; }
591
+ setState(sendOnly ? { err: '' } : { last: Date.now(), err: '' });
592
+ }, function (e) {
593
+ if (g !== _gen || (e && e.stale)) { return; }
594
+ setState({ err: (e && e.message) || U.t('couldn’t reach Stremio') });
595
+ U.log('stremio', 'Stremio sync: ' + ((e && e.message) || 'failed'));
596
+ }).then(function () {
597
+ if (_syncing === p) { _syncing = null; }
598
+ if (g !== _gen) { return; }
599
+ dirty(); save();
600
+ if (!sendOnly) { changed(); }
601
+ if (_again) { _again = false; sendSoon(); }
602
+ });
603
+ _syncing = p;
604
+ return p;
605
+ }
606
+ // The account's records' times against the ones kept here: the newer ones there read.
607
+ function compare(list) {
608
+ var remote = {}, want = [];
609
+ (Array.isArray(list) ? list : []).forEach(function (x) {
610
+ var id = Array.isArray(x) ? x[0] : null, t = Array.isArray(x) ? ms(x[1]) : 0;
611
+ if (typeof id !== 'string' || !t) { return; }
612
+ remote[id] = t;
613
+ var it = _data.items[id];
614
+ if (it ? (sec(mtime(it)) < sec(t) || !_data.rm[id]) : sec(_data.rm[id] || 0) < sec(t)) { want.push(id); } // (one made here, never sent: read, to be merged)
615
+ });
616
+ Object.keys(remote).forEach(function (id) { if (_data.items[id] && _data.rm[id] && sec(_data.rm[id]) < sec(remote[id]) && sec(mtime(_data.items[id])) >= sec(remote[id])) { _data.rm[id] = remote[id]; } }); // (not one made here and never sent: that's merged)
617
+ want.sort(function (a, b) { return remote[b] - remote[a]; });
618
+ return pull(want.slice(0, ITEMS_MAX));
619
+ }
620
+ // Sent a few seconds after a change (however many), with a sync of its own.
621
+ var _timer = null, _every = null;
622
+ function sendSoon() {
623
+ if (_timer) { clearTimeout(_timer); }
624
+ _timer = setTimeout(function () { _timer = null; sync(true); }, SEND_MS);
625
+ }
626
+ function startEvery() {
627
+ if (_every) { return; }
628
+ _every = setInterval(function () {
629
+ if (!isConnected()) { clearInterval(_every); _every = null; return; }
630
+ if (U.isHidden && U.isHidden()) { return; }
631
+ sync();
632
+ }, EVERY_MS);
633
+ }
634
+
635
+ return {
636
+ isConnected: isConnected, authKey: authKey, connect: connect, disconnect: disconnect, connectStatus: connectStatus, sync: sync,
637
+ watchedAt: watchedAt, continueList: continueList, watchedPast: watchedPast, inLibrary: inLibrary, setInLibrary: setInLibrary, synthAddon: synthAddon,
638
+ onProgress: onProgress, onMarked: onMarked, onAdded: onAdded, dismiss: dismiss,
639
+ __bits: { readBits: readBits, writeBits: writeBits, pack: pack, unpack: unpack, videoOrder: videoOrder }
640
+ };
641
+ })();