recycleactor commited on
Commit
2cb6c9f
·
verified ·
1 Parent(s): 78b44e4

Delete server.js

Browse files
Files changed (1) hide show
  1. server.js +0 -774
server.js DELETED
@@ -1,774 +0,0 @@
1
- /**
2
- * Alloha + Cinemar + Turbo Proxy Server
3
- * Endpoints: /alloha/streams, /alloha/player-info, /hls, /srt2vtt,
4
- * /uakinogo/search, /uakinogo/stream, /uakinogo/embed,
5
- * /turbo/search, /turbo/stream, /health
6
- */
7
- const http = require('http');
8
- const https = require('https');
9
-
10
- // Load alloha with error handling — Puppeteer/Chromium may not be available on all platforms
11
- let getStreams, closeBrowser;
12
- try {
13
- const alloha = require('./alloha');
14
- getStreams = alloha.getStreams;
15
- closeBrowser = alloha.closeBrowser;
16
- console.log('[server] Alloha/Puppeteer loaded OK');
17
- } catch(e) {
18
- console.log('[server] Alloha/Puppeteer NOT available:', e.message);
19
- getStreams = async () => { throw new Error('Puppeteer not available on this platform'); };
20
- closeBrowser = async () => {};
21
- }
22
-
23
- const { turboSearch, getTurboStream } = require('./turbo');
24
- const { getCinemarStream } = require('./cinemar');
25
- const { getZetflixHtml, parseZetflixHtml, buildStreams: buildZetflixStreams } = require('./zetflix');
26
-
27
- const PORT = process.env.PORT || 3000;
28
- const ALLOHA_HOST = 'streamalloha.live';
29
- const ALLOHA_TOKEN = '7fda2b04f6ae5e0e228bda812b0dee';
30
-
31
- const CORS = {
32
- 'Access-Control-Allow-Origin': '*',
33
- 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
34
- 'Access-Control-Allow-Headers': '*',
35
- 'Content-Type': 'application/json',
36
- };
37
-
38
- function jsonResp(res, data, status) {
39
- res.writeHead(status || 200, CORS);
40
- res.end(JSON.stringify(data));
41
- }
42
-
43
- function parseQuery(reqUrl) {
44
- try {
45
- const u = new URL('http://x' + reqUrl);
46
- const q = {};
47
- u.searchParams.forEach((v, k) => { q[k] = v; });
48
- return { pathname: u.pathname, query: q };
49
- } catch(e) {
50
- return { pathname: reqUrl.split('?')[0], query: {} };
51
- }
52
- }
53
-
54
- function readBody(req) {
55
- return new Promise(resolve => {
56
- let body = '';
57
- req.setEncoding('utf8');
58
- req.on('data', c => { body += c; });
59
- req.on('end', () => resolve(body));
60
- });
61
- }
62
-
63
- function fetchRaw(reqUrl, headers) {
64
- return new Promise((resolve, reject) => {
65
- let u; try { u = new URL(reqUrl); } catch(e) { return reject(e); }
66
- const mod = u.protocol === 'https:' ? https : http;
67
- const req = mod.request({
68
- hostname: u.hostname,
69
- port: u.port || (u.protocol === 'https:' ? 443 : 80),
70
- path: u.pathname + u.search,
71
- method: 'GET',
72
- headers: headers || {},
73
- }, res => {
74
- // Handle gzip/deflate encoding
75
- const encoding = res.headers['content-encoding'];
76
- let stream = res;
77
- if (encoding === 'gzip' || encoding === 'deflate') {
78
- const zlib = require('zlib');
79
- stream = encoding === 'gzip' ? res.pipe(zlib.createGunzip()) : res.pipe(zlib.createInflate());
80
- }
81
- let data = '';
82
- stream.setEncoding('utf8');
83
- stream.on('data', c => { data += c; });
84
- stream.on('end', () => resolve(data));
85
- stream.on('error', reject);
86
- });
87
- req.on('error', reject);
88
- req.setTimeout(20000, () => { req.destroy(); reject(new Error('timeout')); });
89
- req.end();
90
- });
91
- }
92
-
93
- // ── Cinemar parser ────────────────────────────────────────────────────────────
94
-
95
- function findAllInBuf(buf, pattern) {
96
- const positions = [];
97
- let pos = 0;
98
- while (pos < buf.length) {
99
- const idx = buf.indexOf(pattern, pos);
100
- if (idx < 0) break;
101
- positions.push(idx);
102
- pos = idx + 1;
103
- }
104
- return positions;
105
- }
106
-
107
- function readJsonStr(buf, pos) {
108
- let str = '', i = pos;
109
- while (i < buf.length) {
110
- const b = buf[i];
111
- if (b === 0x22) return { str, end: i };
112
- if (b === 0x5C) {
113
- i++;
114
- if (i >= buf.length) break;
115
- const esc = buf[i];
116
- if (esc === 0x75 && i + 4 < buf.length) {
117
- const hex = buf.slice(i + 1, i + 5).toString('ascii');
118
- if (/^[0-9a-fA-F]{4}$/.test(hex)) { str += String.fromCharCode(parseInt(hex, 16)); i += 5; continue; }
119
- }
120
- str += String.fromCharCode(esc);
121
- } else if (b >= 0x20 && b <= 0x7E) {
122
- str += String.fromCharCode(b);
123
- } else if ((b & 0xE0) === 0xC0 && i + 1 < buf.length && (buf[i+1] & 0xC0) === 0x80) {
124
- str += String.fromCodePoint(((b & 0x1F) << 6) | (buf[i+1] & 0x3F)); i += 2; continue;
125
- } else if ((b & 0xF0) === 0xE0 && i + 2 < buf.length && (buf[i+1] & 0xC0) === 0x80 && (buf[i+2] & 0xC0) === 0x80) {
126
- str += String.fromCodePoint(((b & 0x0F) << 12) | ((buf[i+1] & 0x3F) << 6) | (buf[i+2] & 0x3F)); i += 3; continue;
127
- } else break;
128
- i++;
129
- }
130
- return { str, end: i };
131
- }
132
-
133
- function findBufVal(buf, key, fromPos, maxDist) {
134
- const keyBuf = Buffer.from('"' + key + '":"');
135
- const idx = buf.indexOf(keyBuf, fromPos);
136
- if (idx < 0 || idx > fromPos + (maxDist || 400)) return null;
137
- return readJsonStr(buf, idx + keyBuf.length);
138
- }
139
-
140
- const FOLDER_MARKER_BUF = Buffer.from('"folder":[');
141
-
142
- // Cinemar inserts garbage: 4 hex chars + '&' every ~4000 chars into the base64 string.
143
- // Must split on '&', strip the 4 trailing hex chars from each chunk, decode separately, concat.
144
- function decodeCinemarFile(fileValue) {
145
- const w3sPos = fileValue.indexOf('W3s');
146
- if (w3sPos < 0) return null;
147
- const raw = fileValue.substring(w3sPos);
148
- const chunks = raw.split('&');
149
- const buffers = [];
150
- for (let i = 0; i < chunks.length; i++) {
151
- let chunk = chunks[i];
152
- if (i < chunks.length - 1) chunk = chunk.slice(0, -4); // strip 4 hex garbage chars
153
- const clean = chunk.replace(/[^A-Za-z0-9+/=]/g, '');
154
- if (clean.length > 0) {
155
- const padded = clean + '='.repeat((4 - clean.length % 4) % 4);
156
- try { buffers.push(Buffer.from(padded, 'base64')); } catch(e) {}
157
- }
158
- }
159
- if (!buffers.length) return null;
160
- return Buffer.concat(buffers);
161
- }
162
-
163
- function normUrl(f) { return f ? (f.startsWith('//') ? 'https:' + f : f) : ''; }
164
-
165
- function parseSubs(subtitle) {
166
- const subs = [];
167
- if (!subtitle) return subs;
168
- subtitle.split(',').forEach(part => {
169
- const sm = part.match(/^\[([^\]]+)\](\/\/.+|https?:\/\/.+)/);
170
- if (sm) subs.push({ label: sm[1], url: normUrl(sm[2]) });
171
- });
172
- return subs;
173
- }
174
-
175
- function parseCinemarBase64(html) {
176
- const fileMatch = html.match(/"file":"([^"]+)"/);
177
- if (!fileMatch) return null;
178
- const buf = decodeCinemarFile(fileMatch[1]);
179
- if (!buf || buf.length < 20) return null;
180
-
181
- const isSerial = buf.indexOf(FOLDER_MARKER_BUF) >= 0;
182
-
183
- if (!isSerial) {
184
- const items = [];
185
- findAllInBuf(buf, Buffer.from('"src_id"')).forEach(pos => {
186
- const t = findBufVal(buf, 'title', pos, 300);
187
- const f = findBufVal(buf, 'file', pos, 5000); // dlink field can be very long
188
- const s = findBufVal(buf, 'subtitle', pos, 6000);
189
- if (!f) return;
190
- const url = normUrl(f.str.replace(/\\\//g, '/'));
191
- if (!url || !url.includes('cinemap')) return; // must be a real stream URL
192
- const title = t ? t.str : 'Unknown';
193
- if (!items.find(i => i.title === title)) items.push({ title, file: url, subtitle: s ? s.str.replace(/\\\//g, '/') : '' });
194
- });
195
- return items.length ? items : null;
196
- }
197
-
198
- // Serial: find all episode IDs (sXXeYY) and group by season
199
- const epIdPrefix = Buffer.from('"id":"s');
200
- const allEpPositions = [];
201
- findAllInBuf(buf, epIdPrefix).forEach(pos => {
202
- let i = pos + epIdPrefix.length;
203
- while (i < buf.length && buf[i] >= 0x30 && buf[i] <= 0x39) i++;
204
- if (buf[i] !== 0x65) return;
205
- i++;
206
- while (i < buf.length && buf[i] >= 0x30 && buf[i] <= 0x39) i++;
207
- if (buf[i] !== 0x22) return;
208
- const fullId = buf.slice(pos + 6, i).toString('ascii');
209
- const seasonMatch = fullId.match(/^(s\d+)e(\d+)$/);
210
- if (!seasonMatch) return;
211
- const folderIdx = buf.indexOf(FOLDER_MARKER_BUF, pos);
212
- if (folderIdx < 0 || folderIdx > pos + 2000) return;
213
- const t = findBufVal(buf, 'title', pos, 200);
214
- allEpPositions.push({ id: fullId, seasonId: seasonMatch[1], epNum: parseInt(seasonMatch[2], 10), title: t ? t.str : ('Серия ' + seasonMatch[2]), pos });
215
- });
216
-
217
- const seasonMap = {};
218
- allEpPositions.forEach(ep => {
219
- if (!seasonMap[ep.seasonId]) seasonMap[ep.seasonId] = [];
220
- if (!seasonMap[ep.seasonId].find(e => e.id === ep.id)) seasonMap[ep.seasonId].push(ep);
221
- });
222
- const seasonIds = Object.keys(seasonMap).sort((a, b) => parseInt(a.substring(1)) - parseInt(b.substring(1)));
223
- if (!seasonIds.length) return null;
224
-
225
- return seasonIds.map(seasonId => {
226
- const eps = seasonMap[seasonId].sort((a, b) => a.epNum - b.epNum);
227
- const episodesWithVoices = eps.map((ep, ei) => {
228
- const nextEpPos = ei + 1 < eps.length ? eps[ei + 1].pos : buf.length;
229
- const eBuf = buf.slice(ep.pos, nextEpPos);
230
- const voices = [];
231
- findAllInBuf(eBuf, Buffer.from('"src_id"')).forEach(vpos => {
232
- const t = findBufVal(eBuf, 'title', vpos, 300);
233
- const f = findBufVal(eBuf, 'file', vpos, 2000);
234
- const s = findBufVal(eBuf, 'subtitle', vpos, 3000);
235
- if (!f) return;
236
- const url = normUrl(f.str.replace(/\\\//g, '/'));
237
- if (!url || !url.includes('.m3u8')) return;
238
- const title = t ? t.str : 'Unknown';
239
- if (!voices.find(v => v.title === title)) voices.push({ title, file: url, subtitle: s ? s.str.replace(/\\\//g, '/') : '' });
240
- });
241
- return { id: ep.id, title: ep.title, folder: voices };
242
- });
243
- return { id: seasonId, title: 'Сезон ' + parseInt(seasonId.substring(1)), folder: episodesWithVoices };
244
- });
245
- }
246
-
247
- // ── Multi-fetch helpers ───────────────────────────────────────────────────────
248
-
249
- function parseEpisodesFromHtml(html) {
250
- const fileMatch = html.match(/"file":"([^"]+)"/);
251
- if (!fileMatch) return {};
252
- const buf = decodeCinemarFile(fileMatch[1]);
253
- if (!buf || buf.length < 20) return {};
254
- if (buf.indexOf(FOLDER_MARKER_BUF) < 0) return {};
255
-
256
- const epIdPrefix = Buffer.from('"id":"s');
257
- const episodes = {};
258
- findAllInBuf(buf, epIdPrefix).forEach(pos => {
259
- let i = pos + epIdPrefix.length;
260
- let seasonNum = '';
261
- while (i < buf.length && buf[i] >= 0x30 && buf[i] <= 0x39) { seasonNum += String.fromCharCode(buf[i]); i++; }
262
- if (buf[i] !== 0x65) return;
263
- i++;
264
- let epNum = '';
265
- while (i < buf.length && buf[i] >= 0x30 && buf[i] <= 0x39) { epNum += String.fromCharCode(buf[i]); i++; }
266
- if (buf[i] !== 0x22) return;
267
-
268
- const fullId = 's' + seasonNum + 'e' + epNum;
269
- const seasonId = 's' + seasonNum;
270
- const t = findBufVal(buf, 'title', pos, 200);
271
- const title = t ? t.str : ('Серия ' + epNum);
272
-
273
- const nextEpPos = buf.indexOf(epIdPrefix, pos + 1);
274
- const endPos = nextEpPos > 0 ? Math.min(nextEpPos, pos + 5000) : pos + 5000;
275
- const eBuf = buf.slice(pos, endPos);
276
- const voices = [];
277
- findAllInBuf(eBuf, Buffer.from('"src_id"')).forEach(vpos => {
278
- const vt = findBufVal(eBuf, 'title', vpos, 300);
279
- const f = findBufVal(eBuf, 'file', vpos, 2000);
280
- const s = findBufVal(eBuf, 'subtitle', vpos, 3000);
281
- if (!f) return;
282
- const url = normUrl(f.str.replace(/\\\//g, '/'));
283
- if (!url || !url.includes('.m3u8')) return;
284
- const vtitle = vt ? vt.str : 'Unknown';
285
- if (!voices.find(v => v.title === vtitle)) voices.push({ title: vtitle, file: url, subtitle: s ? s.str.replace(/\\\//g, '/') : '' });
286
- });
287
-
288
- if (!episodes[fullId] || voices.length > episodes[fullId].voices.length)
289
- episodes[fullId] = { id: fullId, seasonId, seasonNum: parseInt(seasonNum), epNum: parseInt(epNum), title, voices };
290
- });
291
- return episodes;
292
- }
293
-
294
- function buildSerialDataFromMerged(mergedEpisodes) {
295
- const seasonMap = {};
296
- Object.values(mergedEpisodes).forEach(ep => {
297
- if (!seasonMap[ep.seasonId]) seasonMap[ep.seasonId] = [];
298
- seasonMap[ep.seasonId].push(ep);
299
- });
300
- const seasonIds = Object.keys(seasonMap).sort((a, b) => parseInt(a.substring(1)) - parseInt(b.substring(1)));
301
- const seasons = [], episodes = {}, voicesMap = {};
302
- seasonIds.forEach(sid => {
303
- const eps = seasonMap[sid].sort((a, b) => a.epNum - b.epNum);
304
- seasons.push({ id: sid, title: 'Сезон ' + parseInt(sid.substring(1)) });
305
- episodes[sid] = [];
306
- voicesMap[sid] = {};
307
- eps.forEach(ep => {
308
- episodes[sid].push({ id: ep.id, title: ep.title });
309
- voicesMap[sid][ep.id] = ep.voices.map(v => ({ label: v.title, url: normUrl(v.file), subtitles: parseSubs(v.subtitle) }));
310
- });
311
- });
312
- return { seasons, episodes, voices: voicesMap };
313
- }
314
-
315
- function parseCinemar(embedHtml) {
316
- let voices = [], masterUrl = null, serialData = null, contentType = 'movie';
317
- const rawItems = parseCinemarBase64(embedHtml);
318
- if (rawItems && rawItems.length) {
319
- const first = rawItems[0];
320
- if (first.folder && first.folder.length && first.folder[0] && first.folder[0].folder) {
321
- contentType = 'serial';
322
- const seasons = [], episodes = {}, voicesMap = {};
323
- rawItems.forEach((season, si) => {
324
- const sid = season.id || String(si + 1);
325
- seasons.push({ id: sid, title: season.title || ('Сезон ' + (si + 1)) });
326
- episodes[sid] = [];
327
- voicesMap[sid] = {};
328
- (season.folder || []).forEach((ep, ei) => {
329
- const eid = ep.id || String(ei + 1);
330
- episodes[sid].push({ id: eid, title: ep.title || ('Серия ' + (ei + 1)) });
331
- voicesMap[sid][eid] = (ep.folder || []).map(v => ({ label: v.title || 'Unknown', url: normUrl(v.file || ''), subtitles: parseSubs(v.subtitle) })).filter(v => v.url);
332
- });
333
- });
334
- serialData = { seasons, episodes, voices: voicesMap };
335
- const fs = seasons[0];
336
- if (fs && episodes[fs.id] && episodes[fs.id][0]) {
337
- const fv = voicesMap[fs.id][episodes[fs.id][0].id];
338
- if (fv && fv[0]) masterUrl = fv[0].url;
339
- }
340
- } else if (first.folder) {
341
- contentType = 'serial';
342
- const seasons = [], episodes = {}, voicesMap = {};
343
- rawItems.forEach((season, si) => {
344
- const sid = season.id || String(si + 1);
345
- seasons.push({ id: sid, title: season.title || ('Сезон ' + (si + 1)) });
346
- episodes[sid] = [];
347
- voicesMap[sid] = {};
348
- (season.folder || []).forEach((ep, ei) => {
349
- const eid = ep.id || String(ei + 1);
350
- episodes[sid].push({ id: eid, title: ep.title || ('Серия ' + (ei + 1)) });
351
- const u = normUrl(ep.file || '');
352
- voicesMap[sid][eid] = u ? [{ label: ep.title || 'Unknown', url: u, subtitles: parseSubs(ep.subtitle) }] : [];
353
- });
354
- });
355
- serialData = { seasons, episodes, voices: voicesMap };
356
- const fs = seasons[0];
357
- if (fs && episodes[fs.id] && episodes[fs.id][0]) {
358
- const fv = voicesMap[fs.id][episodes[fs.id][0].id];
359
- if (fv && fv[0]) masterUrl = fv[0].url;
360
- }
361
- } else {
362
- contentType = 'movie';
363
- voices = rawItems.map(item => ({ label: item.title || 'Unknown', url: normUrl(item.file || ''), subtitles: parseSubs(item.subtitle) })).filter(v => v.url);
364
- if (voices.length) masterUrl = voices[0].url;
365
- }
366
- }
367
- if (!masterUrl) {
368
- const fm = embedHtml.match(/["'](https?:\/\/[^"']*cinemap[^"']*\.m3u8[^"']*)['"]/);
369
- if (fm) masterUrl = fm[1];
370
- }
371
- return { contentType, voices, masterUrl, serialData };
372
- }
373
-
374
- // ── HLS proxy ─────────────────────────────────────────────────────────────────
375
-
376
- function handleHls(req, res) {
377
- const { query } = parseQuery(req.url);
378
- const targetUrl = query.url;
379
- if (!targetUrl) { res.writeHead(400, { 'Access-Control-Allow-Origin': '*' }); res.end('no url'); return; }
380
-
381
- function doRequest(reqUrl, redirectCount) {
382
- if (redirectCount > 5) { res.writeHead(500, { 'Access-Control-Allow-Origin': '*' }); res.end('too many redirects'); return; }
383
- let pu;
384
- try { pu = new URL(reqUrl); } catch(e) { res.writeHead(400); res.end('bad url'); return; }
385
- const mod = pu.protocol === 'https:' ? https : http;
386
- const isObrut = pu.hostname.includes('obrut') || pu.hostname.includes('superdupercdn');
387
- const isCinemap = pu.hostname.includes('cinemap');
388
- const isAlloha = pu.hostname.includes('stream-balancer') || pu.hostname.includes('streamalloha') || pu.hostname.includes('allo-');
389
- const opts = {
390
- hostname: pu.hostname,
391
- port: pu.port || (pu.protocol === 'https:' ? 443 : 80),
392
- path: pu.pathname + pu.search,
393
- headers: {
394
- 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36',
395
- 'accept': '*/*',
396
- 'origin': isCinemap ? 'https://uakinogo.io' : isObrut ? 'https://kinojump.com' : isAlloha ? 'https://streamalloha.live' : 'https://streamalloha.live',
397
- 'referer': isCinemap ? 'https://uakinogo.io/' : isObrut ? 'https://kinojump.com/' : isAlloha ? 'https://streamalloha.live/' : 'https://streamalloha.live/',
398
- },
399
- };
400
- if (req.headers['range']) opts.headers['range'] = req.headers['range'];
401
- const pr = mod.request(opts, upstream => {
402
- // Follow redirects
403
- if (upstream.statusCode >= 300 && upstream.statusCode < 400 && upstream.headers.location) {
404
- upstream.resume();
405
- let loc = upstream.headers.location;
406
- if (!loc.startsWith('http')) loc = pu.origin + loc;
407
- return doRequest(loc, redirectCount + 1);
408
- }
409
- const ct = upstream.headers['content-type'] || '';
410
- const isM3u8 = ct.includes('mpegurl') || (reqUrl.includes('.m3u8') || reqUrl.includes(':hls:manifest')) && !reqUrl.includes(':hls:seg-');
411
- const rh = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': '*' };
412
- if (isM3u8) {
413
- rh['Content-Type'] = 'application/vnd.apple.mpegurl';
414
- res.writeHead(upstream.statusCode, rh);
415
- let body = '';
416
- upstream.setEncoding('utf8');
417
- upstream.on('data', c => { body += c; });
418
- upstream.on('end', () => {
419
- const base = reqUrl.substring(0, reqUrl.lastIndexOf('/') + 1);
420
- const serverBase = 'https://' + (req.headers.host || 'localhost:' + PORT);
421
- function rewriteUrl(rel) {
422
- let a = rel.trim();
423
- if (!a) return a;
424
- if (a.startsWith('//')) a = 'https:' + a;
425
- else if (!a.startsWith('http')) a = base + a;
426
- return serverBase + '/hls?url=' + encodeURIComponent(a);
427
- }
428
- res.end(body.split('\n').map(line => {
429
- const tr = line.trim();
430
- if (!tr) return line;
431
- if (tr.startsWith('#')) return line.replace(/URI="([^"]+)"/g, (m, uri) => `URI="${rewriteUrl(uri)}"`);
432
- return rewriteUrl(tr);
433
- }).join('\n'));
434
- });
435
- } else {
436
- rh['Content-Type'] = ct || 'video/mp2t';
437
- if (upstream.headers['content-length']) rh['Content-Length'] = upstream.headers['content-length'];
438
- if (upstream.headers['content-range']) rh['Content-Range'] = upstream.headers['content-range'];
439
- res.writeHead(upstream.statusCode, rh);
440
- upstream.pipe(res);
441
- }
442
- });
443
- pr.on('error', e => { res.writeHead(500); res.end(e.message); });
444
- pr.end();
445
- }
446
-
447
- doRequest(targetUrl, 0);
448
- }
449
-
450
- // ── Server ────────────────────────────────────────────────────────────────────
451
-
452
- const server = http.createServer(async (req, res) => {
453
- const { pathname, query } = parseQuery(req.url);
454
-
455
- if (req.method === 'OPTIONS') {
456
- res.writeHead(204, { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', 'Access-Control-Allow-Headers': '*' });
457
- res.end();
458
- return;
459
- }
460
-
461
- if (pathname === '/health') { jsonResp(res, { ok: true, time: new Date().toISOString() }); return; }
462
-
463
- // Show outbound IP of this server
464
- if (pathname === '/debug/ip') {
465
- fetchRaw('https://api.ipify.org?format=json', { 'user-agent': 'curl/7.0' })
466
- .then(d => { jsonResp(res, { ok: true, ip: JSON.parse(d).ip }); })
467
- .catch(e => { jsonResp(res, { ok: false, error: e.message }); });
468
- return;
469
- }
470
-
471
- if (pathname === '/debug/platform') {
472
- const fs = require('fs');
473
- const chromiumPaths = [
474
- process.env.PUPPETEER_EXECUTABLE_PATH,
475
- '/usr/bin/chromium',
476
- '/usr/bin/chromium-browser',
477
- '/usr/bin/google-chrome'
478
- ].filter(Boolean);
479
- const available = chromiumPaths.filter(p => { try { return fs.existsSync(p); } catch(e) { return false; } });
480
- jsonResp(res, {
481
- platform: process.platform,
482
- node: process.version,
483
- puppeteer_path: process.env.PUPPETEER_EXECUTABLE_PATH || 'not set',
484
- chromium_found: available,
485
- alloha_available: typeof getStreams === 'function' && getStreams.toString().includes('getBrowser') ? 'yes' : 'fallback'
486
- });
487
- return;
488
- }
489
- if (pathname === '/hls') { handleHls(req, res); return; }
490
-
491
- if (pathname === '/srt2vtt') {
492
- const corsH = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': '*', 'Content-Type': 'text/vtt; charset=utf-8' };
493
- const subUrl = query.url;
494
- if (!subUrl) { res.writeHead(400, corsH); res.end('no url'); return; }
495
- fetchRaw(subUrl, { 'user-agent': 'Mozilla/5.0 Chrome/120' }).then(body => {
496
- const vtt = 'WEBVTT\n\n' + body.replace(/\r\n/g, '\n').replace(/\r/g, '\n').replace(/(\d{2}:\d{2}:\d{2}),(\d{3})/g, '$1.$2');
497
- res.writeHead(200, corsH); res.end(vtt);
498
- }).catch(e => { res.writeHead(500, corsH); res.end(e.message); });
499
- return;
500
- }
501
-
502
- if (pathname === '/alloha/player-info' && req.method === 'POST') {
503
- try {
504
- const params = JSON.parse(await readBody(req));
505
- const { token_movie, partner_token } = params;
506
- if (!token_movie) { jsonResp(res, { ok: false, error: 'token_movie required' }, 400); return; }
507
- const token = partner_token || ALLOHA_TOKEN;
508
- const playerUrl = `https://${ALLOHA_HOST}/?token_movie=${token_movie}&token=${encodeURIComponent(token)}`;
509
- console.log(`[server] /alloha/player-info token_movie=${token_movie}`);
510
- const html = await fetchRaw(playerUrl, { 'user-agent': 'Mozilla/5.0 Chrome/120', 'referer': 'https://kinokrad.my/' });
511
- const nkMatch = html.match(/name="viewporti"\s+content="([^"]+)"/);
512
- const nk = nkMatch ? nkMatch[1] : null;
513
- if (!nk) { jsonResp(res, { ok: false, error: 'nk_not_found' }); return; }
514
- let fileId = null;
515
- const flMatch = html.match(/"active"\s*:\s*\{[^}]*?"id"\s*:\s*(\d+)/);
516
- if (flMatch) fileId = flMatch[1];
517
- if (!fileId) { const m = html.match(/"id"\s*:\s*(\d+)/); if (m) fileId = m[1]; }
518
- let fileList = null;
519
- const flRaw = html.match(/fileList\s*=\s*JSON\.parse\('([\s\S]*?)'\)/);
520
- if (flRaw) { try { fileList = JSON.parse(flRaw[1]); } catch(e) {} }
521
- const appBundle = (html.match(/src="(\/build\/app\.[a-f0-9]+\.js)"/) || [])[1] || null;
522
- const runtimeBundle = (html.match(/src="(\/build\/runtime\.[a-f0-9]+\.js)"/) || [])[1] || null;
523
- const bundle539 = (html.match(/src="(\/build\/539\.[a-f0-9]+\.js)"/) || [])[1] || null;
524
- jsonResp(res, {
525
- ok: true, nk, file_id: fileId, player_url: playerUrl, file_list: fileList,
526
- bundle_app: appBundle ? `https://${ALLOHA_HOST}${appBundle}` : null,
527
- bundle_runtime: runtimeBundle ? `https://${ALLOHA_HOST}${runtimeBundle}` : null,
528
- bundle_539: bundle539 ? `https://${ALLOHA_HOST}${bundle539}` : null,
529
- });
530
- } catch(e) {
531
- console.log('[server] player-info ERROR:', e.message);
532
- jsonResp(res, { ok: false, error: e.message }, 500);
533
- }
534
- return;
535
- }
536
-
537
- if (pathname === '/alloha/streams' && req.method === 'POST') {
538
- try {
539
- const params = JSON.parse(await readBody(req));
540
- const { token_movie, partner_token, referer } = params;
541
- if (!token_movie) { jsonResp(res, { ok: false, error: 'token_movie required' }, 400); return; }
542
- console.log(`[server] /alloha/streams token_movie=${token_movie}`);
543
- const result = await getStreams({ token_movie, partner_token, referer });
544
- const serverBase = 'https://' + (req.headers.host || 'localhost:' + PORT);
545
- if (result.hlsSource) {
546
- result.hlsSource = result.hlsSource.map(src => {
547
- if (src.quality) {
548
- const newQ = {};
549
- for (const [q, u] of Object.entries(src.quality)) {
550
- newQ[q] = u.split(' or ').map(raw => {
551
- const t = raw.trim();
552
- const full = t.startsWith('//') ? 'https:' + t : t;
553
- return serverBase + '/hls?url=' + encodeURIComponent(full);
554
- }).join(' or ');
555
- }
556
- src.quality = newQ;
557
- }
558
- return src;
559
- });
560
- }
561
- jsonResp(res, result);
562
- } catch(e) {
563
- console.log('[server] streams ERROR:', e.message);
564
- jsonResp(res, { ok: false, error: e.message }, 500);
565
- }
566
- return;
567
- }
568
-
569
- if (pathname === '/uakinogo/search') {
570
- const q = query.q || '';
571
- if (!q) { jsonResp(res, { ok: false, error: 'no query' }, 400); return; }
572
- const searchUrl = 'https://uakinogo.io/index.php?do=search&subaction=search&story=' + encodeURIComponent(q);
573
- fetchRaw(searchUrl, { 'user-agent': 'Mozilla/5.0 Chrome/120', 'referer': 'https://uakinogo.io/' }).then(html => {
574
- const results = [];
575
- const re = /href="(https?:\/\/uakinogo\.io\/(?:filmy|serialy|multserialy|multfilmy|zarubezhnye-serialy|russkie-serialy|anime-serialy|anime|novinki)\/(\d+)-([^"]+)\.html)"/g;
576
- let m;
577
- while ((m = re.exec(html)) !== null) {
578
- if (!results.find(r => r.id === m[2])) results.push({ url: m[1], id: m[2], slug: m[3] });
579
- }
580
- jsonResp(res, { ok: true, results: results.slice(0, 10) });
581
- }).catch(e => jsonResp(res, { ok: false, error: e.message }, 500));
582
- return;
583
- }
584
-
585
- if (pathname === '/uakinogo/embed') {
586
- const pageUrl = query.url;
587
- if (!pageUrl) { jsonResp(res, { ok: false, error: 'no url' }, 400); return; }
588
- fetchRaw(pageUrl, { 'user-agent': 'Mozilla/5.0 Chrome/120', 'referer': 'https://uakinogo.io/' }).then(html => {
589
- const m = html.match(/"embedUrl"\s*:\s*"(https:\/\/cinemar\.cc\/embed\/[^"]+)"/);
590
- jsonResp(res, { ok: true, embed_url: m ? m[1] : null });
591
- }).catch(e => jsonResp(res, { ok: false, error: e.message }, 500));
592
- return;
593
- }
594
-
595
- // ── /turbo/search?q=TITLE ─────────────────────────────────────────────────
596
- if (pathname === '/turbo/search') {
597
- const q = query.q || '';
598
- if (!q) { jsonResp(res, { ok: false, error: 'no query' }, 400); return; }
599
- turboSearch(q)
600
- .then(results => jsonResp(res, { ok: true, results }))
601
- .catch(e => jsonResp(res, { ok: false, error: e.message }, 500));
602
- return;
603
- }
604
-
605
- // ── /turbo/search-embed?q=TITLE ──────────────────────────────────────────
606
- if (pathname === '/turbo/search-embed') {
607
- const q = query.q || '';
608
- if (!q) { jsonResp(res, { ok: false, error: 'no query' }, 400); return; }
609
- const { parseObrutEmbed, buildSerialFromEntries, extractMovieVoices, getKinojumpHtml } = require('./turbo');
610
- (async () => {
611
- // Step 1: search kinojump
612
- const results = await turboSearch(q);
613
- if (!results.length) throw new Error('not found on kinojump');
614
- const pageUrl = results[0].url;
615
- console.log('[turbo/search-embed] page:', pageUrl);
616
-
617
- // Step 2: get embed URL — plain HTTP first, Puppeteer fallback
618
- const { getBrowser } = require('./alloha');
619
- const browser = await getBrowser();
620
- const pageHtml = await getKinojumpHtml(pageUrl, browser).catch(e => {
621
- console.log('[turbo/search-embed] getKinojumpHtml error:', e.message);
622
- return '';
623
- });
624
- const em = pageHtml.match(/(?:https?:\/\/)?(?:([a-z0-9]+)\.)?obrut\.show\/embed\/([A-Za-z0-9]+)\/content\/([A-Za-z0-9]+)/);
625
- if (!em) throw new Error('obrut embed URL not found');
626
- const subdomain = em[1] ? em[1] + '.obrut.show' : '49372504.obrut.show';
627
- const embedUrl = 'https://' + subdomain + '/embed/' + em[2] + '/content/' + em[3];
628
- console.log('[turbo/search-embed] embed URL:', embedUrl);
629
- // Step 3: parse embed (retry until enough entries)
630
- const result = await parseObrutEmbed(embedUrl);
631
- if (!result) throw new Error('failed to parse obrut embed');
632
-
633
- if (result.entries.length > 0) {
634
- const serial = buildSerialFromEntries(result.entries);
635
- jsonResp(res, { ok: true, embed_url: embedUrl, content_type: 'serial', serial });
636
- } else if (result.movieVoices.length > 0) {
637
- jsonResp(res, { ok: true, embed_url: embedUrl, content_type: 'movie', voices: result.movieVoices });
638
- } else {
639
- throw new Error('no data found in obrut embed');
640
- }
641
- })().catch(e => { console.log('[turbo/search-embed] error:', e.message); jsonResp(res, { ok: false, error: e.message }, 500); });
642
- return;
643
- }
644
-
645
- // ── /turbo/stream?url=PAGE_URL ────────────────────────────────────────────
646
- if (pathname === '/turbo/stream') {
647
- const pageUrl = query.url;
648
- if (!pageUrl) { jsonResp(res, { ok: false, error: 'no url' }, 400); return; }
649
- getTurboStream(pageUrl)
650
- .then(data => jsonResp(res, { ok: true, ...data }))
651
- .catch(e => { console.log('[turbo] error:', e.message); jsonResp(res, { ok: false, error: e.message }, 500); });
652
- return;
653
- }
654
-
655
- // ── /turbo/proxy-embed?url=OBRUT_EMBED_URL ───────────────────────────────
656
- // Raw HTTP proxy for obrut embed — adds correct Referer header
657
- // Used by browser clients that can't set Referer (file:/// origin)
658
- if (pathname === '/turbo/proxy-embed') {
659
- const embedUrl = query.url;
660
- if (!embedUrl || !embedUrl.includes('obrut.show')) {
661
- jsonResp(res, { ok: false, error: 'invalid url' }, 400); return;
662
- }
663
- (async () => {
664
- const html = await fetchRaw(embedUrl, {
665
- 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
666
- 'referer': 'https://kinojump.com/',
667
- 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
668
- 'accept-language': 'ru-RU,ru;q=0.9,en;q=0.8',
669
- 'accept-encoding': 'identity',
670
- });
671
- console.log('[turbo/proxy-embed] len:', html.length, 'hasPlayer:', html.includes('new Player('));
672
- res.writeHead(200, {
673
- 'Access-Control-Allow-Origin': '*',
674
- 'Access-Control-Allow-Headers': '*',
675
- 'Content-Type': 'text/html; charset=utf-8',
676
- });
677
- res.end(html);
678
- })().catch(e => {
679
- console.log('[turbo/proxy-embed] error:', e.message);
680
- res.writeHead(500, { 'Access-Control-Allow-Origin': '*' });
681
- res.end('error: ' + e.message);
682
- });
683
- return;
684
- }
685
-
686
- // ── /turbo/embed?url=OBRUT_EMBED_URL ─────────────────────────────────────
687
- // Parse obrut embed page directly (no Puppeteer needed)
688
- if (pathname === '/turbo/embed') {
689
- const embedUrl = query.url;
690
- if (!embedUrl) { jsonResp(res, { ok: false, error: 'no url' }, 400); return; }
691
- const { parseObrutEmbed, buildSerialFromEntries } = require('./turbo');
692
- parseObrutEmbed(embedUrl)
693
- .then(result => {
694
- if (!result || (result.entries.length === 0 && result.movieVoices.length === 0)) {
695
- jsonResp(res, { ok: false, error: 'failed to parse embed' }); return;
696
- }
697
- if (result.entries.length > 0) {
698
- const serial = buildSerialFromEntries(result.entries);
699
- jsonResp(res, { ok: true, embed_url: embedUrl, content_type: 'serial', serial, entry_count: result.entries.length });
700
- } else {
701
- jsonResp(res, { ok: true, embed_url: embedUrl, content_type: 'movie', voices: result.movieVoices });
702
- }
703
- })
704
- .catch(e => { console.log('[turbo/embed] error:', e.message); jsonResp(res, { ok: false, error: e.message }, 500); });
705
- return;
706
- }
707
-
708
- // ── /uakinogo/stream?url=PAGE_URL ─────────────────────────────────────────
709
- if (pathname === '/uakinogo/stream') {
710
- const pageUrl = query.url;
711
- if (!pageUrl) { jsonResp(res, { ok: false, error: 'no url' }, 400); return; }
712
- getCinemarStream(pageUrl)
713
- .then(data => jsonResp(res, { ok: true, ...data }))
714
- .catch(e => { console.log('[cinemar] error:', e.message); jsonResp(res, { ok: false, error: e.message }, 500); });
715
- return;
716
- }
717
-
718
- // ── /zetflix/streams?kp=KP_ID&s=SEASON ──────────────────────────────────
719
- if (pathname === '/zetflix/streams') {
720
- const kpId = query.kp;
721
- const season = parseInt(query.s || '0', 10);
722
- if (!kpId) { jsonResp(res, { ok: false, error: 'no kp' }, 400); return; }
723
- (async () => {
724
- try {
725
- const { getBrowser } = require('./alloha');
726
- console.log(`[zetflix] kp=${kpId} s=${season}`);
727
- const html = await getZetflixHtml(kpId, season, getBrowser);
728
- const parsed = parseZetflixHtml(html);
729
- if (!parsed) { jsonResp(res, { ok: false, error: 'not_found' }); return; }
730
- const streams = buildZetflixStreams(parsed);
731
- jsonResp(res, { ok: true, ...streams });
732
- } catch(e) {
733
- console.log('[zetflix] error:', e.message);
734
- jsonResp(res, { ok: false, error: e.message }, 500);
735
- }
736
- })();
737
- return;
738
- }
739
-
740
- // ── /puppeteer/fetch?url=URL — fetch URL via Puppeteer (bypasses Cloudflare JS challenge)
741
- if (pathname === '/puppeteer/fetch') {
742
- const targetUrl = query.url;
743
- if (!targetUrl) { jsonResp(res, { ok: false, error: 'no url' }, 400); return; }
744
- (async () => {
745
- let browser;
746
- try {
747
- const { getBrowser } = require('./alloha');
748
- browser = await getBrowser();
749
- const page = await browser.newPage();
750
- await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');
751
- await page.setExtraHTTPHeaders({ 'Accept-Language': 'ru-RU,ru;q=0.9,en;q=0.8' });
752
- // Navigate and wait for JS challenge to complete
753
- await page.goto(targetUrl, { waitUntil: 'networkidle2', timeout: 20000 });
754
- // Extra wait for fingerprint redirect
755
- await new Promise(r => setTimeout(r, 2500));
756
- const html = await page.content();
757
- const finalUrl = page.url();
758
- await page.close();
759
- jsonResp(res, { ok: true, html, url: finalUrl });
760
- } catch(e) {
761
- console.log('[puppeteer/fetch] error:', e.message);
762
- jsonResp(res, { ok: false, error: e.message }, 500);
763
- }
764
- })();
765
- return;
766
- }
767
-
768
- jsonResp(res, { ok: false, error: 'not found' }, 404);
769
- });
770
-
771
- server.listen(PORT, () => console.log(`[server] Alloha+Cinemar proxy on port ${PORT}`));
772
-
773
- process.on('SIGTERM', async () => { await closeBrowser(); server.close(); });
774
- process.on('SIGINT', async () => { await closeBrowser(); process.exit(0); });