OGLingLing commited on
Commit
6ba084a
·
verified ·
1 Parent(s): 0c6bcf5

Upload 6 files

Browse files
Files changed (6) hide show
  1. Dockerfile +36 -0
  2. index.js +81 -0
  3. package.json +35 -0
  4. scraper_controller.js +71 -0
  5. scraper_routes.js +8 -0
  6. scraper_service.js +375 -0
Dockerfile ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 1. Usar la imagen de Playwright (correcta)
2
+ FROM mcr.microsoft.com/playwright:v1.43.0-jammy
3
+
4
+ # 2. Configurar el puerto de Hugging Face (Crítico)
5
+ # Hugging Face espera que tu app escuche en el puerto 7860 por defecto
6
+ ENV PORT=7860
7
+ EXPOSE 7860
8
+
9
+ # 3. Permisos de usuario
10
+ # Hugging Face corre los contenedores con un usuario con UID 1000.
11
+ # Es mejor crear un usuario para evitar problemas de permisos.
12
+ RUN useradd -m -u 1000 user
13
+ USER user
14
+ ENV HOME=/home/user \
15
+ PATH=/home/user/.local/bin:$PATH
16
+
17
+ WORKDIR $HOME/app
18
+
19
+ # 4. Instalación de dependencias
20
+ # Copiamos como root, instalamos y luego cambiamos dueño
21
+ USER root
22
+ COPY --chown=user:user package*.json ./
23
+ RUN npm install
24
+
25
+ # Reinstalamos chromium para asegurar compatibilidad con la versión de la imagen
26
+ RUN npx playwright install chromium
27
+
28
+ COPY --chown=user:user . .
29
+ RUN npx prisma generate
30
+
31
+ # Volvemos al usuario sin privilegios para ejecutar la app
32
+ USER user
33
+
34
+ # 5. Ejecución
35
+ # Asegúrate de que index.js escuche en 0.0.0.0 y no solo en localhost
36
+ CMD ["node", "index.js"]
index.js ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ require('dotenv').config();
2
+ const express = require('express');
3
+ const cors = require('cors');
4
+
5
+ const app = express();
6
+
7
+ // --- IMPORTACIÓN DE RUTAS ---
8
+ const movieRoutes = require('./routes/movie_routes');
9
+ const authRoutes = require('./routes/auth_routes');
10
+ const adminRoutes = require('./routes/admin_routes');
11
+ const authController = require('./controllers/auth_controller');
12
+ const watchlistRoutes = require('./routes/watchlist_routes');
13
+ const scraperRoutes = require('./routes/scraper_routes');
14
+ const streamRoutes = require('./routes/stream_routes');
15
+
16
+ // 1. CONFIGURACIÓN DE MIDDLEWARES
17
+ // CORRECCIÓN: Añadimos la URL de Hugging Face y Render para que puedan hablar entre ellos
18
+ const allowedOrigins = [
19
+ 'https://oglingling.github.io',
20
+ 'http://localhost:3000',
21
+ 'http://localhost:5173',
22
+ /\.hf\.space$/, // Permite cualquier subdominio de Hugging Face
23
+ /\.onrender\.com$/ // Permite cualquier subdominio de Render
24
+ ];
25
+
26
+ app.use(cors({
27
+ origin: (origin, callback) => {
28
+ // Permitir peticiones sin origen (como apps móviles o Postman)
29
+ if (!origin) return callback(null, true);
30
+
31
+ const isAllowed = allowedOrigins.some(allowed => {
32
+ if (allowed instanceof RegExp) return allowed.test(origin);
33
+ return allowed === origin;
34
+ });
35
+
36
+ if (isAllowed) return callback(null, true);
37
+ return callback(new Error('Origen no permitido por CORS'));
38
+ },
39
+ methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
40
+ allowedHeaders: ['Content-Type', 'Accept', 'Authorization', 'x-api-key'] // Añadimos x-api-key por seguridad
41
+ }));
42
+
43
+ app.use(express.json());
44
+ app.use(express.static('public'));
45
+
46
+ // 2. DEFINICIÓN DE PUNTOS DE ENTRADA
47
+ app.use('/api/movies', movieRoutes);
48
+ app.use('/api/auth', authRoutes);
49
+ app.use('/api/admin', adminRoutes);
50
+ app.use('/api/watchlist', watchlistRoutes);
51
+
52
+ // Prefijos para scraper y stream
53
+ app.use('/api', scraperRoutes);
54
+ app.use('/api', streamRoutes);
55
+
56
+ app.get('/api/users', authController.getUserByEmail);
57
+
58
+ // 3. RUTA DE SALUD (Crítica para Hugging Face)
59
+ app.get('/', (req, res) => {
60
+ res.status(200).send('Servidor MOVIEWIND Activo 🚀');
61
+ });
62
+
63
+ app.get('/health', (req, res) => res.status(200).send('OK'));
64
+
65
+ // Middleware 404
66
+ app.use((req, res) => {
67
+ console.log('❌ 404 Capturado en la ruta:', req.originalUrl);
68
+ res.status(404).json({ error: 'Not Found', path: req.originalUrl });
69
+ });
70
+
71
+ // 4. ARRANQUE DEL SERVIDOR
72
+ // CORRECCIÓN: Hugging Face requiere el puerto 7860 para mostrarse como "Running"
73
+ const PORT = process.env.PORT || 7860;
74
+
75
+ const server = app.listen(PORT, '0.0.0.0', () => {
76
+ console.log(`🚀 Scraper activo en puerto ${PORT}`);
77
+ console.log(`🔗 Endpoint de extracción listo en: /api/extract`);
78
+ });
79
+
80
+ // Aumentamos el timeout porque el scraping puede ser lento
81
+ server.timeout = 120000;
package.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "backend",
3
+ "version": "1.0.0",
4
+ "description": "",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "start": "npx prisma generate && node index.js",
8
+ "build": "npm install && npx prisma generate",
9
+ "postinstall": "npx prisma generate"
10
+ },
11
+ "keywords": [],
12
+ "author": "",
13
+ "license": "ISC",
14
+ "type": "commonjs",
15
+ "dependencies": {
16
+ "@consumet/extensions": "^1.8.8",
17
+ "@prisma/client": "^6.19.2",
18
+ "axios": "^1.14.0",
19
+ "cors": "^2.8.6",
20
+ "express": "^5.2.1",
21
+ "nodemailer": "^8.0.2",
22
+ "resend": "^6.9.4"
23
+ },
24
+ "devDependencies": {
25
+ "@types/cors": "^2.8.19",
26
+ "@types/express": "^5.0.6",
27
+ "@types/node": "^25.5.0",
28
+ "prisma": "^6.19.2",
29
+ "ts-node": "^10.9.2",
30
+ "typescript": "^5.9.3"
31
+ },
32
+ "prisma": {
33
+ "seed": "ts-node prisma/seed.ts"
34
+ }
35
+ }
scraper_controller.js ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const VideoScraper = require('../services/scraper_service');
2
+
3
+ const INVALID_STRINGS = new Set(['null', 'undefined', 'none', 'nan', '']);
4
+
5
+ const firstValue = (...values) => {
6
+ return values.find((item) => {
7
+ if (item === undefined || item === null) return false;
8
+ const s = String(item).toLowerCase().trim();
9
+ return s !== '' && !INVALID_STRINGS.has(s);
10
+ });
11
+ };
12
+
13
+ const isDirectStreamUrl = (url) => {
14
+ const lower = String(url || '').toLowerCase();
15
+ return lower.includes('.m3u8') ||
16
+ lower.includes('.mp4') ||
17
+ lower.includes('googlevideo.com/videoplayback');
18
+ };
19
+
20
+ const extractLink = async (req, res) => {
21
+ const tmdbId = firstValue(req.query.tmdbId, req.query.id, req.body?.tmdbId);
22
+ const url = firstValue(req.query.url, req.body?.url);
23
+ const type = (firstValue(req.query.type, req.body?.type) || 'movie').toLowerCase();
24
+ const season = parseInt(firstValue(req.query.season, req.body?.season)) || 1;
25
+ const episode = parseInt(firstValue(req.query.episode, req.body?.episode)) || 1;
26
+
27
+ console.log(`[extract] Iniciando para ID: ${tmdbId || 'direct-url'}`);
28
+
29
+ if (!tmdbId && !url) {
30
+ return res.status(400).json({ success: false, candidates: [], error: 'No ID or URL' });
31
+ }
32
+
33
+ try {
34
+ const result = await VideoScraper.extractStreamUrl({ url, tmdbId, type, season, episode });
35
+
36
+ const resultCandidates = Array.isArray(result.candidates)
37
+ ? result.candidates
38
+ : Array.isArray(result.results)
39
+ ? result.results.map(r => r.url).filter(Boolean)
40
+ : [];
41
+
42
+ const candidateStrings = [...new Set(resultCandidates)].filter(isDirectStreamUrl);
43
+ const candidateObjects = candidateStrings.map((candidateUrl, index) => ({
44
+ url: candidateUrl,
45
+ name: `Server Mirror ${index + 1}`,
46
+ quality: 'Auto'
47
+ }));
48
+
49
+ const finalResponse = {
50
+ success: true,
51
+ candidates: candidateStrings, // Formato string []
52
+ sources: candidateObjects, // Formato objeto {}
53
+ urls: candidateStrings, // Backup común
54
+ tmdbId: result.tmdbId || tmdbId || null,
55
+ tmdb_id: tmdbId ? parseInt(tmdbId) : null, // Lo enviamos como string y como int por si acaso
56
+ type: type,
57
+ searchMode: Boolean(result.searchMode),
58
+ clientSideCheck: Boolean(result.clientSideCheck),
59
+ debug_info: result.debug_info || null
60
+ };
61
+
62
+ console.log('[extract] SUCCESS: Enviando respuesta universal');
63
+ return res.status(200).json(finalResponse);
64
+
65
+ } catch (error) {
66
+ console.error('[extract] ERROR:', error.message);
67
+ return res.status(500).json({ success: false, candidates: [], error: error.message });
68
+ }
69
+ };
70
+
71
+ module.exports = { extractLink };
scraper_routes.js ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ const express = require('express');
2
+ const router = express.Router();
3
+ const scraperController = require('../controllers/scraper_controller');
4
+
5
+ router.get('/extract', scraperController.extractLink);
6
+ router.post('/extract', scraperController.extractLink);
7
+
8
+ module.exports = router;
scraper_service.js ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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;