Spaces:
Build error
Build error
Upload 13 files
Browse files- controllers/auth_controller.js +158 -0
- controllers/movie_controller.js +139 -0
- controllers/scraper_controller.js +71 -0
- controllers/stream_controller.js +171 -0
- controllers/watchlist_controller.js +67 -0
- routes/admin_routes.js +256 -0
- routes/auth_routes.js +13 -0
- routes/movie_routes.js +8 -0
- routes/scraper_routes.js +8 -0
- routes/stream_routes.js +11 -0
- routes/watchlist_routes.js +9 -0
- services/scraper_service.js +375 -0
- services/stream_session_store.js +49 -0
controllers/auth_controller.js
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const { PrismaClient } = require('@prisma/client');
|
| 2 |
+
const prisma = new PrismaClient();
|
| 3 |
+
|
| 4 |
+
// --- FUNCIÓN PRIVADA: ENVÍO DE EMAIL VÍA BREVO ---
|
| 5 |
+
async function sendEmail(to, subject, htmlContent) {
|
| 6 |
+
const response = await fetch('https://api.brevo.com/v3/smtp/email', {
|
| 7 |
+
method: 'POST',
|
| 8 |
+
headers: {
|
| 9 |
+
'accept': 'application/json',
|
| 10 |
+
'api-key': process.env.BREVO_API_KEY,
|
| 11 |
+
'content-type': 'application/json'
|
| 12 |
+
},
|
| 13 |
+
body: JSON.stringify({
|
| 14 |
+
sender: { name: 'MovieWind', email: 'moviewindsupport@gmail.com' },
|
| 15 |
+
to: [{ email: to }],
|
| 16 |
+
subject: subject,
|
| 17 |
+
htmlContent: htmlContent
|
| 18 |
+
})
|
| 19 |
+
});
|
| 20 |
+
|
| 21 |
+
if (!response.ok) {
|
| 22 |
+
const errorData = await response.json();
|
| 23 |
+
throw new Error(errorData.message || 'Error al enviar email');
|
| 24 |
+
}
|
| 25 |
+
return response.json();
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
// --- 1. ENVIAR OTP ---
|
| 29 |
+
exports.sendOtp = async (req, res) => {
|
| 30 |
+
const { email } = req.body;
|
| 31 |
+
if (!email) return res.status(400).json({ error: "Email requerido" });
|
| 32 |
+
|
| 33 |
+
const otp = Math.floor(1000 + Math.random() * 9000).toString();
|
| 34 |
+
const normalizedEmail = email.toLowerCase().trim();
|
| 35 |
+
|
| 36 |
+
try {
|
| 37 |
+
await prisma.user.upsert({
|
| 38 |
+
where: { email: normalizedEmail },
|
| 39 |
+
update: { pin: otp, pinExpiresAt: new Date(Date.now() + 15 * 60000) },
|
| 40 |
+
create: { email: normalizedEmail, pin: otp, pinExpiresAt: new Date(Date.now() + 15 * 60000), name: "Usuario Nuevo" }
|
| 41 |
+
});
|
| 42 |
+
|
| 43 |
+
await sendEmail(normalizedEmail, "Tu codigo de acceso - MovieWind", `
|
| 44 |
+
<div style="font-family: 'Segoe UI', Arial, sans-serif; max-width: 500px; margin: 0 auto; background: #1a1a2e; border-radius: 16px; overflow: hidden; padding: 20px;">
|
| 45 |
+
<h1 style="color: #E50914; text-align: center;">MovieWind</h1>
|
| 46 |
+
<h2 style="color: white; text-align: center;">Codigo: ${otp}</h2>
|
| 47 |
+
</div>
|
| 48 |
+
`);
|
| 49 |
+
res.json({ success: true });
|
| 50 |
+
} catch (error) {
|
| 51 |
+
console.error("Error en sendOtp:", error);
|
| 52 |
+
res.status(500).json({ error: "Error al enviar el correo" });
|
| 53 |
+
}
|
| 54 |
+
};
|
| 55 |
+
|
| 56 |
+
// --- 2. VERIFICAR OTP ---
|
| 57 |
+
exports.verifyOtp = async (req, res) => {
|
| 58 |
+
const { email, code } = req.body;
|
| 59 |
+
if (!email || !code) return res.status(400).json({ error: "Email y código requeridos" });
|
| 60 |
+
|
| 61 |
+
const normalizedEmail = email.toLowerCase().trim();
|
| 62 |
+
|
| 63 |
+
try {
|
| 64 |
+
const user = await prisma.user.findUnique({ where: { email: normalizedEmail } });
|
| 65 |
+
|
| 66 |
+
if (user && user.pin === code && new Date() < user.pinExpiresAt) {
|
| 67 |
+
const updatedUser = await prisma.user.update({
|
| 68 |
+
where: { email: normalizedEmail },
|
| 69 |
+
data: { pin: null, pinExpiresAt: null, isVerified: true }
|
| 70 |
+
});
|
| 71 |
+
res.json(updatedUser);
|
| 72 |
+
} else {
|
| 73 |
+
res.status(401).json({ error: "Codigo incorrecto o expirado" });
|
| 74 |
+
}
|
| 75 |
+
} catch (error) {
|
| 76 |
+
res.status(500).json({ error: "Error al verificar" });
|
| 77 |
+
}
|
| 78 |
+
};
|
| 79 |
+
|
| 80 |
+
// --- 3. OBTENER USUARIO POR EMAIL ---
|
| 81 |
+
exports.getUserByEmail = async (req, res) => {
|
| 82 |
+
const { email } = req.query;
|
| 83 |
+
if (!email) return res.status(400).json({ error: "Email requerido" });
|
| 84 |
+
|
| 85 |
+
try {
|
| 86 |
+
const user = await prisma.user.findUnique({
|
| 87 |
+
where: { email: String(email).toLowerCase().trim() }
|
| 88 |
+
});
|
| 89 |
+
res.json(user || null);
|
| 90 |
+
} catch (error) {
|
| 91 |
+
res.status(500).json({ error: "Error al buscar usuario" });
|
| 92 |
+
}
|
| 93 |
+
};
|
| 94 |
+
|
| 95 |
+
// --- 4. REGISTRO (UPSERT) ---
|
| 96 |
+
exports.register = async (req, res) => {
|
| 97 |
+
const { email, name, password, plan } = req.body;
|
| 98 |
+
if (!email) return res.status(400).json({ error: "Email requerido" });
|
| 99 |
+
|
| 100 |
+
const normalizedEmail = email.toLowerCase().trim();
|
| 101 |
+
let planNormalizado = plan ? plan.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "") : "basico";
|
| 102 |
+
|
| 103 |
+
try {
|
| 104 |
+
const user = await prisma.user.upsert({
|
| 105 |
+
where: { email: normalizedEmail },
|
| 106 |
+
update: { name, plan: planNormalizado },
|
| 107 |
+
create: { email: normalizedEmail, name, password: password || "123456", plan: planNormalizado, isVerified: true }
|
| 108 |
+
});
|
| 109 |
+
|
| 110 |
+
await sendEmail(normalizedEmail, "Bienvenido a MovieWind!", `<h2>Bienvenido, ${name}!</h2>`);
|
| 111 |
+
res.status(201).json(user);
|
| 112 |
+
} catch (error) {
|
| 113 |
+
res.status(500).json({ error: "Error en registro" });
|
| 114 |
+
}
|
| 115 |
+
};
|
| 116 |
+
|
| 117 |
+
// --- 5. ACTUALIZAR PERFIL (CORREGIDO PARA EVITAR ERROR 500) ---
|
| 118 |
+
exports.updateUser = async (req, res) => {
|
| 119 |
+
try {
|
| 120 |
+
const { id } = req.params;
|
| 121 |
+
const { name, profilePic, plan } = req.body;
|
| 122 |
+
|
| 123 |
+
// Log para que veas en Railway qué ID está llegando
|
| 124 |
+
console.log("Intentando actualizar usuario con ID:", id);
|
| 125 |
+
|
| 126 |
+
// VALIDACIÓN: Si el ID es nulo o inválido, respondemos 400 (Bad Request) en vez de 500
|
| 127 |
+
if (!id || id === "null" || id === "undefined") {
|
| 128 |
+
console.error("Error: Se recibió un ID nulo o inválido desde el frontend");
|
| 129 |
+
return res.status(400).json({ error: "ID de usuario inválido o no proporcionado" });
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
const userUpdated = await prisma.user.update({
|
| 133 |
+
where: { id: id },
|
| 134 |
+
data: {
|
| 135 |
+
...(name && { name }),
|
| 136 |
+
...(profilePic && { profilePic }),
|
| 137 |
+
...(plan && { plan }),
|
| 138 |
+
},
|
| 139 |
+
});
|
| 140 |
+
|
| 141 |
+
console.log("Usuario actualizado correctamente:", userUpdated.id);
|
| 142 |
+
res.json(userUpdated);
|
| 143 |
+
|
| 144 |
+
} catch (error) {
|
| 145 |
+
console.error("Error detallado en el servidor:", error.message);
|
| 146 |
+
|
| 147 |
+
// Si el ID no existe en la base de datos, Prisma lanza este error
|
| 148 |
+
if (error.code === 'P2025') {
|
| 149 |
+
return res.status(404).json({ error: "El usuario no existe en la base de datos" });
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
// Cualquier otro error interno
|
| 153 |
+
res.status(500).json({
|
| 154 |
+
error: "Error interno al actualizar el perfil",
|
| 155 |
+
detalle: error.message
|
| 156 |
+
});
|
| 157 |
+
}
|
| 158 |
+
};
|
controllers/movie_controller.js
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const axios = require('axios');
|
| 2 |
+
const { PrismaClient } = require('@prisma/client');
|
| 3 |
+
const prisma = new PrismaClient();
|
| 4 |
+
|
| 5 |
+
// Configuración de TMDB
|
| 6 |
+
const TMDB_API_KEY = 'd8a00b94f5c00821e497b569fec9a61f';
|
| 7 |
+
const TMDB_BASE_URL = 'https://api.themoviedb.org/3';
|
| 8 |
+
|
| 9 |
+
/**
|
| 10 |
+
* Enriquece los datos básicos de la base de datos con información
|
| 11 |
+
* en tiempo real de TMDB (Posters, Backdrops, Ratings actualizados).
|
| 12 |
+
*/
|
| 13 |
+
async function enrichMovieData(contentItem) {
|
| 14 |
+
const identifier = contentItem.tmdbId || contentItem.imdbId;
|
| 15 |
+
if (!identifier) return contentItem;
|
| 16 |
+
|
| 17 |
+
try {
|
| 18 |
+
let apiUrl;
|
| 19 |
+
if (contentItem.tmdbId) {
|
| 20 |
+
// Se usa el campo 'type' para diferenciar entre serie (tv) o película (movie)
|
| 21 |
+
const path = contentItem.type === 'tv' ? 'tv' : 'movie';
|
| 22 |
+
apiUrl = `${TMDB_BASE_URL}/${path}/${contentItem.tmdbId}?api_key=${TMDB_API_KEY}&language=es-ES`;
|
| 23 |
+
} else {
|
| 24 |
+
apiUrl = `${TMDB_BASE_URL}/find/${contentItem.imdbId}?api_key=${TMDB_API_KEY}&external_source=imdb_id&language=es-ES`;
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
const response = await axios.get(apiUrl);
|
| 28 |
+
const data = contentItem.tmdbId
|
| 29 |
+
? response.data
|
| 30 |
+
: (response.data.movie_results[0] || response.data.tv_results[0]);
|
| 31 |
+
|
| 32 |
+
if (data) {
|
| 33 |
+
return {
|
| 34 |
+
...contentItem, // Mantiene seasons y episodes traídos por Prisma
|
| 35 |
+
title: data.title || data.name || contentItem.title,
|
| 36 |
+
description: data.overview || contentItem.description,
|
| 37 |
+
imageUrl: data.poster_path ? `https://image.tmdb.org/t/p/w500${data.poster_path}` : contentItem.imageUrl,
|
| 38 |
+
backdropUrl: data.backdrop_path ? `https://image.tmdb.org/t/p/original${data.backdrop_path}` : contentItem.backdropUrl,
|
| 39 |
+
rating: data.vote_average ? parseFloat(data.vote_average.toFixed(1)) : (contentItem.rating || 0.0),
|
| 40 |
+
};
|
| 41 |
+
}
|
| 42 |
+
} catch (error) {
|
| 43 |
+
console.error(`[TMDB Enriquecimiento Fallido] ID ${identifier}:`, error.message);
|
| 44 |
+
}
|
| 45 |
+
return contentItem;
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
/**
|
| 49 |
+
* Obtiene el catálogo de contenidos (películas y series) con sus respectivas
|
| 50 |
+
* temporadas y episodios anidados.
|
| 51 |
+
*/
|
| 52 |
+
exports.getMovies = async (req, res) => {
|
| 53 |
+
const { type } = req.query;
|
| 54 |
+
try {
|
| 55 |
+
let whereCondition = {};
|
| 56 |
+
|
| 57 |
+
if (type) {
|
| 58 |
+
const normalizedType = type.toLowerCase().trim().replace('s', '');
|
| 59 |
+
whereCondition = {
|
| 60 |
+
type: {
|
| 61 |
+
contains: normalizedType,
|
| 62 |
+
mode: 'insensitive'
|
| 63 |
+
}
|
| 64 |
+
};
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
// --- CAMBIO CLAVE: prisma.content en lugar de prisma.movie ---
|
| 68 |
+
const contents = await prisma.content.findMany({
|
| 69 |
+
where: whereCondition,
|
| 70 |
+
include: {
|
| 71 |
+
seasons: {
|
| 72 |
+
include: {
|
| 73 |
+
episodes: {
|
| 74 |
+
orderBy: {
|
| 75 |
+
episodeNumber: 'asc'
|
| 76 |
+
}
|
| 77 |
+
}
|
| 78 |
+
},
|
| 79 |
+
orderBy: {
|
| 80 |
+
seasonNumber: 'asc'
|
| 81 |
+
}
|
| 82 |
+
}
|
| 83 |
+
},
|
| 84 |
+
orderBy: { createdAt: 'desc' }
|
| 85 |
+
});
|
| 86 |
+
|
| 87 |
+
// Enriquecemos cada item de contenido con datos de TMDB de forma paralela
|
| 88 |
+
const enrichedContent = await Promise.all(
|
| 89 |
+
contents.map(item => enrichMovieData(item))
|
| 90 |
+
);
|
| 91 |
+
|
| 92 |
+
res.json(enrichedContent);
|
| 93 |
+
} catch (error) {
|
| 94 |
+
console.error("Error crítico en GET /api/movies:", error);
|
| 95 |
+
res.status(500).json({
|
| 96 |
+
error: "Error interno al cargar el catálogo",
|
| 97 |
+
details: error.message
|
| 98 |
+
});
|
| 99 |
+
}
|
| 100 |
+
};
|
| 101 |
+
|
| 102 |
+
/**
|
| 103 |
+
* Proxy para el reproductor de video para evitar bloqueos de CORS.
|
| 104 |
+
*/
|
| 105 |
+
exports.proxyStream = async (req, res) => {
|
| 106 |
+
const targetUrl = req.query.url;
|
| 107 |
+
if (!targetUrl) return res.status(400).send("URL de streaming requerida");
|
| 108 |
+
|
| 109 |
+
try {
|
| 110 |
+
const response = await axios.get(targetUrl, {
|
| 111 |
+
headers: {
|
| 112 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
|
| 113 |
+
'Referer': new URL(targetUrl).origin,
|
| 114 |
+
'Origin': new URL(targetUrl).origin
|
| 115 |
+
},
|
| 116 |
+
timeout: 15000
|
| 117 |
+
});
|
| 118 |
+
|
| 119 |
+
res.set('Content-Type', 'text/html');
|
| 120 |
+
let html = response.data;
|
| 121 |
+
const origin = new URL(targetUrl).origin;
|
| 122 |
+
|
| 123 |
+
// Inyectamos la etiqueta <base>
|
| 124 |
+
html = html.replace('<head>', `<head><base href="${origin}/">`);
|
| 125 |
+
|
| 126 |
+
res.send(html);
|
| 127 |
+
|
| 128 |
+
} catch (error) {
|
| 129 |
+
console.error("Error en Proxy Stream:", error.message);
|
| 130 |
+
res.status(200).send(`
|
| 131 |
+
<body style="background:#000;color:#fff;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;font-family:sans-serif;">
|
| 132 |
+
<div style="text-align:center;">
|
| 133 |
+
<p style="font-size: 1.2rem;">El servidor de video no está disponible en este momento.</p>
|
| 134 |
+
<button onclick="window.location.reload()" style="background:#E50914;color:white;border:none;padding:12px 24px;border-radius:4px;cursor:pointer;font-weight:bold;margin-top:10px;">REINTENTAR</button>
|
| 135 |
+
</div>
|
| 136 |
+
</body>
|
| 137 |
+
`);
|
| 138 |
+
}
|
| 139 |
+
};
|
controllers/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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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const axios = require('axios');
|
| 2 |
+
const {
|
| 3 |
+
createStreamSession,
|
| 4 |
+
getStreamSession
|
| 5 |
+
} = require('../services/stream_session_store');
|
| 6 |
+
|
| 7 |
+
const MOBILE_USER_AGENT =
|
| 8 |
+
'Mozilla/5.0 (Linux; Android 10; Mobile) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Mobile Safari/537.36';
|
| 9 |
+
|
| 10 |
+
const isHttpUrl = (value) => /^https?:\/\//i.test(String(value || ''));
|
| 11 |
+
|
| 12 |
+
const encodeUrl = (url) => Buffer.from(url, 'utf8').toString('base64url');
|
| 13 |
+
const decodeUrl = (value) => Buffer.from(value, 'base64url').toString('utf8');
|
| 14 |
+
|
| 15 |
+
function buildHeaders(targetUrl, sourceUrl, customHeaders = {}) {
|
| 16 |
+
const targetOrigin = new URL(targetUrl).origin;
|
| 17 |
+
const sourceOrigin = sourceUrl && isHttpUrl(sourceUrl)
|
| 18 |
+
? new URL(sourceUrl).origin
|
| 19 |
+
: targetOrigin;
|
| 20 |
+
|
| 21 |
+
return {
|
| 22 |
+
'User-Agent': customHeaders['User-Agent'] || customHeaders['user-agent'] || MOBILE_USER_AGENT,
|
| 23 |
+
'Referer': customHeaders.Referer || customHeaders.referer || `${sourceOrigin}/`,
|
| 24 |
+
'Origin': customHeaders.Origin || customHeaders.origin || sourceOrigin,
|
| 25 |
+
'Accept': customHeaders.Accept || customHeaders.accept || '*/*',
|
| 26 |
+
'Accept-Language': customHeaders['Accept-Language'] || 'es-ES,es;q=0.9,en-US;q=0.8,en;q=0.7'
|
| 27 |
+
};
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
function absoluteUrl(baseUrl, maybeRelativeUrl) {
|
| 31 |
+
if (!maybeRelativeUrl || maybeRelativeUrl.startsWith('#')) return maybeRelativeUrl;
|
| 32 |
+
return new URL(maybeRelativeUrl, baseUrl).toString();
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
function rewriteAttributeUris(line, baseUrl, sessionId, req) {
|
| 36 |
+
return line.replace(/URI="([^"]+)"/g, (_, value) => {
|
| 37 |
+
if (value.startsWith('data:') || value.startsWith('skd:')) {
|
| 38 |
+
return `URI="${value}"`;
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
const absolute = absoluteUrl(baseUrl, value);
|
| 42 |
+
const proxyUrl = `${req.protocol}://${req.get('host')}/api/stream/${sessionId}/resource?u=${encodeUrl(absolute)}`;
|
| 43 |
+
return `URI="${proxyUrl}"`;
|
| 44 |
+
});
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
function rewritePlaylist(body, baseUrl, sessionId, req) {
|
| 48 |
+
return body
|
| 49 |
+
.split(/\r?\n/)
|
| 50 |
+
.map((rawLine) => {
|
| 51 |
+
const line = rawLine.trim();
|
| 52 |
+
if (!line) return rawLine;
|
| 53 |
+
|
| 54 |
+
if (line.startsWith('#')) {
|
| 55 |
+
return rewriteAttributeUris(rawLine, baseUrl, sessionId, req);
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
const absolute = absoluteUrl(baseUrl, line);
|
| 59 |
+
return `${req.protocol}://${req.get('host')}/api/stream/${sessionId}/resource?u=${encodeUrl(absolute)}`;
|
| 60 |
+
})
|
| 61 |
+
.join('\n');
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
async function fetchUpstream(url, session, responseType = 'stream') {
|
| 65 |
+
return axios.get(url, {
|
| 66 |
+
responseType,
|
| 67 |
+
timeout: 20000,
|
| 68 |
+
maxRedirects: 5,
|
| 69 |
+
headers: buildHeaders(url, session.sourceUrl, session.headers),
|
| 70 |
+
validateStatus: (status) => status >= 200 && status < 500
|
| 71 |
+
});
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
async function registerStream(req, res) {
|
| 75 |
+
const targetUrl = req.body?.url || req.query?.url;
|
| 76 |
+
const sourceUrl = req.body?.sourceUrl || req.body?.referer || req.query?.sourceUrl || null;
|
| 77 |
+
|
| 78 |
+
if (!isHttpUrl(targetUrl)) {
|
| 79 |
+
return res.status(400).json({ success: false, error: 'URL de stream invalida' });
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
const headers = buildHeaders(targetUrl, sourceUrl, req.body?.headers || {});
|
| 83 |
+
const session = createStreamSession({ targetUrl, sourceUrl, headers });
|
| 84 |
+
const isHls = targetUrl.toLowerCase().includes('.m3u8');
|
| 85 |
+
const streamPath = isHls ? 'master.m3u8' : 'source';
|
| 86 |
+
|
| 87 |
+
return res.json({
|
| 88 |
+
success: true,
|
| 89 |
+
streamId: session.id,
|
| 90 |
+
streamUrl: `${req.protocol}://${req.get('host')}/api/stream/${session.id}/${streamPath}`,
|
| 91 |
+
expiresAt: new Date(session.expiresAt).toISOString()
|
| 92 |
+
});
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
async function getMasterPlaylist(req, res) {
|
| 96 |
+
const session = getStreamSession(req.params.streamId);
|
| 97 |
+
if (!session) {
|
| 98 |
+
return res.status(404).send('Stream session expired');
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
return serveResource(req, res, session.targetUrl, session);
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
async function getSource(req, res) {
|
| 105 |
+
const session = getStreamSession(req.params.streamId);
|
| 106 |
+
if (!session) {
|
| 107 |
+
return res.status(404).send('Stream session expired');
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
return serveResource(req, res, session.targetUrl, session);
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
async function getResource(req, res) {
|
| 114 |
+
const session = getStreamSession(req.params.streamId);
|
| 115 |
+
if (!session) {
|
| 116 |
+
return res.status(404).send('Stream session expired');
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
let targetUrl;
|
| 120 |
+
try {
|
| 121 |
+
targetUrl = decodeUrl(req.query.u);
|
| 122 |
+
} catch (error) {
|
| 123 |
+
return res.status(400).send('Invalid resource URL');
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
if (!isHttpUrl(targetUrl)) {
|
| 127 |
+
return res.status(400).send('Invalid resource URL');
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
return serveResource(req, res, targetUrl, session);
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
async function serveResource(req, res, targetUrl, session) {
|
| 134 |
+
try {
|
| 135 |
+
const upstream = await fetchUpstream(targetUrl, session, 'arraybuffer');
|
| 136 |
+
const contentType = String(upstream.headers['content-type'] || '').toLowerCase();
|
| 137 |
+
const looksLikePlaylist = targetUrl.toLowerCase().includes('.m3u8') ||
|
| 138 |
+
contentType.includes('mpegurl') ||
|
| 139 |
+
contentType.includes('application/vnd.apple.mpegurl');
|
| 140 |
+
|
| 141 |
+
res.set('Access-Control-Allow-Origin', '*');
|
| 142 |
+
res.set('Cache-Control', 'no-store');
|
| 143 |
+
|
| 144 |
+
if (upstream.status >= 400) {
|
| 145 |
+
return res.status(upstream.status).send(upstream.data);
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
if (looksLikePlaylist) {
|
| 149 |
+
const playlist = Buffer.from(upstream.data).toString('utf8');
|
| 150 |
+
const rewritten = rewritePlaylist(playlist, targetUrl, session.id, req);
|
| 151 |
+
res.set('Content-Type', 'application/vnd.apple.mpegurl');
|
| 152 |
+
return res.send(rewritten);
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
if (contentType) {
|
| 156 |
+
res.set('Content-Type', contentType);
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
return res.send(Buffer.from(upstream.data));
|
| 160 |
+
} catch (error) {
|
| 161 |
+
console.error('[stream] Proxy error:', error.message);
|
| 162 |
+
return res.status(502).send('No se pudo obtener el recurso de video');
|
| 163 |
+
}
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
module.exports = {
|
| 167 |
+
registerStream,
|
| 168 |
+
getMasterPlaylist,
|
| 169 |
+
getSource,
|
| 170 |
+
getResource
|
| 171 |
+
};
|
controllers/watchlist_controller.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const { PrismaClient } = require('@prisma/client');
|
| 2 |
+
const prisma = new PrismaClient();
|
| 3 |
+
|
| 4 |
+
const getWatchlist = async (req, res) => {
|
| 5 |
+
const { userId } = req.query;
|
| 6 |
+
if (!userId) return res.status(400).json({ error: "userId requerido" });
|
| 7 |
+
|
| 8 |
+
try {
|
| 9 |
+
const list = await prisma.watchlist.findMany({
|
| 10 |
+
where: { userId: userId },
|
| 11 |
+
include: {
|
| 12 |
+
content: true // Realiza el JOIN con la tabla Content en Neon
|
| 13 |
+
}
|
| 14 |
+
});
|
| 15 |
+
|
| 16 |
+
const formattedList = list.map(item => ({
|
| 17 |
+
// 1. ID INTERNO: Necesario para que el botón de eliminar (X) funcione
|
| 18 |
+
id: item.contentId,
|
| 19 |
+
|
| 20 |
+
// 2. ID DE TMDB: El campo que falta en tu error actual
|
| 21 |
+
// Extraído directamente de la relación con 'Content'
|
| 22 |
+
tmdb_id: item.content?.tmdb_id,
|
| 23 |
+
|
| 24 |
+
// 3. METADATOS: Para mostrar correctamente el poster y título
|
| 25 |
+
title: item.content?.title || "Sin título",
|
| 26 |
+
image: item.content?.image || item.content?.posterPath || "",
|
| 27 |
+
|
| 28 |
+
// 4. TIPO: Importante para que TMDB sepa si buscar 'movie' o 'tv'
|
| 29 |
+
type: item.content?.type || "movie"
|
| 30 |
+
}));
|
| 31 |
+
|
| 32 |
+
res.status(200).json(formattedList);
|
| 33 |
+
} catch (error) {
|
| 34 |
+
// Log para depuración en Railway
|
| 35 |
+
console.error("Error en getWatchlist:", error);
|
| 36 |
+
res.status(500).json({ error: error.message });
|
| 37 |
+
}
|
| 38 |
+
};
|
| 39 |
+
|
| 40 |
+
const toggleWatchlist = async (req, res) => {
|
| 41 |
+
const { userId, contentId } = req.body;
|
| 42 |
+
if (!userId || !contentId) return res.status(400).json({ error: "Datos incompletos" });
|
| 43 |
+
|
| 44 |
+
try {
|
| 45 |
+
const existing = await prisma.watchlist.findFirst({
|
| 46 |
+
where: { userId, contentId: parseInt(contentId) }
|
| 47 |
+
});
|
| 48 |
+
|
| 49 |
+
if (existing) {
|
| 50 |
+
await prisma.watchlist.delete({ where: { id: existing.id } });
|
| 51 |
+
return res.status(200).json({ message: "Eliminado" });
|
| 52 |
+
} else {
|
| 53 |
+
const newItem = await prisma.watchlist.create({
|
| 54 |
+
data: { userId, contentId: parseInt(contentId) }
|
| 55 |
+
});
|
| 56 |
+
return res.status(201).json(newItem);
|
| 57 |
+
}
|
| 58 |
+
} catch (error) {
|
| 59 |
+
res.status(500).json({ error: error.message });
|
| 60 |
+
}
|
| 61 |
+
};
|
| 62 |
+
|
| 63 |
+
// Exportación estilo CommonJS
|
| 64 |
+
module.exports = {
|
| 65 |
+
getWatchlist,
|
| 66 |
+
toggleWatchlist
|
| 67 |
+
};
|
routes/admin_routes.js
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const express = require('express');
|
| 2 |
+
const router = express.Router();
|
| 3 |
+
const { PrismaClient } = require('@prisma/client');
|
| 4 |
+
const prisma = new PrismaClient();
|
| 5 |
+
|
| 6 |
+
// Middleware de autenticación básica para admin
|
| 7 |
+
const adminAuth = (req, res, next) => {
|
| 8 |
+
const authHeader = req.headers.authorization;
|
| 9 |
+
|
| 10 |
+
if (!authHeader || !authHeader.startsWith('Basic ')) {
|
| 11 |
+
return res.status(401).json({ error: 'Autenticación requerida' });
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
const credentials = Buffer.from(authHeader.slice(6), 'base64').toString('utf-8');
|
| 15 |
+
const [username, password] = credentials.split(':');
|
| 16 |
+
|
| 17 |
+
// Credenciales hardcodeadas (puedes cambiarlas por variables de entorno)
|
| 18 |
+
if (username !== process.env.ADMIN_USERNAME || password !== process.env.ADMIN_PASSWORD) {
|
| 19 |
+
return res.status(401).json({ error: 'Credenciales inválidas' });
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
next();
|
| 23 |
+
};
|
| 24 |
+
|
| 25 |
+
// Aplicar autenticación a todas las rutas admin
|
| 26 |
+
router.use(adminAuth);
|
| 27 |
+
|
| 28 |
+
// --- ESTADÍSTICAS Y ANALYTICS ---
|
| 29 |
+
router.get('/stats', async (req, res) => {
|
| 30 |
+
try {
|
| 31 |
+
console.log('Petición recibida en Admin Stats');
|
| 32 |
+
const [
|
| 33 |
+
totalUsers,
|
| 34 |
+
totalContents,
|
| 35 |
+
scrapingRequests,
|
| 36 |
+
failedScrapes
|
| 37 |
+
] = await Promise.all([
|
| 38 |
+
prisma.user.count(),
|
| 39 |
+
prisma.content.count(),
|
| 40 |
+
prisma.scrapeLog.count(),
|
| 41 |
+
prisma.scrapeLog.count({ where: { success: false } })
|
| 42 |
+
]);
|
| 43 |
+
|
| 44 |
+
res.json({
|
| 45 |
+
totalUsers,
|
| 46 |
+
totalContents,
|
| 47 |
+
scrapingRequests,
|
| 48 |
+
failedScrapes,
|
| 49 |
+
successRate: scrapingRequests > 0
|
| 50 |
+
? ((scrapingRequests - failedScrapes) / scrapingRequests * 100).toFixed(2)
|
| 51 |
+
: 0
|
| 52 |
+
});
|
| 53 |
+
} catch (error) {
|
| 54 |
+
res.status(500).json({ error: error.message });
|
| 55 |
+
}
|
| 56 |
+
});
|
| 57 |
+
|
| 58 |
+
// --- ACTIVIDAD RECIENTE PARA DASHBOARD ---
|
| 59 |
+
router.get('/recent-activity', async (req, res) => {
|
| 60 |
+
try {
|
| 61 |
+
console.log('Petición recibida en Admin Recent Activity');
|
| 62 |
+
|
| 63 |
+
// Obtener logs recientes (últimas 10 actividades)
|
| 64 |
+
const recentLogs = await prisma.scrapeLog.findMany({
|
| 65 |
+
take: 10,
|
| 66 |
+
orderBy: { createdAt: 'desc' }
|
| 67 |
+
});
|
| 68 |
+
|
| 69 |
+
res.json(recentLogs);
|
| 70 |
+
} catch (error) {
|
| 71 |
+
console.error('Error en recent-activity:', error.message);
|
| 72 |
+
res.status(500).json({ error: 'Error al obtener actividad reciente' });
|
| 73 |
+
}
|
| 74 |
+
});
|
| 75 |
+
|
| 76 |
+
// --- GESTIÓN DE USUARIOS ---
|
| 77 |
+
router.get('/users', async (req, res) => {
|
| 78 |
+
try {
|
| 79 |
+
console.log('🔍 Intentando conectar a la base de datos para obtener usuarios...');
|
| 80 |
+
const users = await prisma.user.findMany({
|
| 81 |
+
include: {
|
| 82 |
+
_count: {
|
| 83 |
+
select: { myList: true }
|
| 84 |
+
}
|
| 85 |
+
},
|
| 86 |
+
orderBy: { createdAt: 'desc' }
|
| 87 |
+
});
|
| 88 |
+
console.log(`✅ Obtenidos ${users.length} usuarios correctamente`);
|
| 89 |
+
res.json(users);
|
| 90 |
+
} catch (error) {
|
| 91 |
+
console.error('❌ Error crítico en /api/admin/users:', error);
|
| 92 |
+
console.error('🔧 Detalles del error Prisma:', {
|
| 93 |
+
code: error.code,
|
| 94 |
+
meta: error.meta,
|
| 95 |
+
message: error.message,
|
| 96 |
+
stack: error.stack
|
| 97 |
+
});
|
| 98 |
+
|
| 99 |
+
// Diagnóstico específico de errores de conexión
|
| 100 |
+
if (error.code === 'P1001') {
|
| 101 |
+
console.error('🚨 Error de conexión a la base de datos - Verificar URL de conexión');
|
| 102 |
+
} else if (error.code === 'P1017') {
|
| 103 |
+
console.error('🚨 La base de datos ha cerrado la conexión');
|
| 104 |
+
} else if (error.code === 'P2024') {
|
| 105 |
+
console.error('🚨 Timeout en la conexión a la base de datos');
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
res.status(500).json({
|
| 109 |
+
error: 'Error interno del servidor',
|
| 110 |
+
details: process.env.NODE_ENV === 'development' ? error.message : 'Contacte al administrador'
|
| 111 |
+
});
|
| 112 |
+
}
|
| 113 |
+
});
|
| 114 |
+
|
| 115 |
+
// --- GESTIÓN DE CONTENIDOS (CRUD) ---
|
| 116 |
+
router.get('/contents', async (req, res) => {
|
| 117 |
+
try {
|
| 118 |
+
const { page = 1, limit = 20, search = '', type } = req.query;
|
| 119 |
+
const skip = (parseInt(page) - 1) * parseInt(limit);
|
| 120 |
+
|
| 121 |
+
const where = {
|
| 122 |
+
OR: [
|
| 123 |
+
{ title: { contains: search, mode: 'insensitive' } },
|
| 124 |
+
{ description: { contains: search, mode: 'insensitive' } }
|
| 125 |
+
]
|
| 126 |
+
};
|
| 127 |
+
|
| 128 |
+
if (type) {
|
| 129 |
+
where.type = type;
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
const contents = await prisma.content.findMany({
|
| 133 |
+
where,
|
| 134 |
+
skip,
|
| 135 |
+
take: parseInt(limit),
|
| 136 |
+
orderBy: { createdAt: 'desc' },
|
| 137 |
+
include: {
|
| 138 |
+
seasons: {
|
| 139 |
+
include: {
|
| 140 |
+
episodes: true
|
| 141 |
+
}
|
| 142 |
+
}
|
| 143 |
+
}
|
| 144 |
+
});
|
| 145 |
+
|
| 146 |
+
const total = await prisma.content.count({ where });
|
| 147 |
+
|
| 148 |
+
res.json({ contents, total, page: parseInt(page), totalPages: Math.ceil(total / parseInt(limit)) });
|
| 149 |
+
} catch (error) {
|
| 150 |
+
res.status(500).json({ error: error.message });
|
| 151 |
+
}
|
| 152 |
+
});
|
| 153 |
+
|
| 154 |
+
router.post('/contents', async (req, res) => {
|
| 155 |
+
try {
|
| 156 |
+
const { tmdbId, title, description, type, imageUrl, backdropUrl, vsembedUrl, vidsrcUrl } = req.body;
|
| 157 |
+
|
| 158 |
+
const content = await prisma.content.upsert({
|
| 159 |
+
where: { tmdbId },
|
| 160 |
+
update: { vsembedUrl, vidsrcUrl },
|
| 161 |
+
create: {
|
| 162 |
+
tmdbId,
|
| 163 |
+
title,
|
| 164 |
+
description,
|
| 165 |
+
type: type || 'movie',
|
| 166 |
+
imageUrl,
|
| 167 |
+
backdropUrl,
|
| 168 |
+
vsembedUrl,
|
| 169 |
+
vidsrcUrl
|
| 170 |
+
}
|
| 171 |
+
});
|
| 172 |
+
|
| 173 |
+
res.json(content);
|
| 174 |
+
} catch (error) {
|
| 175 |
+
res.status(500).json({ error: error.message });
|
| 176 |
+
}
|
| 177 |
+
});
|
| 178 |
+
|
| 179 |
+
router.put('/contents/:id', async (req, res) => {
|
| 180 |
+
try {
|
| 181 |
+
const { id } = req.params;
|
| 182 |
+
const { vsembedUrl, vidsrcUrl } = req.body;
|
| 183 |
+
|
| 184 |
+
const content = await prisma.content.update({
|
| 185 |
+
where: { id: parseInt(id) },
|
| 186 |
+
data: { vsembedUrl, vidsrcUrl }
|
| 187 |
+
});
|
| 188 |
+
|
| 189 |
+
res.json(content);
|
| 190 |
+
} catch (error) {
|
| 191 |
+
res.status(500).json({ error: error.message });
|
| 192 |
+
}
|
| 193 |
+
});
|
| 194 |
+
|
| 195 |
+
router.delete('/contents/:id', async (req, res) => {
|
| 196 |
+
try {
|
| 197 |
+
const { id } = req.params;
|
| 198 |
+
|
| 199 |
+
await prisma.content.delete({
|
| 200 |
+
where: { id: parseInt(id) }
|
| 201 |
+
});
|
| 202 |
+
|
| 203 |
+
res.json({ message: 'Contenido eliminado correctamente' });
|
| 204 |
+
} catch (error) {
|
| 205 |
+
res.status(500).json({ error: error.message });
|
| 206 |
+
}
|
| 207 |
+
});
|
| 208 |
+
|
| 209 |
+
// --- LOGS DE SCRAPING Y ERRORES ---
|
| 210 |
+
router.get('/scraping-logs', async (req, res) => {
|
| 211 |
+
try {
|
| 212 |
+
const { page = 1, limit = 50, success } = req.query;
|
| 213 |
+
const skip = (parseInt(page) - 1) * parseInt(limit);
|
| 214 |
+
|
| 215 |
+
const where = {};
|
| 216 |
+
if (success !== undefined) {
|
| 217 |
+
where.success = success === 'true';
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
const logs = await prisma.scrapeLog.findMany({
|
| 221 |
+
where,
|
| 222 |
+
skip,
|
| 223 |
+
take: parseInt(limit),
|
| 224 |
+
orderBy: { createdAt: 'desc' }
|
| 225 |
+
});
|
| 226 |
+
|
| 227 |
+
const total = await prisma.scrapeLog.count({ where });
|
| 228 |
+
|
| 229 |
+
res.json({ logs, total, page: parseInt(page), totalPages: Math.ceil(total / parseInt(limit)) });
|
| 230 |
+
} catch (error) {
|
| 231 |
+
res.status(500).json({ error: error.message });
|
| 232 |
+
}
|
| 233 |
+
});
|
| 234 |
+
|
| 235 |
+
// --- REPORTES DE ENLACES CAÍDOS ---
|
| 236 |
+
router.get('/broken-links', async (req, res) => {
|
| 237 |
+
try {
|
| 238 |
+
const brokenLinks = await prisma.scrapeLog.findMany({
|
| 239 |
+
where: {
|
| 240 |
+
success: false,
|
| 241 |
+
createdAt: {
|
| 242 |
+
gte: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) // Últimos 7 días
|
| 243 |
+
}
|
| 244 |
+
},
|
| 245 |
+
distinct: ['targetUrl'],
|
| 246 |
+
orderBy: { createdAt: 'desc' },
|
| 247 |
+
take: 100
|
| 248 |
+
});
|
| 249 |
+
|
| 250 |
+
res.json(brokenLinks);
|
| 251 |
+
} catch (error) {
|
| 252 |
+
res.status(500).json({ error: error.message });
|
| 253 |
+
}
|
| 254 |
+
});
|
| 255 |
+
|
| 256 |
+
module.exports = router;
|
routes/auth_routes.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// routes/auth.routes.js
|
| 2 |
+
const express = require('express');
|
| 3 |
+
const router = express.Router();
|
| 4 |
+
const authController = require('../controllers/auth_controller');
|
| 5 |
+
|
| 6 |
+
// Mapeo de rutas
|
| 7 |
+
router.post('/send-otp', authController.sendOtp);
|
| 8 |
+
router.post('/verify-otp', authController.verifyOtp);
|
| 9 |
+
router.post('/register', authController.register);
|
| 10 |
+
router.get('/users', authController.getUserByEmail); // Cambié la ruta a /user para ser más descriptivo
|
| 11 |
+
router.put('/users/:id', authController.updateUser);
|
| 12 |
+
|
| 13 |
+
module.exports = router;
|
routes/movie_routes.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const express = require('express');
|
| 2 |
+
const router = express.Router();
|
| 3 |
+
const movieController = require('../controllers/movie_controller');
|
| 4 |
+
|
| 5 |
+
router.get('/', movieController.getMovies);
|
| 6 |
+
router.get('/proxy-stream', movieController.proxyStream);
|
| 7 |
+
|
| 8 |
+
module.exports = router;
|
routes/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;
|
routes/stream_routes.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const express = require('express');
|
| 2 |
+
const router = express.Router();
|
| 3 |
+
const streamController = require('../controllers/stream_controller');
|
| 4 |
+
|
| 5 |
+
router.post('/stream/register', streamController.registerStream);
|
| 6 |
+
router.get('/stream/register', streamController.registerStream);
|
| 7 |
+
router.get('/stream/:streamId/master.m3u8', streamController.getMasterPlaylist);
|
| 8 |
+
router.get('/stream/:streamId/source', streamController.getSource);
|
| 9 |
+
router.get('/stream/:streamId/resource', streamController.getResource);
|
| 10 |
+
|
| 11 |
+
module.exports = router;
|
routes/watchlist_routes.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const express = require('express');
|
| 2 |
+
const { getWatchlist, toggleWatchlist } = require('../controllers/watchlist_controller');
|
| 3 |
+
|
| 4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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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(/&/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;
|
services/stream_session_store.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const crypto = require('crypto');
|
| 2 |
+
|
| 3 |
+
const SESSION_TTL_MS = 20 * 60 * 1000;
|
| 4 |
+
const sessions = new Map();
|
| 5 |
+
|
| 6 |
+
function cleanupExpiredSessions() {
|
| 7 |
+
const now = Date.now();
|
| 8 |
+
for (const [id, session] of sessions.entries()) {
|
| 9 |
+
if (session.expiresAt <= now) {
|
| 10 |
+
sessions.delete(id);
|
| 11 |
+
}
|
| 12 |
+
}
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
function createStreamSession({ targetUrl, headers = {}, sourceUrl = null }) {
|
| 16 |
+
cleanupExpiredSessions();
|
| 17 |
+
|
| 18 |
+
const id = crypto.randomBytes(16).toString('hex');
|
| 19 |
+
const expiresAt = Date.now() + SESSION_TTL_MS;
|
| 20 |
+
|
| 21 |
+
sessions.set(id, {
|
| 22 |
+
id,
|
| 23 |
+
targetUrl,
|
| 24 |
+
sourceUrl,
|
| 25 |
+
headers,
|
| 26 |
+
expiresAt,
|
| 27 |
+
createdAt: Date.now()
|
| 28 |
+
});
|
| 29 |
+
|
| 30 |
+
return sessions.get(id);
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
function getStreamSession(id) {
|
| 34 |
+
cleanupExpiredSessions();
|
| 35 |
+
|
| 36 |
+
const session = sessions.get(id);
|
| 37 |
+
if (!session || session.expiresAt <= Date.now()) {
|
| 38 |
+
sessions.delete(id);
|
| 39 |
+
return null;
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
session.expiresAt = Date.now() + SESSION_TTL_MS;
|
| 43 |
+
return session;
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
module.exports = {
|
| 47 |
+
createStreamSession,
|
| 48 |
+
getStreamSession
|
| 49 |
+
};
|