@obitosouls/tizenbrew-netmirror 0.0.0-stage → 1.0.1

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/web/js/api.js ADDED
@@ -0,0 +1,707 @@
1
+ /**
2
+ * NM — NetMirror backend/API module
3
+ *
4
+ * Domain resolution, auth/token storage, and all /newtv/*.php endpoint
5
+ * helpers for the Tizen TV WGT app. Loaded before app.js.
6
+ *
7
+ * Protocol reference: analysis-report.md (verified from HBC v96 decompilation)
8
+ * All endpoints use HTTP GET — parameters via URL query params + custom headers.
9
+ */
10
+ var NM = (function () {
11
+ 'use strict';
12
+
13
+ /* =====================================================================
14
+ * Base64 domain pool — fallback domains tried during resolve().
15
+ * Source: assets/index.android.bundle bytecode scan.
16
+ * ===================================================================== */
17
+ var DOMAIN_POOL = [
18
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0Lnh5eg==',
19
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0LnRvcA==',
20
+ 'aHR0cHM6Ly9tb2JpbGVkZXRlY3QuYXBw',
21
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0LmFwcA==',
22
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0LmNvbQ==',
23
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0Lm5ldA==',
24
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0Lm9yZw==',
25
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0LmluZm8=',
26
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0LmNj',
27
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0LmNvLmlu',
28
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0LmluLm5ldA==',
29
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0LmluLm5ldA==',
30
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0Lm1l',
31
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0LmxpdmU=',
32
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0LnNpdGU=',
33
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0LnN0b3Jl',
34
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0LnRlY2g=',
35
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0LnVz',
36
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0LmNsdWI=',
37
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0LmZ1bg==',
38
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0LnByZXNz',
39
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0Lndvcmxk',
40
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0Lmlj',
41
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0LnNwYWNl',
42
+ 'aHR0cHM6Ly9tb2JpZGV0ZWN0LnBhZ2U='
43
+ ];
44
+
45
+ /* =====================================================================
46
+ * Default OTT Providers (verified from target app / catalog)
47
+ * ===================================================================== */
48
+ var DEFAULT_OTT = 'nf';
49
+
50
+ function normalizeOtt(v) {
51
+ var s = String(v || '').trim().toLowerCase();
52
+ if (s === 'netflix') return 'nf';
53
+ if (s === 'prime' || s === 'amazon') return 'pv';
54
+ if (s === 'hotstar' || s === 'disney') return 'hs';
55
+ if (s === 'nf' || s === 'pv' || s === 'hs') return s;
56
+ return 'nf';
57
+ }
58
+ var DEFAULT_PROVIDERS = [
59
+ { id: 'nf', name: 'Netflix', logo: 'https://tv.imgcdn.kim/newtv/img/nf.webp' },
60
+ { id: 'pv', name: 'Prime Video', logo: 'https://tv.imgcdn.kim/newtv/img/pv.webp' },
61
+ { id: 'hs', name: 'Disney+ Hotstar', logo: 'https://tv.imgcdn.kim/newtv/img/hs.jpg' }
62
+ ];
63
+
64
+ /* =====================================================================
65
+ * Constants — exact header values from decompiled bytecode
66
+ * ===================================================================== */
67
+ var UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:136.0) Gecko/20100101 Firefox/136.0 /OS.GatuNewTV v1.0';
68
+ var UA_OTP = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:136.0) Gecko/20100101 Firefox/136.0 /OS.Gatu v1.0';
69
+ var XRW = 'NetmirrorNewTV v1.0';
70
+ var CHECK_PATH = '/checknewtv.php';
71
+ var CHECK_TIMEOUT = 5000;
72
+ var API_TIMEOUT = 15000;
73
+
74
+ /* =====================================================================
75
+ * Debug & Diagnostic Logging (visible in on-screen DebugDrawer)
76
+ * ===================================================================== */
77
+ var debugCalls = [];
78
+ function logCall(name, url, reqHeaders, status, resText, data, error) {
79
+ var entry = {
80
+ name: name,
81
+ time: (new Date()).toTimeString().split(' ')[0],
82
+ url: url,
83
+ status: status || 0,
84
+ resStatus: data && data.status ? data.status : '',
85
+ keys: data && typeof data === 'object' && !Array.isArray(data) ? Object.keys(data).slice(0, 10) : (Array.isArray(data) ? ['[Array(' + data.length + ')]'] : []),
86
+ snippet: resText ? resText.replace(/\s+/g, ' ').slice(0, 250) : '',
87
+ error: error ? String(error.message || error) : ''
88
+ };
89
+ debugCalls.unshift(entry);
90
+ if (debugCalls.length > 25) debugCalls.pop();
91
+ if (typeof NM !== 'undefined' && typeof NM.onDebugUpdate === 'function') {
92
+ try { NM.onDebugUpdate(entry); } catch (e) {}
93
+ }
94
+ }
95
+
96
+ /* =====================================================================
97
+ * Local Proxy Support (TizenBrew / localhost:8787)
98
+ * ===================================================================== */
99
+ var proxyUrl = '';
100
+ function setProxyUrl(u) { proxyUrl = (u || '').replace(/\/+$/, ''); }
101
+ function getProxyUrl() { return proxyUrl; }
102
+
103
+ function proxyMediaUrl(url, referer, ua) {
104
+ if (!url) return '';
105
+ var ref = referer || 'https://net52.cc';
106
+ if (!proxyUrl) return url;
107
+ var u = proxyUrl + '/proxy/media?url=' + encodeURIComponent(url);
108
+ if (ref) u += '&referer=' + encodeURIComponent(ref);
109
+ if (ua) u += '&ua=' + encodeURIComponent(ua);
110
+ return u;
111
+ }
112
+
113
+ function detectProxy() {
114
+ // Probe candidates: dedicated port 8787, 8788, then location.origin (excluding 8081)
115
+ var candidates = ['http://127.0.0.1:8787', 'http://127.0.0.1:8788'];
116
+ if (typeof location !== 'undefined' && location.protocol.indexOf('http') === 0 && location.port) {
117
+ var p = String(location.port);
118
+ if (p !== '8081' && p !== '8787' && p !== '8788') {
119
+ candidates.push(location.origin);
120
+ }
121
+ }
122
+
123
+ function tryCandidate(idx) {
124
+ if (idx >= candidates.length) {
125
+ setProxyUrl('');
126
+ return Promise.resolve('');
127
+ }
128
+ var c = candidates[idx];
129
+ return fetchWithTimeout(c + '/proxy/health', {}, 1200)
130
+ .then(function (r) {
131
+ if (!r.ok) return tryCandidate(idx + 1);
132
+ return r.json().then(function (data) {
133
+ // Strictly require data.service === 'tizenbrew-netmirror'
134
+ if (data && data.service === 'tizenbrew-netmirror') {
135
+ setProxyUrl(c);
136
+ return c;
137
+ }
138
+ return tryCandidate(idx + 1);
139
+ }).catch(function () {
140
+ return tryCandidate(idx + 1);
141
+ });
142
+ })
143
+ .catch(function () {
144
+ return tryCandidate(idx + 1);
145
+ });
146
+ }
147
+
148
+ return tryCandidate(0);
149
+ }
150
+
151
+ /* =====================================================================
152
+ * Storage wrapper (localStorage on Tizen TV)
153
+ * ===================================================================== */
154
+ var memStore = {};
155
+ var storage = {
156
+ get: function (k) { try { return (typeof localStorage !== 'undefined' && localStorage.getItem(k)) || memStore[k] || ''; } catch (e) { return memStore[k] || ''; } },
157
+ set: function (k, v) { memStore[k] = (v == null ? '' : String(v)); try { if (typeof localStorage !== 'undefined') localStorage.setItem(k, memStore[k]); } catch (e) {} },
158
+ remove: function (k) { delete memStore[k]; try { if (typeof localStorage !== 'undefined') localStorage.removeItem(k); } catch (e) {} },
159
+ apiUrl: function (v) {
160
+ if (v !== undefined) this.set('apiUrl', v);
161
+ return this.get('apiUrl');
162
+ },
163
+ getUsertoken: function () { return this.get('usertoken'); },
164
+ setUsertoken: function (v) { this.set('usertoken', v); },
165
+ getOtt: function () {
166
+ var v = normalizeOtt(this.get('ott'));
167
+ if (this.get('ott') !== v) this.set('ott', v);
168
+ return v;
169
+ },
170
+ setOtt: function (v) {
171
+ var val = normalizeOtt(v);
172
+ this.set('ott', val);
173
+ },
174
+ getRecentplay: function () {
175
+ var ott = this.getOtt();
176
+ return ott ? this.get(ott + '_recentplay') : '';
177
+ },
178
+ getWatchlist: function () {
179
+ var ott = this.getOtt();
180
+ return ott ? this.get(ott + '_watchlist') : '';
181
+ },
182
+ getProgress: function (id) {
183
+ var raw = this.get('progress_' + id);
184
+ if (!raw) return 0;
185
+ var parts = raw.split(':');
186
+ return parseFloat(parts[0]) || 0;
187
+ },
188
+ setProgress: function (id, seconds) {
189
+ this.set('progress_' + id, String(Math.floor(seconds)));
190
+ }
191
+ };
192
+
193
+ /* =====================================================================
194
+ * Response & Error handling
195
+ * Surface raw text + HTTP status clearly whenever an endpoint returns
196
+ * non-JSON (e.g. PHP error, "Missing OTT Value") instead of crashing.
197
+ * ===================================================================== */
198
+ function handleApiResponse(r, endpointName, reqUrl, reqHeaders) {
199
+ return r.text().then(function (rawText) {
200
+ var text = (rawText || '').trim();
201
+ if (!r.ok) {
202
+ var errSnippet = text ? text.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 200) : ('HTTP ' + r.status);
203
+ var err = new Error('HTTP ' + r.status + ': ' + errSnippet);
204
+ logCall(endpointName || 'api', reqUrl, reqHeaders, r.status, text, null, err);
205
+ throw err;
206
+ }
207
+ if (!text) {
208
+ logCall(endpointName || 'api', reqUrl, reqHeaders, r.status, text, {}, null);
209
+ return {};
210
+ }
211
+ var parsed;
212
+ try {
213
+ parsed = JSON.parse(text);
214
+ } catch (parseErr) {
215
+ var cleanMsg = text.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 250);
216
+ var err2 = new Error((r.status ? 'HTTP ' + r.status + ': ' : '') + (cleanMsg || 'Non-JSON server response'));
217
+ logCall(endpointName || 'api', reqUrl, reqHeaders, r.status, text, null, err2);
218
+ throw err2;
219
+ }
220
+ logCall(endpointName || 'api', reqUrl, reqHeaders, r.status, text, parsed, null);
221
+ return parsed;
222
+ });
223
+ }
224
+
225
+ /* =====================================================================
226
+ * HTTP helpers
227
+ * ===================================================================== */
228
+ function fetchWithTimeout(url, opts, ms) {
229
+ opts = opts || {};
230
+ var ctrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
231
+ if (ctrl) opts.signal = ctrl.signal;
232
+ return new Promise(function (resolve, reject) {
233
+ var t = setTimeout(function () {
234
+ if (ctrl) ctrl.abort();
235
+ reject(new Error('Request timed out after ' + (ms / 1000) + 's'));
236
+ }, ms);
237
+ fetch(url, opts).then(
238
+ function (r) { clearTimeout(t); resolve(r); },
239
+ function (e) { clearTimeout(t); reject(e); }
240
+ );
241
+ });
242
+ }
243
+
244
+ function commonHeaders(customUa) {
245
+ return {
246
+ 'Cache-Control': 'no-cache, no-store, must-revalidate',
247
+ 'Pragma': 'no-cache',
248
+ 'Expires': '0',
249
+ 'X-Requested-With': XRW,
250
+ 'User-Agent': customUa || UA
251
+ };
252
+ }
253
+
254
+ function apiGet(url, extraHeaders, timeout, customUa, endpointName) {
255
+ var headers = commonHeaders(customUa);
256
+ if (extraHeaders) {
257
+ Object.keys(extraHeaders).forEach(function (k) {
258
+ if (extraHeaders[k] != null && extraHeaders[k] !== '') {
259
+ headers[k] = String(extraHeaders[k]);
260
+ }
261
+ });
262
+ }
263
+ if (headers['Ott']) {
264
+ headers['Ott'] = normalizeOtt(headers['Ott']);
265
+ } else {
266
+ headers['Ott'] = storage.getOtt();
267
+ }
268
+
269
+ var dispatchUrl = url;
270
+ if (proxyUrl) {
271
+ var targetUa = customUa || headers['User-Agent'] || UA;
272
+ dispatchUrl = proxyUrl + '/proxy/api?url=' + encodeURIComponent(url) + '&ua=' + encodeURIComponent(targetUa);
273
+ }
274
+
275
+ return fetchWithTimeout(dispatchUrl, { method: 'GET', headers: headers }, timeout || API_TIMEOUT)
276
+ .then(function (r) { return handleApiResponse(r, endpointName, url, headers); });
277
+ }
278
+
279
+ function base() {
280
+ var u = storage.apiUrl();
281
+ if (!u) throw new Error('API not resolved — call NM.resolve() first');
282
+ return u.replace(/\/+$/, '');
283
+ }
284
+
285
+ /* =====================================================================
286
+ * OTP redirect hook
287
+ * ===================================================================== */
288
+ function checkOtp(data) {
289
+ if (data && data.status === 'otp') {
290
+ if (data.pub_msg) storage.set('pub_msg', data.pub_msg);
291
+ if (data.pub_msg_img) {
292
+ var pImg = data.pub_msg_img;
293
+ storage.set('pub_msg_img', typeof pImg === 'object' ? JSON.stringify(pImg) : pImg);
294
+ }
295
+ NM.otpRequired = true;
296
+ if (typeof NM.onOtpRequired === 'function') NM.onOtpRequired(data);
297
+ } else if (data && data.status === 'ok') {
298
+ NM.otpRequired = false;
299
+ }
300
+ return data;
301
+ }
302
+
303
+ /* =====================================================================
304
+ * Domain Resolution — /checknewtv.php
305
+ * ===================================================================== */
306
+ function resolve() {
307
+ var cached = storage.apiUrl();
308
+ if (cached) {
309
+ return apiGet(cached.replace(/\/+$/, '') + CHECK_PATH, {}, CHECK_TIMEOUT, UA, 'checknewtv')
310
+ .then(function (data) {
311
+ if (data && data.token_hash) {
312
+ var real = atob(data.token_hash);
313
+ storage.apiUrl(real);
314
+ return real;
315
+ }
316
+ throw new Error('Invalid cached response');
317
+ })
318
+ .catch(function () {
319
+ return resolveFromPool();
320
+ });
321
+ }
322
+ return resolveFromPool().then(function (res) {
323
+ if (!storage.getUsertoken()) {
324
+ autoLogin().catch(function () {});
325
+ }
326
+ return res;
327
+ });
328
+ }
329
+
330
+ function resolveFromPool() {
331
+ var i = 0;
332
+ function tryNext() {
333
+ if (i >= DOMAIN_POOL.length) {
334
+ return Promise.reject(new Error('All API checks failed. Download updated app from netmirror.app'));
335
+ }
336
+ var decoded;
337
+ try { decoded = atob(DOMAIN_POOL[i]); } catch (e) { i++; return tryNext(); }
338
+ i++;
339
+ var url = decoded.replace(/\/+$/, '') + CHECK_PATH;
340
+ return apiGet(url, {}, CHECK_TIMEOUT, UA, 'checknewtv')
341
+ .then(function (data) {
342
+ if (data && data.token_hash) {
343
+ var real = atob(data.token_hash);
344
+ storage.apiUrl(real);
345
+ return real;
346
+ }
347
+ return tryNext();
348
+ })
349
+ .catch(function () {
350
+ return tryNext();
351
+ });
352
+ }
353
+ return tryNext();
354
+ }
355
+
356
+ /* =====================================================================
357
+ * Endpoints
358
+ * ===================================================================== */
359
+ function otp(code) {
360
+ var c = String(code || '').trim();
361
+ var url = base() + '/newtv/otp.php';
362
+ var headers = {
363
+ 'Otp': c,
364
+ 'Cache-Control': 'no-cache, no-store, must-revalidate',
365
+ 'Pragma': 'no-cache',
366
+ 'Expires': '0',
367
+ 'User-Agent': UA_OTP
368
+ };
369
+ var dispatchUrl = url;
370
+ if (proxyUrl) {
371
+ dispatchUrl = proxyUrl + '/proxy/api?url=' + encodeURIComponent(url) + '&ua=' + encodeURIComponent(UA_OTP);
372
+ }
373
+ return fetchWithTimeout(dispatchUrl, { method: 'GET', headers: headers }, API_TIMEOUT)
374
+ .then(function (r) { return handleApiResponse(r, 'otp', url, headers); })
375
+ .then(function (data) {
376
+ if (data && data.status === 'ok' && data.usertoken) {
377
+ storage.setUsertoken(data.usertoken);
378
+ }
379
+ return data;
380
+ });
381
+ }
382
+
383
+
384
+ function autoLogin() {
385
+ var tok = storage.getUsertoken();
386
+ if (tok && tok.length > 10) return Promise.resolve(tok);
387
+ return otp('111111').then(function (data) {
388
+ if (data && data.usertoken) {
389
+ storage.setUsertoken(data.usertoken);
390
+ return data.usertoken;
391
+ }
392
+ return '';
393
+ }).catch(function () { return ''; });
394
+ }
395
+
396
+ function exportDebugLog() {
397
+ var info = getDebugInfo();
398
+ var txt = '=======================================================\n' +
399
+ ' NETMIRROR TV - LIVE ON-SCREEN DIAGNOSTICS LOG\n' +
400
+ '=======================================================\n' +
401
+ 'Time : ' + (new Date()).toISOString() + '\n' +
402
+ 'API Base : ' + (info.apiUrl || 'Unresolved') + '\n' +
403
+ 'OTT Provider : ' + (info.ott || 'None') + '\n' +
404
+ 'Usertoken : ' + (info.usertoken || 'Missing') + '\n' +
405
+ 'Proxy Server : ' + (info.proxyUrl || 'Direct WebKit') + '\n' +
406
+ 'Total Calls : ' + debugCalls.length + '\n' +
407
+ '=======================================================\n\n';
408
+
409
+ if (debugCalls.length) {
410
+ txt += debugCalls.map(function (c) {
411
+ return '[' + c.time + '] ' + c.name.toUpperCase() + ' (HTTP ' + c.status + ')' +
412
+ (c.resStatus ? (' status="' + c.resStatus + '"') : '') +
413
+ (c.keys && c.keys.length ? (' keys=[' + c.keys.join(',') + ']') : '') +
414
+ (c.error ? (' ERROR: ' + c.error) : '') +
415
+ '\n URL: ' + c.url +
416
+ (c.snippet ? ('\n Snippet: ' + c.snippet) : '');
417
+ }).join('\n\n');
418
+ } else {
419
+ txt += 'No calls recorded yet.\n';
420
+ }
421
+ return txt;
422
+ }
423
+
424
+ var syncDebugTimer = null;
425
+ function syncDebugToProxy() {
426
+ if (!proxyUrl) return;
427
+ var report = exportDebugLog();
428
+ fetch(proxyUrl + '/proxy/debug', {
429
+ method: 'POST',
430
+ headers: { 'Content-Type': 'text/plain; charset=utf-8' },
431
+ body: report
432
+ }).catch(function () {});
433
+ }
434
+
435
+ function main(ott, page) {
436
+ var o = (ott || storage.getOtt() || DEFAULT_OTT).trim();
437
+ var p = page;
438
+ if (!p) p = 'all';
439
+ else if (p === 'series') p = 'show';
440
+ return apiGet(base() + '/newtv/main.php', {
441
+ 'Ott': o,
442
+ 'Page': String(p),
443
+ 'Recentplay': storage.getRecentplay(),
444
+ 'Usertoken': storage.getUsertoken(),
445
+ 'Watchlist': storage.getWatchlist()
446
+ }, API_TIMEOUT, UA, 'main').then(checkOtp);
447
+ }
448
+
449
+ function navbar(ott) {
450
+ var o = (ott || storage.getOtt() || DEFAULT_OTT).trim();
451
+ return apiGet(base() + '/newtv/navbar.php', {
452
+ 'Ott': o
453
+ }, API_TIMEOUT, UA, 'navbar');
454
+ }
455
+
456
+ function search(query) {
457
+ var o = (storage.getOtt() || DEFAULT_OTT).trim();
458
+ var url = base() + '/newtv/search.php?s=' + encodeURIComponent((query || '').trim());
459
+ var headers = {
460
+ 'Cache-Control': 'no-cache, no-store, Smust-revalidate',
461
+ 'Pragma': 'no-cache',
462
+ 'Expires': '0',
463
+ 'Ott': o,
464
+ 'X-Requested-With': XRW,
465
+ 'User-Agent': UA
466
+ };
467
+ var dispatchUrl = url;
468
+ if (proxyUrl) {
469
+ dispatchUrl = proxyUrl + '/proxy/api?url=' + encodeURIComponent(url) + '&ua=' + encodeURIComponent(UA);
470
+ }
471
+ return fetchWithTimeout(dispatchUrl, { method: 'GET', headers: headers }, API_TIMEOUT)
472
+ .then(function (r) { return handleApiResponse(r, 'search', url, headers); });
473
+ }
474
+
475
+ function parseOttList(data) {
476
+ if (!data) return DEFAULT_PROVIDERS;
477
+ if (Array.isArray(data)) {
478
+ var arr = data.map(function (p) {
479
+ if (typeof p === 'string') {
480
+ var norm = normalizeOtt(p);
481
+ return { id: norm, name: norm === 'nf' ? 'Netflix' : (norm === 'pv' ? 'Prime Video' : (norm === 'hs' ? 'Disney+ Hotstar' : norm.toUpperCase())), logo: '' };
482
+ }
483
+ var rawId = p.value || p.id || p.ott || p.code || '';
484
+ var id = normalizeOtt(rawId);
485
+ var name = p.name || p.title || p.label || (id === 'nf' ? 'Netflix' : (id === 'pv' ? 'Prime Video' : (id === 'hs' ? 'Disney+ Hotstar' : id.toUpperCase())));
486
+ var logo = p.img || p.logo || p.icon || '';
487
+ return { id: id, name: name, logo: logo };
488
+ }).filter(function (p) { return p.id; });
489
+ return arr.length ? arr : DEFAULT_PROVIDERS;
490
+ }
491
+ if (typeof data === 'object') {
492
+ var arrayProps = ['data', 'ott', 'providers', 'results', 'list', 'items'];
493
+ for (var i = 0; i < arrayProps.length; i++) {
494
+ var prop = arrayProps[i];
495
+ if (Array.isArray(data[prop]) && data[prop].length) {
496
+ return parseOttList(data[prop]);
497
+ }
498
+ }
499
+ var keys = Object.keys(data).filter(function (k) {
500
+ return k !== 'status' && k !== 'error' && k !== 'error_msg';
501
+ });
502
+ if (keys.length) {
503
+ var dictList = keys.map(function (k) {
504
+ var v = data[k];
505
+ if (typeof v === 'string') return { id: k.toLowerCase(), name: v, logo: '' };
506
+ if (v && typeof v === 'object') {
507
+ return {
508
+ id: String(v.id || v.ott || k).trim().toLowerCase(),
509
+ name: v.name || v.title || k,
510
+ logo: v.logo || v.img || v.icon || ''
511
+ };
512
+ }
513
+ return { id: k.toLowerCase(), name: k, logo: '' };
514
+ }).filter(function (p) { return p.id; });
515
+ if (dictList.length) return dictList;
516
+ }
517
+ }
518
+ return DEFAULT_PROVIDERS;
519
+ }
520
+
521
+ function ottList() {
522
+ return apiGet(base() + '/newtv/ott.php', {}, API_TIMEOUT, UA, 'ott')
523
+ .then(parseOttList)
524
+ .catch(function () {
525
+ return DEFAULT_PROVIDERS;
526
+ });
527
+ }
528
+
529
+ function post(id, lastep) {
530
+ var o = (storage.getOtt() || DEFAULT_OTT).trim();
531
+ return apiGet(base() + '/newtv/post.php?id=' + encodeURIComponent(id), {
532
+ 'Ott': o,
533
+ 'Lastep': lastep || '',
534
+ 'Usertoken': storage.getUsertoken()
535
+ }, API_TIMEOUT, UA, 'post').then(checkOtp);
536
+ }
537
+
538
+ function episodes(id, ott, page) {
539
+ var o = (ott || storage.getOtt() || DEFAULT_OTT).trim();
540
+ var url = base() + '/newtv/episodes.php?id=' + encodeURIComponent(id);
541
+ if (page && page > 1) url += '&page=' + page;
542
+ return apiGet(url, { 'Ott': o }, API_TIMEOUT, UA, 'episodes');
543
+ }
544
+
545
+ function loadAllEpisodes(seasonId, ott) {
546
+ var allEpisodes = [];
547
+ var page = 1;
548
+ var keepGoing = true;
549
+ var maxPages = 25;
550
+
551
+ function fetchNext() {
552
+ if (!keepGoing || page > maxPages) {
553
+ return Promise.resolve(allEpisodes);
554
+ }
555
+ return episodes(seasonId, ott, page).then(function (data) {
556
+ if (!data || !Array.isArray(data.episodes) || !data.episodes.length) {
557
+ return allEpisodes;
558
+ }
559
+ var imgcdn = data.imgcdn || storage.get('imgcdn') || '';
560
+ data.episodes.forEach(function (e, ei) {
561
+ var epNum = e.ep || e.episode || (allEpisodes.length + 1);
562
+ var epTitle = e.t || e.ep_title || e.title || ('Episode ' + epNum);
563
+ var desc = e.ep_desc || e.desc || e.description || '';
564
+ var dur = (Array.isArray(e.info) ? e.info[2] : (e.runtime || e.duration || '')) || '';
565
+ allEpisodes.push({
566
+ id: e.id != null ? String(e.id) : undefined,
567
+ season: e.s || e.season || 1,
568
+ episode: epNum,
569
+ title: epTitle,
570
+ description: desc,
571
+ duration: dur,
572
+ image: (function () {
573
+ var raw = e.img || e.ep_poster || data.ep_poster || '';
574
+ var sid = e.id || epNum;
575
+ if (raw && raw.indexOf('--') > -1) return raw.replace(/--+/, sid);
576
+ if (imgcdn && imgcdn.indexOf('--') > -1) return imgcdn.replace(/--+/, sid);
577
+ return raw;
578
+ })(),
579
+ url: '',
580
+ _sid: e.sid || e.id || ''
581
+ });
582
+ });
583
+
584
+ if (!data.nextPageShow) {
585
+ keepGoing = false;
586
+ return allEpisodes;
587
+ }
588
+ page = data.nextPage || (page + 1);
589
+ return fetchNext();
590
+ }).catch(function (e) {
591
+ console.warn('loadAllEpisodes stopped:', e);
592
+ return allEpisodes;
593
+ });
594
+ }
595
+
596
+ return fetchNext();
597
+ }
598
+
599
+ function player(id) {
600
+ var o = (storage.getOtt() || DEFAULT_OTT).trim();
601
+ return apiGet(base() + '/newtv/player.php?id=' + encodeURIComponent(id), {
602
+ 'Ott': o,
603
+ 'Usertoken': storage.getUsertoken()
604
+ }, API_TIMEOUT, UA, 'player').then(checkOtp);
605
+ }
606
+
607
+ function recentplay(opts) {
608
+ opts = opts || {};
609
+ var o = (opts.ott || storage.getOtt() || DEFAULT_OTT).trim();
610
+ var headers = {
611
+ 'Recentplay': storage.getRecentplay(),
612
+ 'Ott': o
613
+ };
614
+ if (opts.deleteid) {
615
+ headers['Deleteid'] = String(opts.deleteid);
616
+ } else {
617
+ var vid = opts.type === 't' ? 'SE_' + (opts.sid || opts.videoid) : String(opts.videoid || '');
618
+ if (vid) headers['Videoid'] = vid;
619
+ }
620
+ return apiGet(base() + '/newtv/recentplay.php', headers, API_TIMEOUT, UA, 'recentplay')
621
+ .then(function (data) {
622
+ if (data && data.key) storage.set(data.key, data.value || '');
623
+ return data;
624
+ });
625
+ }
626
+
627
+ function watchlist(opts) {
628
+ opts = opts || {};
629
+ var o = (opts.ott || storage.getOtt() || DEFAULT_OTT).trim();
630
+ var headers = {
631
+ 'Watchlist': storage.getWatchlist(),
632
+ 'Ott': o
633
+ };
634
+ if (opts.deleteid) {
635
+ headers['Deleteid'] = String(opts.deleteid);
636
+ } else {
637
+ var vid = opts.type === 't' ? 'SE_' + (opts.sid || opts.videoid) : String(opts.videoid || '');
638
+ if (vid) headers['Videoid'] = vid;
639
+ }
640
+ return apiGet(base() + '/newtv/watchlist.php', headers, API_TIMEOUT, UA, 'watchlist')
641
+ .then(function (data) {
642
+ if (data && data.key) storage.set(data.key, data.value || '');
643
+ return data;
644
+ });
645
+ }
646
+
647
+ function streamHeaders(referer) {
648
+ var h = { 'User-Agent': UA, 'X-Requested-With': XRW };
649
+ if (referer) h['Referer'] = referer;
650
+ return h;
651
+ }
652
+
653
+ function qualityLabel(bitrate) {
654
+ if (!bitrate) return '';
655
+ if (bitrate >= 1000000) return '1080p';
656
+ if (bitrate >= 600000) return '720p';
657
+ if (bitrate >= 400000) return '480p';
658
+ return bitrate + 'p';
659
+ }
660
+
661
+ function getDebugInfo() {
662
+ return {
663
+ apiUrl: storage.apiUrl() || 'Unresolved',
664
+ ott: storage.getOtt() || 'None',
665
+ usertoken: storage.getUsertoken() ? ('Present (' + storage.getUsertoken().length + ' chars)') : 'Missing',
666
+ proxyUrl: proxyUrl || 'Direct (No Proxy)',
667
+ calls: debugCalls.slice(0, 15)
668
+ };
669
+ }
670
+
671
+ return {
672
+ resolve: resolve,
673
+ otp: otp,
674
+ main: main,
675
+ navbar: navbar,
676
+ search: search,
677
+ ott: ottList,
678
+ parseOttList: parseOttList,
679
+ post: post,
680
+ episodes: episodes,
681
+ loadAllEpisodes: loadAllEpisodes,
682
+ player: player,
683
+ recentplay: recentplay,
684
+ watchlist: watchlist,
685
+ streamHeaders: streamHeaders,
686
+ qualityLabel: qualityLabel,
687
+ storage: storage,
688
+ DEFAULT_OTT: DEFAULT_OTT,
689
+ DEFAULT_PROVIDERS: DEFAULT_PROVIDERS,
690
+ setProxyUrl: setProxyUrl,
691
+ getProxyUrl: getProxyUrl,
692
+ proxyMediaUrl: proxyMediaUrl,
693
+ detectProxy: detectProxy,
694
+ getDebugInfo: getDebugInfo,
695
+ debugCalls: debugCalls,
696
+ logCall: logCall,
697
+ autoLogin: autoLogin,
698
+ exportDebugLog: exportDebugLog,
699
+ syncDebugToProxy: syncDebugToProxy,
700
+ onOtpRequired: null,
701
+ onDebugUpdate: null
702
+ };
703
+ })();
704
+
705
+ if (typeof window !== 'undefined') window.NM = NM;
706
+ if (typeof global !== 'undefined') global.NM = NM;
707
+ if (typeof module !== 'undefined' && module.exports) module.exports = NM;