OGLingLing commited on
Commit
e5fab9f
·
verified ·
1 Parent(s): e141564

Delete scraper_service.js

Browse files
Files changed (1) hide show
  1. scraper_service.js +0 -375
scraper_service.js DELETED
@@ -1,375 +0,0 @@
1
- const axios = require('axios');
2
-
3
- // ---------------- CACHE LRU ----------------
4
- const CACHE_MAX_SIZE = 200;
5
- const CACHE_TTL_MS = 12 * 60 * 1000;
6
- const cache = new Map();
7
-
8
- function cacheSet(key, value) {
9
- if (cache.has(key)) cache.delete(key);
10
- cache.set(key, { value, expiresAt: Date.now() + CACHE_TTL_MS });
11
- if (cache.size > CACHE_MAX_SIZE) {
12
- const oldestKey = cache.keys().next().value;
13
- cache.delete(oldestKey);
14
- }
15
- }
16
-
17
- function cacheGet(key) {
18
- if (!cache.has(key)) return null;
19
- const entry = cache.get(key);
20
- if (!entry || entry.expiresAt <= Date.now()) {
21
- cache.delete(key);
22
- return null;
23
- }
24
- cache.delete(key);
25
- cache.set(key, entry);
26
- return entry.value;
27
- }
28
-
29
- // ---------------- UTILS ----------------
30
- const INVALID_STRINGS = new Set(['null', 'undefined', 'none', 'nan', '']);
31
- const MOBILE_USER_AGENT =
32
- 'Mozilla/5.0 (Linux; Android 10; Mobile) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Mobile Safari/537.36';
33
-
34
- const AD_HOST_HINTS = [
35
- 'doubleclick',
36
- 'googlesyndication',
37
- 'google-analytics',
38
- 'adservice',
39
- 'adsterra',
40
- 'popads',
41
- 'propeller',
42
- 'taboola',
43
- 'onclick',
44
- 'tracking'
45
- ];
46
-
47
- const sanitize = (v) => {
48
- if (v === undefined || v === null) return undefined;
49
- const s = String(v).trim();
50
- return INVALID_STRINGS.has(s.toLowerCase()) ? undefined : s;
51
- };
52
-
53
- const isValidUrl = (s) => /^https?:\/\//i.test(String(s || ''));
54
- const isNumericId = (s) => /^\d+$/.test(String(s || ''));
55
-
56
- const isDirectStreamUrl = (url) => {
57
- const lower = String(url || '').toLowerCase();
58
- return lower.includes('.m3u8') ||
59
- lower.includes('.mp4') ||
60
- lower.includes('googlevideo.com/videoplayback');
61
- };
62
-
63
- const unique = (items) => [...new Set(items.filter(Boolean))];
64
-
65
- function buildHeaders(targetUrl, refererUrl) {
66
- const origin = refererUrl && isValidUrl(refererUrl)
67
- ? new URL(refererUrl).origin
68
- : new URL(targetUrl).origin;
69
-
70
- return {
71
- 'User-Agent': MOBILE_USER_AGENT,
72
- 'Referer': `${origin}/`,
73
- 'Origin': origin,
74
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
75
- 'Accept-Language': 'es-ES,es;q=0.9,en-US;q=0.8,en;q=0.7'
76
- };
77
- }
78
-
79
- function decodeEscapedText(value) {
80
- return String(value || '')
81
- .replace(/\\u002F/g, '/')
82
- .replace(/\\\//g, '/')
83
- .replace(/&amp;/g, '&')
84
- .replace(/%3A/gi, ':')
85
- .replace(/%2F/gi, '/')
86
- .replace(/%3F/gi, '?')
87
- .replace(/%3D/gi, '=')
88
- .replace(/%26/gi, '&');
89
- }
90
-
91
- function extractDirectUrlsFromText(text, baseUrl) {
92
- const decoded = decodeEscapedText(text);
93
- const urls = [];
94
- const absoluteUrlPattern = /https?:\/\/[^\s"'<>\\]+?(?:\.m3u8|\.mp4|videoplayback)[^\s"'<>\\]*/gi;
95
- const relativeUrlPattern = /(?:src|file|url|source)\s*[:=]\s*["']([^"']+?(?:\.m3u8|\.mp4)[^"']*)["']/gi;
96
-
97
- for (const match of decoded.matchAll(absoluteUrlPattern)) {
98
- urls.push(match[0]);
99
- }
100
-
101
- for (const match of decoded.matchAll(relativeUrlPattern)) {
102
- try {
103
- urls.push(new URL(match[1], baseUrl).toString());
104
- } catch (_) {
105
- // ignore malformed relative candidates
106
- }
107
- }
108
-
109
- return unique(urls.map((url) => url.replace(/[),;]+$/g, ''))).filter(isDirectStreamUrl);
110
- }
111
-
112
- function isAdOrNoiseUrl(url) {
113
- const lower = String(url || '').toLowerCase();
114
- return AD_HOST_HINTS.some((hint) => lower.includes(hint));
115
- }
116
-
117
- async function fetchHtml(url) {
118
- const response = await axios.get(url, {
119
- headers: buildHeaders(url),
120
- timeout: 12000,
121
- maxRedirects: 5,
122
- responseType: 'text',
123
- validateStatus: (status) => status >= 200 && status < 500
124
- });
125
-
126
- if (response.status >= 400) {
127
- throw new Error(`HTTP ${response.status}`);
128
- }
129
-
130
- return String(response.data || '');
131
- }
132
-
133
- let browserStackPromise = null;
134
-
135
- async function getBrowserStack() {
136
- if (browserStackPromise) return browserStackPromise;
137
-
138
- browserStackPromise = (async () => {
139
- const puppeteerExtra = require('puppeteer-extra');
140
- const StealthPlugin = require('puppeteer-extra-plugin-stealth');
141
- const puppeteer = require('puppeteer');
142
-
143
- puppeteerExtra.use(StealthPlugin());
144
-
145
- return { puppeteer: puppeteerExtra, executablePath: puppeteer.executablePath() };
146
- })();
147
-
148
- return browserStackPromise;
149
- }
150
-
151
- async function extractWithBrowser(embedUrl) {
152
- const found = [];
153
- let browser;
154
-
155
- try {
156
- const { puppeteer, executablePath } = await getBrowserStack();
157
- browser = await puppeteer.launch({
158
- headless: 'new',
159
- executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || executablePath,
160
- args: [
161
- '--no-sandbox',
162
- '--disable-setuid-sandbox',
163
- '--disable-dev-shm-usage',
164
- '--autoplay-policy=no-user-gesture-required',
165
- '--disable-features=IsolateOrigins,site-per-process'
166
- ]
167
- });
168
-
169
- const page = await browser.newPage();
170
- await page.setUserAgent(MOBILE_USER_AGENT);
171
- await page.setViewport({ width: 412, height: 915, isMobile: true, hasTouch: true });
172
- await page.setExtraHTTPHeaders(buildHeaders(embedUrl));
173
- await page.setRequestInterception(true);
174
-
175
- page.on('request', (request) => {
176
- const url = request.url();
177
- const type = request.resourceType();
178
-
179
- if (isDirectStreamUrl(url)) {
180
- found.push(url);
181
- }
182
-
183
- if (['image', 'font'].includes(type) || isAdOrNoiseUrl(url)) {
184
- request.abort().catch(() => {});
185
- return;
186
- }
187
-
188
- request.continue().catch(() => {});
189
- });
190
-
191
- page.on('response', async (response) => {
192
- const url = response.url();
193
- const headers = response.headers();
194
- const contentType = String(headers['content-type'] || '').toLowerCase();
195
-
196
- if (isDirectStreamUrl(url) || contentType.includes('mpegurl') || contentType.includes('video')) {
197
- found.push(url);
198
- }
199
-
200
- if (contentType.includes('javascript') || contentType.includes('json') || contentType.includes('text')) {
201
- try {
202
- const body = await response.text();
203
- found.push(...extractDirectUrlsFromText(body, url));
204
- } catch (_) {
205
- // Some responses are not readable after interception; safe to skip.
206
- }
207
- }
208
- });
209
-
210
- page.on('popup', async (popup) => {
211
- try {
212
- await popup.close();
213
- } catch (_) {
214
- // ignore popup close races
215
- }
216
- });
217
-
218
- await page.goto(embedUrl, { waitUntil: 'domcontentloaded', timeout: 18000 });
219
-
220
- for (let i = 0; i < 4; i += 1) {
221
- await page.evaluate(() => {
222
- const selectors = ['video', 'button', '[role="button"]', '.play', '#play'];
223
- for (const selector of selectors) {
224
- const element = document.querySelector(selector);
225
- if (element) {
226
- element.click();
227
- break;
228
- }
229
- }
230
- }).catch(() => {});
231
- await new Promise((resolve) => setTimeout(resolve, 1800));
232
- if (found.some(isDirectStreamUrl)) break;
233
- }
234
- } catch (error) {
235
- return { urls: unique(found).filter(isDirectStreamUrl), error: error.message };
236
- } finally {
237
- if (browser) {
238
- await browser.close().catch(() => {});
239
- }
240
- }
241
-
242
- return { urls: unique(found).filter(isDirectStreamUrl), error: null };
243
- }
244
-
245
- // ---------------- CLASS ----------------
246
- class VideoScraper {
247
- static normalizeMediaType(value) {
248
- const raw = String(value || '').toLowerCase();
249
- return raw.includes('tv') || raw.includes('serie') ? 'tv' : 'movie';
250
- }
251
-
252
- static normalizeRequest(source) {
253
- const raw = source || {};
254
- const url = sanitize(raw.url);
255
- const tmdbId = sanitize(raw.tmdbId) ?? sanitize(raw.id);
256
- const type = this.normalizeMediaType(raw.type);
257
- const isTV = type === 'tv';
258
- const season = Number(raw.season) || 1;
259
- const episode = Number(raw.episode) || 1;
260
-
261
- if (url && isValidUrl(url)) {
262
- return { scenario: 'url', searchMode: false, url, tmdbId, type, isTV, season, episode };
263
- }
264
- if (tmdbId && isNumericId(tmdbId)) {
265
- return { scenario: 'tmdb', searchMode: true, url: null, tmdbId, type, isTV, season, episode };
266
- }
267
- return { scenario: 'invalid' };
268
- }
269
-
270
- static buildCandidates(n) {
271
- const { tmdbId, isTV, season, episode } = n;
272
- const path = isTV ? `tv/${tmdbId}/${season}/${episode}` : `movie/${tmdbId}`;
273
-
274
- return [
275
- `https://vidsrc.me/embed/${path}`,
276
- `https://vidsrc.to/embed/${path}`,
277
- `https://vidsrc.xyz/embed/${path}`,
278
- `https://vidsrc.win/embed/${path}`,
279
- `https://player.vidsrc.co/embed/${path}`,
280
- isTV
281
- ? `https://www.2embed.cc/embedtv/${tmdbId}&s=${season}&e=${episode}`
282
- : `https://www.2embed.cc/embed/${tmdbId}`
283
- ];
284
- }
285
-
286
- static async extractFromEmbed(embedUrl, options = {}) {
287
- const useBrowser = options.useBrowser !== false;
288
- const debug = { embedUrl, staticCount: 0, browserCount: 0, errors: [] };
289
- const urls = [];
290
-
291
- try {
292
- const html = await fetchHtml(embedUrl);
293
- const staticUrls = extractDirectUrlsFromText(html, embedUrl);
294
- debug.staticCount = staticUrls.length;
295
- urls.push(...staticUrls);
296
- } catch (error) {
297
- debug.errors.push(`static:${error.message}`);
298
- }
299
-
300
- if (urls.length === 0 && useBrowser) {
301
- const browserResult = await extractWithBrowser(embedUrl);
302
- debug.browserCount = browserResult.urls.length;
303
- if (browserResult.error) debug.errors.push(`browser:${browserResult.error}`);
304
- urls.push(...browserResult.urls);
305
- }
306
-
307
- return { urls: unique(urls).filter(isDirectStreamUrl), debug };
308
- }
309
-
310
- static async createPayload(source) {
311
- const n = this.normalizeRequest(source);
312
-
313
- if (n.scenario === 'invalid') {
314
- return { success: false, candidates: [], debug_info: { reason: 'invalid_params' } };
315
- }
316
-
317
- const cacheKey = n.scenario === 'url'
318
- ? `stream-url-${n.url}`
319
- : `stream-${n.type}-${n.tmdbId}-${n.season}-${n.episode}`;
320
- const cached = cacheGet(cacheKey);
321
- if (cached) return cached;
322
-
323
- if (n.scenario === 'url') {
324
- const payload = {
325
- success: isDirectStreamUrl(n.url),
326
- candidates: isDirectStreamUrl(n.url) ? [n.url] : [],
327
- tmdbId: n.tmdbId,
328
- type: n.type,
329
- searchMode: false,
330
- clientSideCheck: false,
331
- debug_info: { source: 'direct_url' }
332
- };
333
- if (payload.success) cacheSet(cacheKey, payload);
334
- return payload;
335
- }
336
-
337
- const embeds = this.buildCandidates(n);
338
- const candidates = [];
339
- const debug = [];
340
- const browserLimit = Number(process.env.SCRAPER_BROWSER_LIMIT) || 3;
341
-
342
- for (const [index, embedUrl] of embeds.entries()) {
343
- const result = await this.extractFromEmbed(embedUrl, {
344
- useBrowser: index < browserLimit
345
- });
346
- debug.push(result.debug);
347
- candidates.push(...result.urls);
348
- if (candidates.length >= 3) break;
349
- }
350
-
351
- const streamCandidates = unique(candidates).filter(isDirectStreamUrl);
352
- const payload = {
353
- success: streamCandidates.length > 0,
354
- candidates: streamCandidates,
355
- tmdbId: n.tmdbId,
356
- type: n.type,
357
- searchMode: true,
358
- clientSideCheck: false,
359
- debug_info: {
360
- embedsChecked: debug.length,
361
- streamsFound: streamCandidates.length,
362
- providers: debug
363
- }
364
- };
365
-
366
- cacheSet(cacheKey, payload);
367
- return payload;
368
- }
369
-
370
- static async extractStreamUrl(source) {
371
- return await this.createPayload(source);
372
- }
373
- }
374
-
375
- module.exports = VideoScraper;