diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..66517b4 --- /dev/null +++ b/.env.example @@ -0,0 +1,10 @@ +VITE_MAIN_API=YOUR_VITE_MAIN_API # Exemple: https://api.movix.rodeo +VITE_TMDB_API_KEY=YOUR_VITE_TMDB_API_KEY # Exemple: 123abc456def7890 +VITE_SITE_URL=YOUR_VITE_SITE_URL # Exemple: https://movix.rodeo +VITE_WATCHPARTY_API=YOUR_VITE_WATCHPARTY_API # Exemple: https://watchparty.movix.rodeo +VITE_PROXY_BASE_URL=YOUR_VITE_PROXY_BASE_URL # Exemple: https://proxy.movix.rodeo +VITE_API_PROXY_BASE_URL=YOUR_VITE_API_PROXY_BASE_URL # Exemple: https://api.movix.rodeo +VITE_PROXIES_EMBED_API=YOUR_VITE_PROXIES_EMBED_API # Exemple: https://proxiesembed.movix.rodeo +VITE_RIVESTREAM_PROXIES=YOUR_VITE_RIVESTREAM_PROXIES # Exemple: rivestream-proxy.a.workers.dev,rivestream-proxy.b.workers.dev +VITE_TURNSTILE_SITE_KEY=YOUR_VITE_TURNSTILE_SITE_KEY # Exemple: 0x4AAAAAAxxxxxxxxxxxxxxx +VITE_TURNSTILE_INVISIBLE_SITEKEY=YOUR_VITE_TURNSTILE_INVISIBLE_SITEKEY # Turnstile invisible (likes, etc.) diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..896e146 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalizatio +* text=auto diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1f61f05 --- /dev/null +++ b/.gitignore @@ -0,0 +1,72 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? + +# Auto-generated entries +# Dependencies +node_modules/ +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Build outputs +dist/ +build/ +*.log + +# Environment files +.env + +# IDE files +.vscode/ +.idea/ +*.swp +*.swo + +# OS files +.DS_Store +Thumbs.db + +# Temporary files +*.tmp +*.temp +.cache/ + +# Sensitive files (auto-detected) +.env +dist +node_modules +.env + +# Project runtime caches and local data +API/cache/ +API/data/ + +# Python artifacts +**/__pycache__/ +*.pyc +*.pyo +/API/Mainapi/data/users +/API/Mainapi/cache +API/Mainapi/linkzy.json diff --git a/API/Mainapi/.env.example b/API/Mainapi/.env.example new file mode 100644 index 0000000..9e250fc --- /dev/null +++ b/API/Mainapi/.env.example @@ -0,0 +1,62 @@ +PORT=YOUR_API_PORT # Exemple: 3000 +JWT_SECRET=YOUR_JWT_SECRET # Exemple: change_me_super_secret_key +OPENROUTER_API_KEY=YOUR_OPENROUTER_API_KEY # Exemple: sk-or-v1-xxxxxxxx +TMDB_API_KEY=YOUR_BACKEND_TMDB_API_KEY # Exemple: 123abc456def7890 +UQLOAD_API_KEY=YOUR_UQLOAD_API_KEY # Cle API XVideoSharing / Uqload +DB_HOST=YOUR_DB_HOST # Exemple: localhost +DB_PORT=YOUR_DB_PORT # Exemple: 3306 +DB_USER=YOUR_DB_USER # Exemple: root +DB_PASSWORD=YOUR_DB_PASSWORD # Exemple: motdepassefort +DB_NAME=YOUR_DB_NAME # Exemple: movix +FRONTEND_BASE_URL=YOUR_FRONTEND_BASE_URL # Exemple: https://movix.rodeo +DISCORD_SYNC_ERROR_WEBHOOK_URL=YOUR_DISCORD_SYNC_ERROR_WEBHOOK_URL # Exemple: https://discord.com/api/webhooks/xxx/yyy +REDIS_HOST=YOUR_REDIS_HOST # Exemple: 127.0.0.1 +REDIS_PORT=YOUR_REDIS_PORT # Exemple: 6379 +REDIS_PASSWORD=YOUR_REDIS_PASSWORD # Exemple: redis_password +NUM_WORKERS=YOUR_NUM_WORKERS # Exemple: 4 +PROXY_SERVER_URL=YOUR_PROXY_SERVER_URL # Exemple: https://proxy.movix.rodeo +CF_PROXY_403_URL=YOUR_CF_PROXY_403_URL # Exemple: https://cf-proxy-403.movix.rodeo +BYPASS403_SERVER_URL=YOUR_BYPASS403_SERVER_URL # Exemple: https://proxy.movix.blog +CLOUDFLARE_WORKERS_PROXIES=YOUR_CLOUDFLARE_WORKERS_PROXIES # Exemple: worker1.example.workers.dev,worker2.example.workers.dev +PROXYSCRAPE_API_TOKEN=YOUR_PROXYSCRAPE_API_TOKEN # Cle API ProxyScrape (header api-token) +PROXYSCRAPE_ACCOUNT_ID=YOUR_PROXYSCRAPE_ACCOUNT_ID +SOCKS5_PROXIES=YOUR_SOCKS5_PROXIES_JSON # Exemple: [{"host":"1.2.3.4","port":12324,"auth":"user:pass","type":"socks5h"}] +HTTP_PROXIES=YOUR_HTTP_PROXIES_JSON # Exemple: [{"host":"1.2.3.4","port":12323,"auth":"user:pass"}] +WITV_SOCKS5_PROXY_URL=YOUR_WITV_SOCKS5_PROXY_URL # Exemple: socks5://user:pass@127.0.0.1:1080 +DARKIWORLD_COOKIES=YOUR_DARKIWORLD_COOKIES # Exemple: SERVERID=S1; XSRF-TOKEN=eyJ....; darkiworld_session=eyJ....; remember_web_3dc7a913ef5fd4b890ecabe3487085573e16cf82=eyJ.... +DARKIWORLD_XSRF_TOKEN=YOUR_DARKIWORLD_XSRF_TOKEN # Exemple: longue-chaine-xsrf-decodée +DARKIWORLD_REMEMBER_TOKEN=YOUR_DARKIWORLD_REMEMBER_TOKEN # Exemple: eyJpdiI6Ik...valeur-du-cookie-remember +DARKIWORLD_XSRF_COOKIE=YOUR_DARKIWORLD_XSRF_COOKIE # Exemple: eyJpdiI6Ik...valeur-du-cookie-XSRF-TOKEN +DARKIWORLD_SESSION=YOUR_DARKIWORLD_SESSION # Exemple: eyJpdiI6Ik...valeur-du-cookie-darkiworld_session +TURNSTILE_SECRET_KEY=YOUR_TURNSTILE_SECRET_KEY # Exemple: 0x4AAAAAAxxxxxxxxxxxxxxxxxxxxxxxx +TURNSTILE_INVISIBLE_SECRETKEY=YOUR_TURNSTILE_INVISIBLE_SECRETKEY # Turnstile invisible (likes, etc.) +BESTDEBRID_API_KEY=YOUR_BESTDEBRID_API_KEY +VIP_SUPPORT_TELEGRAM_URL=YOUR_VIP_SUPPORT_TELEGRAM_URL # Exemple: https://t.me/movix_site +VIP_INVOICE_EXPIRATION_MINUTES=YOUR_VIP_INVOICE_EXPIRATION_MINUTES # Exemple: 210 +VIP_BTC_XPUB=YOUR_VIP_BTC_XPUB # xpub BTC dedie a la reception, sans seed ni cle privee +VIP_BTC_ADDRESS_TYPE=YOUR_VIP_BTC_ADDRESS_TYPE # Type d'adresse derivee: legacy | segwit | p2sh-segwit (optionnel, auto-detecte selon le prefixe si vide) +VIP_BTC_CHAIN=YOUR_VIP_BTC_CHAIN # Branche de derivation sous le xpub: 0 = adresses externes de reception (par defaut) +VIP_BTC_START_INDEX=YOUR_VIP_BTC_START_INDEX # Index de depart optionnel si les premieres adresses du wallet sont deja utilisees +VIP_BTC_CONFIRMATIONS=YOUR_VIP_BTC_CONFIRMATIONS # Exemple: 1 +VIP_LTC_XPUB=YOUR_VIP_LTC_XPUB # xpub/Ltub LTC dedie a la reception, sans seed ni cle privee +VIP_LTC_ADDRESS_TYPE=YOUR_VIP_LTC_ADDRESS_TYPE # Type d'adresse derivee: legacy | segwit | p2sh-segwit (optionnel, auto-detecte selon le prefixe si vide) +VIP_LTC_CHAIN=YOUR_VIP_LTC_CHAIN # Branche de derivation sous le xpub: 0 = adresses externes de reception (par defaut) +VIP_LTC_START_INDEX=YOUR_VIP_LTC_START_INDEX # Index de depart optionnel si les premieres adresses du wallet sont deja utilisees +VIP_LTC_CONFIRMATIONS=YOUR_VIP_LTC_CONFIRMATIONS # Exemple: 1 +VIP_PAYGATE_ENABLED=YOUR_VIP_PAYGATE_ENABLED # Exemple: true +VIP_PAYGATE_DOMAIN=YOUR_VIP_PAYGATE_DOMAIN # Exemple: checkout.paygate.to +VIP_PAYGATE_SETTLEMENT_WALLET=YOUR_VIP_PAYGATE_SETTLEMENT_WALLET # Adresse de settlement configuree chez PayGate +VIP_PAYGATE_CALLBACK_BASE_URL=YOUR_VIP_PAYGATE_CALLBACK_BASE_URL # Optionnel, force l'URL publique backend pour les callbacks +VIP_PAYGATE_LOGO_URL=YOUR_VIP_PAYGATE_LOGO_URL # Optionnel, logo affiche dans le checkout heberge +VIP_PAYGATE_BACKGROUND=YOUR_VIP_PAYGATE_BACKGROUND # Optionnel, code HEX du fond du checkout PayGate (ex: #0A0A0A) +VIP_PAYGATE_THEME=YOUR_VIP_PAYGATE_THEME # Optionnel, code HEX de la couleur de theme PayGate (ex: #FBBF24) +VIP_PAYGATE_BUTTON=YOUR_VIP_PAYGATE_BUTTON # Optionnel, code HEX du bouton PayGate (ex: #EAB308) +VIP_PAYGATE_MIN_AMOUNT_EUR=YOUR_VIP_PAYGATE_MIN_AMOUNT_EUR # Exemple: 6.25 +VIP_PAYGATE_MIN_PACK_EUR=YOUR_VIP_PAYGATE_MIN_PACK_EUR # Exemple: 7 +VIP_PAYGATE_MIN_PAID_RATIO=YOUR_VIP_PAYGATE_MIN_PAID_RATIO # Exemple: 0.60 +BLOCKCYPHER_TOKEN=YOUR_BLOCKCYPHER_TOKEN +FSTREAM_LOGIN_NAME=YOUR_FSTREAM_LOGIN_NAME # Exemple: monlogin +FSTREAM_LOGIN_PASSWORD=YOUR_FSTREAM_LOGIN_PASSWORD # Exemple: monmotdepasse +XTREAM_URL=YOUR_XTREAM_URL # Exemple: http://cf.ru +XTREAM_USER=YOUR_XTREAM_USER # Exemple: 2bf0ac +XTREAM_PASS=YOUR_XTREAM_PASS # Exemple: 9d7fe diff --git a/API/Mainapi/README.md b/API/Mainapi/README.md new file mode 100644 index 0000000..19ab697 --- /dev/null +++ b/API/Mainapi/README.md @@ -0,0 +1,86 @@ +# Main API Movix + +C'est le cœur applicatif du projet. Si le frontend affiche un catalogue, authentifie un user, synchronise du `localStorage`, gère les commentaires, le Wishboard, le Top 10, le Live TV, le debrid ou les pages VIP, il finit très souvent ici. + +Le service tourne en mode cluster via `server.js` : un master lance plusieurs workers, surveille les redémarrages et gère un graceful shutdown. `app.js` monte ensuite Express, Redis, le pool MySQL, les caches disque et les routes injectées par dépendances. + +## Ce que le service gère + +- auth, sessions et profils +- recherche, metadata TMDB et agrégation de sources +- sync frontend <-> backend pour une partie de l'état utilisateur +- commentaires, likes, listes partagées, Wishboard et soumission de liens +- Live TV, proxies, debrid et intégrations de scraping +- VIP, invoices, wrapped et features communautaires + +## Démarrage + +```bash +cd API/Mainapi +cp .env.example .env +npm install +npm run dev +``` + +Ne lance pas le service avec un `.env` vide : MySQL, Redis, JWT, TMDB et plusieurs routes métier en dépendent directement. + +Notes utiles : + +- le serveur HTTP écoute actuellement sur `http://localhost:25565` +- `server.js` bind aujourd'hui le port `25565` en dur +- `NUM_WORKERS` permet de régler le nombre de workers du cluster +- MySQL et Redis sont nécessaires pour une grosse partie des routes + +## Architecture + +```text +API/Mainapi/ +|-- server.js # Master cluster + workers + graceful shutdown +|-- app.js # Bootstrap Express, middleware, deps partagées +|-- mysqlPool.js # Pool MySQL unique +|-- config/redis.js # Redis +|-- middleware/ # CORS, sécurité, auth +|-- routes/ # Modules avec configure(deps) +|-- commentsRoutes.js # Commentaires +|-- likesRoutes.js # Likes / dislikes +|-- sharedListsRoutes.js # Listes partagées +|-- liveTvRoutes.js # Live TV +|-- wishboardRoutes.js # Wishboard +|-- top10Routes.js # Classements +|-- wrappedRoutes.js # Wrapped +|-- linkSubmissionsRoutes.js # Soumission de liens +|-- utils/ # Cache, proxies, axios helpers, VIP, etc. +|-- cache/ # Caches disque +`-- exportscripts/ # SQL et scripts de migration +``` + +Le pattern important dans `routes/` : beaucoup de modules exposent `configure(deps)`. C'est `app.js` qui injecte les clients HTTP, le cache, les helpers et les constantes partagées avant montage. + +## Variables d'environnement à renseigner en premier + +Le fichier `API/Mainapi/.env.example` est la référence complète. En pratique, les groupes de variables à traiter en premier sont : + +- cœur applicatif : `JWT_SECRET`, `TMDB_API_KEY`, `FRONTEND_BASE_URL` +- données : `DB_HOST`, `DB_PORT`, `DB_USER`, `DB_PASSWORD`, `DB_NAME` +- cache et coordination : `REDIS_HOST`, `REDIS_PORT`, `REDIS_PASSWORD`, `NUM_WORKERS` +- scraping / proxy : `PROXY_SERVER_URL`, `CF_PROXY_403_URL`, `BYPASS403_SERVER_URL`, `SOCKS5_PROXIES`, `HTTP_PROXIES` +- anti-abuse / forms : `TURNSTILE_SECRET_KEY`, `TURNSTILE_INVISIBLE_SECRETKEY` +- paiement / VIP : variables `VIP_*`, `BLOCKCYPHER_TOKEN` + +Certaines intégrations sont très spécifiques à des sources données, par exemple les cookies `DARKIWORLD_*`, `FSTREAM_LOGIN_*` ou `XTREAM_*`. + +## Points d'entrée utiles + +- auth et profils : `routes/authRoutes.js`, `routes/sessions.js`, `routes/profiles.js` +- persistance frontend : `routes/sync.js` +- recherche et catalogues : `routes/search.js`, `routes/tmdb.js` +- scraping / lecture : `routes/cpasmal.js`, `routes/fstream.js`, `routes/wiflix.js`, `liveTvRoutes.js` +- communautaire : `commentsRoutes.js`, `likesRoutes.js`, `sharedListsRoutes.js`, `wishboardRoutes.js`, `linkSubmissionsRoutes.js` +- VIP / paiements : `utils/vipDonations.js`, `routes/vipDonations.js` + +## À garder en tête + +- Le backend actif est ici, pas dans l'ancien contenu direct de `API/`. +- Plusieurs tables MySQL sont initialisées automatiquement au démarrage. +- Une partie du comportement applicatif dépend de caches disque et de proxys externes ; un bug peut venir d'ailleurs que du code route lui-même. +- Si une feature touche la lecture vidéo, regarde aussi `API/proxiesembed/`, `API/miscs/` et parfois l'extension navigateur. diff --git a/API/Mainapi/app.js b/API/Mainapi/app.js new file mode 100644 index 0000000..03c8a43 --- /dev/null +++ b/API/Mainapi/app.js @@ -0,0 +1,539 @@ +/** + * Express application setup. + * Extracted from server.js -- creates the app, mounts middleware and routes. + * Does NOT start the server (that remains in server.js). + */ + +const express = require('express'); +const http = require('http'); +const https = require('https'); +const compression = require('compression'); + +// Middleware modules +const corsMiddleware = require('./middleware/cors'); +const { securityHeaders, keepAliveHeaders, domainRestriction, jsonParseErrorHandler } = require('./middleware/security'); + +// Config +const { redis } = require('./config/redis'); + +// Utility modules +const { + getFromCacheWithExpiration, + getFromCacheNoExpiration, + saveToCache, + touchCacheEntry, + shouldUpdateCache, + shouldUpdateCacheFrenchStream, + shouldUpdateCacheLecteurVideo, + shouldUpdateCache24h, + CACHE_DIR +} = require('./utils/cacheManager'); + +const { limitConcurrency3, limitConcurrency10 } = require('./utils/concurrency'); + +const { + CPASMAL_BASE_URL, + makeRequestWithCorsFallback +} = require('./utils/proxyManager'); + +const axios = require('axios'); +const { wrapper } = require('axios-cookiejar-support'); +const tough = require('tough-cookie'); +const axiosHelpers = require('./utils/axiosHelpers'); + +// === Darkino session & headers setup === +const darkiHeaders = { + 'accept': 'application/json', + 'accept-encoding': 'gzip, deflate, br', + 'accept-language': 'fr-FR,fr;q=0.6', + 'cache-control': 'no-cache', + 'cookie': process.env.DARKIWORLD_COOKIES || '', + 'pragma': 'no-cache', + 'priority': 'u=1, i', + 'sec-ch-ua': '"Brave";v="143", "Chromium";v="143", "Not A(Brand";v="24"', + 'sec-ch-ua-mobile': '?0', + 'sec-ch-ua-platform': '"Windows"', + 'sec-fetch-dest': 'empty', + 'sec-fetch-mode': 'cors', + 'sec-fetch-site': 'same-origin', + 'sec-gpc': '1', + 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36', + 'x-xsrf-token': process.env.DARKIWORLD_XSRF_TOKEN || '' +}; + +const cookieJar = new tough.CookieJar(); + +// Pre-fill cookie jar with Darkino session cookies from env +if (process.env.DARKIWORLD_REMEMBER_TOKEN) { + cookieJar.setCookieSync(`remember_web_3dc7a913ef5fd4b890ecabe3487085573e16cf82=${process.env.DARKIWORLD_REMEMBER_TOKEN}`, 'https://darkiworld2026.com'); +} +cookieJar.setCookieSync('SERVERID=S1', 'https://darkiworld2026.com'); +if (process.env.DARKIWORLD_XSRF_COOKIE) { + cookieJar.setCookieSync(`XSRF-TOKEN=${process.env.DARKIWORLD_XSRF_COOKIE}`, 'https://darkiworld2026.com'); +} +if (process.env.DARKIWORLD_SESSION) { + cookieJar.setCookieSync(`darkiworld_session=${process.env.DARKIWORLD_SESSION}`, 'https://darkiworld2026.com'); +} + +// Periodic cleanup of Darkino cookie jar to prevent unbounded memory growth (every 30 min) +setInterval(() => { + try { + cookieJar.removeAllCookiesSync(); + // Re-add essential cookies from env + if (process.env.DARKIWORLD_REMEMBER_TOKEN) { + cookieJar.setCookieSync(`remember_web_3dc7a913ef5fd4b890ecabe3487085573e16cf82=${process.env.DARKIWORLD_REMEMBER_TOKEN}`, 'https://darkiworld2026.com'); + } + cookieJar.setCookieSync('SERVERID=S1', 'https://darkiworld2026.com'); + if (process.env.DARKIWORLD_XSRF_COOKIE) { + cookieJar.setCookieSync(`XSRF-TOKEN=${process.env.DARKIWORLD_XSRF_COOKIE}`, 'https://darkiworld2026.com'); + } + if (process.env.DARKIWORLD_SESSION) { + cookieJar.setCookieSync(`darkiworld_session=${process.env.DARKIWORLD_SESSION}`, 'https://darkiworld2026.com'); + } + } catch (err) { + console.error('[COOKIE JAR] Cleanup error:', err.message); + } +}, 30 * 60 * 1000).unref(); + +// Coflix config +const COFLIX_BASE_URL = 'https://coflix.space'; +const coflixHeaders = { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', + 'Referer': 'https://coflix.space' +}; + +// === Axios instances for each source === +const axiosCoflix = axios.create({ + baseURL: COFLIX_BASE_URL, + timeout: 15000, + headers: coflixHeaders, + decompress: true +}); + +const axiosAnimeSama = axios.create({ + timeout: 30000, + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' + }, + decompress: true +}); + +const FSTREAM_BASE_URL_VAL = 'https://french-stream.one/'; +const axiosFStream = axios.create({ + baseURL: FSTREAM_BASE_URL_VAL, + timeout: 6000, + headers: { + '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', + 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8', + 'Accept-Language': 'fr-FR,fr;q=0.9,en;q=0.8', + 'Accept-Encoding': 'gzip, deflate, br', + 'DNT': '1', + 'Connection': 'keep-alive', + 'Upgrade-Insecure-Requests': '1', + 'Sec-Fetch-Dest': 'document', + 'Sec-Fetch-Mode': 'navigate', + 'Sec-Fetch-Site': 'same-origin', + 'Sec-Fetch-User': '?1', + 'Sec-GPC': '1', + 'Pragma': 'no-cache', + 'Cache-Control': 'no-cache', + 'sec-ch-ua': '"Not(A:Brand";v="8", "Chromium";v="144", "Brave";v="144"', + 'sec-ch-ua-mobile': '?0', + 'sec-ch-ua-platform': '"Windows"', + 'Referer': 'https://french-stream.one/' + }, + decompress: true +}); + +// Darkino session refresh +let lastDarkinoHomeRequest = 0; +const DARKINO_SESSION_REFRESH_INTERVAL = 10 * 60 * 1000; // 10 minutes + +const refreshDarkinoSessionIfNeeded = async () => { + const now = Date.now(); + if (now - lastDarkinoHomeRequest > DARKINO_SESSION_REFRESH_INTERVAL) { + try { + await axiosHelpers.axiosDarkinoRequest({ method: 'get', url: '/' }); + lastDarkinoHomeRequest = now; + console.log('[DARKINO] Session refreshed'); + } catch (error) { + if (!error.response || (error.response.status !== 500 && error.response.status !== 403)) { + console.error('[DARKINO] Failed to refresh session:', error.message); + } + } + } +}; + +// Configure axiosHelpers with darkino session deps + axios instances +axiosHelpers.configure({ + darkiHeaders, + cookieJar, + coflixHeaders, + COFLIX_BASE_URL, + axiosCoflix, + axiosAnimeSama, + axiosFStream, + ANIME_SAMA_URL: 'https://anime-sama.to/', + FSTREAM_BASE_URL: FSTREAM_BASE_URL_VAL +}); + +// === Initialize global agent keep-alive with socket limits === +http.globalAgent.keepAlive = true; +http.globalAgent.maxSockets = 128; // Prevent unbounded socket accumulation +http.globalAgent.maxFreeSockets = 32; +https.globalAgent.keepAlive = true; +https.globalAgent.maxSockets = 128; +https.globalAgent.maxFreeSockets = 32; + +// === Create Express app === +const app = express(); + +// === Mount middleware in correct order === + +// 1. Enable gzip compression for all responses +app.use(compression({ + level: 1, // Balanced compression level (1-9, higher = more compression, slower) + threshold: 1024, // Only compress responses > 1KB + filter: (req, res) => { + // Don't compress if client doesn't accept it + if (req.headers['x-no-compression']) return false; + return compression.filter(req, res); + } +})); + +// 2. Cors Configuration (Restricted in production) +app.use(corsMiddleware); + +// 3. Security headers (minimal set -- replaces Helmet) +app.use(securityHeaders); + +// 4. Keep-Alive headers +app.use(keepAliveHeaders); + +// 5. Domain restriction middleware +app.use(domainRestriction); + +// 6. Body parsing +app.use(express.json({ limit: '30mb' })); // Reduced from 1000mb to prevent abuse + +// 7. JSON parse error handler (must come right after json parser) +app.use(jsonParseErrorHandler); + +app.use(express.urlencoded({ extended: true, limit: '5mb' })); // Reduced from 1000mb to prevent abuse + +// ========================================================================== +// Configure route modules with dependencies from extracted utilities +// ========================================================================== + +const TMDB_API_KEY = process.env.TMDB_API_KEY || ''; +const TMDB_API_URL = 'https://api.themoviedb.org/3'; +const DARKINO_MAINTENANCE = false; +const DARKINOS_CACHE_DIR = require('path').join(__dirname, 'cache', 'darkinos'); +const DOWNLOAD_CACHE_DIR = require('path').join(__dirname, 'cache', 'darkinodownloadlink'); +const ANIME_SAMA_URL = 'https://anime-sama.to/'; + +// Shared deps object for common dependencies +const commonDeps = { + TMDB_API_KEY, + TMDB_API_URL, + DARKINO_MAINTENANCE, + DARKINOS_CACHE_DIR, + getFromCacheNoExpiration, + getFromCacheWithExpiration, + saveToCache, + shouldUpdateCache, + shouldUpdateCacheFrenchStream, + shouldUpdateCacheLecteurVideo, + shouldUpdateCache24h, + limitConcurrency3, + axiosDarkinoRequest: axiosHelpers.axiosDarkinoRequest +}; + +// --- Configure cpasmal --- +const cpasmalRouter = require('./routes/cpasmal'); +cpasmalRouter.configure({ + CPASMAL_BASE_URL, + TMDB_API_URL, + TMDB_API_KEY, + axiosCpasmalRequest: require('./utils/proxyManager').axiosCpasmalRequest, + DARKINO_PROXIES: require('./utils/proxyManager').DARKINO_PROXIES, + getDarkinoHttpProxyAgent: require('./utils/proxyManager').getDarkinoHttpProxyAgent, + getFromCacheNoExpiration, + shouldUpdateCache +}); + +// --- Configure coflix (helper, not a router) --- +const coflix = require('./routes/coflix'); +coflix.configure({ + axiosCoflixRequest: axiosHelpers.axiosCoflixRequest, + axiosLecteurVideoRequest: axiosHelpers.axiosLecteurVideoRequest, + makeCoflixRequest: require('./utils/proxyManager').makeCoflixRequest, + coflixHeaders, + getFromCacheNoExpiration, + saveToCache, + formatCoflixError: axiosHelpers.formatCoflixError +}); + +// --- Configure frenchstream (helper, not a router) --- +const frenchstream = require('./routes/frenchstream'); +frenchstream.configure({ + makeRequestWithCorsFallback, + axiosFrenchStreamRequest: axiosHelpers.axiosFrenchStreamRequest + // findTvSeriesOnTMDB will be injected after tmdb is configured +}); + +// --- Configure animeSama --- +const animeSamaRouter = require('./routes/animeSama'); +animeSamaRouter.configure({ + ANIME_SAMA_URL, + axiosAnimeSama, + axiosAnimeSamaRequest: axiosHelpers.axiosAnimeSamaRequest, + getFromCacheNoExpiration, + saveToCache, + mergeStreamingLinks: axiosHelpers.mergeStreamingLinks, + cleanupOldCacheFiles: axiosHelpers.cleanupOldCacheFiles, + migrateOldCacheFiles: axiosHelpers.migrateOldCacheFiles, + limitConcurrency10 +}); + +// --- Configure tmdb --- +const tmdbRouter = require('./routes/tmdb'); +tmdbRouter.configure({ + TMDB_API_KEY, + TMDB_API_URL, + getFromCacheNoExpiration, + saveToCache, + shouldUpdateCacheFrenchStream, + shouldUpdateCacheLecteurVideo, + limitConcurrency3, + // Coflix helpers + searchCoflixByTitle: coflix.searchCoflixByTitle, + getMovieDataFromCoflix: coflix.getMovieDataFromCoflix, + getTvDataFromCoflix: coflix.getTvDataFromCoflix, + filterEmmmmbedReaders: coflix.filterEmmmmbedReaders, + // FrenchStream helpers + getFrenchStreamMovie: frenchstream.getFrenchStreamMovie, + getFrenchStreamSeries: frenchstream.getFrenchStreamSeries, + getFrenchStreamSeriesDetails: frenchstream.getFrenchStreamSeriesDetails, + extractSeriesInfo: frenchstream.extractSeriesInfo, + mergeSeriesParts: frenchstream.mergeSeriesParts, + cleanTvCacheData: frenchstream.cleanTvCacheData +}); + +// Now inject findTvSeriesOnTMDB back into frenchstream (circular dep) +frenchstream.configure({ + findTvSeriesOnTMDB: tmdbRouter.findTvSeriesOnTMDB +}); + +// --- Configure search --- +const searchRouter = require('./routes/search'); +searchRouter.configure({ + DARKINO_MAINTENANCE, + DARKINOS_CACHE_DIR, + axiosDarkinoRequest: axiosHelpers.axiosDarkinoRequest, + getFromCacheNoExpiration, + saveToCache, + touchCacheEntry, + shouldUpdateCache +}); + +// --- Configure download --- +const downloadRouter = require('./routes/download'); +downloadRouter.configure({ + DARKINO_MAINTENANCE, + DARKINOS_CACHE_DIR, + darkiHeaders, + darkiworld_premium: false, + axiosDarkinoRequest: axiosHelpers.axiosDarkinoRequest, + getFromCacheNoExpiration, + saveToCache, + shouldUpdateCache, + refreshDarkinoSessionIfNeeded +}); + +// --- Configure darkiworld --- +const darkiworldRouter = require('./routes/darkiworld'); +darkiworldRouter.configure({ + DARKINO_MAINTENANCE, + DOWNLOAD_CACHE_DIR, + darkiHeaders, + axiosDarkinoRequest: axiosHelpers.axiosDarkinoRequest, + getFromCacheNoExpiration, + saveToCache, + shouldUpdateCache, + shouldUpdateCache24h, + refreshDarkinoSessionIfNeeded +}); + +// --- Configure voirdrama --- +const voirdramaRouter = require('./routes/voirdrama'); +voirdramaRouter.configure({ + TMDB_API_KEY, + TMDB_API_URL, + getFromCacheNoExpiration, + saveToCache, + shouldUpdateCache24h +}); + +// --- Configure francetv --- +const francetvRouter = require('./routes/francetv'); +francetvRouter.configure({ + getFromCacheWithExpiration, + saveToCache +}); + +const { + router: vipDonationsRouter, + ensureVipDonationsTables +} = require('./routes/vipDonations'); + +// ========================================================================== +// Mount all route modules +// ========================================================================== + +// Pre-existing routes (already extracted before this modularization) +app.use('/api/comments', require('./commentsRoutes')); +app.use('/api/likes', require('./likesRoutes')); +app.use('/api/shared-lists', require('./sharedListsRoutes')); +app.use('/api/livetv', require('./liveTvRoutes')); + +// New modular routes +app.use('/api/cpasmal', cpasmalRouter); +app.use('/anime', animeSamaRouter); +app.use('/api', tmdbRouter); +app.use('/', searchRouter); +app.use('/api', downloadRouter); +app.use('/api/fstream', require('./routes/fstream')); +app.use('/api/wiflix', require('./routes/wiflix')); +app.use('/api', require('./routes/sync')); +app.use('/api/profiles', require('./routes/profiles')); +app.use('/api/auth', require('./routes/authRoutes')); +app.use('/api/sessions', require('./routes/sessions')); +app.use('/api', require('./routes/debrid')); +app.use('/proxy', require('./routes/proxy')); +app.use('/api', require('./routes/admin')); +app.use('/api', vipDonationsRouter); +app.use('/api/darkiworld', darkiworldRouter); +app.use('/api/drama', voirdramaRouter); +app.use('/api/ftv', francetvRouter); +const purstreamRouter = require('./routes/purstream'); +purstreamRouter.configure({ + TMDB_API_KEY, + TMDB_API_URL, + PROXY_SERVER_URL: process.env.PROXY_SERVER_URL, + verifyAccessKey: require('./checkVip').verifyAccessKey, + getFromCacheNoExpiration, + saveToCache, + shouldUpdateCache +}); +app.use('/api/purstream', purstreamRouter); + +// ========================================================================== +// MySQL pool initialization — pool unique via mysqlPool.js +// ========================================================================== + +const { initPool, getPool } = require('./mysqlPool'); +const { ensureAccountLinksStorage } = require('./utils/accountLinks'); +const { ensureCloneLinksStorage } = require('./utils/cloneLinks'); + +(async () => { + try { + const pool = await initPool(); + console.log('MySQL unified pool initialized successfully'); + + // Créer la table user_sessions si elle n'existe pas + await pool.execute(` + CREATE TABLE IF NOT EXISTS user_sessions ( + id VARCHAR(255) PRIMARY KEY, + user_id VARCHAR(255) NOT NULL, + user_type ENUM('oauth', 'bip39') NOT NULL, + user_agent TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + accessed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + INDEX idx_user_sessions_user (user_id, user_type), + INDEX idx_user_sessions_accessed (accessed_at) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci + `); + console.log('Table user_sessions initialized successfully'); + + await ensureAccountLinksStorage(); + console.log('Table account_links initialized successfully'); + + await ensureCloneLinksStorage(); + console.log('Table clone_links initialized successfully'); + + await ensureVipDonationsTables(pool); + console.log('VIP donations tables initialized successfully'); + + // Initialize Wishboard routes + const { createWishboardRouter } = require('./wishboardRoutes'); + const wishboardRouter = createWishboardRouter(pool, redis); + app.use('/api/wishboard', wishboardRouter); + app.use('/api/admin/wishboard', wishboardRouter); + console.log('Wishboard routes initialized successfully'); + + // Initialize Link Submissions routes (user-submitted streaming links) + const { createLinkSubmissionsRouter } = require('./linkSubmissionsRoutes'); + const linkSubmissionsRouter = createLinkSubmissionsRouter(pool, redis); + app.use('/api/link-submissions', linkSubmissionsRouter); + // Create link_submissions table if not exists + await pool.execute(` + CREATE TABLE IF NOT EXISTS link_submissions ( + id INT AUTO_INCREMENT PRIMARY KEY, + user_id VARCHAR(255) NOT NULL, + profile_id VARCHAR(255) NOT NULL, + tmdb_id INT NOT NULL, + media_type ENUM('movie', 'tv') NOT NULL, + season_number INT DEFAULT NULL, + episode_number INT DEFAULT NULL, + url VARCHAR(2048) NOT NULL, + source_name VARCHAR(100) DEFAULT NULL, + status ENUM('pending', 'approved', 'rejected') DEFAULT 'pending', + rejection_reason TEXT DEFAULT NULL, + reviewed_by VARCHAR(255) DEFAULT NULL, + reviewed_at DATETIME DEFAULT NULL, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + INDEX idx_ls_status (status), + INDEX idx_ls_profile (profile_id), + INDEX idx_ls_tmdb (tmdb_id, media_type), + INDEX idx_ls_created (created_at) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci + `); + console.log('Link Submissions routes initialized successfully'); + + // Initialize Top 10 routes (public ranking) + const { router: top10Router, initTop10Routes } = require('./top10Routes'); + initTop10Routes(pool, redis); + app.use('/api/top10', top10Router); + console.log('Top 10 routes initialized successfully'); + + // Initialize Wrapped routes (Movix Wrapped 2026 data collection) + const { router: wrappedRouter, initWrappedRoutes, initTables: initWrappedTables } = require('./wrappedRoutes'); + initWrappedRoutes(pool, redis); + await initWrappedTables(); + app.use('/api/wrapped', wrappedRouter); + console.log('Wrapped routes initialized successfully'); + } catch (error) { + console.error('MySQL connection error:', error.message); + } +})(); + +// === Pool getter for other modules === +function getAppPool() { + return getPool(); +} + +// === Unified error handler === +app.use((err, req, res, next) => { + if (err.message !== 'Not allowed by CORS') { + console.error('Erreur globale:', err); + } + res.status(500).json({ + error: 'Erreur serveur interne', + message: err.message, + path: req.path + }); +}); + +module.exports = { app, getAppPool }; diff --git a/API/Mainapi/checkVip.js b/API/Mainapi/checkVip.js new file mode 100644 index 0000000..b28ef97 --- /dev/null +++ b/API/Mainapi/checkVip.js @@ -0,0 +1,171 @@ +/** + * checkVip.js - Module centralisé de vérification VIP + * + * Vérifie la validité d'une clé d'accès VIP en interrogeant la table `access_keys` MySQL. + * Utilisé par : liveTvRoutes, wishboardRoutes, commentsRoutes, server.js (fstream), etc. + * + * Le frontend envoie la clé via le header `x-access-key`. + * Le serveur vérifie que la clé existe, est active et non expirée. + */ + +const { getPool } = require('./mysqlPool'); + +// Cache en mémoire pour éviter de spammer MySQL à chaque requête +// TTL de 5 minutes — si une clé est révoquée, il faut max 5 min pour que ça prenne effet +const vipCache = new Map(); +const VIP_CACHE_TTL = 5 * 60 * 1000; // 5 minutes + +/** + * Vérifie si une clé d'accès est valide dans la table `access_keys` MySQL. + * + * @param {string} accessKey - La clé d'accès à vérifier + * @returns {Promise<{vip: boolean, expiresAt: string|null, duration: string|null}>} + */ +async function verifyAccessKey(accessKey) { + // Pas de clé = pas VIP + if (!accessKey || typeof accessKey !== 'string' || accessKey.trim() === '') { + return { vip: false, expiresAt: null, duration: null }; + } + + const trimmedKey = accessKey.trim(); + + // Fix encoding: HTTP headers carry non-ASCII bytes as Latin-1. + // Node stores them as-is in the string, so 0xe9 (é) stays as \xe9. + // Convert Latin-1 bytes → Buffer → UTF-8 string to recover proper Unicode. + let fixedKey = trimmedKey; + try { + const buf = Buffer.from(trimmedKey, 'latin1'); + const decoded = buf.toString('utf8'); + // Only use the fixed version if it's valid UTF-8 (no replacement chars) + if (!decoded.includes('\ufffd')) { + fixedKey = decoded; + } + } catch (e) { + // Encoding fix failed, use original + } + + // Vérifier le cache d'abord + const cached = vipCache.get(fixedKey); + if (cached && (Date.now() - cached.timestamp < VIP_CACHE_TTL)) { + return cached.result; + } + + try { + const pool = getPool(); + if (!pool) { + console.warn('[checkVip] MySQL pool not available'); + return { vip: false, expiresAt: null, duration: null }; + } + + const [rows] = await pool.execute( + 'SELECT key_value, active, expires_at, duree_validite FROM access_keys WHERE key_value = ? LIMIT 1', + [fixedKey] + ); + + if (rows.length === 0) { + // Clé inexistante — mettre en cache le résultat négatif (durée plus courte: 1 min) + const result = { vip: false, expiresAt: null, duration: null }; + vipCache.set(fixedKey, { result, timestamp: Date.now() }); + return result; + } + + const keyData = rows[0]; + + // Vérifier si la clé est active + if (!keyData.active) { + const result = { vip: false, expiresAt: null, duration: null, reason: 'key_inactive' }; + vipCache.set(fixedKey, { result, timestamp: Date.now() }); + return result; + } + + // Vérifier si la clé a expiré + if (keyData.expires_at && new Date() > new Date(keyData.expires_at)) { + const result = { vip: false, expiresAt: keyData.expires_at, duration: keyData.duree_validite, reason: 'key_expired' }; + vipCache.set(fixedKey, { result, timestamp: Date.now() }); + return result; + } + + // Clé valide ! + const result = { + vip: true, + expiresAt: keyData.expires_at || null, + duration: keyData.duree_validite || null + }; + vipCache.set(fixedKey, { result, timestamp: Date.now() }); + return result; + + } catch (error) { + console.error('[checkVip] Error verifying access key:', error.message); + // En cas d'erreur DB, ne pas bloquer — retourner non-VIP + return { vip: false, expiresAt: null, duration: null }; + } +} + +/** + * Middleware Express qui extrait la clé du header `x-access-key` + * et attache le résultat VIP à `req.vipStatus`. + * + * Usage: router.get('/route', vipMiddleware, (req, res) => { ... }) + * Puis accéder à req.vipStatus.vip (boolean) + */ +async function vipMiddleware(req, res, next) { + const accessKey = req.headers['x-access-key'] || null; + req.vipStatus = await verifyAccessKey(accessKey); + next(); +} + +/** + * Middleware Express qui BLOQUE l'accès si l'utilisateur n'est pas VIP. + * Renvoie 403 si la clé est absente ou invalide. + * + * Usage: router.get('/vip-only-route', requireVip, (req, res) => { ... }) + */ +async function requireVip(req, res, next) { + const accessKey = req.headers['x-access-key'] || null; + const vipStatus = await verifyAccessKey(accessKey); + req.vipStatus = vipStatus; + + if (!vipStatus.vip) { + return res.status(403).json({ + success: false, + error: 'Accès réservé aux membres VIP', + reason: vipStatus.reason || 'no_valid_key' + }); + } + next(); +} + +// Nettoyage périodique du cache VIP — supprime les entrées expirées pour éviter les fuites mémoire +setInterval(() => { + const now = Date.now(); + for (const [key, cached] of vipCache) { + if (now - cached.timestamp > VIP_CACHE_TTL) { + vipCache.delete(key); + } + } +}, VIP_CACHE_TTL).unref(); // Nettoyage toutes les 5 minutes + +/** + * Invalider le cache pour une clé spécifique (utile quand un admin révoque une clé) + * @param {string} accessKey + */ +function invalidateVipCache(accessKey) { + if (accessKey) { + vipCache.delete(accessKey.trim()); + } +} + +/** + * Invalider tout le cache VIP (utile pour un flush global) + */ +function invalidateAllVipCache() { + vipCache.clear(); +} + +module.exports = { + verifyAccessKey, + vipMiddleware, + requireVip, + invalidateVipCache, + invalidateAllVipCache +}; diff --git a/API/Mainapi/cinepulse_accounts.json b/API/Mainapi/cinepulse_accounts.json new file mode 100644 index 0000000..c041f2b --- /dev/null +++ b/API/Mainapi/cinepulse_accounts.json @@ -0,0 +1,46 @@ +{ + "accounts": [ + { + "id": "survivor.io3681@gmail.com", + "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxZTJjYjI3NS1jMGE1LTRlN2YtOTgyNy01YzY3NDY5NjdiMzAiLCJlbWFpbCI6InN1cnZpdm9yLmlvMzY4MUBnbWFpbC5jb20iLCJzdGF0dXMiOiJmcmVlIiwic2Vzc2lvbklkIjoiM2QwYmJmNDMtZjBmNy00ZWY2LWFjOGYtZTI4OTU5MGM1YzY3IiwiaWF0IjoxNzY5NzE4ODIxLCJleHAiOjE3Njk3MTk3MjEsImF1ZCI6ImNpbmVwdWxzZS1mcm9udGVuZCIsImlzcyI6ImNpbmVwdWxzZS1iYWNrZW5kLWFwaSJ9.uEriHGkZdfNsNE_k1NQF_yFc7CAjd_mpUjHFRYYYsX0", + "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxZTJjYjI3NS1jMGE1LTRlN2YtOTgyNy01YzY3NDY5NjdiMzAiLCJzZXNzaW9uSWQiOiIzZDBiYmY0My1mMGY3LTRlZjYtYWM4Zi1lMjg5NTkwYzVjNjciLCJpYXQiOjE3Njk3MTg4MjEsImV4cCI6MTc3MjMxMDgyMSwiYXVkIjoiY2luZXB1bHNlLWZyb250ZW5kIiwiaXNzIjoiY2luZXB1bHNlLWJhY2tlbmQtYXBpIn0.9HMVXBy3MEaXy1uGr9AyMHjn5LYufVEPnT0EEyKNadE", + "enabled": true + }, + { + "id": "iron-implode-june@duck.com", + "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJjN2VjMTYwMS01NmI4LTQ3ZGEtYTJhYS0xY2UwMzU0YWY3OGIiLCJlbWFpbCI6Imlyb24taW1wbG9kZS1qdW5lQGR1Y2suY29tIiwic3RhdHVzIjoiZnJlZSIsInNlc3Npb25JZCI6IjdkYjQyMGUxLTMyZmQtNGE4MS1hMzhiLTdjYTk2NmE5MGE5ZCIsInByb2ZpbGVJZCI6IjMxYzIxNmE3LWI2OTQtNGEyMC1iNzQ2LWQyYzczOTA5OTMzNiIsImlhdCI6MTc2OTk1MTU4NCwiZXhwIjoxNzY5OTUyNDg0LCJhdWQiOiJjaW5lcHVsc2UtZnJvbnRlbmQiLCJpc3MiOiJjaW5lcHVsc2UtYmFja2VuZC1hcGkifQ.U7Ng0OJmBu0NukZR6ko2CKoGRgy-7BAMVHDdz0010Ts", + "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJjN2VjMTYwMS01NmI4LTQ3ZGEtYTJhYS0xY2UwMzU0YWY3OGIiLCJzZXNzaW9uSWQiOiI3ZGI0MjBlMS0zMmZkLTRhODEtYTM4Yi03Y2E5NjZhOTBhOWQiLCJpYXQiOjE3Njk5NTE1ODQsImV4cCI6MTc3MjU0MzU4NCwiYXVkIjoiY2luZXB1bHNlLWZyb250ZW5kIiwiaXNzIjoiY2luZXB1bHNlLWJhY2tlbmQtYXBpIn0.IR2n570ok-dEBObUlUKyvPpb9TfRIyOaW7nCDLOrgsE", + "enabled": true + }, + { + "id": "each-spied-hulk@duck.com", + "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJkMzBjZTgwMi1mNzIyLTRiODYtOTQwYS1jODkyY2E2ZTM0MTMiLCJlbWFpbCI6ImVhY2gtc3BpZWQtaHVsa0BkdWNrLmNvbSIsInN0YXR1cyI6ImZyZWUiLCJzZXNzaW9uSWQiOiI0YmIwYzkxNy1hN2I5LTRlMTQtOTdiZi1mZjM5YWQ2OGIwYjIiLCJwcm9maWxlSWQiOiI4N2FjZGI1Yi0xMjhkLTRmMzMtOTE1ZS1hMTNlMzIxOGIyNTAiLCJpYXQiOjE3Njk5NTI1MDUsImV4cCI6MTc2OTk1MzQwNSwiYXVkIjoiY2luZXB1bHNlLWZyb250ZW5kIiwiaXNzIjoiY2luZXB1bHNlLWJhY2tlbmQtYXBpIn0.ZoXCtrxYLmnmxIl6vLq6sJYaWy1oS3BmG_lbnG2KNnM", + "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJkMzBjZTgwMi1mNzIyLTRiODYtOTQwYS1jODkyY2E2ZTM0MTMiLCJzZXNzaW9uSWQiOiI0YmIwYzkxNy1hN2I5LTRlMTQtOTdiZi1mZjM5YWQ2OGIwYjIiLCJpYXQiOjE3Njk5NTI1MDUsImV4cCI6MTc3MjU0NDUwNSwiYXVkIjoiY2luZXB1bHNlLWZyb250ZW5kIiwiaXNzIjoiY2luZXB1bHNlLWJhY2tlbmQtYXBpIn0.MJHsz0Qd3zDreJWVpV0RIT114_Tf4yE3d3gIs-c79io", + "enabled": true + }, + { + "id": "banjo-gully-stir@duck.com", + "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJiY2E4ZDcyZC1jNmQ4LTQ0MTYtYTA2NS0xMjMwOTAyZDg3MGYiLCJlbWFpbCI6ImJhbmpvLWd1bGx5LXN0aXJAZHVjay5jb20iLCJzdGF0dXMiOiJmcmVlIiwic2Vzc2lvbklkIjoiZWQyMmYyMmUtNWU3OS00OTdkLWFhMzctZDk1ZWJlMTNmMmE5IiwicHJvZmlsZUlkIjoiZjU4ZmMxZjMtOGM3NS00MDE3LWJjMDItNTlhZTdiMTEyZWY5IiwiaWF0IjoxNzY5OTY2MDU0LCJleHAiOjE3Njk5NjY5NTQsImF1ZCI6ImNpbmVwdWxzZS1mcm9udGVuZCIsImlzcyI6ImNpbmVwdWxzZS1iYWNrZW5kLWFwaSJ9.jC4r4mK_ge0qgVSb4WIxT0GI-Oyzj9HjJIZgOyDbZds", + "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJiY2E4ZDcyZC1jNmQ4LTQ0MTYtYTA2NS0xMjMwOTAyZDg3MGYiLCJzZXNzaW9uSWQiOiJlZDIyZjIyZS01ZTc5LTQ5N2QtYWEzNy1kOTVlYmUxM2YyYTkiLCJpYXQiOjE3Njk5NjYwNTQsImV4cCI6MTc3MjU1ODA1NCwiYXVkIjoiY2luZXB1bHNlLWZyb250ZW5kIiwiaXNzIjoiY2luZXB1bHNlLWJhY2tlbmQtYXBpIn0.jZo0rjNr6PXQ9UH7vWOkA7wJcPQVzSqCIvAV2m8F2Lk", + "enabled": true + }, + { + "id": "energy-object-gala@duck.com", + "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI5NDJkOWE5Yi0yZDU1LTQwNDAtOWQ0ZC00YjA3NjQ1ZTgwMDkiLCJlbWFpbCI6ImVuZXJneS1vYmplY3QtZ2FsYUBkdWNrLmNvbSIsInN0YXR1cyI6ImZyZWUiLCJzZXNzaW9uSWQiOiIxZDVhZjllNi1jNmQxLTQ4ZjMtOTg5Ny04MWNmNmJmODVlMjgiLCJwcm9maWxlSWQiOiIwN2EwZTc5Ny0yNDJiLTQxYzktODJkOC1mNTkxYWNmNWQyZTEiLCJpYXQiOjE3Njk5NjYxMjMsImV4cCI6MTc2OTk2NzAyMywiYXVkIjoiY2luZXB1bHNlLWZyb250ZW5kIiwiaXNzIjoiY2luZXB1bHNlLWJhY2tlbmQtYXBpIn0.CT0RINqhAvwh3RiOR4b1xMrW8xvykN6TmCIzyy_d_rM", + "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI5NDJkOWE5Yi0yZDU1LTQwNDAtOWQ0ZC00YjA3NjQ1ZTgwMDkiLCJzZXNzaW9uSWQiOiIxZDVhZjllNi1jNmQxLTQ4ZjMtOTg5Ny04MWNmNmJmODVlMjgiLCJpYXQiOjE3Njk5NjYxMjMsImV4cCI6MTc3MjU1ODEyMywiYXVkIjoiY2luZXB1bHNlLWZyb250ZW5kIiwiaXNzIjoiY2luZXB1bHNlLWJhY2tlbmQtYXBpIn0.iKdnHkXnD9F3GI1ohsfTk1VQVSE80OYDt2fmrHh1wSU", + "enabled": true + }, + { + "id": "knapsack-pork-oil@duck.com", + "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI3ODU2YjY5Yi1hZDU2LTQwMDUtODIxNC02OGRjMmY2ZTExMDEiLCJlbWFpbCI6ImtuYXBzYWNrLXBvcmstb2lsQGR1Y2suY29tIiwic3RhdHVzIjoiZnJlZSIsInNlc3Npb25JZCI6ImQ3MTBhNDI3LTRhMzAtNDVhNy1iYzUzLTVmNzYzYTQ2ZTYwYyIsInByb2ZpbGVJZCI6ImY2ZjkyNzFhLWVlMDctNDJlYy1iODkyLTkwZmFjYWJlOTJjMSIsImlhdCI6MTc2OTk2NjE2OSwiZXhwIjoxNzY5OTY3MDY5LCJhdWQiOiJjaW5lcHVsc2UtZnJvbnRlbmQiLCJpc3MiOiJjaW5lcHVsc2UtYmFja2VuZC1hcGkifQ.fN7FLezyyiR0aMrBUWYWHM3DBum8wmgC-0xBhyJpSKE", + "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI3ODU2YjY5Yi1hZDU2LTQwMDUtODIxNC02OGRjMmY2ZTExMDEiLCJzZXNzaW9uSWQiOiJkNzEwYTQyNy00YTMwLTQ1YTctYmM1My01Zjc2M2E0NmU2MGMiLCJpYXQiOjE3Njk5NjYxNjksImV4cCI6MTc3MjU1ODE2OSwiYXVkIjoiY2luZXB1bHNlLWZyb250ZW5kIiwiaXNzIjoiY2luZXB1bHNlLWJhY2tlbmQtYXBpIn0.pePSAByPV5xhPYQGN4wXpq4od3Gdf4vmL7f5GbuKToA", + "enabled": true + }, + { + "id": "chess-endeared-elm@duck.com", + "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI5MzMzZWQyOC04NTgzLTQ1NmEtOTQ2YS1iZWNlNzUwZjIxZjgiLCJlbWFpbCI6ImNoZXNzLWVuZGVhcmVkLWVsbUBkdWNrLmNvbSIsInN0YXR1cyI6ImZyZWUiLCJzZXNzaW9uSWQiOiIwZjljODEwNy1mZWEzLTRkMjYtYTg0ZC0yODYyYmVhOGViOWMiLCJwcm9maWxlSWQiOiIyMTk5ZjQ1Zi0yNTk4LTQ0NjUtYjliMC04NzgzYmJhYmZiMmYiLCJpYXQiOjE3Njk5NjYyMzMsImV4cCI6MTc2OTk2NzEzMywiYXVkIjoiY2luZXB1bHNlLWZyb250ZW5kIiwiaXNzIjoiY2luZXB1bHNlLWJhY2tlbmQtYXBpIn0.3zVpl9m8Mh4uqUwq6s3N-u636lG9ELcayoHD5sVKJzw", + "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI5MzMzZWQyOC04NTgzLTQ1NmEtOTQ2YS1iZWNlNzUwZjIxZjgiLCJzZXNzaW9uSWQiOiIwZjljODEwNy1mZWEzLTRkMjYtYTg0ZC0yODYyYmVhOGViOWMiLCJpYXQiOjE3Njk5NjYyMzMsImV4cCI6MTc3MjU1ODIzMywiYXVkIjoiY2luZXB1bHNlLWZyb250ZW5kIiwiaXNzIjoiY2luZXB1bHNlLWJhY2tlbmQtYXBpIn0.5k5mlNsuifJfFgwN9cp1Ax1Hst8XtbHy9rrRoJBl_RQ", + "enabled": true + } + ] +} diff --git a/API/Mainapi/commentsRoutes.js b/API/Mainapi/commentsRoutes.js new file mode 100644 index 0000000..b44c1ca --- /dev/null +++ b/API/Mainapi/commentsRoutes.js @@ -0,0 +1,3417 @@ +const express = require("express"); +const router = express.Router(); +const fs = require("fs").promises; +const path = require("path"); +const axios = require("axios"); +const jwt = require("jsonwebtoken"); +const { getPool } = require("./mysqlPool"); +const { verifyAccessKey } = require("./checkVip"); +// Réutiliser l'instance Redis partagée au lieu d'en créer une nouvelle (évite les fuites mémoire) +const { redis } = require("./config/redis"); +const { verifyTurnstileFromRequest } = require("./utils/turnstile"); + +// === #15: JWT_SECRET chargé une seule fois au démarrage === +const JWT_SECRET = process.env.JWT_SECRET; + +// === Vérification de bannissement === +async function checkBan(userId, userType, ip) { + const now = Date.now(); + // Vérifier ban par user_id + const userBan = await dbGet( + `SELECT * FROM banned_users WHERE ban_type = 'user' AND ban_value = ? AND user_type = ? AND (expires_at IS NULL OR expires_at > ?)`, + [userId, userType, now], + ); + if (userBan) + return { + banned: true, + reason: userBan.reason, + expires_at: userBan.expires_at, + }; + + // Vérifier ban par IP + if (ip) { + const ipBan = await dbGet( + `SELECT * FROM banned_users WHERE ban_type = 'ip' AND ban_value = ? AND (expires_at IS NULL OR expires_at > ?)`, + [ip, now], + ); + if (ipBan) + return { + banned: true, + reason: ipBan.reason, + expires_at: ipBan.expires_at, + }; + } + + return { banned: false }; +} + +// === #16: Pool MySQL caché pour éviter d'appeler getPool() à chaque query === +let _cachedPool = null; +function getCachedPool() { + if (!_cachedPool) _cachedPool = getPool(); + return _cachedPool; +} + +const DISCORD_WEBHOOK_URL = process.env.DISCORD_COMMENTS_WEBHOOK_URL; +const FRONTEND_BASE_URL = process.env.FRONTEND_BASE_URL; + +// Normalize user-entered content while keeping the original characters intact. +function normalizeCommentContent(text) { + if (typeof text !== "string") return text; + // Replace 3+ consecutive newlines (with optional spaces/tabs between them) with max 2 newlines + return text.replace(/(\s*\n\s*){3,}/g, "\n\n").trim(); +} + +function decodeHtmlEntities(text) { + if (typeof text !== "string" || !text.includes("&")) return text; + + const namedEntities = { + amp: "&", + lt: "<", + gt: ">", + quot: '"', + apos: "'", + nbsp: "\u00A0", + }; + + return text.replace(/&(#x?[0-9a-f]+|[a-z]+);/gi, (match, entity) => { + const lowerEntity = entity.toLowerCase(); + + if (namedEntities[lowerEntity]) { + return namedEntities[lowerEntity]; + } + + if (lowerEntity.startsWith("#x")) { + const codePoint = parseInt(lowerEntity.slice(2), 16); + if (Number.isFinite(codePoint)) { + try { + return String.fromCodePoint(codePoint); + } catch { + return match; + } + } + return match; + } + + if (lowerEntity.startsWith("#")) { + const codePoint = parseInt(lowerEntity.slice(1), 10); + if (Number.isFinite(codePoint)) { + try { + return String.fromCodePoint(codePoint); + } catch { + return match; + } + } + } + + return match; + }); +} + +// Decode legacy escaped content before returning it to the frontend. +function formatContentForResponse(text) { + let formatted = normalizeCommentContent(text); + + // Older comments were stored escaped, and some routes escaped them a second time on read. + // Decoding twice fixes both stored legacy entities and previously double-escaped payloads. + for (let i = 0; i < 2; i += 1) { + const decoded = decodeHtmlEntities(formatted); + if (decoded === formatted) break; + formatted = decoded; + } + + return formatted; +} + +// OpenRouter API Configuration for content moderation (using Gemini 2.5 Flash Lite) +const OPENROUTER_API_KEY = process.env.OPENROUTER_API_KEY; +const OPENROUTER_API_URL = "https://openrouter.ai/api/v1/chat/completions"; +const OPENROUTER_MODEL = "google/gemini-2.5-flash-lite"; + +// Fonction de modération avec OpenRouter/Gemini (exécutée en background) +async function moderateContentWithGemini( + contentId, + contentType, + content, + username, +) { + try { + const prompt = `Tu es un modérateur de commentaires. Analyse le commentaire ET le pseudo suivants et réponds UNIQUEMENT par un JSON valide. + +Pseudo de l'utilisateur: ${JSON.stringify(username)} +Commentaire à analyser: ${JSON.stringify(content)} + +Critères de modération (s'appliquent au pseudo ET au commentaire): +1. INSULTES: Contient des insultes, injures, propos haineux ou dégradants +2. EROTIQUE: Contient du contenu érotique, sexuel ou inapproprié +3. DEMANDE_AJOUT: Demande d'ajout de films, séries, fonctionnalités ou autre contenu +4. PSEUDO_INAPPROPRIE: Le pseudo contient des insultes, contenu érotique, ou est inapproprié + +Réponds UNIQUEMENT avec ce format JSON (sans markdown, sans backticks): +{"flagged": true/false, "reason": "INSULTES" ou "EROTIQUE" ou "DEMANDE_AJOUT" ou "PSEUDO_INAPPROPRIE" ou null, "details": "explication courte"}`; + + const response = await axios.post( + OPENROUTER_API_URL, + { + model: OPENROUTER_MODEL, + messages: [ + { + role: "user", + content: prompt, + }, + ], + max_tokens: 500, + temperature: 0.1, + }, + { + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${OPENROUTER_API_KEY}`, + "HTTP-Referer": FRONTEND_BASE_URL, + "X-Title": "Movix Comment Moderation", + }, + timeout: 15000, + }, + ); + + const responseText = response.data?.choices?.[0]?.message?.content || ""; + + // Parser la réponse JSON + let moderationResult; + try { + // Nettoyer la réponse (enlever les backticks markdown si présents) + const cleanedResponse = responseText + .replace(/```json\n?|```\n?/g, "") + .trim(); + moderationResult = JSON.parse(cleanedResponse); + } catch (parseError) { + console.error( + "❌ Erreur parsing réponse OpenRouter:", + parseError, + "Response:", + responseText, + ); + return { flagged: false }; + } + + if (moderationResult.flagged) { + console.log( + `🚨 Contenu flaggé (${contentType} ID: ${contentId}): ${moderationResult.reason} - ${moderationResult.details}`, + ); + + // Marquer le contenu comme supprimé (deleted = 1) et stocker la raison + const table = contentType === "comment" ? "comments" : "comment_replies"; + await dbRun( + `UPDATE ${table} SET deleted = 1, moderation_reason = ?, moderation_details = ?, moderated_at = ? WHERE id = ?`, + [ + moderationResult.reason, + moderationResult.details, + Date.now(), + contentId, + ], + ); + + console.log( + `✅ ${contentType} ID ${contentId} marqué comme supprimé pour modération`, + ); + } + + return moderationResult; + } catch (error) { + console.error( + "❌ Erreur modération OpenRouter (non bloquant):", + error.message, + ); + return { flagged: false }; + } +} + +// Fonctions helper MySQL pour remplacer SQLite (#16: pool caché) +const dbRun = async (sql, params = []) => { + const pool = getCachedPool(); + const [result] = await pool.execute(sql, params); + return { + lastID: result.insertId || 0, + changes: result.affectedRows || 0, + }; +}; + +const dbGet = async (sql, params = []) => { + const pool = getCachedPool(); + const [rows] = await pool.execute(sql, params); + return rows.length > 0 ? rows[0] : null; +}; + +const dbAll = async (sql, params = []) => { + const pool = getCachedPool(); + const [rows] = await pool.execute(sql, params); + return rows; +}; + +// Middleware pour vérifier l'authentification avec validation session MySQL +const requireAuth = async (req, res, next) => { + const token = req.headers.authorization?.split(" ")[1]; + if (!token) { + return res.status(401).json({ error: "Non authentifié" }); + } + + // Vérifier le token JWT (#15: jwt importé au top du fichier) + try { + const decoded = jwt.verify(token, JWT_SECRET, { algorithms: ["HS256"] }); + const { sub: userId, userType, sessionId } = decoded; + + if (!["oauth", "bip39"].includes(userType) || !userId || !sessionId) { + return res.status(401).json({ error: "Token invalide" }); + } + + // Vérifier que la session existe en MySQL + const pool = getCachedPool(); + const [rows] = await pool.execute( + "SELECT id FROM user_sessions WHERE id = ? AND user_id = ? AND user_type = ?", + [sessionId, userId, userType], + ); + + if (rows.length === 0) { + return res.status(401).json({ error: "Session invalide ou expirée" }); + } + + req.user = { + userId: userId, + userType: userType, + sessionId: sessionId, + }; + next(); + } catch (error) { + return res.status(401).json({ error: "Token invalide" }); + } +}; + +// Helper to get allowed profile IDs (security check) +async function getProfileIds(userId, userType) { + try { + // Sanitize userId to prevent path traversal + const safeUserId = String(userId).replace(/[^a-zA-Z0-9_\-]/g, ""); + let userFilePath; + if (userType === "bip39") { + userFilePath = path.join( + __dirname, + "data", + "users", + `bip39-${safeUserId}.json`, + ); + } else { + userFilePath = path.join( + __dirname, + "data", + "users", + `${safeUserId}.json`, + ); + } + + try { + const userFile = await fs.readFile(userFilePath, "utf8"); + const user = JSON.parse(userFile); + + const profileIds = []; + if (user.profiles) { + user.profiles.forEach((p) => profileIds.push(p.id)); + } else { + // Fallback for old structure might be needed but typically not for profileId spoofing protection + } + return profileIds; + } catch (err) { + // if (err.code !== 'ENOENT') console.error('Error reading user file:', err); + return []; + } + } catch (error) { + console.error("Error getting profile IDs:", error); + return []; + } +} + +// === #14: Cache getUserData dans Redis (TTL 5 min) pour éviter les lectures fichier à chaque requête === +const USER_DATA_CACHE_TTL = 300; // 5 minutes en secondes + +// Fonction interne pour récupérer les données utilisateur depuis le disque/MySQL (sans cache) +async function _fetchUserData(userId, userType, profileId = null) { + try { + let userData = { + username: "Utilisateur", + avatar: null, + isVip: false, + isAdmin: false, + }; + + // Sanitize inputs to prevent path traversal + const safeUserId = String(userId).replace(/[^a-zA-Z0-9_\-]/g, ""); + const safeUserType = ["oauth", "bip39"].includes(userType) + ? userType + : "oauth"; + const safeProfileId = profileId + ? String(profileId).replace(/[^a-zA-Z0-9_\-]/g, "") + : null; + + // Chemin vers le fichier utilisateur + let userFilePath; + if (safeUserType === "bip39") { + userFilePath = path.join( + __dirname, + "data", + "users", + `bip39-${safeUserId}.json`, + ); + } else { + userFilePath = path.join( + __dirname, + "data", + "users", + `${safeUserId}.json`, + ); + } + + // Lire le fichier utilisateur + try { + const userFile = await fs.readFile(userFilePath, "utf8"); + const user = JSON.parse(userFile); + + // Récupérer le profil + if (profileId && user.profiles) { + const profile = user.profiles.find((p) => p.id === profileId); + if (profile) { + userData.username = profile.name || "Utilisateur"; + // Sanitize avatar: must start with /avatars/ + if (profile.avatar && profile.avatar.startsWith("/avatars/")) { + userData.avatar = profile.avatar; + } else { + userData.avatar = "/avatars/disney/disney_avatar_1.png"; // Default fallback + } + } + } else if (user.profiles && user.profiles.length > 0) { + // Utiliser le profil par défaut + const defaultProfile = + user.profiles.find((p) => p.isDefault) || user.profiles[0]; + userData.username = defaultProfile.name || "Utilisateur"; + // Sanitize avatar: must start with /avatars/ + if ( + defaultProfile.avatar && + defaultProfile.avatar.startsWith("/avatars/") + ) { + userData.avatar = defaultProfile.avatar; + } else { + userData.avatar = "/avatars/disney/disney_avatar_1.png"; // Default fallback + } + } + } catch (err) { + // Fichier utilisateur introuvable — on garde les valeurs par défaut + } + + // Vérifier le statut VIP en lisant l'access_code depuis les données du profil + // puis en le vérifiant contre la table MySQL access_keys + if (safeProfileId && safeUserId) { + try { + const profileDataPath = path.join( + __dirname, + "data", + "users", + "profiles", + safeUserType, + safeUserId, + `${safeProfileId}.json`, + ); + const profileData = JSON.parse( + await fs.readFile(profileDataPath, "utf8"), + ); + const storedAccessCode = profileData.access_code || null; + if (storedAccessCode) { + const vipStatus = await verifyAccessKey(storedAccessCode); + userData.isVip = vipStatus.vip; + } + } catch (err) { + // Pas de données de profil ou pas d'access_code — isVip reste false + } + } + + // Vérifier si Admin (en utilisant MySQL) + try { + const pool = getCachedPool(); + const authType = userType === "bip39" ? "bip-39" : userType; + const [rows] = await pool.execute( + "SELECT 1 FROM admins WHERE user_id = ? AND auth_type = ? LIMIT 1", + [userId, authType], + ); + userData.isAdmin = rows.length > 0; + } catch (err) { + console.error("❌ Erreur lors de la vérification admin:", err); + } + + return userData; + } catch (error) { + console.error("Erreur _fetchUserData:", error); + return { + username: "Utilisateur", + avatar: null, + isVip: false, + isAdmin: false, + }; + } +} + +// Fonction publique avec cache Redis (#14) +async function getUserData(userId, userType, profileId = null) { + const cacheKey = `userData:${userType}:${userId}:${profileId || "default"}`; + try { + const cached = await redis.get(cacheKey); + if (cached) return JSON.parse(cached); + } catch { + /* Redis indisponible, on continue sans cache */ + } + + const userData = await _fetchUserData(userId, userType, profileId); + + // Mettre en cache (fire-and-forget) + try { + redis + .set(cacheKey, JSON.stringify(userData), "EX", USER_DATA_CACHE_TTL) + .catch(() => {}); + } catch { + /* ignore */ + } + + return userData; +} + +// Fonction pour créer une notification +async function createNotification( + toUserId, + toUserType, + toProfileId, + fromUserId, + fromProfileId, + fromUsername, + fromAvatar, + notificationType, + targetType, + targetId, + contentType, + contentId, + commentPreview, +) { + try { + await dbRun( + `INSERT INTO notifications (user_id, user_type, profile_id, from_user_id, from_profile_id, from_username, from_avatar, notification_type, target_type, target_id, content_type, content_id, comment_preview, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + [ + toUserId, + toUserType, + toProfileId, + fromUserId, + fromProfileId, + fromUsername, + fromAvatar, + notificationType, + targetType, + targetId, + contentType, + contentId, + commentPreview, + Date.now(), + ], + ); + } catch (error) { + console.error("Erreur lors de la création de la notification:", error); + } +} + +// === #18: Batch cascade delete — requêtes batch au lieu de récursion séquentielle === + +// Fonction helper pour récupérer tous les IDs de réponses d'un commentaire (ou sous-arbre d'une réponse) +async function getAllReplyIds( + commentId, + parentReplyId = null, + includeDeleted = false, +) { + const deletedFilter = includeDeleted ? "" : " AND deleted = 0"; + if (parentReplyId === null) { + // Toutes les réponses du commentaire + const replies = await dbAll( + `SELECT id FROM comment_replies WHERE comment_id = ?${deletedFilter}`, + [commentId], + ); + return replies.map((r) => r.id); + } + // Sous-arbre d'une réponse spécifique : récupérer récursivement via hierarchical_path + // Récupérer le path du parent + const parent = await dbGet( + "SELECT hierarchical_path FROM comment_replies WHERE id = ?", + [parentReplyId], + ); + if (!parent || !parent.hierarchical_path) return [parentReplyId]; + + const descendants = await dbAll( + `SELECT id FROM comment_replies WHERE comment_id = ? AND hierarchical_path LIKE ?${deletedFilter}`, + [commentId, `${parent.hierarchical_path}.%`], + ); + return [parentReplyId, ...descendants.map((r) => r.id)]; +} + +// Batch delete des réactions et notifications pour une liste d'IDs de réponses +async function batchDeleteReplyDependencies(replyIds) { + if (replyIds.length === 0) return; + const placeholders = replyIds.map(() => "?").join(","); + + // Supprimer les réactions de toutes les réponses en batch + await dbRun( + `DELETE FROM comment_reactions WHERE target_type = 'reply' AND target_id IN (${placeholders})`, + replyIds, + ); + + // Supprimer les notifications liées à ces réponses en batch + await dbRun( + `DELETE FROM notifications WHERE target_type = 'reply' AND target_id IN (${placeholders})`, + replyIds, + ); + + // Supprimer les notifications de réaction sur ces réponses en batch + await dbRun( + `DELETE FROM notifications WHERE notification_type = 'reaction' AND target_type = 'reply' AND target_id IN (${placeholders})`, + replyIds, + ); +} + +// Soft delete cascade : marquer les réponses comme supprimées en batch +async function deleteRepliesCascade(commentId, replyId = null) { + try { + const replyIds = await getAllReplyIds(commentId, replyId, false); + if (replyIds.length === 0) return; + + await batchDeleteReplyDependencies(replyIds); + + // Soft delete toutes les réponses en batch + const placeholders = replyIds.map(() => "?").join(","); + await dbRun( + `UPDATE comment_replies SET deleted = 1 WHERE id IN (${placeholders})`, + replyIds, + ); + + console.log( + `✅ ${replyIds.length} réponse(s) supprimées en cascade (soft) pour commentaire ${commentId}`, + ); + } catch (error) { + console.error( + "Erreur lors de la suppression en cascade des réponses:", + error, + ); + throw error; + } +} + +// Soft delete cascade pour un commentaire entier +async function deleteCommentCascade(commentId) { + try { + // 1. Récupérer tous les IDs de réponses du commentaire + const replyIds = await getAllReplyIds(commentId, null, false); + + // 2. Supprimer les dépendances de toutes les réponses en batch + if (replyIds.length > 0) { + await batchDeleteReplyDependencies(replyIds); + const placeholders = replyIds.map(() => "?").join(","); + await dbRun( + `UPDATE comment_replies SET deleted = 1 WHERE id IN (${placeholders})`, + replyIds, + ); + } + + // 3. Supprimer les réactions du commentaire + await dbRun( + `DELETE FROM comment_reactions WHERE target_type = 'comment' AND target_id = ?`, + [commentId], + ); + + // 4. Supprimer les notifications du commentaire + await dbRun( + `DELETE FROM notifications WHERE target_type = 'comment' AND target_id = ?`, + [commentId], + ); + await dbRun( + `DELETE FROM notifications WHERE notification_type = 'reaction' AND target_type = 'comment' AND target_id = ?`, + [commentId], + ); + + // 5. Soft delete le commentaire + await dbRun("UPDATE comments SET deleted = 1 WHERE id = ?", [commentId]); + + console.log( + `✅ Commentaire ${commentId} et ${replyIds.length} réponse(s) supprimés en cascade`, + ); + } catch (error) { + console.error( + "Erreur lors de la suppression en cascade du commentaire:", + error, + ); + throw error; + } +} + +// Hard delete cascade : suppression définitive d'une réponse et ses enfants +async function hardDeleteRepliesCascade(commentId, replyId) { + try { + const replyIds = await getAllReplyIds(commentId, replyId, true); + if (replyIds.length === 0) return; + + await batchDeleteReplyDependencies(replyIds); + + // Hard delete toutes les réponses en batch + const placeholders = replyIds.map(() => "?").join(","); + await dbRun( + `DELETE FROM comment_replies WHERE id IN (${placeholders})`, + replyIds, + ); + + console.log( + `🗑️ ${replyIds.length} réponse(s) supprimées définitivement pour commentaire ${commentId}`, + ); + } catch (error) { + console.error( + "Erreur lors de la suppression définitive des réponses:", + error, + ); + throw error; + } +} + +// Hard delete cascade pour un commentaire entier +async function hardDeleteCommentCascade(commentId) { + try { + // 1. Récupérer tous les IDs de réponses (y compris déjà supprimées) + const replyIds = await getAllReplyIds(commentId, null, true); + + // 2. Supprimer les dépendances en batch + if (replyIds.length > 0) { + await batchDeleteReplyDependencies(replyIds); + const placeholders = replyIds.map(() => "?").join(","); + await dbRun( + `DELETE FROM comment_replies WHERE id IN (${placeholders})`, + replyIds, + ); + } + + // 3. Supprimer les réactions et notifications du commentaire + await dbRun( + `DELETE FROM comment_reactions WHERE target_type = 'comment' AND target_id = ?`, + [commentId], + ); + await dbRun( + `DELETE FROM notifications WHERE target_type = 'comment' AND target_id = ?`, + [commentId], + ); + await dbRun( + `DELETE FROM notifications WHERE notification_type = 'reaction' AND target_type = 'comment' AND target_id = ?`, + [commentId], + ); + + // 4. Hard delete le commentaire + await dbRun("DELETE FROM comments WHERE id = ?", [commentId]); + + console.log( + `🗑️ Commentaire ${commentId} et ${replyIds.length} réponse(s) supprimés définitivement`, + ); + } catch (error) { + console.error( + "Erreur lors de la suppression définitive du commentaire:", + error, + ); + throw error; + } +} + +// Fonction pour récupérer l'adresse IP de la requête +// Priorité : cf-connecting-ip (Cloudflare, impossible à spoof) > x-real-ip > x-forwarded-for > fallbacks +function getClientIp(req) { + return ( + req.headers["cf-connecting-ip"] || + req.headers["x-real-ip"] || + req.headers["x-forwarded-for"]?.split(",")[0].trim() || + req.ip || + req.connection?.remoteAddress || + req.socket?.remoteAddress || + "Unknown" + ); +} + +// Fonction pour envoyer un webhook Discord +async function sendDiscordWebhook(type, data) { + try { + const { + username, + avatar, + content, + contentType, + contentId, + isSpoiler, + isVip, + isAdmin, + replyToUsername, + userId, + userType, + profileId, + ipAddress, + } = data; + + // Validation et limitation des valeurs selon les spécifications Discord + // Description: max 2048 caractères + const description = + content && typeof content === "string" + ? content.length > 2048 + ? content.substring(0, 2045) + "..." + : content + : "Aucun contenu"; + + // Titre: max 256 caractères + const title = ( + type === "comment" ? "💬 Nouveau commentaire" : "💬 Nouvelle réponse" + ).substring(0, 256); + + // Champs: name max 256, value max 1024 caractères + const usernameValue = String(username || "Utilisateur").substring(0, 1024); + const contentTypeValue = String( + contentType === "movie" + ? "🎬 Film" + : contentType === "tv" + ? "📺 Série" + : contentType || "Inconnu", + ).substring(0, 1024); + const contentIdValue = String(contentId || "N/A").substring(0, 1024); + + // Construire le lien vers le film/série + const contentUrl = + contentId && contentType + ? `${FRONTEND_BASE_URL}/${contentType === "movie" ? "movie" : "tv"}/${contentId}` + : null; + + const embed = { + title: title, + description: description, + color: isAdmin ? 0xff0000 : isVip ? 0xffd700 : 0x3498db, + url: contentUrl || undefined, // Lien cliquable sur le titre + fields: [ + { + name: "👤 Utilisateur".substring(0, 256), + value: usernameValue, + inline: true, + }, + { + name: "📺 Contenu".substring(0, 256), + value: contentTypeValue, + inline: true, + }, + { + name: "🆔 ID Contenu".substring(0, 256), + value: contentIdValue, + inline: true, + }, + ], + timestamp: new Date().toISOString(), + footer: { + text: String( + isAdmin ? "👑 Administrateur" : isVip ? "⭐ VIP" : "👤 Utilisateur", + ).substring(0, 2048), + }, + }; + + // Ajouter les informations utilisateur + if (userId) { + embed.fields.push({ + name: "🆔 User ID".substring(0, 256), + value: String(userId).substring(0, 1024), + inline: true, + }); + } + + if (profileId) { + embed.fields.push({ + name: "🎭 Profile ID".substring(0, 256), + value: String(profileId).substring(0, 1024), + inline: true, + }); + } + + if (userType) { + embed.fields.push({ + name: "🔐 User Type".substring(0, 256), + value: String(userType).substring(0, 1024), + inline: true, + }); + } + + if (ipAddress) { + embed.fields.push({ + name: "🌐 IP Address".substring(0, 256), + value: String(ipAddress).substring(0, 1024), + inline: true, + }); + } + + // Ajouter un champ avec le lien si disponible + if (contentUrl) { + embed.fields.push({ + name: "🔗 Lien".substring(0, 256), + value: + `[Voir ${contentType === "movie" ? "le film" : "la série"}](${contentUrl})`.substring( + 0, + 1024, + ), + inline: false, + }); + } + + if (isSpoiler) { + embed.fields.push({ + name: "⚠️ Spoiler".substring(0, 256), + value: "Oui", + inline: true, + }); + } + + if (type === "reply" && replyToUsername) { + embed.fields.push({ + name: "↩️ Réponse à".substring(0, 256), + value: String(replyToUsername).substring(0, 1024), + inline: true, + }); + } + + // Vérifier que l'avatar est une URL valide + if ( + avatar && + typeof avatar === "string" && + avatar.trim().length > 0 && + (avatar.startsWith("http://") || avatar.startsWith("https://")) + ) { + embed.thumbnail = { + url: avatar.trim().substring(0, 2048), + }; + } + + await axios.post( + DISCORD_WEBHOOK_URL, + { + embeds: [embed], + }, + { + headers: { + "Content-Type": "application/json", + }, + timeout: 10000, + }, + ); + } catch (error) { + console.error( + "Erreur lors de l'envoi du webhook Discord:", + error.response?.data || error.message, + ); + // Ne pas bloquer l'exécution si le webhook échoue + } +} + +// ==================== ROUTES NOTIFICATIONS ==================== + +// GET /api/comments/notifications - Récupérer les notifications de l'utilisateur +router.get("/notifications", requireAuth, async (req, res) => { + try { + const { page = 1, limit = 20, unreadOnly = false, profileId } = req.query; + const safePage = Math.max(1, Math.min(parseInt(page) || 1, 1000)); + const safeLimit = Math.max(1, Math.min(parseInt(limit) || 20, 100)); + const offset = (safePage - 1) * safeLimit; + + // Validation du profileId + if (!profileId) { + return res.status(400).json({ error: "profileId requis" }); + } + + let query = + "SELECT * FROM notifications WHERE user_id = ? AND user_type = ? AND profile_id = ?"; + const params = [req.user.userId, req.user.userType, profileId]; + + if (unreadOnly === "true") { + query += " AND is_read = 0"; + } + + query += " ORDER BY created_at DESC LIMIT ? OFFSET ?"; + params.push(safeLimit, offset); + + const notifications = await dbAll(query, params); + + res.json({ notifications }); + } catch (error) { + console.error("Erreur lors de la récupération des notifications:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// PUT /api/comments/notifications/:id/read - Marquer une notification comme lue +router.put("/notifications/:id/read", requireAuth, async (req, res) => { + try { + const { id } = req.params; + const { profileId } = req.body; + + // Validation du profileId + if (!profileId) { + return res.status(400).json({ error: "profileId requis" }); + } + + await dbRun( + "UPDATE notifications SET is_read = 1 WHERE id = ? AND user_id = ? AND user_type = ? AND profile_id = ?", + [id, req.user.userId, req.user.userType, profileId], + ); + + res.json({ message: "Notification marquée comme lue" }); + } catch (error) { + console.error("Erreur lors du marquage de la notification:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// PUT /api/comments/notifications/read-all - Marquer toutes les notifications comme lues +router.put("/notifications/read-all", requireAuth, async (req, res) => { + try { + const { profileId } = req.body; + + // Validation du profileId + if (!profileId) { + return res.status(400).json({ error: "profileId requis" }); + } + + await dbRun( + "UPDATE notifications SET is_read = 1 WHERE user_id = ? AND user_type = ? AND profile_id = ?", + [req.user.userId, req.user.userType, profileId], + ); + + res.json({ + message: "Toutes les notifications ont été marquées comme lues", + }); + } catch (error) { + console.error("Erreur lors du marquage des notifications:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// DELETE /api/comments/notifications/:id - Supprimer une notification +router.delete("/notifications/:id", requireAuth, async (req, res) => { + try { + const { id } = req.params; + const { profileId } = req.query; + + // Validation du profileId + if (!profileId) { + return res.status(400).json({ error: "profileId requis" }); + } + + // Vérifier que la notification appartient à l'utilisateur et au profil + const notification = await dbGet( + "SELECT * FROM notifications WHERE id = ? AND user_id = ? AND user_type = ? AND profile_id = ?", + [id, req.user.userId, req.user.userType, profileId], + ); + + if (!notification) { + return res.status(404).json({ error: "Notification non trouvée" }); + } + + // Supprimer la notification + await dbRun( + "DELETE FROM notifications WHERE id = ? AND user_id = ? AND user_type = ? AND profile_id = ?", + [id, req.user.userId, req.user.userType, profileId], + ); + + res.json({ message: "Notification supprimée" }); + } catch (error) { + console.error("Erreur lors de la suppression de la notification:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// ==================== ROUTES RÉACTIONS ==================== + +// POST /api/comments/react - Ajouter/retirer une réaction +router.post("/react", requireAuth, async (req, res) => { + try { + const { targetType, targetId, profileId } = req.body; // targetType: 'comment' ou 'reply' + + // Verify profile ownership + const userProfileIds = await getProfileIds( + req.user.userId, + req.user.userType, + ); + if (!userProfileIds.includes(profileId)) { + return res.status(403).json({ error: "Profil non autorisé" }); + } + + // Vérifier si la réaction existe déjà + const existingReaction = await dbGet( + "SELECT * FROM comment_reactions WHERE target_type = ? AND target_id = ? AND user_id = ? AND user_type = ? AND profile_id = ?", + [targetType, targetId, req.user.userId, req.user.userType, profileId], + ); + + if (existingReaction) { + // Retirer la réaction + await dbRun("DELETE FROM comment_reactions WHERE id = ?", [ + existingReaction.id, + ]); + + res.json({ reacted: false }); + } else { + // Ajouter la réaction + await dbRun( + "INSERT INTO comment_reactions (target_type, target_id, user_id, user_type, profile_id, created_at) VALUES (?, ?, ?, ?, ?, ?)", + [ + targetType, + targetId, + req.user.userId, + req.user.userType, + profileId, + Date.now(), + ], + ); + + // Créer une notification pour l'auteur du commentaire/réponse + let targetUserId, targetUserType, targetProfileId, contentType, contentId; + if (targetType === "comment") { + const comment = await dbGet("SELECT * FROM comments WHERE id = ?", [ + targetId, + ]); + if (comment) { + targetUserId = comment.user_id; + targetUserType = comment.user_type; + targetProfileId = comment.profile_id; + contentType = comment.content_type; + contentId = comment.content_id; + + // Ne pas créer de notification si on réagit à son propre commentaire + if ( + targetUserId !== req.user.userId || + targetUserType !== req.user.userType || + targetProfileId !== profileId + ) { + const userData = await getUserData( + req.user.userId, + req.user.userType, + profileId, + ); + await createNotification( + targetUserId, + targetUserType, + targetProfileId, + req.user.userId, + profileId, + userData.username, + userData.avatar, + "reaction", + targetType, + targetId, + contentType, + contentId, + comment.content.substring(0, 100), + ); + } + } + } else if (targetType === "reply") { + const reply = await dbGet( + "SELECT * FROM comment_replies WHERE id = ?", + [targetId], + ); + if (reply) { + targetUserId = reply.user_id; + targetUserType = reply.user_type; + targetProfileId = reply.profile_id; + + // Récupérer le commentaire parent pour avoir le contentType et contentId + const comment = await dbGet("SELECT * FROM comments WHERE id = ?", [ + reply.comment_id, + ]); + if (comment) { + contentType = comment.content_type; + contentId = comment.content_id; + + // Ne pas créer de notification si on réagit à sa propre réponse + if ( + targetUserId !== req.user.userId || + targetUserType !== req.user.userType || + targetProfileId !== profileId + ) { + const userData = await getUserData( + req.user.userId, + req.user.userType, + profileId, + ); + await createNotification( + targetUserId, + targetUserType, + targetProfileId, + req.user.userId, + profileId, + userData.username, + userData.avatar, + "reaction", + targetType, + targetId, + contentType, + contentId, + reply.content.substring(0, 100), + ); + } + } + } + } + + res.json({ reacted: true }); + } + } catch (error) { + console.error("Erreur lors de la gestion de la réaction:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// GET /api/comments/reactions/:targetType/:targetId - Vérifier si l'utilisateur a réagi +router.get( + "/reactions/:targetType/:targetId", + requireAuth, + async (req, res) => { + try { + const { targetType, targetId } = req.params; + const { profileId } = req.query; + + const reaction = await dbGet( + "SELECT * FROM comment_reactions WHERE target_type = ? AND target_id = ? AND user_id = ? AND user_type = ? AND profile_id = ?", + [targetType, targetId, req.user.userId, req.user.userType, profileId], + ); + + res.json({ reacted: !!reaction }); + } catch (error) { + console.error("Erreur lors de la vérification de la réaction:", error); + res.status(500).json({ error: "Erreur serveur" }); + } + }, +); + +// ==================== ROUTES RÉPONSES ==================== + +// GET /api/comments/:commentId/replies - Récupérer les réponses d'un commentaire (avec ordre hiérarchique) +// === #13: Optimisé — une seule requête SQL avec sous-requêtes au lieu de N+1 === +router.get("/:commentId/replies", async (req, res) => { + try { + const { commentId } = req.params; + const { page = 1, limit = 3 } = req.query; + const offset = (page - 1) * limit; + + // Tenter de récupérer l'utilisateur connecté (optionnel) + let currentUser = null; + const token = req.headers.authorization?.split(" ")[1]; + if (token) { + try { + const decoded = jwt.verify(token, JWT_SECRET, { + algorithms: ["HS256"], + }); + currentUser = { + userId: decoded.sub, + userType: decoded.userType, + sessionId: decoded.sessionId, + }; + } catch (error) { + // Token invalide, on continue sans utilisateur + } + } + + const { profileId } = req.query; + + // Récupérer le total de réponses + const totalResult = await dbGet( + "SELECT COUNT(*) as total FROM comment_replies WHERE comment_id = ? AND deleted = 0", + [commentId], + ); + + // #13: Requête unique avec COUNT des réactions + check user reaction via sous-requête + let repliesQuery; + let repliesParams; + + if (currentUser && profileId) { + repliesQuery = ` + SELECT cr.*, + (SELECT COUNT(*) FROM comment_reactions WHERE target_type = 'reply' AND target_id = cr.id) as reaction_count, + EXISTS(SELECT 1 FROM comment_reactions WHERE target_type = 'reply' AND target_id = cr.id + AND user_id = ? AND user_type = ? AND profile_id = ?) as user_reacted + FROM comment_replies cr + WHERE cr.comment_id = ? AND cr.deleted = 0 + ORDER BY cr.hierarchical_path ASC + LIMIT ? OFFSET ?`; + repliesParams = [ + currentUser.userId, + currentUser.userType, + profileId, + commentId, + parseInt(limit), + parseInt(offset), + ]; + } else { + repliesQuery = ` + SELECT cr.*, + (SELECT COUNT(*) FROM comment_reactions WHERE target_type = 'reply' AND target_id = cr.id) as reaction_count + FROM comment_replies cr + WHERE cr.comment_id = ? AND cr.deleted = 0 + ORDER BY cr.hierarchical_path ASC + LIMIT ? OFFSET ?`; + repliesParams = [commentId, parseInt(limit), parseInt(offset)]; + } + + const replies = await dbAll(repliesQuery, repliesParams); + + // Cache utilisateur en mémoire pour cette requête (getUserData est déjà caché dans Redis via #14) + const userDataCache = new Map(); + + const repliesWithDetails = await Promise.all( + replies.map(async (reply) => { + const userKey = `${reply.user_id}:${reply.user_type}:${reply.profile_id || "default"}`; + let userData = userDataCache.get(userKey); + if (!userData) { + userData = await getUserData( + reply.user_id, + reply.user_type, + reply.profile_id, + ); + userDataCache.set(userKey, userData); + } + + return { + ...reply, + content: formatContentForResponse(reply.content), + username: userData.username, + avatar: userData.avatar, + is_vip: userData.isVip ? 1 : 0, + is_admin: userData.isAdmin ? 1 : 0, + reactions: reply.reaction_count, + userReaction: + reply.user_reacted !== undefined ? !!reply.user_reacted : null, + }; + }), + ); + + res.json({ + replies: repliesWithDetails, + total: totalResult.total, + page: parseInt(page), + limit: parseInt(limit), + hasMore: offset + repliesWithDetails.length < totalResult.total, + }); + } catch (error) { + console.error("Erreur lors de la récupération des réponses:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// POST /api/comments/:commentId/replies - Créer une réponse +router.post("/:commentId/replies", requireAuth, async (req, res) => { + try { + const { commentId } = req.params; + let { + content, + isSpoiler, + profileId, + parentReplyId, + replyToUsername, + turnstileToken, + } = req.body; + + // Vérification Turnstile + const turnstileResult = await verifyTurnstileFromRequest( + req, + turnstileToken, + ); + if (!turnstileResult.valid) + return res + .status(turnstileResult.status) + .json({ error: turnstileResult.error }); + + // Normalize content while preserving the original characters + content = normalizeCommentContent(content); + + console.log("💬 Création de réponse - Données reçues:", { + commentId, + content, + isSpoiler, + profileId, + parentReplyId, + replyToUsername, + }); + + // Verify profile ownership + const userProfileIds = await getProfileIds( + req.user.userId, + req.user.userType, + ); + if (!userProfileIds.includes(profileId)) { + return res.status(403).json({ error: "Profil non autorisé" }); + } + + // Vérification de bannissement + const replyUserData = await getUserData( + req.user.userId, + req.user.userType, + profileId, + ); + if (!replyUserData.isAdmin) { + const banStatus = await checkBan( + req.user.userId, + req.user.userType, + getClientIp(req), + ); + if (banStatus.banned) { + return res.status(403).json({ + error: "Vous êtes banni des commentaires.", + reason: banStatus.reason, + expires_at: banStatus.expires_at, + }); + } + } + + // Validation + if (!content || content.length > 500) { + return res + .status(400) + .json({ error: "La réponse doit contenir entre 1 et 500 caractères" }); + } + + // Vérifier que le commentaire existe + const comment = await dbGet( + "SELECT * FROM comments WHERE id = ? AND deleted = 0", + [commentId], + ); + if (!comment) { + console.log(`❌ Commentaire ${commentId} non trouvé`); + return res.status(404).json({ error: "Commentaire non trouvé" }); + } + console.log(`✅ Commentaire ${commentId} trouvé`); + // Récupérer les données utilisateur + const userData = await getUserData( + req.user.userId, + req.user.userType, + profileId, + ); + console.log("👤 Données utilisateur pour la réponse:", userData); + + // Calculer le hierarchical_path + let hierarchicalPath; + if (!parentReplyId) { + // Réponse racine : trouver le max des réponses racines + const maxPath = await dbGet( + `SELECT MAX(hierarchical_path) as max_path + FROM comment_replies + WHERE comment_id = ? AND parent_reply_id IS NULL AND deleted = 0`, + [commentId], + ); + + if (maxPath && maxPath.max_path) { + // Extraire le numéro et incrémenter + const currentNum = parseInt(maxPath.max_path.split(".")[0], 10); + hierarchicalPath = String(currentNum + 1).padStart(3, "0"); + } else { + // Première réponse + hierarchicalPath = "001"; + } + } else { + // Réponse à une autre réponse : récupérer le path du parent + const parentReply = await dbGet( + "SELECT hierarchical_path FROM comment_replies WHERE id = ?", + [parentReplyId], + ); + + if (!parentReply || !parentReply.hierarchical_path) { + return res.status(404).json({ error: "Réponse parent non trouvée" }); + } + + // Trouver le max des enfants de ce parent + const maxChildPath = await dbGet( + `SELECT MAX(hierarchical_path) as max_path + FROM comment_replies + WHERE comment_id = ? AND parent_reply_id = ? AND deleted = 0`, + [commentId, parentReplyId], + ); + + if (maxChildPath && maxChildPath.max_path) { + // Extraire le dernier numéro et incrémenter + const parts = maxChildPath.max_path.split("."); + const lastNum = parseInt(parts[parts.length - 1], 10); + hierarchicalPath = `${parentReply.hierarchical_path}.${String(lastNum + 1).padStart(3, "0")}`; + } else { + // Premier enfant de ce parent + hierarchicalPath = `${parentReply.hierarchical_path}.001`; + } + } + + console.log(`📊 Hierarchical path calculé: ${hierarchicalPath}`); + + // Insérer la réponse + console.log("💾 Insertion de la réponse dans la base..."); + const result = await dbRun( + `INSERT INTO comment_replies (comment_id, parent_reply_id, user_id, user_type, profile_id, username, avatar, reply_to_username, content, is_spoiler, is_vip, is_admin, created_at, hierarchical_path, ip_address) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + [ + commentId, + parentReplyId || null, + req.user.userId, + req.user.userType, + profileId, + userData.username, + userData.avatar, + replyToUsername || null, + content, + isSpoiler ? 1 : 0, + userData.isVip ? 1 : 0, + userData.isAdmin ? 1 : 0, + Date.now(), + hierarchicalPath, + getClientIp(req), + ], + ); + console.log("✅ Réponse insérée avec ID:", result.lastID); + + // Créer une notification pour l'auteur du commentaire ou de la réponse parent + let targetUserId, targetUserType, targetProfileId; + if (parentReplyId) { + const parentReply = await dbGet( + "SELECT * FROM comment_replies WHERE id = ?", + [parentReplyId], + ); + targetUserId = parentReply.user_id; + targetUserType = parentReply.user_type; + targetProfileId = parentReply.profile_id; + } else { + targetUserId = comment.user_id; + targetUserType = comment.user_type; + targetProfileId = comment.profile_id; + } + + // Ne pas créer de notification si on se répond à soi-même + if ( + targetUserId !== req.user.userId || + targetUserType !== req.user.userType || + targetProfileId !== profileId + ) { + await createNotification( + targetUserId, + targetUserType, + targetProfileId, + req.user.userId, + profileId, + userData.username, + userData.avatar, + "reply", + "reply", + result.lastID, + comment.content_type, + comment.content_id, + content.substring(0, 100), + ); + } + + // Récupérer la réponse créée + const newReply = await dbGet("SELECT * FROM comment_replies WHERE id = ?", [ + result.lastID, + ]); + + // Envoyer le webhook Discord en arrière-plan (ne pas attendre) + sendDiscordWebhook("reply", { + username: userData.username, + avatar: userData.avatar, + content, + contentType: comment.content_type, + contentId: comment.content_id, + isSpoiler, + isVip: userData.isVip, + isAdmin: userData.isAdmin, + replyToUsername, + userId: req.user.userId, + userType: req.user.userType, + profileId: profileId, + ipAddress: getClientIp(req), + }).catch((err) => + console.error("Erreur webhook Discord (non bloquant):", err), + ); + + // Modération automatique avec Gemini en arrière-plan (ne pas attendre) + moderateContentWithGemini( + result.lastID, + "reply", + content, + userData.username, + ).catch((err) => + console.error("Erreur modération Gemini réponse (non bloquant):", err), + ); + + res.status(201).json({ + ...newReply, + content: formatContentForResponse(newReply.content), + reactions: 0, + userReaction: null, + }); + } catch (error) { + console.error("Erreur lors de la création de la réponse:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// PUT /api/comments/replies/:id - Éditer une réponse +router.put("/replies/:id", requireAuth, async (req, res) => { + try { + const { id } = req.params; + let { content, isSpoiler } = req.body; + + // Normalize content while preserving the original characters + content = normalizeCommentContent(content); + + // Validation + if (!content || content.length > 500) { + return res + .status(400) + .json({ error: "La réponse doit contenir entre 1 et 500 caractères" }); + } + + // Vérifier que la réponse appartient à l'utilisateur + const reply = await dbGet("SELECT * FROM comment_replies WHERE id = ?", [ + id, + ]); + if (!reply) { + return res.status(404).json({ error: "Réponse non trouvée" }); + } + + if ( + reply.user_id !== req.user.userId || + reply.user_type !== req.user.userType + ) { + return res.status(403).json({ error: "Non autorisé" }); + } + + // Mettre à jour la réponse + await dbRun( + "UPDATE comment_replies SET content = ?, is_spoiler = ?, is_edited = 1, updated_at = ? WHERE id = ?", + [content, isSpoiler ? 1 : 0, Date.now(), id], + ); + + // Récupérer la réponse mise à jour + const updatedReply = await dbGet( + "SELECT * FROM comment_replies WHERE id = ?", + [id], + ); + + res.json({ + ...updatedReply, + content: formatContentForResponse(updatedReply.content), + }); + } catch (error) { + console.error("Erreur lors de l'édition de la réponse:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// DELETE /api/comments/replies/:id - Supprimer une réponse (admin ou auteur) +router.delete("/replies/:id", requireAuth, async (req, res) => { + try { + const { id } = req.params; + const { profileId } = req.query; + + // Récupérer la réponse + const reply = await dbGet( + "SELECT comment_id, user_id, user_type, profile_id FROM comment_replies WHERE id = ?", + [id], + ); + if (!reply) { + return res.status(404).json({ error: "Réponse non trouvée" }); + } + + // Vérifier que l'utilisateur est admin ou auteur de la réponse + const userData = await getUserData(req.user.userId, req.user.userType); + const userMatch = + String(reply.user_id) === String(req.user.userId) && + String(reply.user_type) === String(req.user.userType); + const profileMatch = + !reply.profile_id || + !profileId || + String(reply.profile_id) === String(profileId); + const isOwner = userMatch && profileMatch; + + if (!userData.isAdmin && !isOwner) { + return res.status(403).json({ error: "Non autorisé" }); + } + + // Supprimer la réponse et tous ses enfants en cascade + await deleteRepliesCascade(reply.comment_id, id); + + res.json({ + message: "Réponse et ses réponses enfants supprimées en cascade", + }); + } catch (error) { + console.error("Erreur lors de la suppression de la réponse:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// ==================== ROUTES COMMENTAIRES ==================== + +// GET /api/comments/admin/list - Lister tous les commentaires (admin uniquement) +router.get("/admin/list", requireAuth, async (req, res) => { + try { + const { + page = 1, + limit = 50, + search = "", + contentType = "all", + } = req.query; + const offset = (page - 1) * limit; + + // Vérifier que l'utilisateur est admin + const userData = await getUserData(req.user.userId, req.user.userType); + if (!userData.isAdmin) { + return res.status(403).json({ error: "Non autorisé" }); + } + + let query = + 'SELECT c.*, COUNT(r.id) as reaction_count FROM comments c LEFT JOIN comment_reactions r ON r.target_type = "comment" AND r.target_id = c.id WHERE c.deleted = 0'; + const params = []; + + if (search) { + query += + " AND (c.content LIKE ? OR c.username LIKE ? OR c.content_id LIKE ?)"; + const searchParam = `%${search}%`; + params.push(searchParam, searchParam, searchParam); + } + + if (contentType !== "all") { + query += " AND c.content_type = ?"; + params.push(contentType); + } + + query += " GROUP BY c.id ORDER BY c.created_at DESC LIMIT ? OFFSET ?"; + params.push(parseInt(limit), parseInt(offset)); + + const rawComments = await dbAll(query, params); + + // Enrichir avec les données utilisateur actuelles (Username, Avatar, VIP, Admin) + const comments = await Promise.all( + rawComments.map(async (comment) => { + const userData = await getUserData( + comment.user_id, + comment.user_type, + comment.profile_id, + ); + return { + ...comment, + content: formatContentForResponse(comment.content), + username: userData.username, + avatar: userData.avatar, + is_vip: userData.isVip, + is_admin: userData.isAdmin, + }; + }), + ); + + // Compter le total pour la pagination + let countQuery = "SELECT COUNT(*) as total FROM comments WHERE deleted = 0"; + const countParams = []; + + if (search) { + countQuery += + " AND (content LIKE ? OR username LIKE ? OR content_id LIKE ?)"; + const searchParam = `%${search}%`; + countParams.push(searchParam, searchParam, searchParam); + } + + if (contentType !== "all") { + countQuery += " AND content_type = ?"; + countParams.push(contentType); + } + + const totalResult = await dbGet(countQuery, countParams); + + // Stats — une seule requête avec CASE pour compter les stats + const statsResult = await dbGet(` + SELECT + COUNT(*) as total, + SUM(CASE WHEN content_type = 'movie' THEN 1 ELSE 0 END) as movies, + SUM(CASE WHEN content_type = 'tv' THEN 1 ELSE 0 END) as tv + FROM comments WHERE deleted = 0 + `); + const moderatedCount = ( + await dbGet(` + SELECT + (SELECT COUNT(*) FROM comments WHERE deleted = 1 AND moderation_reason IS NOT NULL) + + (SELECT COUNT(*) FROM comment_replies WHERE deleted = 1 AND moderation_reason IS NOT NULL) as total + `) + ).total; + + const stats = { + total: statsResult.total, + movies: statsResult.movies, + tv: statsResult.tv, + moderated: moderatedCount, + }; + + res.json({ + comments, + stats, + total: totalResult.total, + page: parseInt(page), + limit: parseInt(limit), + }); + } catch (error) { + console.error( + "Erreur lors de la récupération admin des commentaires:", + error, + ); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// GET /api/comments/admin/moderated - Lister les commentaires/réponses modérés (admin uniquement) +// === #17: Pagination SQL avec UNION ALL au lieu de charger tout en mémoire === +router.get("/admin/moderated", requireAuth, async (req, res) => { + try { + const { page = 1, limit = 50, type = "all" } = req.query; + const safePage = Math.max(1, parseInt(page) || 1); + const safeLimit = Math.max(1, Math.min(parseInt(limit) || 50, 100)); + const offset = (safePage - 1) * safeLimit; + + // Vérifier que l'utilisateur est admin + const userData = await getUserData(req.user.userId, req.user.userType); + if (!userData.isAdmin) { + return res.status(403).json({ error: "Non autorisé" }); + } + + // Construire les requêtes avec UNION ALL et pagination SQL + let unionParts = []; + let countParts = []; + + if (type === "all" || type === "comments") { + unionParts.push(` + SELECT c.id, c.user_id, c.user_type, c.profile_id, c.content, c.content_type, c.content_id, + c.is_spoiler, c.is_edited, c.created_at, c.moderation_reason, c.moderation_details, c.moderated_at, + 'comment' as item_type, + (SELECT COUNT(*) FROM comment_reactions WHERE target_type = 'comment' AND target_id = c.id) as reaction_count + FROM comments c + WHERE c.deleted = 1 AND c.moderation_reason IS NOT NULL + `); + countParts.push( + `SELECT COUNT(*) as cnt FROM comments WHERE deleted = 1 AND moderation_reason IS NOT NULL`, + ); + } + + if (type === "all" || type === "replies") { + unionParts.push(` + SELECT cr.id, cr.user_id, cr.user_type, cr.profile_id, cr.content, c2.content_type, c2.content_id, + cr.is_spoiler, cr.is_edited, cr.created_at, cr.moderation_reason, cr.moderation_details, cr.moderated_at, + 'reply' as item_type, + (SELECT COUNT(*) FROM comment_reactions WHERE target_type = 'reply' AND target_id = cr.id) as reaction_count + FROM comment_replies cr + JOIN comments c2 ON c2.id = cr.comment_id + WHERE cr.deleted = 1 AND cr.moderation_reason IS NOT NULL + `); + countParts.push( + `SELECT COUNT(*) as cnt FROM comment_replies WHERE deleted = 1 AND moderation_reason IS NOT NULL`, + ); + } + + if (unionParts.length === 0) { + return res.json({ + items: [], + total: 0, + page: safePage, + limit: safeLimit, + hasMore: false, + }); + } + + // Compter le total + const countQuery = + countParts.length === 1 + ? countParts[0] + : `SELECT (${countParts.map((q) => `(${q})`).join(" + ")}) as cnt`; + const totalResult = await dbGet(countQuery); + const total = totalResult.cnt; + + // Requête combinée avec UNION ALL, tri et pagination + const dataQuery = ` + SELECT * FROM ( + ${unionParts.join(" UNION ALL ")} + ) AS combined + ORDER BY moderated_at DESC + LIMIT ? OFFSET ? + `; + + const items = await dbAll(dataQuery, [safeLimit, offset]); + + // Enrichir avec les données utilisateur (getUserData est caché dans Redis via #14) + const userDataCache = new Map(); + const enrichedItems = await Promise.all( + items.map(async (item) => { + const userKey = `${item.user_id}:${item.user_type}:${item.profile_id || "default"}`; + let ud = userDataCache.get(userKey); + if (!ud) { + ud = await getUserData(item.user_id, item.user_type, item.profile_id); + userDataCache.set(userKey, ud); + } + return { + ...item, + content: formatContentForResponse(item.content), + username: ud.username, + avatar: ud.avatar, + is_vip: ud.isVip, + is_admin: ud.isAdmin, + }; + }), + ); + + res.json({ + items: enrichedItems, + total, + page: safePage, + limit: safeLimit, + hasMore: offset + enrichedItems.length < total, + }); + } catch (error) { + console.error( + "Erreur lors de la récupération des contenus modérés:", + error, + ); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// PUT /api/comments/admin/moderated/:type/:id/approve - Approuver un contenu modéré (rendre visible) +router.put( + "/admin/moderated/:type/:id/approve", + requireAuth, + async (req, res) => { + try { + const { type, id } = req.params; + + // Validate type parameter to prevent SQL injection via table name + if (!["comment", "reply"].includes(type)) { + return res + .status(400) + .json({ error: 'Type invalide. Doit être "comment" ou "reply"' }); + } + + // Vérifier que l'utilisateur est admin + const userData = await getUserData(req.user.userId, req.user.userType); + if (!userData.isAdmin) { + return res.status(403).json({ error: "Non autorisé" }); + } + + const table = type === "comment" ? "comments" : "comment_replies"; + + // Remettre deleted à 0 et garder les infos de modération pour historique + await dbRun( + `UPDATE ${table} SET deleted = 0, approved_by_admin = 1, approved_at = ? WHERE id = ?`, + [Date.now(), id], + ); + + console.log(`✅ ${type} ID ${id} approuvé par admin`); + res.json({ message: "Contenu approuvé et rendu visible" }); + } catch (error) { + console.error("Erreur lors de l'approbation du contenu:", error); + res.status(500).json({ error: "Erreur serveur" }); + } + }, +); + +// DELETE /api/comments/admin/moderated/:type/:id - Supprimer définitivement un contenu modéré +router.delete("/admin/moderated/:type/:id", requireAuth, async (req, res) => { + try { + const { type, id } = req.params; + + // Validate type parameter + if (!["comment", "reply"].includes(type)) { + return res + .status(400) + .json({ error: 'Type invalide. Doit être "comment" ou "reply"' }); + } + + // Vérifier que l'utilisateur est admin + const userData = await getUserData(req.user.userId, req.user.userType); + if (!userData.isAdmin) { + return res.status(403).json({ error: "Non autorisé" }); + } + + if (type === "comment") { + // Supprimer définitivement le commentaire et toutes ses dépendances + await hardDeleteCommentCascade(id); + } else if (type === "reply") { + // Récupérer la réponse pour obtenir le commentId + const reply = await dbGet( + "SELECT comment_id FROM comment_replies WHERE id = ?", + [id], + ); + if (reply) { + await hardDeleteRepliesCascade(reply.comment_id, id); + } + } + + console.log(`🗑️ ${type} ID ${id} supprimé définitivement par admin`); + res.json({ message: "Contenu supprimé définitivement" }); + } catch (error) { + console.error("Erreur lors de la suppression définitive:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// ==================== ROUTES BANNISSEMENT ==================== +// IMPORTANT: Ces routes doivent être AVANT /:contentType/:contentId pour éviter les conflits Express + +// POST /api/comments/admin/ban - Bannir un utilisateur ou une IP +router.post("/admin/ban", requireAuth, async (req, res) => { + try { + const userData = await getUserData(req.user.userId, req.user.userType); + if (!userData.isAdmin) { + return res.status(403).json({ error: "Non autorisé" }); + } + + const { + banType, + banValue, + userType: targetUserType, + reason, + duration, + username, + deleteAll, + } = req.body; + + if (!["ip", "user"].includes(banType) || !banValue) { + return res + .status(400) + .json({ error: "banType (ip/user) et banValue requis" }); + } + + if (banType === "user" && !targetUserType) { + return res + .status(400) + .json({ error: "userType requis pour un ban utilisateur" }); + } + + let expiresAt = null; + if (duration && duration !== "permanent") { + const durations = { + "1h": 3600000, + "24h": 86400000, + "7d": 604800000, + "30d": 2592000000, + }; + if (durations[duration]) { + expiresAt = Date.now() + durations[duration]; + } + } + + const userTypeValue = banType === "user" ? targetUserType : null; + + const existingBan = await dbGet( + "SELECT id FROM banned_users WHERE ban_type = ? AND ban_value = ? AND (user_type = ? OR (user_type IS NULL AND ? IS NULL))", + [banType, banValue, userTypeValue, userTypeValue], + ); + + if (existingBan) { + await dbRun( + "UPDATE banned_users SET reason = ?, banned_by = ?, banned_at = ?, expires_at = ?, username = ? WHERE id = ?", + [ + reason || null, + req.user.userId, + Date.now(), + expiresAt, + username || null, + existingBan.id, + ], + ); + } else { + await dbRun( + "INSERT INTO banned_users (ban_type, ban_value, user_type, reason, banned_by, banned_at, expires_at, username) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + [ + banType, + banValue, + userTypeValue, + reason || null, + req.user.userId, + Date.now(), + expiresAt, + username || null, + ], + ); + } + + let deletedCount = 0; + if (deleteAll && banType === "user") { + const commentsResult = await dbRun( + "UPDATE comments SET deleted = 1 WHERE user_id = ? AND deleted = 0", + [banValue], + ); + const repliesResult = await dbRun( + "UPDATE comment_replies SET deleted = 1 WHERE user_id = ? AND deleted = 0", + [banValue], + ); + deletedCount = + (commentsResult.changes || 0) + (repliesResult.changes || 0); + } + + res.json({ + message: "Utilisateur banni avec succès", + deletedCount, + expiresAt, + }); + } catch (error) { + console.error("Erreur lors du bannissement:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// DELETE /api/comments/admin/ban/:id - Débannir + restaurer les commentaires +router.delete("/admin/ban/:id", requireAuth, async (req, res) => { + try { + const userData = await getUserData(req.user.userId, req.user.userType); + if (!userData.isAdmin) { + return res.status(403).json({ error: "Non autorisé" }); + } + + const { id } = req.params; + const restoreComments = req.query.restore === "true"; + + let restoredCount = 0; + if (restoreComments) { + const ban = await dbGet("SELECT * FROM banned_users WHERE id = ?", [id]); + if (ban && ban.ban_type === "user") { + const r1 = await dbRun( + "UPDATE comments SET deleted = 0 WHERE user_id = ? AND deleted = 1 AND moderation_reason IS NULL", + [ban.ban_value], + ); + const r2 = await dbRun( + "UPDATE comment_replies SET deleted = 0 WHERE user_id = ? AND deleted = 1 AND moderation_reason IS NULL", + [ban.ban_value], + ); + restoredCount = (r1.changes || 0) + (r2.changes || 0); + } + } + + await dbRun("DELETE FROM banned_users WHERE id = ?", [id]); + res.json({ message: "Ban supprimé avec succès", restoredCount }); + } catch (error) { + console.error("Erreur lors du débannissement:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// DELETE /api/comments/admin/bans - Supprimer tous les bans + restaurer les commentaires +router.delete("/admin/bans", requireAuth, async (req, res) => { + try { + const userData = await getUserData(req.user.userId, req.user.userType); + if (!userData.isAdmin) { + return res.status(403).json({ error: "Non autorisé" }); + } + + const restoreComments = req.query.restore === "true"; + + let restoredCount = 0; + if (restoreComments) { + const userBans = await dbAll( + "SELECT ban_value FROM banned_users WHERE ban_type = 'user'", + ); + if (userBans.length > 0) { + const placeholders = userBans.map(() => "?").join(","); + const userIds = userBans.map((b) => b.ban_value); + const r1 = await dbRun( + `UPDATE comments SET deleted = 0 WHERE user_id IN (${placeholders}) AND deleted = 1 AND moderation_reason IS NULL`, + userIds, + ); + const r2 = await dbRun( + `UPDATE comment_replies SET deleted = 0 WHERE user_id IN (${placeholders}) AND deleted = 1 AND moderation_reason IS NULL`, + userIds, + ); + restoredCount = (r1.changes || 0) + (r2.changes || 0); + } + } + + const result = await dbRun("DELETE FROM banned_users"); + res.json({ + message: `${result.changes || 0} ban(s) supprimé(s)`, + deletedCount: result.changes || 0, + restoredCount, + }); + } catch (error) { + console.error("Erreur lors de la suppression de tous les bans:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// GET /api/comments/admin/bans - Lister les bans actifs +router.get("/admin/bans", requireAuth, async (req, res) => { + try { + const userData = await getUserData(req.user.userId, req.user.userType); + if (!userData.isAdmin) { + return res.status(403).json({ error: "Non autorisé" }); + } + + const { showExpired, page = "1", limit = "30", search } = req.query; + const pageNum = Math.max(1, parseInt(page)); + const limitNum = Math.min(100, Math.max(1, parseInt(limit))); + const offset = (pageNum - 1) * limitNum; + + let whereClause = ""; + const params = []; + const countParams = []; + + if (showExpired !== "true") { + whereClause = " WHERE (expires_at IS NULL OR expires_at > ?)"; + params.push(Date.now()); + countParams.push(Date.now()); + } + + if (search && search.trim()) { + const searchTerm = `%${search.trim()}%`; + whereClause += whereClause ? " AND" : " WHERE"; + whereClause += " (ban_value LIKE ? OR username LIKE ? OR reason LIKE ?)"; + params.push(searchTerm, searchTerm, searchTerm); + countParams.push(searchTerm, searchTerm, searchTerm); + } + + const countResult = await dbAll( + `SELECT COUNT(*) as total FROM banned_users${whereClause}`, + countParams, + ); + const total = countResult[0]?.total || 0; + + params.push(limitNum, offset); + const bans = await dbAll( + `SELECT * FROM banned_users${whereClause} ORDER BY banned_at DESC LIMIT ? OFFSET ?`, + params, + ); + res.json({ + bans, + total, + page: pageNum, + limit: limitNum, + hasMore: offset + bans.length < total, + }); + } catch (error) { + console.error("Erreur lors de la récupération des bans:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// POST /api/comments/admin/delete-all-by-user - Supprimer tous les commentaires d'un utilisateur +router.post("/admin/delete-all-by-user", requireAuth, async (req, res) => { + try { + const userData = await getUserData(req.user.userId, req.user.userType); + if (!userData.isAdmin) { + return res.status(403).json({ error: "Non autorisé" }); + } + + const { userId } = req.body; + if (!userId) { + return res.status(400).json({ error: "userId requis" }); + } + + const commentsResult = await dbRun( + "UPDATE comments SET deleted = 1 WHERE user_id = ? AND deleted = 0", + [userId], + ); + const repliesResult = await dbRun( + "UPDATE comment_replies SET deleted = 1 WHERE user_id = ? AND deleted = 0", + [userId], + ); + + const totalDeleted = + (commentsResult.changes || 0) + (repliesResult.changes || 0); + res.json({ + message: `${totalDeleted} commentaire(s) et réponse(s) supprimé(s)`, + deletedComments: commentsResult.changes || 0, + deletedReplies: repliesResult.changes || 0, + }); + } catch (error) { + console.error("Erreur lors de la suppression en masse:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// Normalise le texte Unicode : petites majuscules, caractères spéciaux → ASCII, puis trim + lowercase +function normalizeText(text) { + if (!text) return ""; + // Map des petites majuscules Unicode et variantes courantes → ASCII + const unicodeMap = { + ᴀ: "a", + ʙ: "b", + ᴄ: "c", + ᴅ: "d", + ᴇ: "e", + ꜰ: "f", + ɢ: "g", + ʜ: "h", + ɪ: "i", + ᴊ: "j", + ᴋ: "k", + ʟ: "l", + ᴍ: "m", + ɴ: "n", + ᴏ: "o", + ᴘ: "p", + ǫ: "q", + ʀ: "r", + ꜱ: "s", + ᴛ: "t", + ᴜ: "u", + ᴠ: "v", + ᴡ: "w", + x: "x", + ʏ: "y", + ᴢ: "z", + a: "a", + b: "b", + c: "c", + d: "d", + e: "e", + f: "f", + g: "g", + h: "h", + i: "i", + j: "j", + k: "k", + l: "l", + m: "m", + n: "n", + o: "o", + p: "p", + q: "q", + r: "r", + s: "s", + t: "t", + u: "u", + v: "v", + w: "w", + x: "x", + y: "y", + z: "z", + A: "a", + B: "b", + C: "c", + D: "d", + E: "e", + F: "f", + G: "g", + H: "h", + I: "i", + J: "j", + K: "k", + L: "l", + M: "m", + N: "n", + O: "o", + P: "p", + Q: "q", + R: "r", + S: "s", + T: "t", + U: "u", + V: "v", + W: "w", + X: "x", + Y: "y", + Z: "z", + "𝐚": "a", + "𝐛": "b", + "𝐜": "c", + "𝐝": "d", + "𝐞": "e", + "𝐟": "f", + "𝐠": "g", + "𝐡": "h", + "𝐢": "i", + "𝐣": "j", + "𝐤": "k", + "𝐥": "l", + "𝐦": "m", + "𝐧": "n", + "𝐨": "o", + "𝐩": "p", + "𝐪": "q", + "𝐫": "r", + "𝐬": "s", + "𝐭": "t", + "𝐮": "u", + "𝐯": "v", + "𝐰": "w", + "𝐱": "x", + "𝐲": "y", + "𝐳": "z", + "⒜": "a", + "⒝": "b", + "⒞": "c", + "⒟": "d", + "⒠": "e", + "⒡": "f", + "⒢": "g", + "⒣": "h", + "⒤": "i", + "⒥": "j", + "⒦": "k", + "⒧": "l", + "⒨": "m", + "⒩": "n", + "⒪": "o", + "⒫": "p", + "⒬": "q", + "⒭": "r", + "⒮": "s", + "⒯": "t", + "⒰": "u", + "⒱": "v", + "⒲": "w", + "⒳": "x", + "⒴": "y", + "⒵": "z", + ".": ".", + "。": ".", + "·": ".", + "⋅": ".", + "∙": ".", + }; + let normalized = ""; + for (const char of text) { + normalized += unicodeMap[char] || char; + } + return normalized + .normalize("NFKD") + .replace(/[\u0300-\u036f]/g, "") // supprimer les accents diacritiques + .toLowerCase() + .trim() + .replace(/\s+/g, " "); // normaliser les espaces multiples +} + +// Détecte si un texte contient des caractères Unicode "fancy" (spam) +function containsFancyUnicode(text) { + if (!text) return false; + // IPA Extensions (ʟ,ʀ,ɴ,ʏ,ɢ,ʙ,ʜ,ɪ), petites majuscules latines, fullwidth, math bold/italic, parenthesized, circled + return /[\u0250-\u02AF\u1D00-\u1D7F\uFF01-\uFF5E\u{1D400}-\u{1D7FF}\u2474-\u2497\u249C-\u24E9\u2460-\u2473]/u.test( + text, + ); +} + +// POST /api/comments/admin/detect-duplicates - Détecter les commentaires en doublons +router.post("/admin/detect-duplicates", requireAuth, async (req, res) => { + try { + const userData = await getUserData(req.user.userId, req.user.userType); + if (!userData.isAdmin) { + return res.status(403).json({ error: "Non autorisé" }); + } + + // Récupérer tous les commentaires non supprimés + const allComments = await dbAll(` + SELECT id, user_id, user_type, profile_id, username, avatar, + content, content_type, content_id, created_at + FROM comments + WHERE deleted = 0 + ORDER BY created_at ASC + `); + + // Grouper par contenu normalisé (trim + lowercase + unicode → ASCII) + const groupMap = new Map(); + const fancyUnicodeComments = []; + + for (const c of allComments) { + const key = normalizeText(c.content); + + if (!groupMap.has(key)) { + groupMap.set(key, { + content: c.content, + normalizedContent: key, + count: 0, + firstPosted: c.created_at, + lastPosted: c.created_at, + comments: [], + }); + } + const group = groupMap.get(key); + group.count++; + group.lastPosted = c.created_at; + group.comments.push({ + id: c.id, + user_id: c.user_id, + user_type: c.user_type, + profile_id: c.profile_id, + username: c.username, + avatar: c.avatar, + content: c.content, + content_type: c.content_type, + content_id: c.content_id, + created_at: c.created_at, + ip_address: c.ip_address, + }); + + // Détecter les commentaires avec polices Unicode spéciales (spam) + if (containsFancyUnicode(c.content)) { + fancyUnicodeComments.push({ + id: c.id, + user_id: c.user_id, + user_type: c.user_type, + profile_id: c.profile_id, + username: c.username, + avatar: c.avatar, + content: c.content, + content_type: c.content_type, + content_id: c.content_id, + created_at: c.created_at, + ip_address: c.ip_address, + }); + } + } + + // Ne garder que les vrais doublons (>1 commentaire par groupe) + const duplicates = [...groupMap.values()] + .filter((g) => g.count > 1) + .sort((a, b) => b.count - a.count) + .slice(0, 50); + + // Grouper les commentaires fancy unicode + const fancyGroup = + fancyUnicodeComments.length > 0 + ? { + content: "⚠️ Polices Unicode spéciales (spam)", + normalizedContent: "__fancy_unicode__", + count: fancyUnicodeComments.length, + firstPosted: fancyUnicodeComments[0]?.created_at, + lastPosted: + fancyUnicodeComments[fancyUnicodeComments.length - 1]?.created_at, + comments: fancyUnicodeComments, + isFancyUnicode: true, + } + : null; + + res.json({ duplicates, fancyUnicode: fancyGroup }); + } catch (error) { + console.error("Erreur lors de la détection des doublons:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// POST /api/comments/admin/delete-duplicates - Supprimer les doublons et optionnellement bannir les auteurs +router.post("/admin/delete-duplicates", requireAuth, async (req, res) => { + try { + const userData = await getUserData(req.user.userId, req.user.userType); + if (!userData.isAdmin) { + return res.status(403).json({ error: "Non autorisé" }); + } + + const { commentIds, banAuthors, banDuration, banReason } = req.body; + + if (!commentIds || !Array.isArray(commentIds) || commentIds.length === 0) { + return res.status(400).json({ error: "commentIds requis (tableau)" }); + } + + const BATCH_SIZE = 500; + let totalDeleted = 0; + + for (let i = 0; i < commentIds.length; i += BATCH_SIZE) { + const batch = commentIds.slice(i, i + BATCH_SIZE); + const placeholders = batch.map(() => "?").join(","); + const result = await dbRun( + `UPDATE comments SET deleted = 1 WHERE id IN (${placeholders}) AND deleted = 0`, + batch, + ); + totalDeleted += result.changes || 0; + } + + let bannedCount = 0; + if (banAuthors) { + const allPlaceholders = commentIds.map(() => "?").join(","); + const authors = await dbAll( + `SELECT DISTINCT user_id, user_type, username FROM comments WHERE id IN (${allPlaceholders})`, + commentIds, + ); + + if (authors.length > 0) { + const adminCheckPlaceholders = authors.map(() => "(?, ?)").join(","); + const adminCheckParams = authors.flatMap((a) => [ + a.user_id, + a.user_type === "bip39" ? "bip-39" : a.user_type, + ]); + const adminRows = await dbAll( + `SELECT user_id, auth_type FROM admins WHERE (user_id, auth_type) IN (${adminCheckPlaceholders})`, + adminCheckParams, + ); + const adminSet = new Set( + adminRows.map((a) => `${a.user_id}:${a.auth_type}`), + ); + + const banCheckPlaceholders = authors.map(() => "(?, ?)").join(","); + const banCheckParams = authors.flatMap((a) => [a.user_id, a.user_type]); + const existingBans = await dbAll( + `SELECT ban_value, user_type FROM banned_users WHERE ban_type = 'user' AND (ban_value, user_type) IN (${banCheckPlaceholders})`, + banCheckParams, + ); + const bannedSet = new Set( + existingBans.map((b) => `${b.ban_value}:${b.user_type}`), + ); + + let expiresAt = null; + if (banDuration && banDuration !== "permanent") { + const durations = { + "1h": 3600000, + "24h": 86400000, + "7d": 604800000, + "30d": 2592000000, + }; + if (durations[banDuration]) + expiresAt = Date.now() + durations[banDuration]; + } + + const now = Date.now(); + const reasonText = banReason || "Spam / Doublons"; + const toBan = authors.filter((a) => { + const authType = a.user_type === "bip39" ? "bip-39" : a.user_type; + const isAdmin = adminSet.has(`${a.user_id}:${authType}`); + const alreadyBanned = bannedSet.has(`${a.user_id}:${a.user_type}`); + return !isAdmin && !alreadyBanned; + }); + + for (let i = 0; i < toBan.length; i += 100) { + const batch = toBan.slice(i, i + 100); + const insertPlaceholders = batch + .map(() => "(?, ?, ?, ?, ?, ?, ?, ?)") + .join(","); + const insertParams = batch.flatMap((a) => [ + "user", + a.user_id, + a.user_type, + reasonText, + req.user.userId, + now, + expiresAt, + a.username || null, + ]); + await dbRun( + `INSERT IGNORE INTO banned_users (ban_type, ban_value, user_type, reason, banned_by, banned_at, expires_at, username) VALUES ${insertPlaceholders}`, + insertParams, + ); + } + bannedCount = toBan.length; + } + } + + res.json({ + message: `${totalDeleted} commentaire(s) supprimé(s), ${bannedCount} utilisateur(s) banni(s)`, + deletedCount: totalDeleted, + bannedCount, + }); + } catch (error) { + console.error("Erreur lors de la suppression des doublons:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// GET /api/comments/limits - Vérifier les limites de commentaires +router.get("/limits", requireAuth, async (req, res) => { + try { + const { contentType, contentId, profileId } = req.query; + + if (!contentType || !contentId) { + return res.status(400).json({ error: "contentType et contentId requis" }); + } + + const userData = await getUserData( + req.user.userId, + req.user.userType, + profileId, + ); + + if (userData.isAdmin) { + return res.json({ + movieCount: 0, + hourCount: 0, + movieLimit: null, + hourLimit: null, + isAdmin: true, + }); + } + + const movieComments = await dbGet( + "SELECT COUNT(*) as count FROM comments WHERE user_id = ? AND content_type = ? AND content_id = ? AND deleted = 0", + [req.user.userId, contentType, contentId], + ); + + const oneHourAgo = Date.now() - 3600000; + const hourComments = await dbGet( + "SELECT COUNT(*) as count FROM comments WHERE user_id = ? AND created_at > ?", + [req.user.userId, oneHourAgo], + ); + + res.json({ + movieCount: movieComments.count, + hourCount: hourComments.count, + movieLimit: 3, + hourLimit: 10, + isAdmin: false, + }); + } catch (error) { + console.error("Erreur lors de la récupération des limites:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// ==================== ROUTES REPORTS (avant les routes dynamiques) ==================== + +const rateLimit = require("express-rate-limit"); + +const reportRateLimit = rateLimit({ + windowMs: 15 * 60 * 1000, + max: 10, + standardHeaders: true, + legacyHeaders: false, + message: { error: "Trop de signalements. Réessayez dans 15 minutes." }, + keyGenerator: (req) => + req.headers["cf-connecting-ip"] || + req.headers["x-forwarded-for"]?.split(",")[0].trim() || + req.ip, + validate: { + xForwardedForHeader: false, + ip: false, + keyGeneratorIpFallback: false, + }, +}); + +const VALID_REPORT_REASONS = [ + "spam", + "harassment", + "sexual_content", + "unmarked_spoiler", + "impersonation", + "other", +]; +const VALID_TARGET_TYPES = ["comment", "reply", "shared_list"]; + +// POST /api/comments/report - Créer un signalement +router.post("/report", requireAuth, reportRateLimit, async (req, res) => { + try { + const { targetType, targetId, reason, details } = req.body; + const { userId, userType } = req.user; + const profileId = req.body.profileId; + + if (!targetType || !targetId || !reason) { + return res + .status(400) + .json({ error: "targetType, targetId et reason sont requis" }); + } + if (!VALID_TARGET_TYPES.includes(targetType)) { + return res.status(400).json({ error: "targetType invalide" }); + } + if (!VALID_REPORT_REASONS.includes(reason)) { + return res.status(400).json({ error: "reason invalide" }); + } + if (!profileId) { + return res.status(400).json({ error: "profileId requis" }); + } + if (details && details.length > 500) { + return res + .status(400) + .json({ error: "Les détails ne peuvent pas dépasser 500 caractères" }); + } + + const allowedProfiles = await getProfileIds(userId, userType); + if (allowedProfiles.length > 0 && !allowedProfiles.includes(profileId)) { + return res + .status(403) + .json({ error: "Ce profil ne vous appartient pas" }); + } + + if (targetType === "comment") { + const comment = await dbGet( + "SELECT id, user_id, profile_id FROM comments WHERE id = ? AND deleted = 0", + [targetId], + ); + if (!comment) + return res.status(404).json({ error: "Commentaire non trouvé" }); + if ( + String(comment.user_id) === String(userId) && + String(comment.profile_id) === String(profileId) + ) { + return res + .status(400) + .json({ + error: "Vous ne pouvez pas signaler votre propre commentaire", + }); + } + } else if (targetType === "reply") { + const reply = await dbGet( + "SELECT id, user_id, profile_id FROM comment_replies WHERE id = ? AND deleted = 0", + [targetId], + ); + if (!reply) return res.status(404).json({ error: "Réponse non trouvée" }); + if ( + String(reply.user_id) === String(userId) && + String(reply.profile_id) === String(profileId) + ) { + return res + .status(400) + .json({ error: "Vous ne pouvez pas signaler votre propre réponse" }); + } + } else if (targetType === "shared_list") { + const pool = getCachedPool(); + const [rows] = await pool.execute( + "SELECT id, user_id, share_code FROM shared_lists WHERE share_code = ? OR id = ?", + [targetId, targetId], + ); + if (rows.length === 0) + return res.status(404).json({ error: "Liste partagée non trouvée" }); + if (String(rows[0].user_id) === String(userId)) { + return res + .status(400) + .json({ error: "Vous ne pouvez pas signaler votre propre liste" }); + } + } + + try { + await dbRun( + `INSERT INTO reports (reporter_user_id, reporter_user_type, reporter_profile_id, target_type, target_id, reason, details, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + [ + userId, + userType, + profileId, + targetType, + targetId, + reason, + details || null, + Date.now(), + ], + ); + } catch (err) { + if (err.code === "ER_DUP_ENTRY") { + return res + .status(409) + .json({ error: "Vous avez déjà signalé ce contenu" }); + } + throw err; + } + + res.status(201).json({ success: true, message: "Signalement envoyé" }); + } catch (error) { + console.error("Erreur lors du signalement:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// GET /api/comments/admin/reports - Lister les signalements (admin) +router.get("/admin/reports", requireAuth, async (req, res) => { + try { + const userData = await getUserData(req.user.userId, req.user.userType); + if (!userData.isAdmin) + return res.status(403).json({ error: "Non autorisé" }); + + const status = req.query.status || "pending"; + const targetType = req.query.targetType || "all"; + const pageNum = Math.max(1, Number(req.query.page) || 1); + const limitNum = Math.min(100, Math.max(1, Number(req.query.limit) || 30)); + const offset = (pageNum - 1) * limitNum; + + let query = `SELECT r.*, + (SELECT COUNT(*) FROM reports r2 WHERE r2.target_type = r.target_type AND r2.target_id = r.target_id AND r2.status = 'pending') as report_count + FROM reports r WHERE 1=1`; + const params = []; + + if (status !== "all") { + query += " AND r.status = ?"; + params.push(status); + } + if (targetType !== "all") { + query += " AND r.target_type = ?"; + params.push(targetType); + } + + query += " ORDER BY r.created_at DESC LIMIT ? OFFSET ?"; + params.push(limitNum, offset); + + const reports = await dbAll(query, params); + + const enriched = await Promise.all( + reports.map(async (report) => { + let reporterData = { username: "Inconnu", avatar: null }; + try { + reporterData = await getUserData( + report.reporter_user_id, + report.reporter_user_type, + report.reporter_profile_id, + ); + } catch { + /* fallback */ + } + + let targetData = {}; + try { + if (report.target_type === "comment") { + const comment = await dbGet( + "SELECT id, content, content_id, content_type, user_id, user_type, profile_id, username, created_at FROM comments WHERE id = ?", + [report.target_id], + ); + if (comment) { + const authorData = await getUserData( + comment.user_id, + comment.user_type, + comment.profile_id, + ); + targetData = { + ...comment, + content: formatContentForResponse(comment.content), + authorUsername: authorData.username, + authorAvatar: authorData.avatar, + }; + } else { + targetData = { deleted: true }; + } + } else if (report.target_type === "reply") { + const reply = await dbGet( + "SELECT id, content, comment_id, user_id, user_type, profile_id, username, created_at FROM comment_replies WHERE id = ?", + [report.target_id], + ); + if (reply) { + const authorData = await getUserData( + reply.user_id, + reply.user_type, + reply.profile_id, + ); + const parentComment = await dbGet( + "SELECT content_id, content_type FROM comments WHERE id = ?", + [reply.comment_id], + ); + targetData = { + ...reply, + content: formatContentForResponse(reply.content), + authorUsername: authorData.username, + authorAvatar: authorData.avatar, + content_id: parentComment?.content_id, + content_type: parentComment?.content_type, + }; + } else { + targetData = { deleted: true }; + } + } else if (report.target_type === "shared_list") { + const pool = getCachedPool(); + const [rows] = await pool.execute( + "SELECT id, name, user_id, share_code FROM shared_lists WHERE share_code = ? OR id = ?", + [report.target_id, report.target_id], + ); + if (rows.length > 0) { + targetData = rows[0]; + } else { + targetData = { deleted: true }; + } + } + } catch (err) { + console.error("Erreur enrichissement report:", err.message); + targetData = { error: true }; + } + + return { + ...report, + reporter: { + username: reporterData.username, + avatar: reporterData.avatar, + }, + target: targetData, + }; + }), + ); + + const statsResult = await dbGet(` + SELECT + IFNULL(COUNT(*), 0) as total, + IFNULL(SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END), 0) as pending, + IFNULL(SUM(CASE WHEN status = 'resolved' THEN 1 ELSE 0 END), 0) as resolved, + IFNULL(SUM(CASE WHEN status = 'dismissed' THEN 1 ELSE 0 END), 0) as dismissed, + IFNULL(SUM(CASE WHEN target_type = 'comment' OR target_type = 'reply' THEN 1 ELSE 0 END), 0) as comments, + IFNULL(SUM(CASE WHEN target_type = 'shared_list' THEN 1 ELSE 0 END), 0) as lists + FROM reports + `); + + let countQuery = "SELECT COUNT(*) as total FROM reports WHERE 1=1"; + const countParams = []; + if (status !== "all") { + countQuery += " AND status = ?"; + countParams.push(status); + } + if (targetType !== "all") { + countQuery += " AND target_type = ?"; + countParams.push(targetType); + } + const totalResult = await dbGet(countQuery, countParams); + const total = Number(totalResult?.total) || 0; + + res.json({ + success: true, + reports: enriched, + stats: { + total: Number(statsResult?.total) || 0, + pending: Number(statsResult?.pending) || 0, + resolved: Number(statsResult?.resolved) || 0, + dismissed: Number(statsResult?.dismissed) || 0, + comments: Number(statsResult?.comments) || 0, + lists: Number(statsResult?.lists) || 0, + }, + total, + hasMore: offset + limitNum < total, + }); + } catch (error) { + console.error("Erreur lors de la récupération des reports:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// PUT /api/comments/admin/reports/:id/resolve +router.put("/admin/reports/:id/resolve", requireAuth, async (req, res) => { + try { + const userData = await getUserData(req.user.userId, req.user.userType); + if (!userData.isAdmin) + return res.status(403).json({ error: "Non autorisé" }); + + const { id } = req.params; + const { deleteContent } = req.body; + + const report = await dbGet("SELECT * FROM reports WHERE id = ?", [id]); + if (!report) + return res.status(404).json({ error: "Signalement non trouvé" }); + + if (deleteContent) { + if (report.target_type === "comment") { + await deleteCommentCascade(report.target_id); + } else if (report.target_type === "reply") { + const reply = await dbGet( + "SELECT comment_id FROM comment_replies WHERE id = ?", + [report.target_id], + ); + if (reply) + await deleteRepliesCascade(reply.comment_id, report.target_id); + } else if (report.target_type === "shared_list") { + const pool = getCachedPool(); + await pool.execute( + "DELETE FROM shared_lists WHERE share_code = ? OR id = ?", + [report.target_id, report.target_id], + ); + } + } + + await dbRun( + `UPDATE reports SET status = 'resolved', resolved_by = ?, resolved_at = ? WHERE target_type = ? AND target_id = ? AND status = 'pending'`, + [req.user.userId, Date.now(), report.target_type, report.target_id], + ); + + res.json({ success: true, message: "Signalement résolu" }); + } catch (error) { + console.error("Erreur résolution report:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// PUT /api/comments/admin/reports/:id/dismiss +router.put("/admin/reports/:id/dismiss", requireAuth, async (req, res) => { + try { + const userData = await getUserData(req.user.userId, req.user.userType); + if (!userData.isAdmin) + return res.status(403).json({ error: "Non autorisé" }); + + const { id } = req.params; + const report = await dbGet("SELECT * FROM reports WHERE id = ?", [id]); + if (!report) + return res.status(404).json({ error: "Signalement non trouvé" }); + + await dbRun( + `UPDATE reports SET status = 'dismissed', resolved_by = ?, resolved_at = ? WHERE target_type = ? AND target_id = ? AND status = 'pending'`, + [req.user.userId, Date.now(), report.target_type, report.target_id], + ); + + res.json({ success: true, message: "Signalement rejeté" }); + } catch (error) { + console.error("Erreur dismiss report:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// ==================== ROUTES DYNAMIQUES (doivent être en dernier) ==================== + +// GET /api/comments/:contentType/:contentId - Récupérer les commentaires avec pagination +// === #13: Optimisé — une seule requête SQL avec sous-requêtes au lieu de N+1 === +router.get("/:contentType/:contentId", async (req, res) => { + try { + const { contentType, contentId } = req.params; + const { page = 1, limit = 20 } = req.query; + const offset = (page - 1) * limit; + + // Tenter de récupérer l'utilisateur connecté (optionnel) + let currentUser = null; + const token = req.headers.authorization?.split(" ")[1]; + if (token) { + try { + const decoded = jwt.verify(token, JWT_SECRET, { + algorithms: ["HS256"], + }); + currentUser = { + userId: decoded.sub, + userType: decoded.userType, + sessionId: decoded.sessionId, + }; + } catch (error) { + // Token invalide, on continue sans utilisateur + } + } + + const { profileId } = req.query; + + // Récupérer le total de commentaires + const totalResult = await dbGet( + "SELECT COUNT(*) as total FROM comments WHERE content_type = ? AND content_id = ? AND deleted = 0", + [contentType, contentId], + ); + + // #13: Requête unique — reaction_count + replies_count + user_reacted en sous-requêtes + let commentsQuery; + let commentsParams; + + if (currentUser && profileId) { + commentsQuery = ` + SELECT c.*, + (SELECT COUNT(*) FROM comment_reactions WHERE target_type = 'comment' AND target_id = c.id) as reaction_count, + (SELECT COUNT(*) FROM comment_replies WHERE comment_id = c.id AND deleted = 0) as replies_count, + EXISTS(SELECT 1 FROM comment_reactions WHERE target_type = 'comment' AND target_id = c.id + AND user_id = ? AND user_type = ? AND profile_id = ?) as user_reacted + FROM comments c + WHERE c.content_type = ? AND c.content_id = ? AND c.deleted = 0 + ORDER BY (SELECT COUNT(*) FROM comment_reactions WHERE target_type = 'comment' AND target_id = c.id) DESC, c.created_at DESC + LIMIT ? OFFSET ?`; + commentsParams = [ + currentUser.userId, + currentUser.userType, + profileId, + contentType, + contentId, + parseInt(limit), + parseInt(offset), + ]; + } else { + commentsQuery = ` + SELECT c.*, + (SELECT COUNT(*) FROM comment_reactions WHERE target_type = 'comment' AND target_id = c.id) as reaction_count, + (SELECT COUNT(*) FROM comment_replies WHERE comment_id = c.id AND deleted = 0) as replies_count + FROM comments c + WHERE c.content_type = ? AND c.content_id = ? AND c.deleted = 0 + ORDER BY (SELECT COUNT(*) FROM comment_reactions WHERE target_type = 'comment' AND target_id = c.id) DESC, c.created_at DESC + LIMIT ? OFFSET ?`; + commentsParams = [ + contentType, + contentId, + parseInt(limit), + parseInt(offset), + ]; + } + + const comments = await dbAll(commentsQuery, commentsParams); + + // Cache utilisateur en mémoire pour cette requête (getUserData est déjà caché dans Redis via #14) + const userDataCache = new Map(); + + const commentsWithDetails = await Promise.all( + comments.map(async (comment) => { + const userKey = `${comment.user_id}:${comment.user_type}:${comment.profile_id || "default"}`; + let userData = userDataCache.get(userKey); + if (!userData) { + userData = await getUserData( + comment.user_id, + comment.user_type, + comment.profile_id, + ); + userDataCache.set(userKey, userData); + } + + return { + ...comment, + content: formatContentForResponse(comment.content), + username: userData.username, + avatar: userData.avatar, + is_vip: userData.isVip ? 1 : 0, + is_admin: userData.isAdmin ? 1 : 0, + repliesCount: comment.replies_count, + reactions: comment.reaction_count, + userReaction: + comment.user_reacted !== undefined ? !!comment.user_reacted : null, + }; + }), + ); + + res.json({ + comments: commentsWithDetails, + total: totalResult.total, + page: parseInt(page), + limit: parseInt(limit), + hasMore: offset + commentsWithDetails.length < totalResult.total, + }); + } catch (error) { + console.error("Erreur lors de la récupération des commentaires:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// POST /api/comments - Créer un commentaire +router.post("/", requireAuth, async (req, res) => { + try { + let { + contentType, + contentId, + content, + isSpoiler, + profileId, + turnstileToken, + } = req.body; + + // Vérification Turnstile + const turnstileResult = await verifyTurnstileFromRequest( + req, + turnstileToken, + ); + if (!turnstileResult.valid) + return res + .status(turnstileResult.status) + .json({ error: turnstileResult.error }); + + // Normalize content while preserving the original characters + content = normalizeCommentContent(content); + + // Verify profile ownership + const userProfileIds = await getProfileIds( + req.user.userId, + req.user.userType, + ); + if (!userProfileIds.includes(profileId)) { + return res.status(403).json({ error: "Profil non autorisé" }); + } + + // Récupérer les données utilisateur + const userData = await getUserData( + req.user.userId, + req.user.userType, + profileId, + ); + + // Vérification de bannissement + if (!userData.isAdmin) { + const banStatus = await checkBan( + req.user.userId, + req.user.userType, + getClientIp(req), + ); + if (banStatus.banned) { + return res.status(403).json({ + error: "Vous êtes banni des commentaires.", + reason: banStatus.reason, + expires_at: banStatus.expires_at, + }); + } + } + + // Rate Limit 1: Max 3 comments per movie/content (sauf pour les admins) + if (!userData.isAdmin) { + const movieComments = await dbGet( + "SELECT COUNT(*) as count FROM comments WHERE user_id = ? AND content_type = ? AND content_id = ? AND deleted = 0", + [req.user.userId, contentType, contentId], + ); + + if (movieComments.count >= 3) { + return res + .status(429) + .json({ error: "Limite de 3 commentaires par film atteinte." }); + } + + // Rate Limit 2: Max 10 comments per hour (sauf pour les admins) + const oneHourAgo = Date.now() - 3600000; + const hourComments = await dbGet( + "SELECT COUNT(*) as count FROM comments WHERE user_id = ? AND created_at > ?", + [req.user.userId, oneHourAgo], + ); + + if (hourComments.count >= 10) { + return res + .status(429) + .json({ error: "Limite de 10 commentaires par heure atteinte." }); + } + } + + // Validation + if (!content || content.length > 500) { + return res + .status(400) + .json({ + error: "Le commentaire doit contenir entre 1 et 500 caractères", + }); + } + + // Insérer le commentaire + const result = await dbRun( + `INSERT INTO comments (content_type, content_id, user_id, user_type, profile_id, username, avatar, content, is_spoiler, is_vip, is_admin, created_at, ip_address) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + [ + contentType, + contentId, + req.user.userId, + req.user.userType, + profileId, + userData.username, + userData.avatar, + content, + isSpoiler ? 1 : 0, + userData.isVip ? 1 : 0, + userData.isAdmin ? 1 : 0, + Date.now(), + getClientIp(req), + ], + ); + + // Récupérer le commentaire créé + const newComment = await dbGet("SELECT * FROM comments WHERE id = ?", [ + result.lastID, + ]); + + // Envoyer le webhook Discord en arrière-plan (ne pas attendre) + sendDiscordWebhook("comment", { + username: userData.username, + avatar: userData.avatar, + content, + contentType, + contentId, + isSpoiler, + isVip: userData.isVip, + isAdmin: userData.isAdmin, + userId: req.user.userId, + userType: req.user.userType, + profileId: profileId, + ipAddress: getClientIp(req), + }).catch((err) => + console.error("Erreur webhook Discord (non bloquant):", err), + ); + + // Modération automatique avec Gemini en arrière-plan (ne pas attendre) + moderateContentWithGemini( + result.lastID, + "comment", + content, + userData.username, + ).catch((err) => + console.error( + "Erreur modération Gemini commentaire (non bloquant):", + err, + ), + ); + + res.status(201).json({ + ...newComment, + content: formatContentForResponse(newComment.content), + repliesCount: 0, + reactions: 0, + userReaction: null, + }); + } catch (error) { + console.error("Erreur lors de la création du commentaire:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// PUT /api/comments/:id - Éditer un commentaire +router.put("/:id", requireAuth, async (req, res) => { + try { + const { id } = req.params; + let { content, isSpoiler } = req.body; + + // Normalize content while preserving the original characters + content = normalizeCommentContent(content); + + // Validation + if (!content || content.length > 500) { + return res + .status(400) + .json({ + error: "Le commentaire doit contenir entre 1 et 500 caractères", + }); + } + + // Vérifier que le commentaire appartient à l'utilisateur + const comment = await dbGet("SELECT * FROM comments WHERE id = ?", [id]); + if (!comment) { + return res.status(404).json({ error: "Commentaire non trouvé" }); + } + + if ( + comment.user_id !== req.user.userId || + comment.user_type !== req.user.userType + ) { + return res.status(403).json({ error: "Non autorisé" }); + } + + // Mettre à jour le commentaire + await dbRun( + "UPDATE comments SET content = ?, is_spoiler = ?, is_edited = 1, updated_at = ? WHERE id = ?", + [content, isSpoiler ? 1 : 0, Date.now(), id], + ); + + // Récupérer le commentaire mis à jour + const updatedComment = await dbGet("SELECT * FROM comments WHERE id = ?", [ + id, + ]); + + res.json({ + ...updatedComment, + content: formatContentForResponse(updatedComment.content), + }); + } catch (error) { + console.error("Erreur lors de l'édition du commentaire:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +// DELETE /api/comments/:id - Supprimer un commentaire (admin ou auteur) +router.delete("/:id", requireAuth, async (req, res) => { + try { + const { id } = req.params; + const { profileId } = req.query; + + // Vérifier que le commentaire existe + const comment = await dbGet( + "SELECT id, user_id, user_type, profile_id FROM comments WHERE id = ?", + [id], + ); + if (!comment) { + return res.status(404).json({ error: "Commentaire non trouvé" }); + } + + // Vérifier que l'utilisateur est admin ou auteur du commentaire + const userData = await getUserData(req.user.userId, req.user.userType); + const userMatch = + String(comment.user_id) === String(req.user.userId) && + String(comment.user_type) === String(req.user.userType); + // Vérifier le profile_id si le commentaire en a un + const profileMatch = + !comment.profile_id || + !profileId || + String(comment.profile_id) === String(profileId); + const isOwner = userMatch && profileMatch; + + if (!userData.isAdmin && !isOwner) { + return res.status(403).json({ error: "Non autorisé" }); + } + + // Supprimer le commentaire et toutes ses dépendances en cascade + await deleteCommentCascade(id); + + res.json({ + message: + "Commentaire, réponses, réactions et notifications supprimés en cascade", + }); + } catch (error) { + console.error("Erreur lors de la suppression du commentaire:", error); + res.status(500).json({ error: "Erreur serveur" }); + } +}); + +module.exports = router; diff --git a/API/Mainapi/config/redis.js b/API/Mainapi/config/redis.js new file mode 100644 index 0000000..c46b09e --- /dev/null +++ b/API/Mainapi/config/redis.js @@ -0,0 +1,36 @@ +/** + * Redis connection and memory cache wrapper. + * Extracted from server.js — centralizes Redis configuration. + */ + +const Redis = require('ioredis'); + +// === REDIS CACHE POUR OPTIMISER LES PERFORMANCES === +const redis = new Redis({ + host: process.env.REDIS_HOST, + port: parseInt(process.env.REDIS_PORT), + password: process.env.REDIS_PASSWORD, + retryDelayOnFailover: 100, + maxRetriesPerRequest: 3, + lazyConnect: true +}); + +redis.on('connect', () => console.log('[Redis] Connecté')); +redis.on('error', (err) => console.error('[Redis] Erreur:', err.message)); + +// Wrapper autour de Redis pour garder l'interface memoryCache (get/set avec JSON auto) +const memoryCache = { + async get(key) { + try { + const data = await redis.get(key); + return data ? JSON.parse(data) : undefined; + } catch { return undefined; } + }, + async set(key, value, ttl = 300) { + try { + await redis.set(key, JSON.stringify(value), 'EX', ttl); + } catch { /* ignore */ } + } +}; + +module.exports = { redis, memoryCache }; diff --git a/API/Mainapi/exportscripts/add_admins_table.sql b/API/Mainapi/exportscripts/add_admins_table.sql new file mode 100644 index 0000000..c636ac0 --- /dev/null +++ b/API/Mainapi/exportscripts/add_admins_table.sql @@ -0,0 +1,22 @@ +-- Script pour ajouter la table admins à la base de données MySQL +-- Généré le 2025-01-27 + +-- Table des administrateurs +CREATE TABLE IF NOT EXISTS admins ( + id INT AUTO_INCREMENT PRIMARY KEY, + user_id VARCHAR(255) NOT NULL UNIQUE, + auth_type ENUM('oauth', 'bip-39') NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + INDEX idx_user_id (user_id), + INDEX idx_auth_type (auth_type) +); + +-- Commentaires sur la table +ALTER TABLE admins COMMENT = 'Table des administrateurs avec types d\'authentification'; + + + +-- Vérification de la création +SELECT 'Table admins créée avec succès' as Status; +DESCRIBE admins; diff --git a/API/Mainapi/exportscripts/add_comments_tables.sql b/API/Mainapi/exportscripts/add_comments_tables.sql new file mode 100644 index 0000000..0a7fdc7 --- /dev/null +++ b/API/Mainapi/exportscripts/add_comments_tables.sql @@ -0,0 +1,120 @@ +-- Script pour créer les tables de commentaires, likes et notifications dans MySQL +-- Généré le 2025-01-27 +-- À importer dans phpMyAdmin + +-- Table des commentaires principaux +CREATE TABLE IF NOT EXISTS comments ( + id INT AUTO_INCREMENT PRIMARY KEY, + content_type VARCHAR(50) NOT NULL, + content_id VARCHAR(255) NOT NULL, + user_id VARCHAR(255) NOT NULL, + user_type VARCHAR(50) NOT NULL, + profile_id VARCHAR(255), + username VARCHAR(255) NOT NULL, + avatar TEXT, + content TEXT NOT NULL, + is_spoiler TINYINT(1) DEFAULT 0, + is_vip TINYINT(1) DEFAULT 0, + is_admin TINYINT(1) DEFAULT 0, + is_edited TINYINT(1) DEFAULT 0, + created_at BIGINT NOT NULL, + updated_at BIGINT, + deleted TINYINT(1) DEFAULT 0, + INDEX idx_comments_content (content_type, content_id), + INDEX idx_comments_user (user_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- Table des réponses aux commentaires +CREATE TABLE IF NOT EXISTS comment_replies ( + id INT AUTO_INCREMENT PRIMARY KEY, + comment_id INT NOT NULL, + parent_reply_id INT, + user_id VARCHAR(255) NOT NULL, + user_type VARCHAR(50) NOT NULL, + profile_id VARCHAR(255), + username VARCHAR(255) NOT NULL, + avatar TEXT, + reply_to_username VARCHAR(255), + content TEXT NOT NULL, + is_spoiler TINYINT(1) DEFAULT 0, + is_vip TINYINT(1) DEFAULT 0, + is_admin TINYINT(1) DEFAULT 0, + is_edited TINYINT(1) DEFAULT 0, + created_at BIGINT NOT NULL, + updated_at BIGINT, + deleted TINYINT(1) DEFAULT 0, + hierarchical_path VARCHAR(255), + INDEX idx_replies_comment (comment_id), + INDEX idx_replies_user (user_id), + INDEX idx_replies_hierarchical_path (comment_id, hierarchical_path), + FOREIGN KEY (comment_id) REFERENCES comments(id) ON DELETE CASCADE, + FOREIGN KEY (parent_reply_id) REFERENCES comment_replies(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- Table des réactions (cœurs) +CREATE TABLE IF NOT EXISTS comment_reactions ( + id INT AUTO_INCREMENT PRIMARY KEY, + target_type VARCHAR(50) NOT NULL, + target_id INT NOT NULL, + user_id VARCHAR(255) NOT NULL, + user_type VARCHAR(50) NOT NULL, + profile_id VARCHAR(255), + created_at BIGINT NOT NULL, + UNIQUE KEY unique_reaction (target_type, target_id, user_id, user_type, profile_id), + INDEX idx_reactions_target (target_type, target_id), + INDEX idx_reactions_user (user_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- Table des notifications +CREATE TABLE IF NOT EXISTS notifications ( + id INT AUTO_INCREMENT PRIMARY KEY, + user_id VARCHAR(255) NOT NULL, + user_type VARCHAR(50) NOT NULL, + profile_id VARCHAR(255), + from_user_id VARCHAR(255) NOT NULL, + from_profile_id VARCHAR(255), + from_username VARCHAR(255) NOT NULL, + from_avatar TEXT, + notification_type VARCHAR(50) NOT NULL, + target_type VARCHAR(50) NOT NULL, + target_id INT NOT NULL, + content_type VARCHAR(50) NOT NULL, + content_id VARCHAR(255) NOT NULL, + comment_preview TEXT, + is_read TINYINT(1) DEFAULT 0, + created_at BIGINT NOT NULL, + INDEX idx_notifications_user (user_id, is_read), + INDEX idx_notifications_created (created_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- Table des likes/dislikes pour les films et séries +CREATE TABLE IF NOT EXISTS likes ( + id INT AUTO_INCREMENT PRIMARY KEY, + content_type VARCHAR(50) NOT NULL, + content_id VARCHAR(255) NOT NULL, + user_id VARCHAR(255) NOT NULL, + user_type VARCHAR(50) NOT NULL, + profile_id VARCHAR(255), + vote_type VARCHAR(20) NOT NULL, + created_at BIGINT NOT NULL, + updated_at BIGINT, + UNIQUE KEY unique_like (content_type, content_id, user_id, user_type, profile_id), + INDEX idx_likes_content (content_type, content_id), + INDEX idx_likes_user (user_id, user_type, profile_id), + INDEX idx_likes_content_vote (content_type, content_id, vote_type), + INDEX idx_likes_stats (content_type, content_id, vote_type, created_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- Commentaires sur les tables +ALTER TABLE comments COMMENT = 'Table des commentaires principaux'; +ALTER TABLE comment_replies COMMENT = 'Table des réponses aux commentaires avec hiérarchie'; +ALTER TABLE comment_reactions COMMENT = 'Table des réactions (cœurs) sur commentaires et réponses'; +ALTER TABLE notifications COMMENT = 'Table des notifications utilisateur'; +ALTER TABLE likes COMMENT = 'Table des likes/dislikes pour films et séries'; + +-- Vérification de la création +SELECT 'Tables créées avec succès' as Status; +SHOW TABLES LIKE '%comment%'; +SHOW TABLES LIKE '%notification%'; +SHOW TABLES LIKE '%like%'; + diff --git a/API/Mainapi/exportscripts/add_greenlight_tracking.sql b/API/Mainapi/exportscripts/add_greenlight_tracking.sql new file mode 100644 index 0000000..32400b2 --- /dev/null +++ b/API/Mainapi/exportscripts/add_greenlight_tracking.sql @@ -0,0 +1,14 @@ +-- Script pour ajouter le tracking admin aux changements de statut wishboard +-- Permet de savoir quel admin/uploader a greenlight une demande + +-- Ajouter les colonnes admin_id et admin_auth_type a wishboard_status_history +ALTER TABLE wishboard_status_history + ADD COLUMN admin_id VARCHAR(255) DEFAULT NULL COMMENT 'ID de l admin qui a change le statut', + ADD COLUMN admin_auth_type VARCHAR(10) DEFAULT NULL COMMENT 'Type auth de l admin (oauth ou bip-39)'; + +-- Index pour faciliter les requetes de leaderboard +CREATE INDEX idx_wsh_admin_status ON wishboard_status_history (admin_id, status); + +-- Verification +SELECT 'Colonnes admin_id et admin_auth_type ajoutees a wishboard_status_history' as Status; +DESCRIBE wishboard_status_history; diff --git a/API/Mainapi/exportscripts/add_link_submissions_table.sql b/API/Mainapi/exportscripts/add_link_submissions_table.sql new file mode 100644 index 0000000..5a39268 --- /dev/null +++ b/API/Mainapi/exportscripts/add_link_submissions_table.sql @@ -0,0 +1,25 @@ +-- Link Submissions table +-- Allows authenticated users to propose streaming links for movies/episodes/seasons +-- Links must be approved by staff (admin/uploader) before being added to films/series tables + +CREATE TABLE IF NOT EXISTS link_submissions ( + id INT AUTO_INCREMENT PRIMARY KEY, + user_id VARCHAR(255) NOT NULL, + profile_id VARCHAR(255) NOT NULL, + tmdb_id INT NOT NULL, + media_type ENUM('movie', 'tv') NOT NULL, + season_number INT DEFAULT NULL, + episode_number INT DEFAULT NULL, + url VARCHAR(2048) NOT NULL, + source_name VARCHAR(100) DEFAULT NULL COMMENT 'Optional label for the source (e.g. SeekStreaming, VidMoly, etc.)', + status ENUM('pending', 'approved', 'rejected') DEFAULT 'pending', + rejection_reason TEXT DEFAULT NULL, + reviewed_by VARCHAR(255) DEFAULT NULL, + reviewed_at DATETIME DEFAULT NULL, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + INDEX idx_status (status), + INDEX idx_profile (profile_id), + INDEX idx_tmdb (tmdb_id, media_type), + INDEX idx_created (created_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/API/Mainapi/exportscripts/add_moderation_columns.sql b/API/Mainapi/exportscripts/add_moderation_columns.sql new file mode 100644 index 0000000..1b21a97 --- /dev/null +++ b/API/Mainapi/exportscripts/add_moderation_columns.sql @@ -0,0 +1,23 @@ +-- Script pour ajouter les colonnes de modération aux tables de commentaires +-- Généré le 2025-01-04 +-- À importer dans phpMyAdmin + +-- Ajouter les colonnes de modération à la table comments +ALTER TABLE comments + ADD COLUMN moderation_reason VARCHAR(50) DEFAULT NULL COMMENT 'INSULTES, EROTIQUE, DEMANDE_AJOUT', + ADD COLUMN moderation_details TEXT DEFAULT NULL COMMENT 'Détails de la modération par Gemini', + ADD COLUMN moderated_at BIGINT DEFAULT NULL COMMENT 'Timestamp de la modération', + ADD COLUMN approved_by_admin TINYINT(1) DEFAULT 0 COMMENT 'Si approuvé par un admin après modération', + ADD COLUMN approved_at BIGINT DEFAULT NULL COMMENT 'Timestamp de l\'approbation admin'; + +-- Ajouter les colonnes de modération à la table comment_replies +ALTER TABLE comment_replies + ADD COLUMN moderation_reason VARCHAR(50) DEFAULT NULL COMMENT 'INSULTES, EROTIQUE, DEMANDE_AJOUT', + ADD COLUMN moderation_details TEXT DEFAULT NULL COMMENT 'Détails de la modération par Gemini', + ADD COLUMN moderated_at BIGINT DEFAULT NULL COMMENT 'Timestamp de la modération', + ADD COLUMN approved_by_admin TINYINT(1) DEFAULT 0 COMMENT 'Si approuvé par un admin après modération', + ADD COLUMN approved_at BIGINT DEFAULT NULL COMMENT 'Timestamp de l\'approbation admin'; + +-- Index pour faciliter les requêtes de modération +CREATE INDEX idx_comments_moderation ON comments (deleted, moderation_reason); +CREATE INDEX idx_replies_moderation ON comment_replies (deleted, moderation_reason); diff --git a/API/Mainapi/exportscripts/add_sessions_table.sql b/API/Mainapi/exportscripts/add_sessions_table.sql new file mode 100644 index 0000000..a8a188e --- /dev/null +++ b/API/Mainapi/exportscripts/add_sessions_table.sql @@ -0,0 +1,14 @@ +-- Table pour les sessions utilisateur +-- Cette table remplace le stockage des sessions dans les fichiers JSON + +CREATE TABLE IF NOT EXISTS user_sessions ( + id VARCHAR(255) PRIMARY KEY, + user_id VARCHAR(255) NOT NULL, + user_type ENUM('oauth', 'bip39') NOT NULL, + device TEXT, + user_agent TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + accessed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + INDEX idx_user_sessions_user (user_id, user_type), + INDEX idx_user_sessions_accessed (accessed_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/API/Mainapi/exportscripts/add_shared_lists_table.sql b/API/Mainapi/exportscripts/add_shared_lists_table.sql new file mode 100644 index 0000000..8a2efd4 --- /dev/null +++ b/API/Mainapi/exportscripts/add_shared_lists_table.sql @@ -0,0 +1,23 @@ +-- Script pour créer la table shared_lists dans MySQL +-- À importer dans phpMyAdmin + +CREATE TABLE IF NOT EXISTS shared_lists ( + id INT AUTO_INCREMENT PRIMARY KEY, + user_id VARCHAR(255) NOT NULL, + user_type VARCHAR(50) NOT NULL, + profile_id VARCHAR(255) NOT NULL, + list_id VARCHAR(255) NOT NULL, + share_code VARCHAR(20) NOT NULL, + is_public_in_catalog TINYINT(1) NOT NULL DEFAULT 0, + moderation_flagged TINYINT(1) NOT NULL DEFAULT 0, + moderation_reason VARCHAR(255), + moderation_details TEXT, + moderated_at BIGINT, + created_at BIGINT NOT NULL, + updated_at BIGINT NOT NULL, + UNIQUE KEY uq_share_code (share_code), + UNIQUE KEY uq_user_list (user_id, user_type, profile_id, list_id), + INDEX idx_shared_lists_share_code (share_code), + INDEX idx_shared_lists_user_profile (user_id, user_type, profile_id), + INDEX idx_shared_lists_moderation (moderation_flagged, is_public_in_catalog) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/API/Mainapi/france.m3u b/API/Mainapi/france.m3u new file mode 100644 index 0000000..35abcdb --- /dev/null +++ b/API/Mainapi/france.m3u @@ -0,0 +1,649 @@ +#EXTM3U +#EXTINF:-1 tvg-id="TF14k.fr" tvg-name="FR | TF1 4K" tvg-chno="0" tvg-logo="https://i.ibb.co/QGLSSfy/tf1-4-K-logo.png" tvg-poster="https://i.ibb.co/LzpLbDq6/tf1-4k-poster.png" tvg-back="https://i.ibb.co/JRLCV12N/tf1-logo-topaz-removedddd-upscale-1-6x-remove.jpg" group-title="FR | General",FR | TF1 4K +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/53268 +#EXTINF:-1 tvg-id="TF1.fr" tvg-name="FR | TF1 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/tf1.png" tvg-poster="https://tvmio.gleeze.com/poster/general/TF1.png" tvg-back="https://i.ibb.co/JRLCV12N/tf1-logo-topaz-removedddd-upscale-1-6x-remove.jpg" group-title="FR | General",FR | TF1 FHD +http://176.65.146.138:8047/play/a074/index.m3u8 +#EXTINF:-1 tvg-id="TF1.fr" tvg-name="FR | TF1 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/tf1.png" tvg-poster="https://tvmio.gleeze.com/poster/general/TF1.png" tvg-back="https://i.ibb.co/JRLCV12N/tf1-logo-topaz-removedddd-upscale-1-6x-remove.jpg" group-title="FR | General",FR | TF1 HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116066 +#EXTINF:-1 tvg-id="TF1.fr" tvg-name="FR | TF1 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/tf1.png" tvg-poster="https://tvmio.gleeze.com/poster/general/TF1.png" tvg-back="https://i.ibb.co/JRLCV12N/tf1-logo-topaz-removedddd-upscale-1-6x-remove.jpg" group-title="FR | General",FR | TF1 FHD +https://live.streamgatos.top/hls/9508/stream.m3u8 +#EXTINF:-1 tvg-id="TF1.fr" tvg-name="FR | TF1 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/tf1.png" tvg-poster="https://tvmio.gleeze.com/poster/general/TF1.png" tvg-back="https://i.ibb.co/JRLCV12N/tf1-logo-topaz-removedddd-upscale-1-6x-remove.jpg" group-title="FR | General",FR | TF1 HD +http://151.80.18.177:86/TF1_HD/index.m3u8 +#EXTINF:-1 tvg-id="France2.fr" tvg-name="FR | France 2 FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/france_2.png" tvg-poster="https://tvmio.gleeze.com/poster/general/france_2.png" tvg-back="https://i.ibb.co/MyWGfCdN/dec8d421-8eb4-4aa4-aca0-aefb28ea52c9-cover-topaz-removedddd-remove.png" group-title="FR | General",FR | France 2 FHD +http://176.65.146.138:8047/play/a07e/index.m3u8 +#EXTINF:-1 tvg-id="France2.fr" tvg-name="FR | France 2 HD" tvg-logo="https://tvmio.gleeze.com/logos/general/france_2.png" tvg-poster="https://tvmio.gleeze.com/poster/general/france_2.png" tvg-back="https://i.ibb.co/MyWGfCdN/dec8d421-8eb4-4aa4-aca0-aefb28ea52c9-cover-topaz-removedddd-remove.png" group-title="FR | General",FR | France 2 HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116070 +#EXTINF:-1 tvg-id="France2.fr" tvg-name="FR | France 2 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/france_2.png" tvg-poster="https://tvmio.gleeze.com/poster/general/france_2.png" tvg-back="https://i.ibb.co/MyWGfCdN/dec8d421-8eb4-4aa4-aca0-aefb28ea52c9-cover-topaz-removedddd-remove.png" group-title="FR | General",FR | France 2 HD +http://151.80.18.177:86/France_2_HD/index.m3u8 +#EXTINF:-1 tvg-id="France2.fr" tvg-name="FR | France 2 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/france_2.png" tvg-poster="https://tvmio.gleeze.com/poster/general/france_2.png" tvg-back="https://i.ibb.co/MyWGfCdN/dec8d421-8eb4-4aa4-aca0-aefb28ea52c9-cover-topaz-removedddd-remove.png" group-title="FR | General",FR | France 2 HD +http://sewv654wfcsdwfi87fwvgbngh.siauliairsavlt.pw/iptv/VEXVELA6Z7PXH6/6147/index.m3u8 +#EXTINF:-1 tvg-id="France2.fr" tvg-name="FR | France 2 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/france_2.png" tvg-poster="https://tvmio.gleeze.com/poster/general/france_2.png" tvg-back="https://i.ibb.co/MyWGfCdN/dec8d421-8eb4-4aa4-aca0-aefb28ea52c9-cover-topaz-removedddd-remove.png" group-title="FR | General",FR | France 2 HD +https://live.streamgatos.top/hls/666/stream.m3u8 +#EXTINF:-1 tvg-id="France3.fr" tvg-name="FR | France 3 FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/france_3.png" tvg-poster="https://tvmio.gleeze.com/poster/general/france_3.png" tvg-back="https://i.ibb.co/MyWGfCdN/dec8d421-8eb4-4aa4-aca0-aefb28ea52c9-cover-topaz-removedddd-remove.png" group-title="FR | General",FR | France 3 FHD +http://176.65.146.138:8047/play/a07h/index.m3u8 +#EXTINF:-1 tvg-id="France3.fr" tvg-name="FR | France 3 HD" tvg-logo="https://tvmio.gleeze.com/logos/general/france_3.png" tvg-poster="https://tvmio.gleeze.com/poster/general/france_3.png" tvg-back="https://i.ibb.co/MyWGfCdN/dec8d421-8eb4-4aa4-aca0-aefb28ea52c9-cover-topaz-removedddd-remove.png" group-title="FR | General",FR | France 3 HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116071 +#EXTINF:-1 tvg-id="France3.fr" tvg-name="FR | France 3 FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/france_3.png" tvg-poster="https://tvmio.gleeze.com/poster/general/france_3.png" tvg-back="https://i.ibb.co/MyWGfCdN/dec8d421-8eb4-4aa4-aca0-aefb28ea52c9-cover-topaz-removedddd-remove.png" group-title="FR | General",FR | France 3 FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116072 +#EXTINF:-1 tvg-id="France3.fr" tvg-name="FR | France 3 FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/france_3.png" tvg-poster="https://tvmio.gleeze.com/poster/general/france_3.png" tvg-back="https://i.ibb.co/MyWGfCdN/dec8d421-8eb4-4aa4-aca0-aefb28ea52c9-cover-topaz-removedddd-remove.png" group-title="FR | General",FR | France 3 FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116073 +#EXTINF:-1 tvg-id="France3.fr" tvg-name="FR | France 3 FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/france_3.png" tvg-poster="https://tvmio.gleeze.com/poster/general/france_3.png" tvg-back="https://i.ibb.co/MyWGfCdN/dec8d421-8eb4-4aa4-aca0-aefb28ea52c9-cover-topaz-removedddd-remove.png" group-title="FR | General",FR | France 3 FHD +http://sewv654wfcsdwfi87fwvgbngh.siauliairsavlt.pw/iptv/VEXVELA6Z7PXH6/6148/index.m3u8 +#EXTINF:-1 tvg-id="France3.fr" tvg-name="FR | France 3 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/france_3.png" tvg-poster="https://tvmio.gleeze.com/poster/general/france_3.png" tvg-back="https://i.ibb.co/MyWGfCdN/dec8d421-8eb4-4aa4-aca0-aefb28ea52c9-cover-topaz-removedddd-remove.png" group-title="FR | General",FR | France 3 HD +http://151.80.18.177:86/France_3_HD/index.m3u8 +#EXTINF:-1 tvg-id="France3.fr" tvg-name="FR | France 3 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/france_3.png" tvg-poster="https://tvmio.gleeze.com/poster/general/france_3.png" tvg-back="https://i.ibb.co/MyWGfCdN/dec8d421-8eb4-4aa4-aca0-aefb28ea52c9-cover-topaz-removedddd-remove.png" group-title="FR | General",FR | France 3 HD +https://live.streamgatos.top/hls/9513/stream.m3u8 +#EXTINF:-1 tvg-id="France4.fr" tvg-name="FR | France 4 FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/france_4.png" tvg-poster="https://tvmio.gleeze.com/poster/general/france_4.png" tvg-back="https://i.ibb.co/MyWGfCdN/dec8d421-8eb4-4aa4-aca0-aefb28ea52c9-cover-topaz-removedddd-remove.png" group-title="FR | General",FR | France 4 FHD +http://176.65.146.138:8047/play/a07f/index.m3u8 +#EXTINF:-1 tvg-id="France4.fr" tvg-name="FR | France 4 FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/france_4.png" tvg-poster="https://tvmio.gleeze.com/poster/general/france_4.png" tvg-back="https://i.ibb.co/MyWGfCdN/dec8d421-8eb4-4aa4-aca0-aefb28ea52c9-cover-topaz-removedddd-remove.png" group-title="FR | General",FR | France 4 FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116074 +#EXTINF:-1 tvg-id="France5.fr" tvg-name="FR | France 5 FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/france_5.png" tvg-poster="https://tvmio.gleeze.com/poster/general/france_5.png" tvg-back="https://i.ibb.co/MyWGfCdN/dec8d421-8eb4-4aa4-aca0-aefb28ea52c9-cover-topaz-removedddd-remove.png" group-title="FR | General",FR | France 5 FHD +http://176.65.146.138:8047/play/a07l/index.m3u8 +#EXTINF:-1 tvg-id="France5.fr" tvg-name="FR | France 5 HD" tvg-logo="https://tvmio.gleeze.com/logos/general/france_5.png" tvg-poster="https://tvmio.gleeze.com/poster/general/france_5.png" tvg-back="https://i.ibb.co/MyWGfCdN/dec8d421-8eb4-4aa4-aca0-aefb28ea52c9-cover-topaz-removedddd-remove.png" group-title="FR | General",FR | France 5 HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116076 +#EXTINF:-1 tvg-id="France5.fr" tvg-name="FR | France 5 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/france_5.png" tvg-poster="https://tvmio.gleeze.com/poster/general/france_5.png" tvg-back="https://i.ibb.co/MyWGfCdN/dec8d421-8eb4-4aa4-aca0-aefb28ea52c9-cover-topaz-removedddd-remove.png" group-title="FR | General",FR | France 5 FHD +http://sewv654wfcsdwfi87fwvgbngh.siauliairsavlt.pw/iptv/VEXVELA6Z7PXH6/6150/index.m3u8 +#EXTINF:-1 tvg-id="France5.fr" tvg-name="FR | France 5 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/france_5.png" tvg-poster="https://tvmio.gleeze.com/poster/general/france_5.png" tvg-back="https://i.ibb.co/MyWGfCdN/dec8d421-8eb4-4aa4-aca0-aefb28ea52c9-cover-topaz-removedddd-remove.png" group-title="FR | General",FR | France 5 HD +http://151.80.18.177:86/France_5_HD/index.m3u8 +#EXTINF:-1 tvg-id="CanalPlus.fr" tvg-name="FR | Canal+ FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/canal.png" tvg-poster="https://tvmio.gleeze.com/poster/general/canalplus.png" tvg-back="https://fondation.canal-plus.com/_next/image?url=%2Fuploads%2FFONDATION_16_9_FOND_DEFAUT_SOMBRE_c99ca0690c.JPG%3Fs%3D2560x1440%26f%3Dwebp&w=2560&q=75" group-title="FR | General",FR | Canal+ FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/53279 +#EXTINF:-1 tvg-id="CanalPlus.fr" tvg-name="FR | Canal+ HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/canal.png" tvg-poster="https://tvmio.gleeze.com/poster/general/canalplus.png" tvg-back="https://fondation.canal-plus.com/_next/image?url=%2Fuploads%2FFONDATION_16_9_FOND_DEFAUT_SOMBRE_c99ca0690c.JPG%3Fs%3D2560x1440%26f%3Dwebp&w=2560&q=75" group-title="FR | General",FR | Canal+ HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116409 +#EXTINF:-1 tvg-id="CanalPlus.fr" tvg-name="FR | Canal+ HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/canal.png" tvg-poster="https://tvmio.gleeze.com/poster/general/canalplus.png" tvg-back="https://fondation.canal-plus.com/_next/image?url=%2Fuploads%2FFONDATION_16_9_FOND_DEFAUT_SOMBRE_c99ca0690c.JPG%3Fs%3D2560x1440%26f%3Dwebp&w=2560&q=75" group-title="FR | General",FR | Canal+ HD +http://151.80.18.177:86/Canal+_HD/index.m3u8 +#EXTINF:-1 tvg-id="CanalPlus.fr" tvg-name="FR | Canal+ HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/canal.png" tvg-poster="https://tvmio.gleeze.com/poster/general/canalplus.png" tvg-back="https://fondation.canal-plus.com/_next/image?url=%2Fuploads%2FFONDATION_16_9_FOND_DEFAUT_SOMBRE_c99ca0690c.JPG%3Fs%3D2560x1440%26f%3Dwebp&w=2560&q=75" group-title="FR | General",FR | Canal+ HD +http://sewv654wfcsdwfi87fwvgbngh.siauliairsavlt.pw/iptv/VEXVELA6Z7PXH6/6005/index.m3u8 +#EXTINF:-1 tvg-id="CanalPlus.fr" tvg-name="FR | Canal+ HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/canal.png" tvg-poster="https://tvmio.gleeze.com/poster/general/canalplus.png" tvg-back="https://fondation.canal-plus.com/_next/image?url=%2Fuploads%2FFONDATION_16_9_FOND_DEFAUT_SOMBRE_c99ca0690c.JPG%3Fs%3D2560x1440%26f%3Dwebp&w=2560&q=75" group-title="FR | General",FR | Canal+ HD +http://sewv654wfcsdwfi87fwvgbngh.siauliairsavlt.pw/iptv/VEXVELA6Z7PXH6/6007/index.m3u8 +#EXTINF:-1 tvg-id="Arte.fr" tvg-name="FR | Arte HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/arte.png" tvg-poster="https://tvmio.gleeze.com/poster/general/arte.png" tvg-back="https://www.arte.tv/sites/corporate/files/ident-confettis_b.jpg" group-title="FR | General",FR | Arte HD +http://151.80.18.177:86/ARTE_HD/index.m3u8 +#EXTINF:-1 tvg-id="Arte.fr" tvg-name="FR | Arte HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/arte.png" tvg-poster="https://tvmio.gleeze.com/poster/general/arte.png" tvg-back="https://www.arte.tv/sites/corporate/files/ident-confettis_b.jpg" group-title="FR | General",FR | Arte HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116105 +#EXTINF:-1 tvg-id="Arte.fr" tvg-name="FR | Arte FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/arte.png" tvg-poster="https://tvmio.gleeze.com/poster/general/arte.png" tvg-back="https://www.arte.tv/sites/corporate/files/ident-confettis_b.jpg" group-title="FR | General",FR | Arte FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116106 +#EXTINF:-1 tvg-id="Arte.fr" tvg-name="FR | Arte HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/arte.png" tvg-poster="https://tvmio.gleeze.com/poster/general/arte.png" tvg-back="https://www.arte.tv/sites/corporate/files/ident-confettis_b.jpg" group-title="FR | General",FR | Arte HD +https://live.streamgatos.top/hls/143713/stream.m3u8 +#EXTINF:-1 tvg-id="Arte.fr" tvg-name="FR | Arte SD" tvg-logo="https://tvmio.gleeze.com/logos/general/arte.png" tvg-poster="https://tvmio.gleeze.com/poster/general/arte.png" tvg-back="https://www.arte.tv/sites/corporate/files/ident-confettis_b.jpg" group-title="FR | General",FR | Arte SD +http://176.65.146.138:8047/play/a07k/index.m3u8 +#EXTINF:-1 tvg-id="M6.fr" tvg-name="FR | M6 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/m6.png" tvg-poster="https://tvmio.gleeze.com/poster/general/m6.png" tvg-back="https://i.ibb.co/vx1S5yxL/groupe-m6-w9-6ter-topaz-removedddd-remove.png" group-title="FR | General",FR | M6 FHD +http://176.65.146.138:8047/play/a07i/index.m3u8 +#EXTINF:-1 tvg-id="M6.fr" tvg-name="FR | M6 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/m6.png" tvg-poster="https://tvmio.gleeze.com/poster/general/m6.png" tvg-back="https://i.ibb.co/vx1S5yxL/groupe-m6-w9-6ter-topaz-removedddd-remove.png" group-title="FR | General",FR | M6 HD +http://151.80.18.177:86/M6_HD/index.m3u8 +#EXTINF:-1 tvg-id="M6.fr" tvg-name="FR | M6 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/m6.png" tvg-poster="https://tvmio.gleeze.com/poster/general/m6.png" tvg-back="https://i.ibb.co/vx1S5yxL/groupe-m6-w9-6ter-topaz-removedddd-remove.png" group-title="FR | General",FR | M6 HD +https://live.streamgatos.top/hls/9507/stream.m3u8 +#EXTINF:-1 tvg-id="W9.fr" tvg-name="FR | W9 FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/w9.png" tvg-poster="https://tvmio.gleeze.com/poster/general/w9.png" tvg-back="https://i.ibb.co/vx1S5yxL/groupe-m6-w9-6ter-topaz-removedddd-remove.png" group-title="FR | General",FR | W9 FHD +http://176.65.146.138:8047/play/a07j/index.m3u8 +#EXTINF:-1 tvg-id="W9.fr" tvg-name="FR | W9 FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/w9.png" tvg-poster="https://tvmio.gleeze.com/poster/general/w9.png" tvg-back="https://i.ibb.co/vx1S5yxL/groupe-m6-w9-6ter-topaz-removedddd-remove.png" group-title="FR | General",FR | W9 FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116085 +#EXTINF:-1 tvg-id="W9.fr" tvg-name="FR | W9 HD" tvg-logo="https://tvmio.gleeze.com/logos/general/w9.png" tvg-poster="https://tvmio.gleeze.com/poster/general/w9.png" tvg-back="https://i.ibb.co/vx1S5yxL/groupe-m6-w9-6ter-topaz-removedddd-remove.png" group-title="FR | General",FR | W9 HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116084 +#EXTINF:-1 tvg-id="W9.fr" tvg-name="FR | W9 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/w9.png" tvg-poster="https://tvmio.gleeze.com/poster/general/w9.png" tvg-back="https://i.ibb.co/vx1S5yxL/groupe-m6-w9-6ter-topaz-removedddd-remove.png" group-title="FR | General",FR | W9 HD +http://151.80.18.177:86/W9_HD/index.m3u8 +#EXTINF:-1 tvg-id="W9.fr" tvg-name="FR | W9 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/w9.png" tvg-poster="https://tvmio.gleeze.com/poster/general/w9.png" tvg-back="https://i.ibb.co/vx1S5yxL/groupe-m6-w9-6ter-topaz-removedddd-remove.png" group-title="FR | General",FR | W9 HD +https://live.streamgatos.top/hls/29707/stream.m3u8 +#EXTINF:-1 tvg-id="TMC.fr" tvg-name="FR | TMC FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/tmc.png" tvg-poster="https://tvmio.gleeze.com/poster/general/tmc.png" tvg-back="https://i.ibb.co/zh7cY7j1/monte-carlo-monaco-wallpaper-1920x1080-topaz-removedddd-remove.jpg" group-title="FR | General",FR | TMC FHD +http://176.65.146.138:8047/play/a076/index.m3u8 +#EXTINF:-1 tvg-id="TMC.fr" tvg-name="FR | TMC SD" tvg-logo="https://tvmio.gleeze.com/logos/general/tmc.png" tvg-poster="https://tvmio.gleeze.com/poster/general/tmc.png" tvg-back="https://i.ibb.co/zh7cY7j1/monte-carlo-monaco-wallpaper-1920x1080-topaz-removedddd-remove.jpg" group-title="FR | General",FR | TMC SD +https://viamotionhsi.netplus.ch/live/eds/tmc/browser-HLS8/tmc.m3u8 +#EXTINF:-1 tvg-id="TMC.fr" tvg-name="FR | TMC FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/tmc.png" tvg-poster="https://tvmio.gleeze.com/poster/general/tmc.png" tvg-back="https://i.ibb.co/zh7cY7j1/monte-carlo-monaco-wallpaper-1920x1080-topaz-removedddd-remove.jpg" group-title="FR | General",FR | TMC FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116088 +#EXTINF:-1 tvg-id="TMC.fr" tvg-name="FR | TMC HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/tmc.png" tvg-poster="https://tvmio.gleeze.com/poster/general/tmc.png" tvg-back="https://i.ibb.co/zh7cY7j1/monte-carlo-monaco-wallpaper-1920x1080-topaz-removedddd-remove.jpg" group-title="FR | General",FR | TMC HD +https://live.streamgatos.top/hls/918/stream.m3u8 +#EXTINF:-1 tvg-id="NT1.fr" tvg-name="FR | TFX FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/tfx.png" tvg-poster="https://tvmio.gleeze.com/poster/general/tfx.png" tvg-back="https://i.ibb.co/99CxJGF0/tfx-topaz-removedddd-upscale-1-3x-remove.png" group-title="FR | General",FR | TFX FHD +http://176.65.146.138:8047/play/a077/index.m3u8 +#EXTINF:-1 tvg-id="NT1.fr" tvg-name="FR | TFX SD" tvg-logo="https://tvmio.gleeze.com/logos/general/tfx.png" tvg-poster="https://tvmio.gleeze.com/poster/general/tfx.png" tvg-back="https://i.ibb.co/99CxJGF0/tfx-topaz-removedddd-upscale-1-3x-remove.png" group-title="FR | General",FR | TFX SD +https://viamotionhsi.netplus.ch/live/eds/nt1/browser-HLS8/nt1.m3u8 +#EXTINF:-1 tvg-id="NT1.fr" tvg-name="FR | TFX HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/tfx.png" tvg-poster="https://tvmio.gleeze.com/poster/general/tfx.png" tvg-back="https://i.ibb.co/99CxJGF0/tfx-topaz-removedddd-upscale-1-3x-remove.png" group-title="FR | General",FR | TFX HD +https://live.streamgatos.top/hls/8887/stream.m3u8 +#EXTINF:-1 tvg-id="T18.fr" tvg-name="FR | T18 SD" tvg-logo="https://i.ibb.co/q3V1Jrfh/t18-logo.png" tvg-poster="https://i.ibb.co/v6MYTWBt/t18-poster.png" tvg-back="https://i.ibb.co/Lb6FjVR/t18-jingle-04.png" group-title="FR | General",FR | T18 SD +https://tvradiozap.eu/tools/np-m3u8.php/t18.m3u8 +#EXTINF:-1 tvg-id="T18.fr" tvg-name="FR | T18 FHD" tvg-logo="https://i.ibb.co/q3V1Jrfh/t18-logo.png" tvg-poster="https://i.ibb.co/v6MYTWBt/t18-poster.png" tvg-back="https://i.ibb.co/Lb6FjVR/t18-jingle-04.png" group-title="FR | General",FR | T18 FHD +https://raw.githubusercontent.com/Paradise-91/ParaTV/main/streams/t18/res/t18-dm-highest.m3u8 +#EXTINF:-1 tvg-id="13eRue.fr" tvg-name="FR | 13eme Rue FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/Mkcmq7TH/13eme-rue-logo.png" tvg-poster="https://i.ibb.co/d4L94Bwr/13-eme-rue-poster.png" tvg-back="https://i.ibb.co/Mkcmq7TH/13eme-rue-logo.png" group-title="FR | General",FR | 13eme Rue FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/3346 +#EXTINF:-1 tvg-id="13eRue.fr" tvg-name="FR | 13eme Rue FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/Mkcmq7TH/13eme-rue-logo.png" tvg-poster="https://i.ibb.co/d4L94Bwr/13-eme-rue-poster.png" tvg-back="https://i.ibb.co/Mkcmq7TH/13eme-rue-logo.png" group-title="FR | General",FR | 13eme Rue FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116444 +#EXTINF:-1 tvg-id="13eRue.fr" tvg-name="FR | 13eme Rue FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/Mkcmq7TH/13eme-rue-logo.png" tvg-poster="https://i.ibb.co/d4L94Bwr/13-eme-rue-poster.png" tvg-back="https://i.ibb.co/Mkcmq7TH/13eme-rue-logo.png" group-title="FR | General",FR | 13eme Rue FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/104 +#EXTINF:-1 tvg-id="6ter.fr" tvg-name="FR | 6ter FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/6ter.png" tvg-poster="https://tvmio.gleeze.com/poster/general/6ter.png" tvg-back="https://i.ibb.co/vx1S5yxL/groupe-m6-w9-6ter-topaz-removedddd-remove.png" group-title="FR | General",FR | 6ter FHD +http://176.65.146.138:8047/play/a07m/index.m3u8 +#EXTINF:-1 tvg-id="6ter.fr" tvg-name="FR | 6ter HD" tvg-logo="https://tvmio.gleeze.com/logos/general/6ter.png" tvg-poster="https://tvmio.gleeze.com/poster/general/6ter.png" tvg-back="https://i.ibb.co/vx1S5yxL/groupe-m6-w9-6ter-topaz-removedddd-remove.png" group-title="FR | General",FR | 6ter HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116080 +#EXTINF:-1 tvg-id="6ter.fr" tvg-name="FR | 6ter HD" tvg-logo="https://tvmio.gleeze.com/logos/general/6ter.png" tvg-poster="https://tvmio.gleeze.com/poster/general/6ter.png" tvg-back="https://i.ibb.co/vx1S5yxL/groupe-m6-w9-6ter-topaz-removedddd-remove.png" group-title="FR | General",FR | 6ter HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116081 +#EXTINF:-1 tvg-id="6ter.fr" tvg-name="FR | 6ter FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/6ter.png" tvg-poster="https://tvmio.gleeze.com/poster/general/6ter.png" tvg-back="https://i.ibb.co/vx1S5yxL/groupe-m6-w9-6ter-topaz-removedddd-remove.png" group-title="FR | General",FR | 6ter FHD +https://live.streamgatos.top/hls/437/stream.m3u8 +#EXTINF:-1 tvg-id="Cherie25.fr" tvg-name="FR | RMC Life FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/rmc_life.png" tvg-poster="https://tvmio.gleeze.com/poster/general/rmc_life.png" tvg-back="https://i.ibb.co/WNmqSZ6Y/rmclife-jpd-ble-2025-topaz-removedddd-sharpen-remove.jpg" group-title="FR | General",FR | RMC Life FHD +http://176.65.146.138:8047/play/a07b/index.m3u8 +#EXTINF:-1 tvg-id="Cherie25.fr" tvg-name="FR | RMC Life SD" tvg-logo="https://tvmio.gleeze.com/logos/general/rmc_life.png" tvg-poster="https://tvmio.gleeze.com/poster/general/rmc_life.png" tvg-back="https://i.ibb.co/WNmqSZ6Y/rmclife-jpd-ble-2025-topaz-removedddd-sharpen-remove.jpg" group-title="FR | General",FR | RMC Life SD +https://viamotionhsi.netplus.ch/live/eds/cherie25/browser-HLS8/cherie25.m3u8 +#EXTINF:-1 tvg-id="Cherie25.fr" tvg-name="FR | RMC Life FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/rmc_life.png" tvg-poster="https://tvmio.gleeze.com/poster/general/rmc_life.png" tvg-back="https://i.ibb.co/WNmqSZ6Y/rmclife-jpd-ble-2025-topaz-removedddd-sharpen-remove.jpg" group-title="FR | General",FR | RMC Life FHD +http://sewv654wfcsdwfi87fwvgbngh.siauliairsavlt.pw/iptv/VEXVELA6Z7PXH6/15186/index.m3u8 +#EXTINF:-1 tvg-id="Numero23.fr" tvg-name="FR | RMC Story FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/rmc_story.png" tvg-poster="https://tvmio.gleeze.com/poster/general/rmc_story.png" tvg-back="https://i.ibb.co/7JY94nxW/rmcstory-topaz-removedddd-denoise-sharpen-remove.png" group-title="FR | General",FR | RMC Story FHD +http://176.65.146.138:8047/play/a07d/index.m3u8 +#EXTINF:-1 tvg-id="Numero23.fr" tvg-name="FR | RMC Story FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/rmc_story.png" tvg-poster="https://tvmio.gleeze.com/poster/general/rmc_story.png" tvg-back="https://i.ibb.co/7JY94nxW/rmcstory-topaz-removedddd-denoise-sharpen-remove.png" group-title="FR | General",FR | RMC Story FHD +https://d15aro46bnpfm8.cloudfront.net/v1/master/3722c60a815c199d9c0ef36c5b73da68a62b09d1/cc-fqkqiax1078up/RMC_Story_FR.m3u8 +#EXTINF:-1 tvg-id="Numero23.fr" tvg-name="FR | RMC Story FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/rmc_story.png" tvg-poster="https://tvmio.gleeze.com/poster/general/rmc_story.png" tvg-back="https://i.ibb.co/7JY94nxW/rmcstory-topaz-removedddd-denoise-sharpen-remove.png" group-title="FR | General",FR | RMC Story FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116116 +#EXTINF:-1 tvg-id="Numero23.fr" tvg-name="FR | RMC Story SD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/rmc_story.png" tvg-poster="https://tvmio.gleeze.com/poster/general/rmc_story.png" tvg-back="https://i.ibb.co/7JY94nxW/rmcstory-topaz-removedddd-denoise-sharpen-remove.png" group-title="FR | General",FR | RMC Story SD +https://live.streamgatos.top/hls/8840/stream.m3u8 +#EXTINF:-1 tvg-id="RMCDecouverte.fr" tvg-name="FR | RMC Decouverte FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/rmc_decouverte.png" tvg-poster="https://tvmio.gleeze.com/poster/general/rmc_decouverte.png" tvg-back="https://screenplus.fr/wp-content/uploads/2025/10/En-tete-S-2025-10-08T205213.761.png" group-title="FR | General",FR | RMC Decouverte FHD +http://176.65.146.138:8047/play/a07c/index.m3u8 +#EXTINF:-1 tvg-id="RMCDecouverte.fr" tvg-name="FR | RMC Decouverte FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/rmc_decouverte.png" tvg-poster="https://tvmio.gleeze.com/poster/general/rmc_decouverte.png" tvg-back="https://screenplus.fr/wp-content/uploads/2025/10/En-tete-S-2025-10-08T205213.761.png" group-title="FR | General",FR | RMC Decouverte FHD +https://d16zzycxcd0m0r.cloudfront.net/v1/master/3722c60a815c199d9c0ef36c5b73da68a62b09d1/cc-hixvx5kymecr9/RMC_Decouverte_FR.m3u8 +#EXTINF:-1 tvg-id="RMCDecouverte.fr" tvg-name="FR | RMC Decouverte FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/rmc_decouverte.png" tvg-poster="https://tvmio.gleeze.com/poster/general/rmc_decouverte.png" tvg-back="https://screenplus.fr/wp-content/uploads/2025/10/En-tete-S-2025-10-08T205213.761.png" group-title="FR | General",FR | RMC Decouverte FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116115 +#EXTINF:-1 tvg-id="RMCDecouverte.fr" tvg-name="FR | RMC Decouverte FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/rmc_decouverte.png" tvg-poster="https://tvmio.gleeze.com/poster/general/rmc_decouverte.png" tvg-back="https://screenplus.fr/wp-content/uploads/2025/10/En-tete-S-2025-10-08T205213.761.png" group-title="FR | General",FR | RMC Decouverte FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116114 +#EXTINF:-1 tvg-id="RMCDecouverte.fr" tvg-name="FR | RMC Decouverte HD" tvg-logo="https://tvmio.gleeze.com/logos/general/rmc_decouverte.png" tvg-poster="https://tvmio.gleeze.com/poster/general/rmc_decouverte.png" tvg-back="https://screenplus.fr/wp-content/uploads/2025/10/En-tete-S-2025-10-08T205213.761.png" group-title="FR | General",FR | RMC Decouverte HD +http://151.80.18.177:86/RMC_Decouverte_HD/index.m3u8 +#EXTINF:-1 tvg-id="RMCDecouverte.fr" tvg-name="FR | RMC Decouverte HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/rmc_decouverte.png" tvg-poster="https://tvmio.gleeze.com/poster/general/rmc_decouverte.png" tvg-back="https://screenplus.fr/wp-content/uploads/2025/10/En-tete-S-2025-10-08T205213.761.png" group-title="FR | General",FR | RMC Decouverte HD +https://live.streamgatos.top/hls/2483/stream.m3u8 +#EXTINF:-1 tvg-id="AB1.fr" tvg-name="FR | AB1 FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/zWcTgLpv/ab1-logo.png" tvg-poster="https://i.ibb.co/LzwhGLgn/ab1-poster.png" tvg-back="https://i.ibb.co/zWcTgLpv/ab1-logo.png" group-title="FR | General",FR | AB1 FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/48676 +#EXTINF:-1 tvg-id="AB1.fr" tvg-name="FR | AB1 HD" tvg-chno="0" tvg-logo="https://i.ibb.co/zWcTgLpv/ab1-logo.png" tvg-poster="https://i.ibb.co/LzwhGLgn/ab1-poster.png" tvg-back="https://i.ibb.co/zWcTgLpv/ab1-logo.png" group-title="FR | General",FR | AB1 HD +http://151.80.18.177:86/AB1/index.m3u8 +#EXTINF:-1 tvg-id="AB3.fr" tvg-name="FR | AB3 HD" tvg-chno="0" tvg-logo="https://i.ibb.co/BH4gt3sk/ab3-logo.png" tvg-poster="https://i.ibb.co/36jhkPf/ab3-poster.png" tvg-back="https://i.ibb.co/BH4gt3sk/ab3-logo.png" group-title="FR | General",FR | AB3 HD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/1694 +#EXTINF:-1 tvg-id="ComediePlus.fr" tvg-name="FR | Comedie+ FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/comedie.png" tvg-poster="https://tvmio.gleeze.com/poster/general/comedie.png" tvg-back="https://media.istockphoto.com/id/1341241233/fr/vectoriel/lieu-de-travail-dun-acteur-ou-dun-com%C3%A9dien-rideaux-de-th%C3%A9%C3%A2tre-rouges.jpg?s=612x612&w=0&k=20&c=l9CYNjfnExclsa1JUyZRH3TX6frukpWM9ELU8yAh7W8=" group-title="FR | General",FR | Comedie+ FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/48674 +#EXTINF:-1 tvg-id="ComediePlus.fr" tvg-name="FR | Comedie+ FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/comedie.png" tvg-poster="https://tvmio.gleeze.com/poster/general/comedie.png" tvg-back="https://media.istockphoto.com/id/1341241233/fr/vectoriel/lieu-de-travail-dun-acteur-ou-dun-com%C3%A9dien-rideaux-de-th%C3%A9%C3%A2tre-rouges.jpg?s=612x612&w=0&k=20&c=l9CYNjfnExclsa1JUyZRH3TX6frukpWM9ELU8yAh7W8=" group-title="FR | General",FR | Comedie+ FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/1458 +#EXTINF:-1 tvg-id="ComediePlus.fr" tvg-name="FR | Comedie+ HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/comedie.png" tvg-poster="https://tvmio.gleeze.com/poster/general/comedie.png" tvg-back="https://media.istockphoto.com/id/1341241233/fr/vectoriel/lieu-de-travail-dun-acteur-ou-dun-com%C3%A9dien-rideaux-de-th%C3%A9%C3%A2tre-rouges.jpg?s=612x612&w=0&k=20&c=l9CYNjfnExclsa1JUyZRH3TX6frukpWM9ELU8yAh7W8=" group-title="FR | General",FR | Comedie+ HD +http://151.80.18.177:86/Comedie+_HD/index.m3u8 +#EXTINF:-1 tvg-id="EEntertainment.fr" tvg-name="FR | E! Entertainment FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/e.png" tvg-poster="https://tvmio.gleeze.com/poster/general/e.png" tvg-back="https://wallpapercave.com/wp/yrfZUun.jpg" group-title="FR | General",FR | E! Entertainment FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/52238 +#EXTINF:-1 tvg-id="NOVO19.fr" tvg-name="FR | Novo 19" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/novo19.png" tvg-poster="https://tvmio.gleeze.com/poster/general/novo19.png" tvg-back="https://i.ibb.co/hF58r4N5/novo19-jingle-lancement-violet-2025.jpg" group-title="FR | General",FR | Novo 19 HD +https://viamotionhsi.netplus.ch/live/eds/novo19/browser-HLS8/novo19.m3u8 +#EXTINF:-1 tvg-id="NOVO19.fr" tvg-name="FR | Novo 19" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/novo19.png" tvg-poster="https://tvmio.gleeze.com/poster/general/novo19.png" tvg-back="https://i.ibb.co/hF58r4N5/novo19-jingle-lancement-violet-2025.jpg" group-title="FR | General",FR | Novo 19 +https://tvradiozap.eu/tools/np-m3u8.php/novo19 +#EXTINF:-1 tvg-id="ParisPremiere.fr" tvg-name="FR | Paris Premiere HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/paris_premiere.png" tvg-poster="https://tvmio.gleeze.com/poster/general/paris_premiere.png" tvg-back="https://wallpapers.com/images/hd/paris-eiffel-tower-ah19sagu2co2m8s1.jpg" group-title="FR | General",FR | Paris Premiere HD +http://sewv654wfcsdwfi87fwvgbngh.siauliairsavlt.pw/iptv/VEXVELA6Z7PXH6/6146/index.m3u8 +#EXTINF:-1 tvg-id="ParisPremiere.fr" tvg-name="FR | Paris Premiere HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/paris_premiere.png" tvg-poster="https://tvmio.gleeze.com/poster/general/paris_premiere.png" tvg-back="https://wallpapers.com/images/hd/paris-eiffel-tower-ah19sagu2co2m8s1.jpg" group-title="FR | General",FR | Paris Premiere HD +http://151.80.18.177:86/Paris_Premiere_HD/index.m3u8 +#EXTINF:-1 tvg-id="RTL9.fr" tvg-name="FR | RTL 9 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/rtl_9.png" tvg-poster="https://tvmio.gleeze.com/poster/general/rtl_9.png" tvg-back="https://i.ibb.co/WW2yY0bm/DEF-rtl9-169.jpg" group-title="FR | General",FR | RTL 9 HD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/3676 +#EXTINF:-1 tvg-id="RTL9.fr" tvg-name="FR | RTL 9 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/rtl_9.png" tvg-poster="https://tvmio.gleeze.com/poster/general/rtl_9.png" tvg-back="https://i.ibb.co/WW2yY0bm/DEF-rtl9-169.jpg" group-title="FR | General",FR | RTL 9 HD +http://151.80.18.177:86/RTL9/index.m3u8 +#EXTINF:-1 tvg-id="RTS.sn" tvg-name="FR | RTS 1 SD" tvg-chno="0" tvg-logo="https://i.ibb.co/spm1VJvJ/rts1-logo.png" tvg-poster="https://i.ibb.co/cXN2ZPR0/rts1-poster.png" tvg-back="https://i.ibb.co/3tsv2y3/rts1.png" group-title="FR | General",FR | RTS 1 SD +https://viamotionhsi.netplus.ch/live/eds/rts1hd/browser-HLS8/rts1hd.m3u8 +#EXTINF:-1 tvg-id="RTS.sn" tvg-name="FR | RTS 1 HD" tvg-chno="0" tvg-logo="https://i.ibb.co/spm1VJvJ/rts1-logo.png" tvg-poster="https://i.ibb.co/cXN2ZPR0/rts1-poster.png" tvg-back="https://i.ibb.co/3tsv2y3/rts1.png" group-title="FR | General",FR | RTS 1 HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116614 +#EXTINF:-1 tvg-id="RTS2.sn" tvg-name="FR | RTS 2 SD" tvg-chno="0" tvg-logo="https://i.ibb.co/hhycvKw/rts2-logo.png" tvg-poster="https://i.ibb.co/Q7Pkm46w/rts2-poster.png" tvg-back="https://i.ibb.co/WNdkKRCD/rts2.png" group-title="FR | General",FR | RTS 2 SD +https://viamotionhsi.netplus.ch/live/eds/rts2hd/browser-HLS8/rts2hd.m3u8 +#EXTINF:-1 tvg-id="RTS2.sn" tvg-name="FR | RTS 2 HD" tvg-chno="0" tvg-logo="https://i.ibb.co/hhycvKw/rts2-logo.png" tvg-poster="https://i.ibb.co/Q7Pkm46w/rts2-poster.png" tvg-back="https://i.ibb.co/WNdkKRCD/rts2.png" group-title="FR | General",FR | RTS 2 HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/128219 +#EXTINF:-1 tvg-id="Teva.fr" tvg-name="FR | Teva FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/yn5NLpb7/teva-logo.png" tvg-poster="https://i.ibb.co/1JZXNbXz/teva-poster.png" tvg-back="https://png.pngtree.com/background/20250102/original/pngtree-green-wave-shine-bright-background-vector-picture-image_15440186.jpg" group-title="FR | General",FR | Teva FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/108 +#EXTINF:-1 tvg-id="Teva.fr" tvg-name="FR | Teva HD" tvg-chno="0" tvg-logo="https://i.ibb.co/yn5NLpb7/teva-logo.png" tvg-poster="https://i.ibb.co/1JZXNbXz/teva-poster.png" tvg-back="https://png.pngtree.com/background/20250102/original/pngtree-green-wave-shine-bright-background-vector-picture-image_15440186.jpg" group-title="FR | General",FR | Teva HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116436 +#EXTINF:-1 tvg-id="Teva.fr" tvg-name="FR | Teva HD" tvg-chno="0" tvg-logo="https://i.ibb.co/yn5NLpb7/teva-logo.png" tvg-poster="https://i.ibb.co/1JZXNbXz/teva-poster.png" tvg-back="https://png.pngtree.com/background/20250102/original/pngtree-green-wave-shine-bright-background-vector-picture-image_15440186.jpg" group-title="FR | General",FR | Teva HD +http://151.80.18.177:86/Teva_HD/index.m3u8 +#EXTINF:-1 tvg-id="beINSPORTS1.fr" tvg-name="FR | BeIN Sports 1 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/beinsport_1.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/beinsport_1.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports 1 FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/53324 +#EXTINF:-1 tvg-id="beINSPORTS1.fr" tvg-name="FR | BeIN Sports 1 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/beinsport_1.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/beinsport_1.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports 1 HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116514 +#EXTINF:-1 tvg-id="beINSPORTS1.fr" tvg-name="FR | BeIN Sports 1 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/beinsport_1.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/beinsport_1.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports 1 HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116513 +#EXTINF:-1 tvg-id="beINSPORTS1.fr" tvg-name="FR | BeIN Sports 1 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/beinsport_1.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/beinsport_1.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports 1 FHD +https://live.streamgatos.top/hls/8821/stream.m3u8 +#EXTINF:-1 tvg-id="beINSPORTS1.fr" tvg-name="FR | BeIN Sports 1 FHD" tvg-logo="https://tvmio.gleeze.com/logos/sports/beinsport_1.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/beinsport_1.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports 1 FHD +http://drmv3-m6.info:80/play/live.php?mac=00:1A:79:84:1A:60&stream=146116&extension=ts +#EXTINF:-1 tvg-id="beINSPORTS2.fr" tvg-name="FR | BeIN Sports 2 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/beinsport_2.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/beinsport_2.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports 2 HD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:C1:E3:9A&stream=149773&extension=ts +#EXTINF:-1 tvg-id="beINSPORTS2.fr" tvg-name="FR | BeIN Sports 2 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/beinsport_2.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/beinsport_2.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports 2 HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116515 +#EXTINF:-1 tvg-id="beINSPORTS2.fr" tvg-name="FR | BeIN Sports 2 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/beinsport_2.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/beinsport_2.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports 2 HD +https://live.streamgatos.top/hls/883/stream.m3u8 +#EXTINF:-1 tvg-id="beINSPORTS2.fr" tvg-name="FR | BeIN Sports 2 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/beinsport_2.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/beinsport_2.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports 2 HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116516 +#EXTINF:-1 tvg-id="beINSPORTS2.fr" tvg-name="FR | BeIN Sports 2 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/beinsport_2.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/beinsport_2.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports 2 HD +http://medotv.nl:8000/RAMBOfoundedoninternetsoIchangedTheFuckinguSERNAMelol123/5caU9cN5jFjZ/116516 +#EXTINF:-1 tvg-id="beINSPORTS3.fr" tvg-name="FR | BeIN Sports 3 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/beinsport_3.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/beinsport_3.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports 3 FHD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:C1:E3:9A&stream=250663&extension=ts +#EXTINF:-1 tvg-id="beINSPORTS3.fr" tvg-name="FR | BeIN Sports 3 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/beinsport_3.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/beinsport_3.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports 3 FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116517 +#EXTINF:-1 tvg-id="beINSPORTS3.fr" tvg-name="FR | BeIN Sports 3 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/beinsport_3.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/beinsport_3.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports 3 HD +https://live.streamgatos.top/hls/884/stream.m3u8 +#EXTINF:-1 tvg-id="beINSPORTS3.fr" tvg-name="FR | BeIN Sports 3 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/beinsport_3.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/beinsport_3.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports 3 FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116518 +#EXTINF:-1 tvg-id="beINSPORTSMAX4.fr" tvg-name="FR | BeIN Sports Max 4 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/beinsportsmax_4.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/beinsportsmax_4.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports Max 4 FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/49620 +#EXTINF:-1 tvg-id="beINSPORTSMAX4.fr" tvg-name="FR | BeIN Sports Max 4 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/beinsportsmax_4.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/beinsportsmax_4.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports Max 4 HD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:84:0F:1B&stream=212588&extension=ts +#EXTINF:-1 tvg-id="beINSPORTSMAX5.fr" tvg-name="FR | BeIN Sports Max 5 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/beinsportsmax_5.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/beinsportsmax_5.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports Max 5 HD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/49619 +#EXTINF:-1 tvg-id="beINSPORTSMAX5.fr" tvg-name="FR | BeIN Sports Max 5 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/beinsportsmax_5.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/beinsportsmax_5.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports Max 5 HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116520 +#EXTINF:-1 tvg-id="beINSPORTSMAX5.fr" tvg-name="FR | BeIN Sports Max 5 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/beinsportsmax_5.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/beinsportsmax_5.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports Max 5 HD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:84:0F:1B&stream=212587&extension=ts +#EXTINF:-1 tvg-id="beINSPORTSMAX6.fr" tvg-name="FR | BeIN Sports Max 6 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/beinsportsmax_6.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/beinsportsmax_6.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports Max 6 HD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/49618 +#EXTINF:-1 tvg-id="beINSPORTSMAX6.fr" tvg-name="FR | BeIN Sports Max 6 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/beinsportsmax_6.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/beinsportsmax_6.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports Max 6 HD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:84:0F:1B&stream=212586&extension=ts +#EXTINF:-1 tvg-id="beINSPORTSMAX7.fr" tvg-name="FR | beIN Sports Max 7 FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/fcfSvXt/beinsport-max-7-logo.png" tvg-poster="https://i.ibb.co/35cV0xYP/beinsportmax-7-poster.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports Max 7 FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/49617 +#EXTINF:-1 tvg-id="beINSPORTSMAX7.fr" tvg-name="FR | beIN Sports Max 7 FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/fcfSvXt/beinsport-max-7-logo.png" tvg-poster="https://i.ibb.co/35cV0xYP/beinsportmax-7-poster.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports Max 7 FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116522 +#EXTINF:-1 tvg-id="beINSPORTSMAX8.fr" tvg-name="FR | BeIN Sports Max 8 HD" tvg-chno="0" tvg-logo="https://i.ibb.co/hFPQTdrJ/beinsport-max-8-logo.png" tvg-poster="https://i.ibb.co/MDfySBgF/beinsportmax8poster.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports Max 8 HD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/49616 +#EXTINF:-1 tvg-id="beINSPORTSMAX8.fr" tvg-name="FR | BeIN Sports Max 8 FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/hFPQTdrJ/beinsport-max-8-logo.png" tvg-poster="https://i.ibb.co/MDfySBgF/beinsportmax8poster.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports Max 8 FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116523 +#EXTINF:-1 tvg-id="beINSPORTSMAX9.fr" tvg-name="FR | BeIN Sports Max 9 FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/35TFFcsz/beinsport-max-9-logo.png" tvg-poster="https://i.ibb.co/WpMJLgVv/beinsportmax9poster.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports Max 9 FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/49615 +#EXTINF:-1 tvg-id="beINSPORTSMAX9.fr" tvg-name="FR | BeIN Sports Max 9 FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/35TFFcsz/beinsport-max-9-logo.png" tvg-poster="https://i.ibb.co/WpMJLgVv/beinsportmax9poster.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports Max 9 FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116524 +#EXTINF:-1 tvg-id="beINSPORTSMAX10.fr" tvg-name="FR | BeIN Sports Max 10 FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/v63VGkM0/beinsport-max-10-logo.png" tvg-poster="https://i.ibb.co/ycDTBZw7/beinsportmax10poster.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports Max 10 FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/49614 +#EXTINF:-1 tvg-id="beINSPORTSMAX10.fr" tvg-name="FR | BeIN Sports Max 10 HD" tvg-chno="0" tvg-logo="https://i.ibb.co/v63VGkM0/beinsport-max-10-logo.png" tvg-poster="https://i.ibb.co/ycDTBZw7/beinsportmax10poster.png" tvg-back="https://i.ibb.co/xK2ZZpLP/bein-sports-en-clair-orange-gigapixel-high-fidelity-v2-1080h.png" group-title="FR | Sports",FR | BeIN Sports Max 10 HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116525 +#EXTINF:-1 tvg-id="Ligue1Plus.fr" tvg-name="FR | Ligue 1+ FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/ligue_1.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/ligue_1.png" tvg-back="https://fistf.com/wp-content/uploads/2017/08/cropped-UEFA-Champions-League-Stadium-Wallpaper.jpg" group-title="FR | Sports",FR | Ligue 1+ FHD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:84:0F:1B&stream=1813243&extension=ts +#EXTINF:-1 tvg-id="Ligue1Plus.fr" tvg-name="FR | Ligue 1+ HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/ligue_1.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/ligue_1.png" tvg-back="https://fistf.com/wp-content/uploads/2017/08/cropped-UEFA-Champions-League-Stadium-Wallpaper.jpg" group-title="FR | Sports",FR | Ligue 1+ HD +https://live.streamgatos.top/hls/196665/stream.m3u8 +#EXTINF:-1 tvg-id="Ligue1Plus.fr" tvg-name="FR | Ligue 1+ FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/ligue_1.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/ligue_1.png" tvg-back="https://fistf.com/wp-content/uploads/2017/08/cropped-UEFA-Champions-League-Stadium-Wallpaper.jpg" group-title="FR | Sports",FR | Ligue 1+ FHD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:84:0F:1B&stream=1523608&extension=ts +#EXTINF:-1 tvg-id="Ligue1Plus2.fr" tvg-name="FR | Ligue 1+ 2 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/ligue_1_2.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/ligue_1_2.png" tvg-back="https://fistf.com/wp-content/uploads/2017/08/cropped-UEFA-Champions-League-Stadium-Wallpaper.jpg" group-title="FR | Sports",FR | Ligue 1+ 2 FHD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:84:0F:1B&stream=1813244&extension=ts +#EXTINF:-1 tvg-id="Ligue1Plus3.fr" tvg-name="FR | Ligue 1+ 3 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/ligue_1_3.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/ligue_1_3.png" tvg-back="https://fistf.com/wp-content/uploads/2017/08/cropped-UEFA-Champions-League-Stadium-Wallpaper.jpg" group-title="FR | Sports",FR | Ligue 1+ 3 HD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:84:0F:1B&stream=1102180&extension=ts +#EXTINF:-1 tvg-id="Ligue1Plus4.fr" tvg-name="FR | Ligue 1+ 4 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/ligue_1_4.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/ligue_1_4.png" tvg-back="https://fistf.com/wp-content/uploads/2017/08/cropped-UEFA-Champions-League-Stadium-Wallpaper.jpg" group-title="FR | Sports",FR | Ligue 1+ 4 FHD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:84:0F:1B&stream=1523611&extension=ts +#EXTINF:-1 tvg-id="Ligue1Plus5.fr" tvg-name="FR | Ligue 1+ 5 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/ligue_1_5.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/ligue_1_5.png" tvg-back="https://fistf.com/wp-content/uploads/2017/08/cropped-UEFA-Champions-League-Stadium-Wallpaper.jpg" group-title="FR | Sports",FR | Ligue 1+ 5 FHD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:84:0F:1B&stream=1523612&extension=ts +#EXTINF:-1 tvg-id="Ligue1Plus6.fr" tvg-name="FR | Ligue 1+ 6 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/ligue_1_6.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/ligue_1_6.png" tvg-back="https://fistf.com/wp-content/uploads/2017/08/cropped-UEFA-Champions-League-Stadium-Wallpaper.jpg" group-title="FR | Sports",FR | Ligue 1+ 6 FHD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:84:0F:1B&stream=1523613&extension=ts +#EXTINF:-1 tvg-id="RMCSport1.fr" tvg-name="FR | RMC Sport 1 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/rmc_sport_1.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/rmc_sport_1.png" tvg-back="https://i.ibb.co/BJWTqtT/image-1-topaz-removedddd-upscale-1-5x-remove.png" group-title="FR | Sports",FR | RMC Sport 1 FHD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:84:0F:1B&stream=/play/live.php?mac=00:1A:79:BF:47:35&stream=32835&extension=ts +#EXTINF:-1 tvg-id="RMCSport1.fr" tvg-name="FR | RMC Sport 1 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/rmc_sport_1.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/rmc_sport_1.png" tvg-back="https://i.ibb.co/BJWTqtT/image-1-topaz-removedddd-upscale-1-5x-remove.png" group-title="FR | Sports",FR | RMC Sport 1 HD +http://sewv654wfcsdwfi87fwvgbngh.siauliairsavlt.pw/iptv/VEXVELA6Z7PXH6/2545/index.m3u8 +#EXTINF:-1 tvg-id="RMCSport2.fr" tvg-name="FR | RMC Sport 2 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/rmc_sport_2.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/rmc_sport_2.png" tvg-back="https://i.ibb.co/BJWTqtT/image-1-topaz-removedddd-upscale-1-5x-remove.png" group-title="FR | Sports",FR | RMC Sport 2 FHD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:84:0F:1B&stream=275813&extension=ts +#EXTINF:-1 tvg-id="RMCSport2.fr" tvg-name="FR | RMC Sport 2 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/rmc_sport_2.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/rmc_sport_2.png" tvg-back="https://i.ibb.co/BJWTqtT/image-1-topaz-removedddd-upscale-1-5x-remove.png" group-title="FR | Sports",FR | RMC Sport 2 HD +http://sewv654wfcsdwfi87fwvgbngh.siauliairsavlt.pw/iptv/VEXVELA6Z7PXH6/2546/index.m3u8 +#EXTINF:-1 tvg-id="RMCSport3.fr" tvg-name="FR | RMC Sport 3 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/rmc_sport_3.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/rmc_sport_3.png" tvg-back="https://i.ibb.co/BJWTqtT/image-1-topaz-removedddd-upscale-1-5x-remove.png" group-title="FR | Sports",FR | RMC Sport 3 HD +http://sewv654wfcsdwfi87fwvgbngh.siauliairsavlt.pw/iptv/VEXVELA6Z7PXH6/2547/index.m3u8 +#EXTINF:-1 tvg-id="LEquipe21.fr" tvg-name="FR | LEquipe FHD" tvg-logo="https://tvmio.gleeze.com/logos/sports/lequipe.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/lequipe.png" tvg-back="https://www.lequipe.fr/_medias/img-photo-jpg/benterki-messaoud-a-mounic-l-equipe/1500000001809824/0:0,1994:1329-828-552-75/8ebfd.jpg" group-title="FR | Sports",FR | LEquipe FHD +http://176.65.146.138:8047/play/a07a/index.m3u8 +#EXTINF:-1 tvg-id="LEquipe21.fr" tvg-name="FR | LEquipe HD" tvg-logo="https://tvmio.gleeze.com/logos/sports/lequipe.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/lequipe.png" tvg-back="https://www.lequipe.fr/_medias/img-photo-jpg/benterki-messaoud-a-mounic-l-equipe/1500000001809824/0:0,1994:1329-828-552-75/8ebfd.jpg" group-title="FR | Sports",FR | LEquipe HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116535 +#EXTINF:-1 tvg-id="LEquipe21.fr" tvg-name="FR | LEquipe SD" tvg-logo="https://tvmio.gleeze.com/logos/sports/lequipe.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/lequipe.png" tvg-back="https://www.lequipe.fr/_medias/img-photo-jpg/benterki-messaoud-a-mounic-l-equipe/1500000001809824/0:0,1994:1329-828-552-75/8ebfd.jpg" group-title="FR | Sports",FR | LEquipe SD +https://tvradiozap.eu/tools/dm-m3u8.php/1/x2lefik.m3u8 +#EXTINF:-1 tvg-id="LEquipe21.fr" tvg-name="FR | LEquipe HD" tvg-logo="https://tvmio.gleeze.com/logos/sports/lequipe.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/lequipe.png" tvg-back="https://www.lequipe.fr/_medias/img-photo-jpg/benterki-messaoud-a-mounic-l-equipe/1500000001809824/0:0,1994:1329-828-552-75/8ebfd.jpg" group-title="FR | Sports",FR | LEquipe HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116536 +#EXTINF:-1 tvg-id="LEquipe21.fr" tvg-name="FR | LEquipe SD" tvg-logo="https://tvmio.gleeze.com/logos/sports/lequipe.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/lequipe.png" tvg-back="https://www.lequipe.fr/_medias/img-photo-jpg/benterki-messaoud-a-mounic-l-equipe/1500000001809824/0:0,1994:1329-828-552-75/8ebfd.jpg" group-title="FR | Sports",FR | LEquipe SD +https://raw.githubusercontent.com/Paradise-91/ParaTV/main/streams/lequipe/la-chaine-l-equipe-en-direct-dm.m3u8 +#EXTINF:-1 tvg-id="LEquipe21.fr" tvg-name="FR | LEquipe HD" tvg-logo="https://tvmio.gleeze.com/logos/sports/lequipe.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/lequipe.png" tvg-back="https://www.lequipe.fr/_medias/img-photo-jpg/benterki-messaoud-a-mounic-l-equipe/1500000001809824/0:0,1994:1329-828-552-75/8ebfd.jpg" group-title="FR | Sports",FR | LEquipe HD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/52719 +#EXTINF:-1 tvg-id="LEquipeLive1.fr" tvg-name="FR | LEquipe Live 1 FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/BVnqRnbq/lequipe-live-1-logo.png" tvg-poster="https://i.ibb.co/1J8MVP1V/lequipe-live-1-poster.png" tvg-back="https://www.lequipe.fr/_medias/img-photo-jpg/benterki-messaoud-a-mounic-l-equipe/1500000001809824/0:0,1994:1329-828-552-75/8ebfd.jpg" group-title="FR | Sports",FR | LEquipe Live 1 FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/56911 +#EXTINF:-1 tvg-id="LEquipeLive1.fr" tvg-name="FR | LEquipe Live 1 SD" tvg-chno="0" tvg-logo="https://i.ibb.co/BVnqRnbq/lequipe-live-1-logo.png" tvg-poster="https://i.ibb.co/1J8MVP1V/lequipe-live-1-poster.png" tvg-back="https://www.lequipe.fr/_medias/img-photo-jpg/benterki-messaoud-a-mounic-l-equipe/1500000001809824/0:0,1994:1329-828-552-75/8ebfd.jpg" group-title="FR | Sports",FR | LEquipe Live 1 SD +https://live2.eu-north-1b.cf.dmcdn.net/sec2(tv4fF1WdXufLMYRr9dFKeGX-daJgJR2TMz-RZOAq_XpQekpV-n0g5qvrFB17bQd-Fd-8-RLK-yJFZ2y93sfDU2S_8-apS-6gQzBktsR0SNEjQRks5tsOjWkO1xxQSYJd)/cloud/3/x6hczsw/d/live-480@60.m3u8 +#EXTINF:-1 tvg-id="LEquipeLive2.fr" tvg-name="FR | LEquipe Live 2 FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/qMT3KVpX/lequipe-live-2-logo.png" tvg-poster="https://i.ibb.co/cSzxfNZS/lequipe-live-2-poster.png" tvg-back="https://www.lequipe.fr/_medias/img-photo-jpg/benterki-messaoud-a-mounic-l-equipe/1500000001809824/0:0,1994:1329-828-552-75/8ebfd.jpg" group-title="FR | Sports",FR | LEquipe Live 2 FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/56910 +#EXTINF:-1 tvg-id="LEquipeLive2.fr" tvg-name="FR | LEquipe Live 2 HD" tvg-chno="0" tvg-logo="https://i.ibb.co/qMT3KVpX/lequipe-live-2-logo.png" tvg-poster="https://i.ibb.co/cSzxfNZS/lequipe-live-2-poster.png" tvg-back="https://www.lequipe.fr/_medias/img-photo-jpg/benterki-messaoud-a-mounic-l-equipe/1500000001809824/0:0,1994:1329-828-552-75/8ebfd.jpg" group-title="FR | Sports",FR | LEquipe Live 2 HD +https://d2sfyr4abdyf7s.cloudfront.net/v1/master/3722c60a815c199d9c0ef36c5b73da68a62b09d1/cc-d5yhiqv8rl7x3/Lequipe2_FR.m3u8 +#EXTINF:-1 tvg-id="Eurosport1.fr" tvg-name="FR | EuroSport 1 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/eurosport_1.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/eurosport_1.png" tvg-back="https://i.ibb.co/CKVmssW3/eurosport-2011-tv-idents-g002-gigapixel-low-resolution-v2-1080h-faceai-v2.png" group-title="FR | Sports",FR | EuroSport 1 FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/51644 +#EXTINF:-1 tvg-id="Eurosport1.fr" tvg-name="FR | EuroSport 1 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/eurosport_1.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/eurosport_1.png" tvg-back="https://i.ibb.co/CKVmssW3/eurosport-2011-tv-idents-g002-gigapixel-low-resolution-v2-1080h-faceai-v2.png" group-title="FR | Sports",FR | EuroSport 1 HD +https://live.streamgatos.top/hls/655/stream.m3u8 +#EXTINF:-1 tvg-id="Eurosport1.fr" tvg-name="FR | EuroSport 1 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/eurosport_1.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/eurosport_1.png" tvg-back="https://i.ibb.co/CKVmssW3/eurosport-2011-tv-idents-g002-gigapixel-low-resolution-v2-1080h-faceai-v2.png" group-title="FR | Sports",FR | EuroSport 1 HD +http://151.80.18.177:86/Eurosport_HD/index.m3u8 +#EXTINF:-1 tvg-id="Eurosport2.fr" tvg-name="FR | EuroSport 2 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/eurosport_2.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/eurosport_2.png" tvg-back="https://i.ibb.co/CKVmssW3/eurosport-2011-tv-idents-g002-gigapixel-low-resolution-v2-1080h-faceai-v2.png" group-title="FR | Sports",FR | EuroSport 2 FHD +http://151.80.18.177:86/Eurosport_2_HD/index.m3u8 +#EXTINF:-1 tvg-id="Eurosport2.fr" tvg-name="FR | EuroSport 2 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/eurosport_2.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/eurosport_2.png" tvg-back="https://i.ibb.co/CKVmssW3/eurosport-2011-tv-idents-g002-gigapixel-low-resolution-v2-1080h-faceai-v2.png" group-title="FR | Sports",FR | EuroSport 2 FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116568 +#EXTINF:-1 tvg-id="Eurosport2.fr" tvg-name="FR | EuroSport 2 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/eurosport_2.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/eurosport_2.png" tvg-back="https://i.ibb.co/CKVmssW3/eurosport-2011-tv-idents-g002-gigapixel-low-resolution-v2-1080h-faceai-v2.png" group-title="FR | Sports",FR | EuroSport 2 FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/51645 +#EXTINF:-1 tvg-id="CanalPlusFoot.fr" tvg-name="FR | Canal+ Foot FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/canal_foot.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_foot.png" tvg-back="https://i.ibb.co/chvb9V72/canalplusfoot2-topaz-removedddd-upscale-2-6x.jpg" group-title="FR | Sports",FR | Canal+ Foot FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/53295 +#EXTINF:-1 tvg-id="CanalPlusFoot.fr" tvg-name="FR | Canal+ Foot HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/canal_foot.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_foot.png" tvg-back="https://i.ibb.co/chvb9V72/canalplusfoot2-topaz-removedddd-upscale-2-6x.jpg" group-title="FR | Sports",FR | Canal+ Foot HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116413 +#EXTINF:-1 tvg-id="CanalPlusPremierLeague.fr" tvg-name="FR | Canal+ Premier League FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/ccm78DXD/canal-league-logo.png" tvg-poster="https://i.ibb.co/99JVdhBv/canal-premier-league-poster.png" tvg-back="https://i.ibb.co/9kzqvsfD/canalpremierleague-topaz-removedddd-remove.png" group-title="FR | Sports",FR | Canal+ Premier League FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/53531 +#EXTINF:-1 tvg-id="CanalPlusSport360.fr" tvg-name="FR | Canal+ Sport 360 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/canal_sport_360.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_sport_360.png" tvg-back="https://i.ibb.co/yF1ChNjz/canal360sport-topaz-removedddd-remove-sharpen-denoise.jpg" group-title="FR | Sports",FR | Canal+ Sport 360 HD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/54657 +#EXTINF:-1 tvg-id="CanalPlusSport360.fr" tvg-name="FR | Canal+ Sport 360 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/canal_sport_360.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_sport_360.png" tvg-back="https://i.ibb.co/yF1ChNjz/canal360sport-topaz-removedddd-remove-sharpen-denoise.jpg" group-title="FR | Sports",FR | Canal+ Sport 360 HD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/54657 +#EXTINF:-1 tvg-id="CanalPlusSport.fr" tvg-name="FR | Canal+ Sport FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/canal_sport.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_sport.png" tvg-back="https://wallpapers.com/images/hd/best-sports-9mo6eiyv8hxj5jln.jpg" group-title="FR | Sports",FR | Canal+ Sport HD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/49208 +#EXTINF:-1 tvg-id="CanalPlusSport.fr" tvg-name="FR | Canal+ Sport HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/canal_sport.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_sport.png" tvg-back="https://wallpapers.com/images/hd/best-sports-9mo6eiyv8hxj5jln.jpg" group-title="FR | Sports",FR | Canal+ Sport HD +http://151.80.18.177:86/Canal+_sport_HD/index.m3u8 +#EXTINF:-1 tvg-id="CanalPlusLive1.fr" tvg-name="FR | Canal+ Live 1 FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/93q3ZB9f/canal-live-1-logo.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_live_1.png" tvg-back="https://i.ibb.co/v6zYX51n/canalpluslive-topaz-removedddd-remove.jpg" group-title="FR | Sports",FR | Canal+ Live 1 FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/56553 +#EXTINF:-1 tvg-id="CanalPlusLive1.fr" tvg-name="FR | Canal+ Live 1 HD" tvg-chno="0" tvg-logo="https://i.ibb.co/93q3ZB9f/canal-live-1-logo.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_live_1.png" tvg-back="https://i.ibb.co/v6zYX51n/canalpluslive-topaz-removedddd-remove.jpg" group-title="FR | Sports",FR | Canal+ Live 1 HD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:84:0F:1B&stream=1854094&extension=ts +#EXTINF:-1 tvg-id="CanalPlusLive2.fr" tvg-name="FR | Canal+ Live 2 FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/8gbKgsmW/canal-live-2-logo.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_live_2.png" tvg-back="https://i.ibb.co/nNkCP2rJ/canalpluslive-topaz-removedddd-remove.jpg" group-title="FR | Sports",FR | Canal+ Live 2 FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/56554 +#EXTINF:-1 tvg-id="CanalPlusLive2.fr" tvg-name="FR | Canal+ Live 2 FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/8gbKgsmW/canal-live-2-logo.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_live_2.png" tvg-back="https://i.ibb.co/nNkCP2rJ/canalpluslive-topaz-removedddd-remove.jpg" group-title="FR | Sports",FR | Canal+ Live 2 FHD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:84:0F:1B&stream=1854096&extension=ts +#EXTINF:-1 tvg-id="CanalPlusLive3.fr" tvg-name="FR | Canal+ Live 3 FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/cSSSpTh9/canal-live-3-logo.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_live_3.png" tvg-back="https://i.ibb.co/nNkCP2rJ/canalpluslive-topaz-removedddd-remove.jpg" group-title="FR | Sports",FR | Canal+ Live 3 FHD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:84:0F:1B&stream=1854098&extension=ts +#EXTINF:-1 tvg-id="CanalPlusLive3.fr" tvg-name="FR | Canal+ Live 3 FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/cSSSpTh9/canal-live-3-logo.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_live_3.png" tvg-back="https://i.ibb.co/nNkCP2rJ/canalpluslive-topaz-removedddd-remove.jpg" group-title="FR | Sports",FR | Canal+ Live 3 FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/56555 +#EXTINF:-1 tvg-id="CanalPlusLive4.fr" tvg-name="FR | Canal+ Live 4 FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/XkfwbdFN/canal-live-4-logo.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_live_4.png" tvg-back="https://i.ibb.co/nNkCP2rJ/canalpluslive-topaz-removedddd-remove.jpg" group-title="FR | Sports",FR | Canal+ Live 4 FHD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:84:0F:1B&stream=1854100&extension=ts +#EXTINF:-1 tvg-id="CanalPlusLive4.fr" tvg-name="FR | Canal+ Live 4 FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/XkfwbdFN/canal-live-4-logo.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_live_4.png" tvg-back="https://i.ibb.co/nNkCP2rJ/canalpluslive-topaz-removedddd-remove.jpg" group-title="FR | Sports",FR | Canal+ Live 4 FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/56556 +#EXTINF:-1 tvg-id="CanalPlusLive5.fr" tvg-name="FR | Canal+ Live 5 FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/hFHxZhgC/canal-live-5-logo.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_live_5.png" tvg-back="https://i.ibb.co/nNkCP2rJ/canalpluslive-topaz-removedddd-remove.jpg" group-title="FR | Sports",FR | Canal+ Live 5 FHD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:84:0F:1B&stream=1854102&extension=ts +#EXTINF:-1 tvg-id="CanalPlusLive5.fr" tvg-name="FR | Canal+ Live 5 HD" tvg-chno="0" tvg-logo="https://i.ibb.co/hFHxZhgC/canal-live-5-logo.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_live_5.png" tvg-back="https://i.ibb.co/nNkCP2rJ/canalpluslive-topaz-removedddd-remove.jpg" group-title="FR | Sports",FR | Canal+ Live 5 HD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/56557 +#EXTINF:-1 tvg-id="CanalPlusLive6.fr" tvg-name="FR | Canal+ Live 6 FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/PsHpRnQT/canal-live-6-logo.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_live_6.png" tvg-back="https://i.ibb.co/nNkCP2rJ/canalpluslive-topaz-removedddd-remove.jpg" group-title="FR | Sports",FR | Canal+ Live 6 FHD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:84:0F:1B&stream=1854104&extension=ts +#EXTINF:-1 tvg-id="CanalPlusLive6.fr" tvg-name="FR | Canal+ Live 6 HD" tvg-chno="0" tvg-logo="https://i.ibb.co/PsHpRnQT/canal-live-6-logo.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_live_6.png" tvg-back="https://i.ibb.co/nNkCP2rJ/canalpluslive-topaz-removedddd-remove.jpg" group-title="FR | Sports",FR | Canal+ Live 6 HD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/56558 +#EXTINF:-1 tvg-id="CanalPlusLive7.fr" tvg-name="FR | Canal+ Live 7 FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/VpgfwPmK/canal-live-7-logo.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_live_7.png" tvg-back="https://i.ibb.co/nNkCP2rJ/canalpluslive-topaz-removedddd-remove.jpg" group-title="FR | Sports",FR | Canal+ Live 7 FHD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:84:0F:1B&stream=1854106&extension=ts +#EXTINF:-1 tvg-id="CanalPlusLive7.fr" tvg-name="FR | Canal+ Live 7 HD" tvg-chno="0" tvg-logo="https://i.ibb.co/VpgfwPmK/canal-live-7-logo.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_live_7.png" tvg-back="https://i.ibb.co/nNkCP2rJ/canalpluslive-topaz-removedddd-remove.jpg" group-title="FR | Sports",FR | Canal+ Live 7 HD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/56559 +#EXTINF:-1 tvg-id="CanalPlusLive8.fr" tvg-name="FR | Canal+ Live 8 FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/YTPzFb55/canal-live-8-logo.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_live_8.png" tvg-back="https://i.ibb.co/nNkCP2rJ/canalpluslive-topaz-removedddd-remove.jpg" group-title="FR | Sports",FR | Canal+ Live 8 FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/56560 +#EXTINF:-1 tvg-id="CanalPlusLive8.fr" tvg-name="FR | Canal+ Live 8 FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/YTPzFb55/canal-live-8-logo.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_live_8.png" tvg-back="https://i.ibb.co/nNkCP2rJ/canalpluslive-topaz-removedddd-remove.jpg" group-title="FR | Sports",FR | Canal+ Live 8 FHD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:84:0F:1B&stream=1854108&extension=ts +#EXTINF:-1 tvg-id="CanalPlusLive9.fr" tvg-name="FR | Canal+ Live 9 FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/Sw2ZHSBb/canal-live-9-logo.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_live_9.png" tvg-back="https://i.ibb.co/nNkCP2rJ/canalpluslive-topaz-removedddd-remove.jpg" group-title="FR | Sports",FR | Canal+ Live 9 FHD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:84:0F:1B&stream=1854110&extension=ts +#EXTINF:-1 tvg-id="CanalPlusLive9.fr" tvg-name="FR | Canal+ Live 9 HD" tvg-chno="0" tvg-logo="https://i.ibb.co/Sw2ZHSBb/canal-live-9-logo.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/canal_live_9.png" tvg-back="https://i.ibb.co/nNkCP2rJ/canalpluslive-topaz-removedddd-remove.jpg" group-title="FR | Sports",FR | Canal+ Live 9 HD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/56561 +#EXTINF:-1 tvg-id="Equidia.fr" tvg-name="FR | Equidia Live FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/equidia.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/equidia.png" tvg-back="https://www.digitalstudioindia.com/cloud/2022/09/07/Globecast-Equidia-release-image.jpg" group-title="FR | Sports",FR | Equidia Live FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/49748 +#EXTINF:-1 tvg-id="ABMoteurs.fr" tvg-name="FR | Auto Moto FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/automoto.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/automoto.png" tvg-back="https://images.hdqwalls.com/wallpapers/lamborghini-and-bike-image.jpg" group-title="FR | Sports",FR | Auto Moto FHD +https://live.streamgatos.top/hls/7321/stream.m3u8 +#EXTINF:-1 tvg-id="GolfPlus.fr" tvg-name="FR | Golf+ HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/golfplus.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/golfplus.png" tvg-back="https://miramarpaintcenter.com/cdn/shop/files/GolfWallpaperCourse0_2048x.jpg?v=1717609486" group-title="FR | Sports",FR | Golf+ HD +http://151.80.18.177:86/GOLF+_HD/index.m3u8 +#EXTINF:-1 tvg-id="Africa24Sport.fr" tvg-name="FR | Africa 24 Sport FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/RGKdhgkh/africa-sport-logo.png" tvg-poster="https://i.ibb.co/xKVwgWLK/africa-24-poster.png" tvg-back="https://cdn.wallpapersafari.com/86/39/bXsrFP.jpg" group-title="FR | Sports",FR | Africa 24 Sport FHD +https://africa24.vedge.infomaniak.com/livecast/ik:africa24sport/manifest.m3u8 +#EXTINF:-1 tvg-id="PlanetePlus.fr" tvg-name="FR | Planete+ HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/planete.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/planete.png" tvg-back="https://i.ibb.co/gZmdBFNv/planeteplus-gigapixel-high-fidelity-v2-1920w.png" group-title="FR | Documentaires",FR | Planete+ HD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/4494 +#EXTINF:-1 tvg-id="PlanetePlus.fr" tvg-name="FR | Planete+ FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/planete.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/planete.png" tvg-back="https://i.ibb.co/gZmdBFNv/planeteplus-gigapixel-high-fidelity-v2-1920w.png" group-title="FR | Documentaires",FR | Planete+ FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116100 +#EXTINF:-1 tvg-id="PlanetePlus.fr" tvg-name="FR | Planete+ HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/planete.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/planete.png" tvg-back="https://i.ibb.co/gZmdBFNv/planeteplus-gigapixel-high-fidelity-v2-1920w.png" group-title="FR | Documentaires",FR | Planete+ HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116099 +#EXTINF:-1 tvg-id="PlanetePlus.fr" tvg-name="FR | Planete+ SD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/planete.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/planete.png" tvg-back="https://i.ibb.co/gZmdBFNv/planeteplus-gigapixel-high-fidelity-v2-1920w.png" group-title="FR | Documentaires",FR | Planete+ SD +https://viamotionhsi.netplus.ch/live/eds/planeteplus/browser-HLS8/planeteplus.m3u8 +#EXTINF:-1 tvg-id="PlaneteAction.fr" tvg-name="FR | Planete A&E FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/planete_ae.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/planete_ae.png" tvg-back="https://i.ibb.co/V09RXjzf/planete-a-et-e-gigapixel-standard-v2-2x-faceai-v2.png" group-title="FR | Documentaires",FR | Planete A&E FHD +https://live.streamgatos.top/hls/319/stream.m3u8 +#EXTINF:-1 tvg-id="PlaneteAction.fr" tvg-name="FR | Planete A&E FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/planete_ae.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/planete_ae.png" tvg-back="https://i.ibb.co/V09RXjzf/planete-a-et-e-gigapixel-standard-v2-2x-faceai-v2.png" group-title="FR | Documentaires",FR | Planete A&E FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/53300 +#EXTINF:-1 tvg-id="PLANTEJustice.fr" tvg-name="FR | Planete+ CI FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/planete_crime.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/planete_crime.png" tvg-back="https://media.ouest-france.fr/v1/pictures/b2941d97430ddf6368b0fae45a4b81cd-les-crimes-qui-ont-change-le-monde-documentaire-justice-programme-tv" group-title="FR | Documentaires",FR | Planete+ CI FHD +https://live.streamgatos.top/hls/143711/stream.m3u8 +#EXTINF:-1 tvg-id="PLANTEJustice.fr" tvg-name="FR | Planete+ CI HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/planete_crime.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/planete_crime.png" tvg-back="https://media.ouest-france.fr/v1/pictures/b2941d97430ddf6368b0fae45a4b81cd-les-crimes-qui-ont-change-le-monde-documentaire-justice-programme-tv" group-title="FR | Documentaires",FR | Planete+ CI HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116104 +#EXTINF:-1 tvg-id="PLANTEJustice.fr" tvg-name="FR | Planete+ CI FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/planete_crime.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/planete_crime.png" tvg-back="https://media.ouest-france.fr/v1/pictures/b2941d97430ddf6368b0fae45a4b81cd-les-crimes-qui-ont-change-le-monde-documentaire-justice-programme-tv" group-title="FR | Documentaires",FR | Planete+ CI FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116103 +#EXTINF:-1 tvg-id="PLANTEJustice.fr" tvg-name="FR | Planete+ CI FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/planete_crime.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/planete_crime.png" tvg-back="https://media.ouest-france.fr/v1/pictures/b2941d97430ddf6368b0fae45a4b81cd-les-crimes-qui-ont-change-le-monde-documentaire-justice-programme-tv" group-title="FR | Documentaires",FR | Planete+ CI FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/50482 +#EXTINF:-1 tvg-id="NationalGeographic.fr" tvg-name="FR | National Geographic FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/nat_geo.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/nat_geo.png" tvg-back="https://lumiere-a.akamaihd.net/v1/images/ng_videobackground_wave_5658d367.jpeg?region=0,0,1927,1084" group-title="FR | Documentaires",FR | National Geographic FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/4502 +#EXTINF:-1 tvg-id="NationalGeographic.fr" tvg-name="FR | National Geographic HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/nat_geo.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/nat_geo.png" tvg-back="https://lumiere-a.akamaihd.net/v1/images/ng_videobackground_wave_5658d367.jpeg?region=0,0,1927,1084" group-title="FR | Documentaires",FR | National Geographic HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116109 +#EXTINF:-1 tvg-id="NationalGeographic.fr" tvg-name="FR | National Geographic HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/nat_geo.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/nat_geo.png" tvg-back="https://lumiere-a.akamaihd.net/v1/images/ng_videobackground_wave_5658d367.jpeg?region=0,0,1927,1084" group-title="FR | Documentaires",FR | National Geographic HD +http://151.80.18.177:86/National_Geo_HD/index.m3u8 +#EXTINF:-1 tvg-id="NatGeoWild.fr" tvg-name="FR | Nat Geo Wild FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/nat_geo_wild.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/nat_geo_wild.png" tvg-back="https://i.ibb.co/wZyzgcCK/nat-geo-wild-topaz-removedddd-upscale-1-5x-remove.png" group-title="FR | Documentaires",FR | Nat Geo Wild FHD +https://live.streamgatos.top/hls/10849/stream.m3u8 +#EXTINF:-1 tvg-id="NatGeoWild.fr" tvg-name="FR | Nat Geo Wild FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/nat_geo_wild.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/nat_geo_wild.png" tvg-back="https://i.ibb.co/wZyzgcCK/nat-geo-wild-topaz-removedddd-upscale-1-5x-remove.png" group-title="FR | Documentaires",FR | Nat Geo Wild FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116111 +#EXTINF:-1 tvg-id="NatGeoWild.fr" tvg-name="FR | Nat Geo Wild FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/nat_geo_wild.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/nat_geo_wild.png" tvg-back="https://i.ibb.co/wZyzgcCK/nat-geo-wild-topaz-removedddd-upscale-1-5x-remove.png" group-title="FR | Documentaires",FR | Nat Geo Wild FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116110 +#EXTINF:-1 tvg-id="NatGeoWild.fr" tvg-name="FR | Nat Geo Wild FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/nat_geo_wild.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/nat_geo_wild.png" tvg-back="https://i.ibb.co/wZyzgcCK/nat-geo-wild-topaz-removedddd-upscale-1-5x-remove.png" group-title="FR | Documentaires",FR | Nat Geo Wild FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/48679 +#EXTINF:-1 tvg-name="FR | BBC Earth FHD" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/bbcearth.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/bbcearth.png" tvg-back="https://ichef.bbci.co.uk/images/ic/1920x1080/p0gktm38.jpg" group-title="FR | Documentaires",FR | BBC Earth +https://amg00793-amg00793c22-samsung-fr-4776.playouts.now.amagi.tv/playlist/amg00793-bbcstudios-bbcearthfrance-samsungfr/playlist.m3u8 +#EXTINF:-1 tvg-id="Animaux.fr" tvg-name="FR | Animaux HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/animaux.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/animaux.png" tvg-back="https://i.ibb.co/Xrw8dncL/animauxtv-topaz-removedddd-upscale-3-1x.jpg" group-title="FR | Documentaires",FR | Animaux HD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/47758 +#EXTINF:-1 tvg-id="Animaux.fr" tvg-name="FR | Animaux SD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/animaux.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/animaux.png" tvg-back="https://i.ibb.co/Xrw8dncL/animauxtv-topaz-removedddd-upscale-3-1x.jpg" group-title="FR | Documentaires",FR | Animaux SD +http://cfd-v4-service-channel-stitcher-use1-1.prd.pluto.tv/stitch/hls/channel/60925a44f0350600075a1fdc/master.m3u8?appName=web&appVersion=unknown&clientTime=0&deviceDNT=0&deviceId=8e05edb2-1f2c-11ef-86d8-5d587df108c6&deviceMake=Chrome&deviceModel=web&deviceType=web&deviceVersion=unknown&includeExtendedEvents=false&serverSideAds=false&sid=754cd30f-6a34-42d3-9e06-63128a8e07e3 +#EXTINF:-1 tvg-id="Animaux.fr" tvg-name="FR | Animaux SD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/animaux.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/animaux.png" tvg-back="https://i.ibb.co/Xrw8dncL/animauxtv-topaz-removedddd-upscale-3-1x.jpg" group-title="FR | Documentaires",FR | Animaux SD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116134 +#EXTINF:-1 tvg-id="Animaux.fr" tvg-name="FR | Animaux FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/animaux.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/animaux.png" tvg-back="https://i.ibb.co/Xrw8dncL/animauxtv-topaz-removedddd-upscale-3-1x.jpg" group-title="FR | Documentaires",FR | Animaux FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116133 +#EXTINF:-1 tvg-id="Animaux.fr" tvg-name="FR | Animaux FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/animaux.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/animaux.png" tvg-back="https://i.ibb.co/Xrw8dncL/animauxtv-topaz-removedddd-upscale-3-1x.jpg" group-title="FR | Documentaires",FR | Animaux FHD +https://live.streamgatos.top/hls/368/stream.m3u8 +#EXTINF:-1 tvg-id="CanalPlusDocs.fr" tvg-name="FR | Canal+ Docs FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/canal_docs.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/canal_docs.png" tvg-back="https://i.ibb.co/whpK2V6d/canalplusdocs-topaz-removedddd-remove-upscale-1-5x.png" group-title="FR | Documentaires",FR | Canal+ Docs FHD +https://live.streamgatos.top/hls/144976/stream.m3u8 +#EXTINF:-1 tvg-id="CanalPlusDocs.fr" tvg-name="FR | Canal+ Docs FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/canal_docs.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/canal_docs.png" tvg-back="https://i.ibb.co/whpK2V6d/canalplusdocs-topaz-removedddd-remove-upscale-1-5x.png" group-title="FR | Documentaires",FR | Canal+ Docs FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116412 +#EXTINF:-1 tvg-id="CanalPlusDocs.fr" tvg-name="FR | Canal+ Docs HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/canal_docs.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/canal_docs.png" tvg-back="https://tvmio.gleeze.com/logos/documentaires/canal_docs.png" group-title="FR | Documentaires",FR | Canal+ Docs HD +http://eagle2024.xyz:80/play/live.php?mac=00:1A:79:84:0F:1B&stream=274705&extension=ts +#EXTINF:-1 tvg-id="ChasseEtPeche.fr" tvg-name="FR | Chasse Et Peche HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/chasse_et_peche.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/chasse_et_peche.png" tvg-back="https://auroreinfo.com/_next/image?url=https%3A%2F%2Fauroreinfo.com%2Fapi%2Farticles%2Ffile%2Fimage-chasse-et-peche-1920x1080.jpg&w=3840&q=75" group-title="FR | Documentaires",FR | Chasse Et Peche HD +https://live.streamgatos.top/hls/356/stream.m3u8 +#EXTINF:-1 tvg-id="ChasseEtPeche.fr" tvg-name="FR | Chasse Et Peche FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/chasse_et_peche.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/chasse_et_peche.png" tvg-back="https://auroreinfo.com/_next/image?url=https%3A%2F%2Fauroreinfo.com%2Fapi%2Farticles%2Ffile%2Fimage-chasse-et-peche-1920x1080.jpg&w=3840&q=75" group-title="FR | Documentaires",FR | Chasse Et Peche FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116136 +#EXTINF:-1 tvg-id="CrimeDistrict.fr" tvg-name="FR | Crime District HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/crime_district.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/crime_district.png" tvg-back="https://inout.fr/wp-content/uploads/2020/10/AB_CRIME_DISTRICT_15.jpg" group-title="FR | Documentaires",FR | Crime District HD +https://live.streamgatos.top/hls/8505/stream.m3u8 +#EXTINF:-1 tvg-id="DiscoveryChannel.fr" tvg-name="FR | Discovery Channel HD" tvg-chno="0" tvg-logo="https://i.ibb.co/8Lz75rBv/discovery-channel-logo.png" tvg-poster="https://i.ibb.co/jP6yJSXn/discovery-channel-poster.png" tvg-back="https://cdn.wallpapersafari.com/60/58/7muxZe.jpg" group-title="FR | Documentaires",FR | Discovery Channel HD +http://151.80.18.177:86/Discovery_HD/index.m3u8 +#EXTINF:-1 tvg-id="DiscoveryInvestigation.fr" tvg-name="FR | Discovery ID FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/investigation.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/investigation.png" tvg-back="https://i.ibb.co/My8GpF6Y/investigationdiscovery2-topaz-removedddd-upscale-2-3x.jpg" group-title="FR | Documentaires",FR | Discovery ID FHD +https://live.streamgatos.top/hls/184485/stream.m3u8 +#EXTINF:-1 tvg-id="DiscoveryInvestigation.fr" tvg-name="FR | Discovery ID FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/investigation.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/investigation.png" tvg-back="https://i.ibb.co/My8GpF6Y/investigationdiscovery2-topaz-removedddd-upscale-2-3x.jpg" group-title="FR | Documentaires",FR | Discovery ID FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116126 +#EXTINF:-1 tvg-id="DiscoveryInvestigation.fr" tvg-name="FR | Discovery ID HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/investigation.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/investigation.png" tvg-back="https://i.ibb.co/My8GpF6Y/investigationdiscovery2-topaz-removedddd-upscale-2-3x.jpg" group-title="FR | Documentaires",FR | Discovery ID HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116123 +#EXTINF:-1 tvg-id="DiscoveryScience.fr" tvg-name="FR | Discovery Science HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/science_channel.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/science_channel.png" tvg-back="https://i.ibb.co/jZhtw8t5/science-channel.png" group-title="FR | Documentaires",FR | Discovery Science HD +https://live.streamgatos.top/hls/349/stream.m3u8 +#EXTINF:-1 tvg-id="DiscoveryScience.fr" tvg-name="FR | Discovery Science HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/science_channel.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/science_channel.png" tvg-back="https://i.ibb.co/jZhtw8t5/science-channel.png" group-title="FR | Documentaires",FR | Discovery Science HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116127 +#EXTINF:-1 tvg-id="DiscoveryScience.fr" tvg-name="FR | Discovery Science HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/science_channel.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/science_channel.png" tvg-back="https://i.ibb.co/jZhtw8t5/science-channel.png" group-title="FR | Documentaires",FR | Discovery Science HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116121 +#EXTINF:-1 tvg-id="Histoire.fr" tvg-name="FR | Histoire HD" tvg-chno="0" tvg-logo="https://i.ibb.co/KpQMFndZ/histoire-logo.png" tvg-poster="https://i.ibb.co/d4ZdtJZ4/histoire-poster.png" tvg-back="https://histoire.fr/sites/default/files//styles/image_carrousel/public/2025-12/CARR%20SOUS%20LA%20TERRE.png?itok=gWhS8USh" group-title="FR | Documentaires",FR | Histoire HD +http://151.80.18.177:86/Histoire/index.m3u8 +#EXTINF:-1 tvg-id="Histoire.fr" tvg-name="FR | Histoire SD" tvg-chno="0" tvg-logo="https://i.ibb.co/KpQMFndZ/histoire-logo.png" tvg-poster="https://i.ibb.co/d4ZdtJZ4/histoire-poster.png" tvg-back="https://histoire.fr/sites/default/files//styles/image_carrousel/public/2025-12/CARR%20SOUS%20LA%20TERRE.png?itok=gWhS8USh" group-title="FR | Documentaires",FR | Histoire SD +http://cfd-v4-service-channel-stitcher-use1-1.prd.pluto.tv/stitch/hls/channel/611e771e2f5f180007002224/master.m3u8?appName=web&appVersion=unknown&clientTime=0&deviceDNT=0&deviceId=8e063bd3-1f2c-11ef-86d8-5d587df108c6&deviceMake=Chrome&deviceModel=web&deviceType=web&deviceVersion=unknown&includeExtendedEvents=false&serverSideAds=false&sid=a7663e8d-062c-4293-9b93-a2bd07b5cb20 +#EXTINF:-1 tvg-id="Histoire.fr" tvg-name="FR | Histoire HD" tvg-chno="0" tvg-logo="https://i.ibb.co/KpQMFndZ/histoire-logo.png" tvg-poster="https://i.ibb.co/d4ZdtJZ4/histoire-poster.png" tvg-back="https://histoire.fr/sites/default/files//styles/image_carrousel/public/2025-12/CARR%20SOUS%20LA%20TERRE.png?itok=gWhS8USh" group-title="FR | Documentaires",FR | Histoire HD +http://sewv654wfcsdwfi87fwvgbngh.siauliairsavlt.pw/iptv/VEXVELA6Z7PXH6/17041/index.m3u8 +#EXTINF:-1 tvg-id="ScienceEtVieTV.fr" tvg-name="FR | Sciences & Vie TV FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/science_et_vie.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/science_et_vie.png" tvg-back="https://i.ibb.co/3mB07wh2/sciencevie-topaz-removedddd-upscale-2-4x-remove.png" group-title="FR | Documentaires",FR | Sciences & Vie TV FHD +https://live.streamgatos.top/hls/317/stream.m3u8 +#EXTINF:-1 tvg-id="ScienceEtVieTV.fr" tvg-name="FR | Sciences & Vie TV SD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/science_et_vie.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/science_et_vie.png" tvg-back="https://i.ibb.co/3mB07wh2/sciencevie-topaz-removedddd-upscale-2-4x-remove.png" group-title="FR | Documentaires",FR | Sciences & Vie TV SD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116119 +#EXTINF:-1 tvg-id="ScienceEtVieTV.fr" tvg-name="FR | Sciences & Vie TV FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/science_et_vie.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/science_et_vie.png" tvg-back="https://i.ibb.co/3mB07wh2/sciencevie-topaz-removedddd-upscale-2-4x-remove.png" group-title="FR | Documentaires",FR | Sciences & Vie TV FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116120 +#EXTINF:-1 tvg-id="ScienceEtVieTV.fr" tvg-name="FR | Sciences & Vie TV FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/science_et_vie.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/science_et_vie.png" tvg-back="https://i.ibb.co/3mB07wh2/sciencevie-topaz-removedddd-upscale-2-4x-remove.png" group-title="FR | Documentaires",FR | Sciences & Vie TV FHD +http://sewv654wfcsdwfi87fwvgbngh.siauliairsavlt.pw/iptv/VEXVELA6Z7PXH6/15192/index.m3u8 +#EXTINF:-1 tvg-id="TouteHistoire.fr" tvg-name="FR | Toute L Histoire FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/toute_lhistoire.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/toute_lhistoire.png" tvg-back="https://media.ouest-france.fr/v1/pictures/92393deb8360132bc99284b581dc49c3-toute-l-histoire-en-6-minutes-documentaire-histoire-programme-tv" group-title="FR | Documentaires",FR | Toute L Histoire FHD +https://live.streamgatos.top/hls/336/stream.m3u8 +#EXTINF:-1 tvg-id="TouteHistoire.fr" tvg-name="FR | Toute L Histoire HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/toute_lhistoire.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/toute_lhistoire.png" tvg-back="https://media.ouest-france.fr/v1/pictures/92393deb8360132bc99284b581dc49c3-toute-l-histoire-en-6-minutes-documentaire-histoire-programme-tv" group-title="FR | Documentaires",FR | Toute L Histoire HD +http://sewv654wfcsdwfi87fwvgbngh.siauliairsavlt.pw/iptv/VEXVELA6Z7PXH6/17040/index.m3u8 +#EXTINF:-1 tvg-id="UshuaiaTV.fr" tvg-name="FR | Ushuaia HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/ushuaia.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/ushuaia.png" tvg-back="https://i.ibb.co/G3PzVB9M/ushuaia-4079989-1280-topaz-removedddd-upscale-1-5x.jpg" group-title="FR | Documentaires",FR | Ushuaia HD +https://live.streamgatos.top/hls/307/stream.m3u8 +#EXTINF:-1 tvg-id="UshuaiaTV.fr" tvg-name="FR | Ushuaia FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/ushuaia.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/ushuaia.png" tvg-back="https://i.ibb.co/G3PzVB9M/ushuaia-4079989-1280-topaz-removedddd-upscale-1-5x.jpg" group-title="FR | Documentaires",FR | Ushuaia FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116113 +#EXTINF:-1 tvg-id="UshuaiaTV.fr" tvg-name="FR | Ushuaia FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/documentaires/ushuaia.png" tvg-poster="https://tvmio.gleeze.com/poster/documentaire/ushuaia.png" tvg-back="https://i.ibb.co/G3PzVB9M/ushuaia-4079989-1280-topaz-removedddd-upscale-1-5x.jpg" group-title="FR | Documentaires",FR | Ushuaia FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116112 +#EXTINF:-1 tvg-id="Syfy.fr" tvg-name="FR | SyFy FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/syfy.png" tvg-poster="https://tvmio.gleeze.com/poster/films/syfy.png" tvg-back="https://getwallpapers.com/wallpaper/full/c/f/8/1492766-top-syfy-desktop-wallpaper-1920x1080-for-android-50.jpg" group-title="FR | Films",FR | SyFy FHD +https://live.streamgatos.top/hls/25811/stream.m3u8 +#EXTINF:-1 tvg-id="Syfy.fr" tvg-name="FR | SyFy FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/syfy.png" tvg-poster="https://tvmio.gleeze.com/poster/films/syfy.png" tvg-back="https://getwallpapers.com/wallpaper/full/c/f/8/1492766-top-syfy-desktop-wallpaper-1920x1080-for-android-50.jpg" group-title="FR | Films",FR | SyFy FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/106 +#EXTINF:-1 tvg-id="Action.fr" tvg-name="FR | Action FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/nTRgcB0/action-logo.png" tvg-poster="https://i.ibb.co/r2LWfkTW/action-poster.png" tvg-back="https://wallpapercave.com/wp/wp3285535.jpg" group-title="FR | Films",FR | Action FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/4555 +#EXTINF:-1 tvg-id="Action.fr" tvg-name="FR | Action HD" tvg-chno="0" tvg-logo="https://i.ibb.co/nTRgcB0/action-logo.png" tvg-poster="https://i.ibb.co/r2LWfkTW/action-poster.png" tvg-back="https://wallpapercave.com/wp/wp3285535.jpg" group-title="FR | Films",FR | Action HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116425 +#EXTINF:-1 tvg-id="Action.fr" tvg-name="FR | Action SD" tvg-chno="0" tvg-logo="https://i.ibb.co/nTRgcB0/action-logo.png" tvg-poster="https://i.ibb.co/r2LWfkTW/action-poster.png" tvg-back="https://wallpapercave.com/wp/wp3285535.jpg" group-title="FR | Films",FR | Action SD +http://cfd-v4-service-channel-stitcher-use1-1.prd.pluto.tv/stitch/hls/channel/5f8ed1ff5c39700007e2204a/master.m3u8?appName=web&appVersion=unknown&clientTime=0&deviceDNT=0&deviceId=8e055171-1f2c-11ef-86d8-5d587df108c6&deviceMake=Chrome&deviceModel=web&deviceType=web&deviceVersion=unknown&includeExtendedEvents=false&serverSideAds=false&sid=c3b67254-4628-4f0e-8164-5a50e8969a42 +#EXTINF:-1 tvg-id="CanalPlusCinema.ch" tvg-name="FR | Canal+ Cinema FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/canal_cinema.png" tvg-poster="https://tvmio.gleeze.com/poster/films/canal_cinema.png" tvg-back="https://i.ibb.co/G3t7DsRc/canal-cinema-topaz-removedddd-remove-sharpen-denoise.png" group-title="FR | Films",FR | Canal+ Cinema FHD +http://151.80.18.177:86/Canal+_cinema_HD/index.m3u8 +#EXTINF:-1 tvg-id="CanalPlusCinema.ch" tvg-name="FR | Canal+ Cinema FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/canal_cinema.png" tvg-poster="https://tvmio.gleeze.com/poster/films/canal_cinema.png" tvg-back="https://i.ibb.co/G3t7DsRc/canal-cinema-topaz-removedddd-remove-sharpen-denoise.png" group-title="FR | Films",FR | Canal+ Cinema FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116411 +#EXTINF:-1 tvg-id="CanalPlusCinema.ch" tvg-name="FR | Canal+ Cinema HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/canal_cinema.png" tvg-poster="https://tvmio.gleeze.com/poster/films/canal_cinema.png" tvg-back="https://i.ibb.co/G3t7DsRc/canal-cinema-topaz-removedddd-remove-sharpen-denoise.png" group-title="FR | Films",FR | Canal+ Cinema HD +http://sewv654wfcsdwfi87fwvgbngh.siauliairsavlt.pw/iptv/VEXVELA6Z7PXH6/6004/index.m3u8 +#EXTINF:-1 tvg-id="CanalPlusCinema.ch" tvg-name="FR | Canal+ Cinema HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/canal_cinema.png" tvg-poster="https://tvmio.gleeze.com/poster/films/canal_cinema.png" tvg-back="https://i.ibb.co/G3t7DsRc/canal-cinema-topaz-removedddd-remove-sharpen-denoise.png" group-title="FR | Films",FR | Canal+ Cinema HD +https://live.streamgatos.top/hls/684/stream.m3u8 +#EXTINF:-1 tvg-id="CanalPlusGrandEcran.fr" tvg-name="FR | Canal+ Grand Ecran FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/canal_gd_ecran.png" tvg-poster="https://tvmio.gleeze.com/poster/films/canal_gd_ecran.png" tvg-back="https://i.ibb.co/Qvg2tGDV/Canal-Grand-Ecran-topaz-removedddd-remove-upscale-1-4x.png" group-title="FR | Films",FR | Canal+ Grand Ecran FHD +https://live.streamgatos.top/hls/90087/stream.m3u8 +#EXTINF:-1 tvg-id="CanalPlusGrandEcran.fr" tvg-name="FR | Canal+ Grand Ecran FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/canal_gd_ecran.png" tvg-poster="https://tvmio.gleeze.com/poster/films/canal_gd_ecran.png" tvg-back="https://i.ibb.co/Qvg2tGDV/Canal-Grand-Ecran-topaz-removedddd-remove-upscale-1-4x.png" group-title="FR | Films",FR | Canal+ Grand Ecran FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116414 +#EXTINF:-1 tvg-id="CanalPlusGrandEcran.fr" tvg-name="FR | Canal+ Grand Ecran HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/canal_gd_ecran.png" tvg-poster="https://tvmio.gleeze.com/poster/films/canal_gd_ecran.png" tvg-back="https://i.ibb.co/Qvg2tGDV/Canal-Grand-Ecran-topaz-removedddd-remove-upscale-1-4x.png" group-title="FR | Films",FR | Canal+ Grand Ecran HD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/54508 +#EXTINF:-1 tvg-id="CinePlusPremier.fr" tvg-name="FR | Cine+ Premier FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/cineplus_premier.png" tvg-poster="https://tvmio.gleeze.com/poster/films/cineplus_premier.png" tvg-back="https://i.ibb.co/LzfV2ySy/cinepluspremier-jpubf-2014-topaz-removedddd-remove.jpg" group-title="FR | Films",FR | Cine+ Premier FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/53288 +#EXTINF:-1 tvg-id="CinePlusPremier.fr" tvg-name="FR | Cine+ Premier FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/cineplus_premier.png" tvg-poster="https://tvmio.gleeze.com/poster/films/cineplus_premier.png" tvg-back="https://i.ibb.co/LzfV2ySy/cinepluspremier-jpubf-2014-topaz-removedddd-remove.jpg" group-title="FR | Films",FR | Cine+ Premier FHD +https://live.streamgatos.top/hls/182442/stream.m3u8 +#EXTINF:-1 tvg-id="CinePlusClub.fr" tvg-name="FR | Cine+ Club FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/cine_club.png" tvg-poster="https://tvmio.gleeze.com/poster/films/cine_club.png" tvg-back="https://wallpapercave.com/wp/wp5306675.jpg" group-title="FR | Films",FR | Cine+ Club FHD +https://live.streamgatos.top/hls/8921/stream.m3u8 +#EXTINF:-1 tvg-id="CinePlusEmotion.fr" tvg-name="FR | Cine+ Emotion FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/cine_emotion.png" tvg-poster="https://tvmio.gleeze.com/poster/films/cine_emotion.png" tvg-back="https://i.ibb.co/6J0WRx1t/cineplusemotion-03-07-2024h-cinecourts-topaz-removedddd-remove-sharpen-denoise.jpg" group-title="FR | Films",FR | Cine+ Emotion FHD +https://live.streamgatos.top/hls/354/stream.m3u8 +#EXTINF:-1 tvg-id="CinePlusEmotion.fr" tvg-name="FR | Cine+ Emotion FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/cine_emotion.png" tvg-poster="https://tvmio.gleeze.com/poster/films/cine_emotion.png" tvg-back="https://i.ibb.co/6J0WRx1t/cineplusemotion-03-07-2024h-cinecourts-topaz-removedddd-remove-sharpen-denoise.jpg" group-title="FR | Films",FR | Cine+ Emotion FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/53286 +#EXTINF:-1 tvg-id="CinePlusClassic.fr" tvg-name="FR | Cine+ Classic FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/cine_classic.png" tvg-poster="https://tvmio.gleeze.com/poster/films/cine_classic.png" tvg-back="https://i.ibb.co/1f6KzC0y/cineplusclassic-03-07-2024h-cinecourts-topaz-removedddd-remove-denoise-sharpen.jpg" group-title="FR | Films",FR | Cine+ Classic FHD +https://live.streamgatos.top/hls/689/stream.m3u8 +#EXTINF:-1 tvg-id="CinePlusClassic.fr" tvg-name="FR | Cine+ Classic HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/cine_classic.png" tvg-poster="https://tvmio.gleeze.com/poster/films/cine_classic.png" tvg-back="https://i.ibb.co/1f6KzC0y/cineplusclassic-03-07-2024h-cinecourts-topaz-removedddd-remove-denoise-sharpen.jpg" group-title="FR | Films",FR | Cine+ Classic HD +http://sewv654wfcsdwfi87fwvgbngh.siauliairsavlt.pw/iptv/VEXVELA6Z7PXH6/17039/index.m3u8 +#EXTINF:-1 tvg-id="CinePlusFamiz.fr" tvg-name="FR | Cine+ Famiz FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/cine_family.png" tvg-poster="https://tvmio.gleeze.com/poster/films/cine_family.png" tvg-back="https://i.ibb.co/395JKPw3/cinefamily-03-07-2024h-animation-topaz-removedddd-remove-sharpen-denoise.jpg" group-title="FR | Films",FR | Cine+ Famiz FHD +https://live.streamgatos.top/hls/4905/stream.m3u8 +#EXTINF:-1 tvg-id="CinePlusFamiz.fr" tvg-name="FR | Cine+ Famiz FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/cine_family.png" tvg-poster="https://tvmio.gleeze.com/poster/films/cine_family.png" tvg-back="https://i.ibb.co/395JKPw3/cinefamily-03-07-2024h-animation-topaz-removedddd-remove-sharpen-denoise.jpg" group-title="FR | Films",FR | Cine+ Famiz FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/53356 +#EXTINF:-1 tvg-id="PolarPlus.fr" tvg-name="FR | Polar+ HD" tvg-chno="0" tvg-logo="https://i.ibb.co/21WnHfQL/polar-logo.png" tvg-poster="https://i.ibb.co/848z6Bpf/polar.png" tvg-back="https://static.vecteezy.com/system/resources/thumbnails/013/289/777/original/beautiful-northern-lights-animation-green-lights-aurora-borealis-in-norway-canada-finland-iceland-and-sweden-polar-weather-and-blue-starry-sky-on-a-cold-night-fantastic-motion-background-in-4k-video.jpg" group-title="FR | Films",FR | Polar+ HD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/4548 +#EXTINF:-1 tvg-id="ocsmax.fr" tvg-name="FR | OCS Max HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/ocs_max.png" tvg-poster="https://tvmio.gleeze.com/poster/films/ocs_max.png" tvg-back="https://i.ibb.co/FkWwfQq2/ocs-03-07-2024h-cinecourts-topaz-removedddd-remove.jpg" group-title="FR | Films",FR | OCS Max HD +https://live.streamgatos.top/hls/197152/stream.m3u8 +#EXTINF:-1 tvg-id="ocsmax.fr" tvg-name="FR | OCS Max HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/ocs_max.png" tvg-poster="https://tvmio.gleeze.com/poster/films/ocs_max.png" tvg-back="https://i.ibb.co/FkWwfQq2/ocs-03-07-2024h-cinecourts-topaz-removedddd-remove.jpg" group-title="FR | Films",FR | OCS Max HD +https://live.streamgatos.top/hls/197152/stream.m3u8 +#EXTINF:-1 tvg-id="serieclub.fr" tvg-name="FR | Serie Club FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/serie_club.png" tvg-poster="https://tvmio.gleeze.com/poster/films/serie_club.png" tvg-back="https://i.ibb.co/zHm2KBxV/serieclub-2012-decoupe1-topaz-removedddd-remove-upscale-3x.jpg" group-title="FR | Films",FR | Serie Club FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/105 +#EXTINF:-1 tvg-id="TCM.fr" tvg-name="FR | TCM Cinema FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/0Rt0RrFR/tcm-cinema-logo.png" tvg-poster="https://i.ibb.co/ZzXFh9bT/tcm-cinema-poster.png" tvg-back="https://cdn.wallpapersafari.com/29/24/4Vg92a.jpg" group-title="FR | Films",FR | TCM Cinema FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/4547 +#EXTINF:-1 tvg-id="TCM.fr" tvg-name="FR | TCM Cinema HD" tvg-chno="0" tvg-logo="https://i.ibb.co/0Rt0RrFR/tcm-cinema-logo.png" tvg-poster="https://i.ibb.co/ZzXFh9bT/tcm-cinema-poster.png" tvg-back="https://cdn.wallpapersafari.com/29/24/4Vg92a.jpg" group-title="FR | Films",FR | TCM Cinema HD +https://live.streamgatos.top/hls/6106/stream.m3u8 +#EXTINF:-1 tvg-id="TF1SeriesFilms.fr" tvg-name="FR | TF1 Series Films FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/tf1_serie_film.png" tvg-poster="https://tvmio.gleeze.com/poster/general/tf1_serie_film.png" tvg-back="https://i.ibb.co/W43LBVFQ/tf1-serie-film-topaz-removedddd-upscale-2x-remove.png" group-title="FR | Films",FR | TF1 Series Films FHD +http://176.65.146.138:8047/play/a079/index.m3u8 +#EXTINF:-1 tvg-id="TF1SeriesFilms.fr" tvg-name="FR | TF1 Series Films FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/general/tf1_serie_film.png" tvg-poster="https://tvmio.gleeze.com/poster/general/tf1_serie_film.png" tvg-back="https://i.ibb.co/W43LBVFQ/tf1-serie-film-topaz-removedddd-upscale-2x-remove.png" group-title="FR | Films",FR | TF1 Series Films FHD +http://sewv654wfcsdwfi87fwvgbngh.siauliairsavlt.pw/iptv/VEXVELA6Z7PXH6/15187/index.m3u8 +#EXTINF:-1 tvg-id="TF1SeriesFilms.fr" tvg-name="FR | TF1 Series Films FHD" tvg-logo="https://tvmio.gleeze.com/logos/general/tf1_serie_film.png" tvg-poster="https://tvmio.gleeze.com/poster/general/tf1_serie_film.png" tvg-back="https://i.ibb.co/W43LBVFQ/tf1-serie-film-topaz-removedddd-upscale-2x-remove.png" group-title="FR | Films",FR | TF1 Series Films SD +https://tvradiozap.eu/tools/np-m3u8.php/hd1.m3u8 +#EXTINF:-1 tvg-id="WarnerTV.fr" tvg-name="FR | Warner FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/warner_tv.png" tvg-poster="https://tvmio.gleeze.com/poster/films/warner_tv.png" tvg-back="https://i.ibb.co/Xx1VWnxP/Warner-TV-topaz-removedddd-remove-upscale-1-7x.jpg" group-title="FR | Films",FR | Warner FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/49198 +#EXTINF:-1 tvg-id="WarnerTV.fr" tvg-name="FR | Warner FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/warner_tv.png" tvg-poster="https://tvmio.gleeze.com/poster/films/warner_tv.png" tvg-back="https://i.ibb.co/Xx1VWnxP/Warner-TV-topaz-removedddd-remove-upscale-1-7x.jpg" group-title="FR | Films",FR | Warner FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116433 +#EXTINF:-1 tvg-id="WarnerTV.fr" tvg-name="FR | Warner HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/films/warner_tv.png" tvg-poster="https://tvmio.gleeze.com/poster/films/warner_tv.png" tvg-back="https://i.ibb.co/Xx1VWnxP/Warner-TV-topaz-removedddd-remove-upscale-1-7x.jpg" group-title="FR | Films",FR | Warner HD +https://live.streamgatos.top/hls/8905/stream.m3u8 +#EXTINF:-1 tvg-id="BFMBusiness.fr" tvg-name="FR | BFM Business SD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/bfm_business.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/bfm_business.png" tvg-back="https://ledbox.fr/wp-content/uploads/2020/03/BFM-BUSINESS-Campus-ALTICE-3.jpg" group-title="FR | Informations",FR | BFM Business SD +https://live-cdn-stream-euw1.bfmb.bct.nextradiotv.com/master.m3u8 +#EXTINF:-1 tvg-id="BFMBusiness.fr" tvg-name="FR | BFM Business FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/bfm_business.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/bfm_business.png" tvg-back="https://ledbox.fr/wp-content/uploads/2020/03/BFM-BUSINESS-Campus-ALTICE-3.jpg" group-title="FR | Informations",FR | BFM Business FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116148 +#EXTINF:-1 tvg-id="BFMTV.fr" tvg-name="FR | BFM TV FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/bfm_tv.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/bfm_tv.png" tvg-back="https://media.ouest-france.fr/v1/pictures/MjAyMjExYzdlMjA1ZDQzODMyYWI2NmQyNzZjNmQ3N2QwNTM0MWQ?width=1260&height=708&focuspoint=50%2C25&cropresize=1&client_id=bpeditorial&sign=1f077f198b337c1d2560c1820a01d2cfe25bc72835b8b0599db11d7e8c2d4148" group-title="FR | Informations",FR | BFM TV FHD +https://live.streamgatos.top/hls/103328/stream.m3u8 +#EXTINF:-1 tvg-id="BFMTV.fr" tvg-name="FR | BFM TV HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/bfm_tv.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/bfm_tv.png" tvg-back="https://media.ouest-france.fr/v1/pictures/MjAyMjExYzdlMjA1ZDQzODMyYWI2NmQyNzZjNmQ3N2QwNTM0MWQ?width=1260&height=708&focuspoint=50%2C25&cropresize=1&client_id=bpeditorial&sign=1f077f198b337c1d2560c1820a01d2cfe25bc72835b8b0599db11d7e8c2d4148" group-title="FR | Informations",FR | BFM TV HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116146 +#EXTINF:-1 tvg-id="BFMTV.fr" tvg-name="FR | BFM TV HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/bfm_tv.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/bfm_tv.png" tvg-back="https://media.ouest-france.fr/v1/pictures/MjAyMjExYzdlMjA1ZDQzODMyYWI2NmQyNzZjNmQ3N2QwNTM0MWQ?width=1260&height=708&focuspoint=50%2C25&cropresize=1&client_id=bpeditorial&sign=1f077f198b337c1d2560c1820a01d2cfe25bc72835b8b0599db11d7e8c2d4148" group-title="FR | Informations",FR | BFM TV HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116147 +#EXTINF:-1 tvg-id="BFMTV.fr" tvg-name="FR | BFM TV SD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/bfm_tv.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/bfm_tv.png" tvg-back="https://media.ouest-france.fr/v1/pictures/MjAyMjExYzdlMjA1ZDQzODMyYWI2NmQyNzZjNmQ3N2QwNTM0MWQ?width=1260&height=708&focuspoint=50%2C25&cropresize=1&client_id=bpeditorial&sign=1f077f198b337c1d2560c1820a01d2cfe25bc72835b8b0599db11d7e8c2d4148" group-title="FR | Informations",FR | BFM TV SD +https://live-cdn-stream-euw1.bfmtv.bct.nextradiotv.com/master.m3u8#origine-727=https://tvradiozap.eu +#EXTINF:-1 tvg-id="BFMTV.fr" tvg-name="FR | BFM TV HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/bfm_tv.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/bfm_tv.png" tvg-back="https://media.ouest-france.fr/v1/pictures/MjAyMjExYzdlMjA1ZDQzODMyYWI2NmQyNzZjNmQ3N2QwNTM0MWQ?width=1260&height=708&focuspoint=50%2C25&cropresize=1&client_id=bpeditorial&sign=1f077f198b337c1d2560c1820a01d2cfe25bc72835b8b0599db11d7e8c2d4148" group-title="FR | Informations",FR | BFM TV HD +https://live.streamgatos.top/hls/4908/stream.m3u8 +#EXTINF:-1 tvg-id="BFMTV.fr" tvg-name="FR | BFM TV HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/bfm_tv.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/bfm_tv.png" tvg-back="https://media.ouest-france.fr/v1/pictures/MjAyMjExYzdlMjA1ZDQzODMyYWI2NmQyNzZjNmQ3N2QwNTM0MWQ?width=1260&height=708&focuspoint=50%2C25&cropresize=1&client_id=bpeditorial&sign=1f077f198b337c1d2560c1820a01d2cfe25bc72835b8b0599db11d7e8c2d4148" group-title="FR | Informations",FR | BFM TV HD +https://live.streamgatos.top/hls/7853/stream.m3u8 +#EXTINF:-1 tvg-id="BFMTV.fr" tvg-name="FR | BFM TV SD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/bfm_tv.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/bfm_tv.png" tvg-back="https://media.ouest-france.fr/v1/pictures/MjAyMjExYzdlMjA1ZDQzODMyYWI2NmQyNzZjNmQ3N2QwNTM0MWQ?width=1260&height=708&focuspoint=50%2C25&cropresize=1&client_id=bpeditorial&sign=1f077f198b337c1d2560c1820a01d2cfe25bc72835b8b0599db11d7e8c2d4148" group-title="FR | Informations",FR | BFM TV SD +https://live-cdn-stream-euw1.bfmtv.bct.nextradiotv.com/master.m3u8 +#EXTINF:-1 tvg-id="CNews.fr" tvg-name="FR | CNews FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/cnews.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/cnews.png" tvg-back="https://www.cnews.fr/sites/default/files/2024-12/micro-cnews_65afe00c0e230_6758fd423a45b.jpeg" group-title="FR | Informations",FR | CNews FHD +https://live.streamgatos.top/hls/10613/stream.m3u8 +#EXTINF:-1 tvg-id="CNews.fr" tvg-name="FR | CNews SD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/cnews.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/cnews.png" tvg-back="https://www.cnews.fr/sites/default/files/2024-12/micro-cnews_65afe00c0e230_6758fd423a45b.jpeg" group-title="FR | Informations",FR | CNews SD +https://raw.githubusercontent.com/Paradise-91/ParaTV/main/streams/canalplus/cnews-dm.m3u8 +#EXTINF:-1 tvg-id="CNews.fr" tvg-name="FR | CNews SD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/cnews.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/cnews.png" tvg-back="https://www.cnews.fr/sites/default/files/2024-12/micro-cnews_65afe00c0e230_6758fd423a45b.jpeg" group-title="FR | Informations",FR | CNews SD +https://raw.githubusercontent.com/Paradise-91/ParaTV/main/streams/canalplus/cnews-clair-hd.m3u8 +#EXTINF:-1 tvg-id="CNews.fr" tvg-name="FR | CNews SD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/cnews.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/cnews.png" tvg-back="https://www.cnews.fr/sites/default/files/2024-12/micro-cnews_65afe00c0e230_6758fd423a45b.jpeg" group-title="FR | Informations",FR | CNews SD +https://hls-m015-live-aka-canalplus.akamaized.net/live/disk/cnews-clair-hd/hls-v3-hd-clair/cnews-clair-hd.m3u8 +#EXTINF:-1 tvg-id="CNews.fr" tvg-name="FR | CNews FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/cnews.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/cnews.png" tvg-back="https://www.cnews.fr/sites/default/files/2024-12/micro-cnews_65afe00c0e230_6758fd423a45b.jpeg" group-title="FR | Informations",FR | CNews FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116144 +#EXTINF:-1 tvg-id="CNews.fr" tvg-name="FR | CNews" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/cnews.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/cnews.png" tvg-back="https://www.cnews.fr/sites/default/files/2024-12/micro-cnews_65afe00c0e230_6758fd423a45b.jpeg" group-title="FR | Informations",FR | CNews +https://raw.githubusercontent.com/LeBazarDeBryan/XTVZ_/main/Stream/Live/CNews.m3u8 +#EXTINF:-1 tvg-id="Euronews.fr" tvg-name="FR | EuroNews HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/euronews.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/euronews.png" tvg-back="https://imimedia.com/_astro/euronews.DA677nER_ZhPk63.webp" group-title="FR | Informations",FR | EuroNews HD +https://live.streamgatos.top/hls/184509/stream.m3u8 +#EXTINF:-1 tvg-id="Euronews.fr" tvg-name="FR | EuroNews FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/euronews.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/euronews.png" tvg-back="https://imimedia.com/_astro/euronews.DA677nER_ZhPk63.webp" group-title="FR | Informations",FR | EuroNews FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116141 +#EXTINF:-1 tvg-id="Euronews.fr" tvg-name="FR | EuroNews SD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/euronews.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/euronews.png" tvg-back="https://imimedia.com/_astro/euronews.DA677nER_ZhPk63.webp" group-title="FR | Informations",FR | EuroNews SD +https://euronews-live-fre-fr.fast.rakuten.tv/v1/master/0547f18649bd788bec7b67b746e47670f558b6b2/production-LiveChannel-6564/bitok/e/26032/euronews-fr.m3u8 +#EXTINF:-1 tvg-id="France24.fr" tvg-name="FR | France 24 FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/france_24.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/france_24.png" tvg-back="https://s.france24.com/media/display/99f8a93a-e6c1-11ee-9116-005056bf30b7/w:1280/p:16x9/img-default-F24.jpg" group-title="FR | Informations",FR | France 24 FHD +https://live.france24.com/hls/live/2037179/F24_FR_HI_HLS/master_5000.m3u8 +#EXTINF:-1 tvg-id="France24.fr" tvg-name="FR | France 24 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/france_24.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/france_24.png" tvg-back="https://s.france24.com/media/display/99f8a93a-e6c1-11ee-9116-005056bf30b7/w:1280/p:16x9/img-default-F24.jpg" group-title="FR | Informations",FR | France 24 HD +https://live.france24.com/hls/live/2037179/F24_FR_HI_HLS/master_2300.m3u8 +#EXTINF:-1 tvg-id="France24.fr" tvg-name="FR | France 24 HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/france_24.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/france_24.png" tvg-back="https://s.france24.com/media/display/99f8a93a-e6c1-11ee-9116-005056bf30b7/w:1280/p:16x9/img-default-F24.jpg" group-title="FR | Informations",FR | France 24 HD +http://sewv654wfcsdwfi87fwvgbngh.siauliairsavlt.pw/iptv/VEXVELA6Z7PXH6/947/index.m3u8 +#EXTINF:-1 tvg-id="France24.fr" tvg-name="FR | France 24 SD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/france_24.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/france_24.png" tvg-back="https://s.france24.com/media/display/99f8a93a-e6c1-11ee-9116-005056bf30b7/w:1280/p:16x9/img-default-F24.jpg" group-title="FR | Informations",FR | France 24 SD +https://live.france24.com/hls/live/2037179/F24_FR_HI_HLS/master_900.m3u8 +#EXTINF:-1 tvg-id="FranceInfo.fr" tvg-name="FR | France Info FHD" tvg-logo="https://tvmio.gleeze.com/logos/informations/france_info.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/france_info.png" tvg-back="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSUswga4OIc8RGSuGuxRfEqOoOdA1BKUMntVQ&s" group-title="FR | Informations",FR | France Info FHD +http://176.65.146.138:8047/play/a07g/index.m3u8 +#EXTINF:-1 tvg-id="FranceInfo.fr" tvg-name="FR | France Info HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/france_info.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/france_info.png" tvg-back="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSUswga4OIc8RGSuGuxRfEqOoOdA1BKUMntVQ&s" group-title="FR | Informations",FR | France Info HD +http://sewv654wfcsdwfi87fwvgbngh.siauliairsavlt.pw/iptv/VEXVELA6Z7PXH6/6151/index.m3u8 +#EXTINF:-1 tvg-id="InfosportPlus.fr" tvg-name="FR | InfoSport + HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/infosport.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/infsport.png" tvg-back="https://www.lequipe.fr/_medias/img-photo-jpg/le-nouveau-decor-d-infosport/1500000000711948/0:190,2048:1223-1200-603-75/e4aa5.jpg" group-title="FR | Informations",FR | InfoSport + HD +http://sewv654wfcsdwfi87fwvgbngh.siauliairsavlt.pw/iptv/VEXVELA6Z7PXH6/2544/index.m3u8 +#EXTINF:-1 tvg-id="InfosportPlus.fr" tvg-name="FR | InfoSport FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/infosport.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/infsport.png" tvg-back="https://www.lequipe.fr/_medias/img-photo-jpg/le-nouveau-decor-d-infosport/1500000000711948/0:190,2048:1223-1200-603-75/e4aa5.jpg" group-title="FR | Informations",FR | InfoSport FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116538 +#EXTINF:-1 tvg-id="InfosportPlus.fr" tvg-name="FR | InfoSport FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/sports/infosport.png" tvg-poster="https://tvmio.gleeze.com/poster/sports/infsport.png" tvg-back="https://www.lequipe.fr/_medias/img-photo-jpg/le-nouveau-decor-d-infosport/1500000000711948/0:190,2048:1223-1200-603-75/e4aa5.jpg" group-title="FR | Informations",FR | InfoSport FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116537 +#EXTINF:-1 tvg-id="LCI.fr" tvg-name="FR | LCI FHD" tvg-logo="https://tvmio.gleeze.com/logos/informations/lci.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/lci.png" tvg-back="https://media.licdn.com/dms/image/v2/D5605AQGaX28CCTbxCQ/videocover-low/B56Zc7fY23GQBk-/0/1749049776673?e=2147483647&v=beta&t=cS7QHR3MciRSQKCX1odjQAKgDRQUMzLDYUNeYf_CsEg" group-title="FR | Informations",FR | LCI FHD +http://176.65.146.138:8047/play/a07p/index.m3u8 +#EXTINF:-1 tvg-id="LCI.fr" tvg-name="FR | LCI FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/lci.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/lci.png" tvg-back="https://media.licdn.com/dms/image/v2/D5605AQGaX28CCTbxCQ/videocover-low/B56Zc7fY23GQBk-/0/1749049776673?e=2147483647&v=beta&t=cS7QHR3MciRSQKCX1odjQAKgDRQUMzLDYUNeYf_CsEg" group-title="FR | Informations",FR | LCI FHD +http://sewv654wfcsdwfi87fwvgbngh.siauliairsavlt.pw/iptv/VEXVELA6Z7PXH6/15188/index.m3u8 +#EXTINF:-1 tvg-id="LCI.fr" tvg-name="FR | LCI HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/informations/lci.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/lci.png" tvg-back="https://media.licdn.com/dms/image/v2/D5605AQGaX28CCTbxCQ/videocover-low/B56Zc7fY23GQBk-/0/1749049776673?e=2147483647&v=beta&t=cS7QHR3MciRSQKCX1odjQAKgDRQUMzLDYUNeYf_CsEg" group-title="FR | Informations",FR | LCI HD +http://151.80.18.177:86/LCI_HD/index.m3u8 +#EXTINF:-1 tvg-id="IDF1.fr" tvg-name="FR | 20 Minutes TV LD" tvg-chno="0" tvg-logo="https://focus.telerama.fr/500x500/0000/00/01/clear-701.png" tvg-poster="https://focus.telerama.fr/500x500/0000/00/01/clear-701.png" tvg-back="https://focus.telerama.fr/500x500/0000/00/01/clear-701.png" group-title="FR | Informations",FR | 20 Minutes TV LD +https://live-20minutestv.digiteka.com/1961167769/index.m3u8 +#EXTINF:-1 tvg-id="AfricanewsFrench.fr" tvg-name="FR | Africanews French" tvg-chno="0" tvg-logo="https://upload.wikimedia.org/wikipedia/commons/d/d3/Africanews._alternative_logo_2016.png" tvg-poster="https://upload.wikimedia.org/wikipedia/commons/d/d3/Africanews._alternative_logo_2016.png" tvg-back="https://upload.wikimedia.org/wikipedia/commons/d/d3/Africanews._alternative_logo_2016.png" group-title="FR | Informations",FR | Africanews French +https://cdn-euronews.akamaized.net/live/eds/africanews-fr/25050/index.m3u8 +#EXTINF:-1 tvg-id="Africa24.af" tvg-name="FR | Africa 24 FHD" tvg-chno="0" tvg-logo="https://thumb.canalplus.pro/http/unsafe/{resolutionXY}/filters:quality({imageQualityPercentage})/canalplus-cdn.canal-plus.io/p1/channel/180168/canal-ouah/CHN43FB/AFRICA24_myCANAL_640x480" tvg-poster="https://thumb.canalplus.pro/http/unsafe/{resolutionXY}/filters:quality({imageQualityPercentage})/canalplus-cdn.canal-plus.io/p1/channel/180168/canal-ouah/CHN43FB/AFRICA24_myCANAL_640x480" tvg-back="https://thumb.canalplus.pro/http/unsafe/{resolutionXY}/filters:quality({imageQualityPercentage})/canalplus-cdn.canal-plus.io/p1/channel/180168/canal-ouah/CHN43FB/AFRICA24_myCANAL_640x480" group-title="FR | Informations",FR | Africa 24 FHD +https://africa24.vedge.infomaniak.com/livecast/ik:africa24/manifest.m3u8 +#EXTINF:-1 tvg-id="CanalJ.fr" tvg-name="FR | Canal J FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/enfants/canal_j.png" tvg-poster="https://tvmio.gleeze.com/poster/enfants/canal_j.png" tvg-back="https://www.megazap.fr/photo/art/grande/35094136-31881813.jpg?v=1561533690" group-title="FR | Enfants",FR | Canal J FHD +https://live.streamgatos.top/hls/711/stream.m3u8 +#EXTINF:-1 tvg-id="Boing.fr" tvg-name="FR | Boing HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/enfants/boing.png" tvg-poster="https://tvmio.gleeze.com/poster/enfants/boing.png" tvg-back="https://artandgraft.com/wp-content/uploads/2023/11/B_main8_1800-1.jpg" group-title="FR | Enfants",FR | Boing HD +https://live.streamgatos.top/hls/707/stream.m3u8 +#EXTINF:-1 tvg-id="CanalPlusKIDS.fr" tvg-name="FR | Canal+ Kids HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/enfants/canal_kids.png" tvg-poster="https://tvmio.gleeze.com/poster/enfants/canal_kids.png" tvg-back="https://i.ytimg.com/vi/z-qr_fxv18o/hq720.jpg?sqp=-oaymwExCK4FEIIDSFryq4qpAyMIARUAAIhCGAHwAQH4AdQGgALgA4oCDAgAEAEYRiBlKFQwDw==&rs=AOn4CLAO6MSGShlpFSpNXLwl-eQ-kSQOjQ" group-title="FR | Enfants",FR | Canal+ Kids HD +http://sewv654wfcsdwfi87fwvgbngh.siauliairsavlt.pw/iptv/VEXVELA6Z7PXH6/6006/index.m3u8 +#EXTINF:-1 tvg-id="CanalPlusKIDS.fr" tvg-name="FR | Canal+ Kids HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/enfants/canal_kids.png" tvg-poster="https://tvmio.gleeze.com/poster/enfants/canal_kids.png" tvg-back="https://i.ytimg.com/vi/z-qr_fxv18o/hq720.jpg?sqp=-oaymwExCK4FEIIDSFryq4qpAyMIARUAAIhCGAHwAQH4AdQGgALgA4oCDAgAEAEYRiBlKFQwDw==&rs=AOn4CLAO6MSGShlpFSpNXLwl-eQ-kSQOjQ" group-title="FR | Enfants",FR | Canal+ Kids HD +https://live.streamgatos.top/hls/362/stream.m3u8 +#EXTINF:-1 tvg-id="CartoonNetwork.fr" tvg-name="FR | Cartoon Network HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/enfants/cartoon_network.png" tvg-poster="https://tvmio.gleeze.com/poster/enfants/cartoon_network.png" tvg-back="https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/e592924b-d3d8-4a2b-8c5d-a93f871a7cac/dfudqxz-fb72dafb-c499-4bb5-b5cd-99a83d7ca824.jpg/v1/fill/w_1280,h_880,q_75,strp/full_cartoon_network_2010_background_by_cs2studios_dfudqxz-fullview.jpg?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7ImhlaWdodCI6Ijw9ODgwIiwicGF0aCI6Ii9mL2U1OTI5MjRiLWQzZDgtNGEyYi04YzVkLWE5M2Y4NzFhN2NhYy9kZnVkcXh6LWZiNzJkYWZiLWM0OTktNGJiNS1iNWNkLTk5YTgzZDdjYTgyNC5qcGciLCJ3aWR0aCI6Ijw9MTI4MCJ9XV0sImF1ZCI6WyJ1cm46c2VydmljZTppbWFnZS5vcGVyYXRpb25zIl19.oIwDIgugthR_EE7e35_nuOI__YKCD0gO_eDa-yG5B7I" group-title="FR | Enfants",FR | Cartoon Network HD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/53328 +#EXTINF:-1 tvg-id="Boomerang.fr" tvg-name="FR | Boomerang FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/pvXzvcyM/boomerang-logo.png" tvg-poster="https://i.ibb.co/4nVSKPd9/boomerang-poster.png" tvg-back="https://artandgraft.com/wp-content/uploads/2023/10/Boomerang_main.jpg" group-title="FR | Enfants",FR | Boomerang FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/48565 +#EXTINF:-1 tvg-id="Boomerang.fr" tvg-name="FR | Boomerang HD" tvg-chno="0" tvg-logo="https://i.ibb.co/pvXzvcyM/boomerang-logo.png" tvg-poster="https://i.ibb.co/4nVSKPd9/boomerang-poster.png" tvg-back="https://artandgraft.com/wp-content/uploads/2023/10/Boomerang_main.jpg" group-title="FR | Enfants",FR | Boomerang HD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116646 +#EXTINF:-1 tvg-id="DisneyChannel.fr" tvg-name="FR | Disney Channel HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/enfants/disney_channel.png" tvg-poster="https://tvmio.gleeze.com/poster/enfants/disney_channel.png" tvg-back="https://64.media.tumblr.com/b63dc6e2a56b43acf278bdead375d9b0/04293b9d5dd1dd70-cf/s1280x1920/794873b56d2d5f7bd8e5ca568be972e5b1dcb66b.png" group-title="FR | Enfants",FR | Disney Channel HD +http://151.80.18.177:86/Disney_Channel_HD/index.m3u8 +#EXTINF:-1 tvg-id="DisneyChannel.fr" tvg-name="FR | Disney Channel HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/enfants/disney_channel.png" tvg-poster="https://tvmio.gleeze.com/poster/enfants/disney_channel.png" tvg-back="https://64.media.tumblr.com/b63dc6e2a56b43acf278bdead375d9b0/04293b9d5dd1dd70-cf/s1280x1920/794873b56d2d5f7bd8e5ca568be972e5b1dcb66b.png" group-title="FR | Enfants",FR | Disney Channel HD +http://sewv654wfcsdwfi87fwvgbngh.siauliairsavlt.pw/iptv/VEXVELA6Z7PXH6/15185/index.m3u8 +#EXTINF:-1 tvg-id="Gulli.fr" tvg-name="FR | Gulli FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/enfants/gulli.png" tvg-poster="https://tvmio.gleeze.com/poster/enfants/gulli.png" tvg-back="https://mir-s3-cdn-cf.behance.net/project_modules/fs/9b8878100723723.5f17211474fb1.png" group-title="FR | Enfants",FR | Gulli FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/47800 +#EXTINF:-1 tvg-id="Gulli.fr" tvg-name="FR | Gulli SD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/enfants/gulli.png" tvg-poster="https://tvmio.gleeze.com/poster/enfants/gulli.png" tvg-back="https://mir-s3-cdn-cf.behance.net/project_modules/fs/9b8878100723723.5f17211474fb1.png" group-title="FR | Enfants",FR | Gulli SD +https://viamotionhsi.netplus.ch/live/eds/gulli/browser-HLS8/gulli.m3u8 +#EXTINF:-1 tvg-id="Gulli.fr" tvg-name="FR | Gulli SD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/enfants/gulli.png" tvg-poster="https://tvmio.gleeze.com/poster/enfants/gulli.png" tvg-back="https://mir-s3-cdn-cf.behance.net/project_modules/fs/9b8878100723723.5f17211474fb1.png" group-title="FR | Enfants",FR | Gulli SD +https://live.streamgatos.top/hls/337/stream.m3u8 +#EXTINF:-1 tvg-id="EPGNA" tvg-name="FR | ADN TV+ HD" tvg-chno="0" tvg-logo="https://i.ibb.co/20Vgnnb0/adn-logo.png" tvg-poster="https://i.ibb.co/F4zsTLcL/adn-poster.png" tvg-back="https://www.livreshebdo.fr/sites/default/files/styles/article_principal/public/2022-07/ADN.jpg?itok=jy6ZCHfo" group-title="FR | Enfants",FR | ADN TV+ HD +https://d3b73b34o7cvkq.cloudfront.net/v1/master/3722c60a815c199d9c0ef36c5b73da68a62b09d1/cc-gz2sgqzp076kf/adn.m3u8 +#EXTINF:-1 tvg-id="Mangas.fr" tvg-name="FR | Mangas FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/enfants/mangas.png" tvg-poster="https://tvmio.gleeze.com/poster/enfants/mangas.png" tvg-back="https://image.over-blog.com/NrEnSvX_yReNSCNE1LMTrPx-rxo=/filters:no_upscale()/image%2F0874959%2F20220623%2Fob_e9d36d_mangas2022.jpg" group-title="FR | Enfants",FR | Mangas FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/47803 +#EXTINF:-1 tvg-id="Mangas.fr" tvg-name="FR | Mangas HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/enfants/mangas.png" tvg-poster="https://tvmio.gleeze.com/poster/enfants/mangas.png" tvg-back="https://image.over-blog.com/NrEnSvX_yReNSCNE1LMTrPx-rxo=/filters:no_upscale()/image%2F0874959%2F20220623%2Fob_e9d36d_mangas2022.jpg" group-title="FR | Enfants",FR | Mangas HD +https://live.streamgatos.top/hls/329/stream.m3u8 +#EXTINF:-1 tvg-id="Nickelodeon.fr" tvg-name="FR | Nickelodeon FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/enfants/nickelodeon.png" tvg-poster="https://tvmio.gleeze.com/poster/enfants/nickelodeon.png" tvg-back="https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/52c74659-151c-4a1e-9eaf-b20fb4106ff1/dg0kdto-a883b907-6af1-4230-8aa1-037be591e9ff.png?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7InBhdGgiOiIvZi81MmM3NDY1OS0xNTFjLTRhMWUtOWVhZi1iMjBmYjQxMDZmZjEvZGcwa2R0by1hODgzYjkwNy02YWYxLTQyMzAtOGFhMS0wMzdiZTU5MWU5ZmYucG5nIn1dXSwiYXVkIjpbInVybjpzZXJ2aWNlOmZpbGUuZG93bmxvYWQiXX0.UryU0KaEqPTMgXPkfHfposWBigSUC_LZ6q9IO5mQvoM" group-title="FR | Enfants",FR | Nickelodeon FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/52782 +#EXTINF:-1 tvg-id="Nickelodeon.fr" tvg-name="FR | Nickelodeon FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/enfants/nickelodeon.png" tvg-poster="https://tvmio.gleeze.com/poster/enfants/nickelodeon.png" tvg-back="https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/52c74659-151c-4a1e-9eaf-b20fb4106ff1/dg0kdto-a883b907-6af1-4230-8aa1-037be591e9ff.png?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7InBhdGgiOiIvZi81MmM3NDY1OS0xNTFjLTRhMWUtOWVhZi1iMjBmYjQxMDZmZjEvZGcwa2R0by1hODgzYjkwNy02YWYxLTQyMzAtOGFhMS0wMzdiZTU5MWU5ZmYucG5nIn1dXSwiYXVkIjpbInVybjpzZXJ2aWNlOmZpbGUuZG93bmxvYWQiXX0.UryU0KaEqPTMgXPkfHfposWBigSUC_LZ6q9IO5mQvoM" group-title="FR | Enfants",FR | Nickelodeon FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116647 +#EXTINF:-1 tvg-id="Nickelodeon.fr" tvg-name="FR | Nickelodeon HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/enfants/nickelodeon.png" tvg-poster="https://tvmio.gleeze.com/poster/enfants/nickelodeon.png" tvg-back="https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/52c74659-151c-4a1e-9eaf-b20fb4106ff1/dg0kdto-a883b907-6af1-4230-8aa1-037be591e9ff.png?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7InBhdGgiOiIvZi81MmM3NDY1OS0xNTFjLTRhMWUtOWVhZi1iMjBmYjQxMDZmZjEvZGcwa2R0by1hODgzYjkwNy02YWYxLTQyMzAtOGFhMS0wMzdiZTU5MWU5ZmYucG5nIn1dXSwiYXVkIjpbInVybjpzZXJ2aWNlOmZpbGUuZG93bmxvYWQiXX0.UryU0KaEqPTMgXPkfHfposWBigSUC_LZ6q9IO5mQvoM" group-title="FR | Enfants",FR | Nickelodeon HD +https://live.streamgatos.top/hls/2101/stream.m3u8 +#EXTINF:-1 tvg-id="PIWI.fr" tvg-name="FR | Piwi+ FHD" tvg-chno="0" tvg-logo="https://i.ibb.co/MkyvJcsm/piwi-logo.png" tvg-poster="https://i.ibb.co/fG1s7S9Z/piwi-poster.png" tvg-back="https://blog.lenodal.com/uploads/actualitedelhabillage/2011/mth-2011-piwiplus-univers.jpg" group-title="FR | Enfants",FR | Piwi+ FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/47793 +#EXTINF:-1 tvg-id="TeleToonPlus.fr" tvg-name="FR | Teletoon+ HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/enfants/teletoon.png" tvg-poster="https://tvmio.gleeze.com/poster/enfants/teletoon.png" tvg-back="https://i.ytimg.com/vi/uW8ctHg5RYQ/hq720.jpg?sqp=-oaymwEhCK4FEIIDSFryq4qpAxMIARUAAAAAGAElAADIQj0AgKJD&rs=AOn4CLAM-0L4UsWHo-v-Nn2StJshxQWmMA" group-title="FR | Enfants",FR | Teletoon+ HD +https://live.streamgatos.top/hls/710/stream.m3u8 +#EXTINF:-1 tvg-id="TIJI.fr" tvg-name="FR | Tiji HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/enfants/tiji.png" tvg-poster="https://tvmio.gleeze.com/poster/enfants/tiji.png" tvg-back="https://i.vimeocdn.com/video/651692309-10778c2166494e9bef5c03de7905fc262af2499294c63ebf8a2b02dca599de5a-d?f=webp" group-title="FR | Enfants",FR | Tiji HD +http://151.80.18.177:86/Tiji_HD/index.m3u8 +#EXTINF:-1 tvg-id="Toonami.fr" tvg-name="FR | Toonami SD+" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/enfants/toonami.png" tvg-poster="https://tvmio.gleeze.com/poster/enfants/toonami.png" tvg-back="https://www.awn.com/sites/default/files/styles/original/public/image/featured/1032461-adult-swims-toonami-celebrates-20-years-action.jpg?itok=ivNl4Ri7" group-title="FR | Enfants",FR | Toonami SD+ +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/48782 +#EXTINF:-1 tvg-name="FR | Inazuma Eleven" tvg-logo="https://tvmio.gleeze.com/logos/enfants/inazuma_eleven.png" tvg-poster="https://tvmio.gleeze.com/poster/enfants/inazuma_eleven.png" tvg-back="https://i.pinimg.com/736x/de/dd/a6/dedda6c1f0a22581a837f26b2d9ead57.jpg" group-title="FR | Enfants",FR | Inazuma Eleven +http://cfd-v4-service-channel-stitcher-use1-1.prd.pluto.tv/stitch/hls/channel/611e75226b7f420007c3f319/master.m3u8?appName=web&appVersion=unknown&clientTime=0&deviceDNT=0&deviceId=8e063bd2-1f2c-11ef-86d8-5d587df108c6&deviceMake=Chrome&deviceModel=web&deviceType=web&deviceVersion=unknown&includeExtendedEvents=false&serverSideAds=false&sid=80879397-91d6-4d71-9c36-ad9f3ac25c0e +#EXTINF:-1 tvg-id="CStar.fr" tvg-name="FR | CStar FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/music/cstar.png" tvg-poster="https://i.ibb.co/VkHjzmR/cstar-poster.png" tvg-back="https://i.ytimg.com/vi/aZSP1siMuFQ/hq720.jpg?sqp=-oaymwEhCK4FEIIDSFryq4qpAxMIARUAAAAAGAElAADIQj0AgKJD&rs=AOn4CLC6B7cZfZhjjT-BFWCA2Oidezqjcw" group-title="FR | Music",FR | CStar FHD +https://live.streamgatos.top/hls/4907/stream.m3u8 +#EXTINF:-1 tvg-id="CStar.fr" tvg-name="FR | CStar FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/music/cstar.png" tvg-poster="https://i.ibb.co/VkHjzmR/cstar-poster.png" tvg-back="https://i.ytimg.com/vi/aZSP1siMuFQ/hq720.jpg?sqp=-oaymwEhCK4FEIIDSFryq4qpAxMIARUAAAAAGAElAADIQj0AgKJD&rs=AOn4CLC6B7cZfZhjjT-BFWCA2Oidezqjcw" group-title="FR | Music",FR | CStar FHD +http://ip.xtremetv.eu:8000/hizirarkadashollanda/V39WCmGCgSp8/116612 +#EXTINF:-1 tvg-id="CStar.fr" tvg-name="FR | CStar SD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/music/cstar.png" tvg-poster="https://i.ibb.co/VkHjzmR/cstar-poster.png" tvg-back="https://i.ytimg.com/vi/aZSP1siMuFQ/hq720.jpg?sqp=-oaymwEhCK4FEIIDSFryq4qpAxMIARUAAAAAGAElAADIQj0AgKJD&rs=AOn4CLC6B7cZfZhjjT-BFWCA2Oidezqjcw" group-title="FR | Music",FR | CStar SD +https://raw.githubusercontent.com/Paradise-91/ParaTV/main/streams/canalplus/cstar-dm.m3u8 +#EXTINF:-1 tvg-id="CStar.fr" tvg-name="FR | CStar HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/music/cstar.png" tvg-poster="https://i.ibb.co/VkHjzmR/cstar-poster.png" tvg-back="https://i.ytimg.com/vi/aZSP1siMuFQ/hq720.jpg?sqp=-oaymwEhCK4FEIIDSFryq4qpAxMIARUAAAAAGAElAADIQj0AgKJD&rs=AOn4CLC6B7cZfZhjjT-BFWCA2Oidezqjcw" group-title="FR | Music",FR | CStar HD +http://151.80.18.177:86/D17_HD/index.m3u8 +#EXTINF:-1 tvg-id="M6Music.fr" tvg-name="FR | M6 Music FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/music/m6_music.png" tvg-poster="https://tvmio.gleeze.com/poster/music/m6_music.png" tvg-back="https://www.groupem6.fr/app/uploads/sites/3/2018/09/m6-music-20-ans.jpg" group-title="FR | Music",FR | M6 Music FHD +http://vip.sibfungold.org:8080/restream1/LKuZiN5Idu2DpgG4y4pa/52779 +#EXTINF:-1 tvg-id="MCM.fr" tvg-name="FR | MCM HD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/music/mcm.png" tvg-poster="https://tvmio.gleeze.com/poster/music/mcm.png" tvg-back="https://tvmio.gleeze.com/logos/music/mcm.png" group-title="FR | Music",FR | MCM HD +https://live.streamgatos.top/hls/7320/stream.m3u8 +#EXTINF:-1 tvg-id="MTV.fr" tvg-name="FR | MTV France FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/music/mtv.png" tvg-poster="https://tvmio.gleeze.com/poster/music/mtv.png" tvg-back="https://t3.ftcdn.net/jpg/05/70/97/60/360_F_570976021_LZVbZQsjh6onPj0pJlGCeOSC2xrg06Dk.jpg" group-title="FR | Music",FR | MTV France FHD +https://live.streamgatos.top/hls/5154/stream.m3u8 +#EXTINF:-1 tvg-id="NRJHits.fr" tvg-name="FR | NRJ Hits FHD" tvg-chno="0" tvg-logo="https://tvmio.gleeze.com/logos/music/nrj_hits.png" tvg-poster="https://tvmio.gleeze.com/poster/music/nrj_hits.png" tvg-back="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRN_mJg_DWaua5zo85IddBlurJNrqZXEKhZIA&s" group-title="FR | Music",FR | NRJ Hits FHD +https://live.streamgatos.top/hls/7322/stream.m3u8 +#EXTINF:-1 tvg-id="TraceUrban.fr" tvg-name="FR | Trace Urban HD" tvg-chno="0" tvg-logo="https://i.ibb.co/TD25G44h/trace-urban-logo.png" tvg-poster="https://i.ibb.co/LdYqQvh3/trace-urban-poster.png" group-title="FR | Music",FR | Trace Urban HD +http://151.80.18.177:86/Trace_Urban_HD/index.m3u8 +#EXTINF:-1 tvg-id="LCP100.fr" tvg-name="FR | LCP FHD" tvg-logo="https://tvmio.gleeze.com/logos/informations/lcp.png" tvg-poster="https://tvmio.gleeze.com/poster/informations/lcp.png" tvg-back="https://tvmio.gleeze.com/logos/informations/lcp.png" group-title="FR | Informations",FR | LCP FHD +http://176.65.146.138:8047/play/a078/index.m3u8 diff --git a/API/Mainapi/likesRoutes.js b/API/Mainapi/likesRoutes.js new file mode 100644 index 0000000..8e8b4d2 --- /dev/null +++ b/API/Mainapi/likesRoutes.js @@ -0,0 +1,314 @@ +const express = require('express'); +const router = express.Router(); +const { getPool } = require('./mysqlPool'); +const fs = require('fs').promises; +const path = require('path'); +const { verifyTurnstileFromRequest } = require('./utils/turnstile'); + +const TURNSTILE_INVISIBLE_SECRETKEY = process.env.TURNSTILE_INVISIBLE_SECRETKEY; + +// Helper to get user data (duplicated from commentsRoutes.js to avoid dependency issues) +async function getProfileIds(userId, userType) { + try { + // Sanitize userId to prevent path traversal + const safeUserId = String(userId).replace(/[^a-zA-Z0-9_\-]/g, ''); + let userFilePath; + if (userType === 'bip39') { + userFilePath = path.join(__dirname, 'data', 'users', `bip39-${safeUserId}.json`); + } else { + userFilePath = path.join(__dirname, 'data', 'users', `${safeUserId}.json`); + } + + try { + const userFile = await fs.readFile(userFilePath, 'utf8'); + const user = JSON.parse(userFile); + + const profileIds = []; + if (user.profiles) { + user.profiles.forEach(p => profileIds.push(p.id)); + } else { + // Fallback for old structure or default profile + // Often default profile ID is same as user ID or specific generated one + // We'll try to find it in the data structure + } + return profileIds; + } catch (err) { + if (err.code !== 'ENOENT') console.error('Error reading user file:', err); + return []; + } + } catch (error) { + console.error('Error getting profile IDs:', error); + return []; + } +} + + +// Fonctions helper MySQL pour remplacer SQLite +const dbRun = async (sql, params = []) => { + const pool = getPool(); + const [result] = await pool.execute(sql, params); + return { + lastID: result.insertId || 0, + changes: result.affectedRows || 0 + }; +}; + +const dbGet = async (sql, params = []) => { + const pool = getPool(); + const [rows] = await pool.execute(sql, params); + return rows.length > 0 ? rows[0] : null; +}; + +const dbAll = async (sql, params = []) => { + const pool = getPool(); + const [rows] = await pool.execute(sql, params); + return rows; +}; + +// Middleware pour vérifier l'authentification (optionnel pour GET) avec validation session MySQL +const optionalAuth = async (req, res, next) => { + const token = req.headers.authorization?.split(' ')[1]; + if (!token) { + req.user = null; + return next(); + } + + const jwt = require('jsonwebtoken'); + const JWT_SECRET = process.env.JWT_SECRET; + if (!JWT_SECRET) { + req.user = null; + return next(); + } + + try { + const decoded = jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] }); + const { sub: userId, userType, sessionId } = decoded; + + if (!['oauth', 'bip39'].includes(userType) || !userId || !sessionId) { + req.user = null; + return next(); + } + + // Vérifier que la session existe en MySQL + const pool = getPool(); + const [rows] = await pool.execute( + 'SELECT id FROM user_sessions WHERE id = ? AND user_id = ? AND user_type = ?', + [sessionId, userId, userType] + ); + + if (rows.length === 0) { + req.user = null; + return next(); + } + + req.user = { + userId: userId, + userType: userType, + sessionId: sessionId + }; + next(); + } catch (error) { + req.user = null; + next(); + } +}; + +// Middleware pour vérifier l'authentification (requis pour POST) avec validation session MySQL +const requireAuth = async (req, res, next) => { + const token = req.headers.authorization?.split(' ')[1]; + if (!token) { + return res.status(401).json({ error: 'Non authentifié' }); + } + + const jwt = require('jsonwebtoken'); + const JWT_SECRET = process.env.JWT_SECRET; + if (!JWT_SECRET) return res.status(500).json({ error: 'Server misconfiguration' }); + + try { + const decoded = jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] }); + const { sub: userId, userType, sessionId } = decoded; + + if (!['oauth', 'bip39'].includes(userType) || !userId || !sessionId) { + return res.status(401).json({ error: 'Token invalide' }); + } + + // Vérifier que la session existe en MySQL + const pool = getPool(); + const [rows] = await pool.execute( + 'SELECT id FROM user_sessions WHERE id = ? AND user_id = ? AND user_type = ?', + [sessionId, userId, userType] + ); + + if (rows.length === 0) { + return res.status(401).json({ error: 'Session invalide ou expirée' }); + } + + req.user = { + userId: userId, + userType: userType, + sessionId: sessionId + }; + next(); + } catch (error) { + return res.status(401).json({ error: 'Token invalide' }); + } +}; + +// GET /api/likes/:contentType/:contentId - Récupérer les statistiques de likes pour un contenu +router.get('/:contentType/:contentId', optionalAuth, async (req, res) => { + try { + const { contentType, contentId } = req.params; + const profileId = req.query.profileId; + + // Compter les likes + const likesCount = await dbGet( + `SELECT COUNT(*) as count FROM likes + WHERE content_type = ? AND content_id = ? AND vote_type = 'like'`, + [contentType, contentId] + ); + + // Compter les dislikes + const dislikesCount = await dbGet( + `SELECT COUNT(*) as count FROM likes + WHERE content_type = ? AND content_id = ? AND vote_type = 'dislike'`, + [contentType, contentId] + ); + + const response = { + likes: likesCount?.count || 0, + dislikes: dislikesCount?.count || 0, + userVote: null + }; + + // Si l'utilisateur est authentifié, vérifier s'il a voté (par userId, pas profileId) + if (req.user) { + const userVote = await dbGet( + `SELECT vote_type FROM likes + WHERE content_type = ? AND content_id = ? + AND user_id = ? AND user_type = ?`, + [contentType, contentId, req.user.userId, req.user.userType] + ); + + if (userVote) { + response.userVote = userVote.vote_type; + } + } + + res.json(response); + } catch (error) { + console.error('Erreur lors de la récupération des likes:', error); + res.status(500).json({ error: 'Erreur serveur' }); + } +}); + +// POST /api/likes - Ajouter/modifier/supprimer un vote +router.post('/', requireAuth, async (req, res) => { + try { + const { contentType, contentId, voteType, profileId, turnstileToken } = req.body; + + // Verification Turnstile (invisible captcha) + if (TURNSTILE_INVISIBLE_SECRETKEY) { + const check = await verifyTurnstileFromRequest(req, turnstileToken, TURNSTILE_INVISIBLE_SECRETKEY); + if (!check.valid) { + return res.status(check.status).json({ error: check.error }); + } + } + + // Validation + if (!contentType || !contentId) { + return res.status(400).json({ error: 'Données manquantes' }); + } + + // Whitelist contentType to prevent data pollution + const allowedContentTypes = ['movie', 'tv', 'anime', 'live-tv', 'comment', 'reply', 'shared-list']; + if (!allowedContentTypes.includes(contentType)) { + return res.status(400).json({ error: 'Type de contenu invalide' }); + } + + if (voteType && !['like', 'dislike'].includes(voteType)) { + return res.status(400).json({ error: 'Type de vote invalide' }); + } + + const userId = req.user.userId; + const userType = req.user.userType; + + // Vérifier si l'utilisateur a déjà voté (par userId, pas profileId) + const existingVote = await dbGet( + `SELECT * FROM likes + WHERE content_type = ? AND content_id = ? + AND user_id = ? AND user_type = ?`, + [contentType, contentId, userId, userType] + ); + + if (!voteType) { + // Supprimer le vote si voteType est null ou undefined + if (existingVote) { + await dbRun( + `DELETE FROM likes + WHERE content_type = ? AND content_id = ? + AND user_id = ? AND user_type = ?`, + [contentType, contentId, userId, userType] + ); + } + } else if (existingVote) { + // Si le vote est le même, on le supprime (toggle) + if (existingVote.vote_type === voteType) { + await dbRun( + `DELETE FROM likes + WHERE content_type = ? AND content_id = ? + AND user_id = ? AND user_type = ?`, + [contentType, contentId, userId, userType] + ); + } else { + // Sinon, on met à jour le vote + await dbRun( + `UPDATE likes + SET vote_type = ?, updated_at = ? + WHERE content_type = ? AND content_id = ? + AND user_id = ? AND user_type = ?`, + [voteType, Date.now(), contentType, contentId, userId, userType] + ); + } + } else { + // Créer un nouveau vote + await dbRun( + `INSERT INTO likes (content_type, content_id, user_id, user_type, profile_id, vote_type, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?)`, + [contentType, contentId, userId, userType, profileId || null, voteType, Date.now()] + ); + } + + // Récupérer les nouvelles statistiques + const likesCount = await dbGet( + `SELECT COUNT(*) as count FROM likes + WHERE content_type = ? AND content_id = ? AND vote_type = 'like'`, + [contentType, contentId] + ); + + const dislikesCount = await dbGet( + `SELECT COUNT(*) as count FROM likes + WHERE content_type = ? AND content_id = ? AND vote_type = 'dislike'`, + [contentType, contentId] + ); + + // Vérifier le vote actuel de l'utilisateur + const currentVote = await dbGet( + `SELECT vote_type FROM likes + WHERE content_type = ? AND content_id = ? + AND user_id = ? AND user_type = ?`, + [contentType, contentId, userId, userType] + ); + + res.json({ + success: true, + likes: likesCount?.count || 0, + dislikes: dislikesCount?.count || 0, + userVote: currentVote?.vote_type || null + }); + } catch (error) { + console.error('Erreur lors du vote:', error); + res.status(500).json({ error: 'Erreur serveur' }); + } +}); + +module.exports = router; \ No newline at end of file diff --git a/API/Mainapi/linkSubmissionsRoutes.js b/API/Mainapi/linkSubmissionsRoutes.js new file mode 100644 index 0000000..1c5ac42 --- /dev/null +++ b/API/Mainapi/linkSubmissionsRoutes.js @@ -0,0 +1,776 @@ +/** + * Link Submissions API Routes + * System for users to propose streaming links for movies/episodes/seasons + * Links must be approved by staff before being added + * + * Encourages usage of https://seekstreaming.com/ as a preferred source + * + * Uses MySQL database (same as the rest of the app) + */ + +const express = require('express'); +const jwt = require('jsonwebtoken'); +const fs = require('fs').promises; +const path = require('path'); +const { verifyAccessKey } = require('./checkVip'); + +const JWT_SECRET = process.env.JWT_SECRET; + +/** + * Creates and returns the link submissions router + * @param {Object} mysqlPool - MySQL connection pool from server.js + * @param {Object} redis - Redis client instance from server.js + * @returns {express.Router} Express router with link submission routes + */ +function createLinkSubmissionsRouter(mysqlPool, redis) { + const router = express.Router(); + + // ===================================== + // MIDDLEWARE + // ===================================== + + // Verify JWT token with MySQL session validation (same as wishboardRoutes) + const requireAuth = async (req, res, next) => { + const token = req.headers.authorization?.split(' ')[1]; + if (!token) { + return res.status(401).json({ error: 'Non authentifié' }); + } + + try { + const decoded = jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] }); + const { sub: userId, userType, sessionId } = decoded; + + if (!['oauth', 'bip39'].includes(userType) || !userId || !sessionId) { + return res.status(401).json({ error: 'Token invalide' }); + } + + if (!mysqlPool) { + return res.status(503).json({ error: 'Service temporairement indisponible' }); + } + + const [rows] = await mysqlPool.execute( + 'SELECT id FROM user_sessions WHERE id = ? AND user_id = ? AND user_type = ?', + [sessionId, userId, userType] + ); + + if (rows.length === 0) { + return res.status(401).json({ error: 'Session invalide ou expirée' }); + } + + req.user = { userId, userType, sessionId }; + next(); + } catch (error) { + return res.status(401).json({ error: 'Token invalide' }); + } + }; + + // Check admin or uploader status + const requireUploaderOrAdmin = async (req, res, next) => { + try { + if (!mysqlPool) { + return res.status(503).json({ error: 'Service temporairement indisponible' }); + } + + const authType = req.user.userType === 'bip39' ? 'bip-39' : req.user.userType; + const [rows] = await mysqlPool.execute( + 'SELECT * FROM admins WHERE user_id = ? AND auth_type = ?', + [req.user.userId, authType] + ); + + if (rows.length === 0) { + return res.status(403).json({ error: 'Accès refusé - Droits requis' }); + } + + const role = rows[0].role || 'admin'; + if (role !== 'admin' && role !== 'uploader') { + return res.status(403).json({ error: 'Accès refusé - Droits insuffisants' }); + } + + req.admin = { userId: req.user.userId, userType: req.user.userType, role }; + next(); + } catch (error) { + console.error('Admin/Uploader check error:', error); + return res.status(500).json({ error: 'Erreur lors de la vérification des droits' }); + } + }; + + // Get profile ID from headers or body + const getProfileId = (req) => { + return req.headers['x-profile-id'] || req.body?.profileId || req.query?.profileId || null; + }; + + // Verify that the profileId belongs to the authenticated user + async function verifyProfileOwnership(userId, userType, profileId) { + try { + const safeUserId = String(userId).replace(/[^a-zA-Z0-9_\-]/g, ''); + let userFilePath; + if (userType === 'bip39') { + userFilePath = path.join(__dirname, 'data', 'users', `bip39-${safeUserId}.json`); + } else { + userFilePath = path.join(__dirname, 'data', 'users', `${safeUserId}.json`); + } + const userFile = await fs.readFile(userFilePath, 'utf8'); + const user = JSON.parse(userFile); + if (user.profiles) { + return user.profiles.some(p => p.id === profileId); + } + return false; + } catch { + return false; + } + } + + // Get user data from JSON files + async function getUserData(userId, userType, profileId = null) { + try { + let userData = { username: 'Utilisateur', avatar: null, isVip: false }; + const safeUserId = String(userId).replace(/[^a-zA-Z0-9_\-]/g, ''); + + let userFilePath; + if (userType === 'bip39') { + userFilePath = path.join(__dirname, 'data', 'users', `bip39-${safeUserId}.json`); + } else { + userFilePath = path.join(__dirname, 'data', 'users', `${safeUserId}.json`); + } + + try { + const userFile = await fs.readFile(userFilePath, 'utf8'); + const user = JSON.parse(userFile); + if (profileId && user.profiles) { + const profile = user.profiles.find(p => p.id === profileId); + if (profile) { + userData.username = profile.name || 'Utilisateur'; + userData.avatar = profile.avatar; + } + } + } catch (err) { + // File not found — keep defaults + } + + return userData; + } catch (error) { + return { username: 'Utilisateur', avatar: null, isVip: false }; + } + } + + // Rate limiting: check submission count (15 movies, 10 unique series per 24h) + const checkSubmissionLimit = async (profileId) => { + // Count movies submitted in last 24h + const [movieResult] = await mysqlPool.execute( + `SELECT COUNT(*) as count FROM link_submissions + WHERE profile_id = ? AND media_type = 'movie' + AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)`, + [profileId] + ); + // Count unique series (by tmdb_id) submitted in last 24h + const [seriesResult] = await mysqlPool.execute( + `SELECT COUNT(DISTINCT tmdb_id) as count FROM link_submissions + WHERE profile_id = ? AND media_type = 'tv' + AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)`, + [profileId] + ); + const movieCount = movieResult[0].count; + const seriesCount = seriesResult[0].count; + const movieLimit = 15; + const seriesLimit = 10; + return { + movies: { count: movieCount, limit: movieLimit, remaining: Math.max(0, movieLimit - movieCount) }, + series: { count: seriesCount, limit: seriesLimit, remaining: Math.max(0, seriesLimit - seriesCount) }, + }; + }; + + // Check if a specific series tmdb_id was already counted in the 24h window + const isSeriesAlreadyCounted = async (profileId, tmdbId) => { + const [result] = await mysqlPool.execute( + `SELECT COUNT(*) as count FROM link_submissions + WHERE profile_id = ? AND media_type = 'tv' AND tmdb_id = ? + AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)`, + [profileId, tmdbId] + ); + return result[0].count > 0; + }; + + // ===================================== + // USER ENDPOINTS + // ===================================== + + /** + * POST /api/link-submissions + * Submit a new link for a movie/episode/season + */ + router.post('/', requireAuth, async (req, res) => { + try { + const { tmdb_id, media_type, season_number, episode_number, url, source_name } = req.body; + const userId = req.user.userId; + const profileId = getProfileId(req); + + if (!profileId) { + return res.status(400).json({ error: 'Profile ID requis' }); + } + + const isOwner = await verifyProfileOwnership(userId, req.user.userType, profileId); + if (!isOwner) { + return res.status(403).json({ error: 'Ce profil ne vous appartient pas' }); + } + + if (!tmdb_id || !media_type || !url) { + return res.status(400).json({ error: 'tmdb_id, media_type et url sont requis' }); + } + + if (!['movie', 'tv'].includes(media_type)) { + return res.status(400).json({ error: 'media_type doit être movie ou tv' }); + } + + // Validate URL format + try { + new URL(url); + } catch { + return res.status(400).json({ error: 'URL invalide' }); + } + + // Basic URL sanitization + const cleanUrl = url.trim(); + if (cleanUrl.length > 2048) { + return res.status(400).json({ error: 'URL trop longue' }); + } + + // Check rate limit based on media type + const limits = await checkSubmissionLimit(profileId); + if (media_type === 'movie') { + if (limits.movies.remaining <= 0) { + return res.status(429).json({ + error: 'Limite de films atteinte (15 films/24h).', + limit_reached: true + }); + } + } else { + // For TV: only count against limit if it's a NEW series + const alreadyCounted = await isSeriesAlreadyCounted(profileId, tmdb_id); + if (!alreadyCounted && limits.series.remaining <= 0) { + return res.status(429).json({ + error: 'Limite de séries atteinte (10 séries/24h).', + limit_reached: true + }); + } + } + + // Check for duplicate (same URL for same content) + const [existing] = await mysqlPool.execute( + `SELECT id FROM link_submissions WHERE tmdb_id = ? AND media_type = ? AND url = ? AND status != 'rejected'`, + [tmdb_id, media_type, cleanUrl] + ); + + if (existing.length > 0) { + return res.status(409).json({ error: 'Ce lien a déjà été soumis pour ce contenu' }); + } + + // Insert submission + const seasonNum = (media_type === 'tv' && season_number !== undefined && season_number !== null) ? parseInt(season_number, 10) : null; + const episodeNum = (media_type === 'tv' && episode_number !== undefined && episode_number !== null) ? parseInt(episode_number, 10) : null; + const sourceName = source_name ? source_name.trim().substring(0, 100) : null; + + const [result] = await mysqlPool.execute( + `INSERT INTO link_submissions + (user_id, profile_id, tmdb_id, media_type, season_number, episode_number, url, source_name, status) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending')`, + [userId, profileId, tmdb_id, media_type, seasonNum, episodeNum, cleanUrl, sourceName] + ); + + res.status(201).json({ + id: result.insertId, + message: 'Lien soumis avec succès ! Il sera examiné par notre équipe.' + }); + } catch (error) { + console.error('Error creating link submission:', error); + res.status(500).json({ error: 'Erreur lors de la soumission du lien' }); + } + }); + + /** + * GET /api/link-submissions/my + * Get current user's submissions + */ + router.get('/my', requireAuth, async (req, res) => { + try { + const profileId = getProfileId(req); + if (!profileId) { + return res.status(400).json({ error: 'Profile ID requis' }); + } + + const isOwner = await verifyProfileOwnership(req.user.userId, req.user.userType, profileId); + if (!isOwner) { + return res.status(403).json({ error: 'Ce profil ne vous appartient pas' }); + } + + const [submissions] = await mysqlPool.execute( + `SELECT * FROM link_submissions WHERE profile_id = ? ORDER BY created_at DESC LIMIT 50`, + [profileId] + ); + + res.json({ submissions }); + } catch (error) { + console.error('Error fetching user submissions:', error); + res.status(500).json({ error: 'Erreur lors de la récupération des soumissions' }); + } + }); + + /** + * GET /api/link-submissions/limits + * Get user's submission rate limit status + */ + router.get('/limits', requireAuth, async (req, res) => { + try { + const profileId = getProfileId(req); + if (!profileId) { + return res.status(400).json({ error: 'Profile ID requis' }); + } + + const isOwner = await verifyProfileOwnership(req.user.userId, req.user.userType, profileId); + if (!isOwner) { + return res.status(403).json({ error: 'Ce profil ne vous appartient pas' }); + } + + const limitStatus = await checkSubmissionLimit(profileId); + res.json(limitStatus); + } catch (error) { + console.error('Error fetching limits:', error); + res.status(500).json({ error: 'Erreur lors de la récupération des limites' }); + } + }); + + /** + * POST /api/link-submissions/bulk + * Submit links for multiple episodes at once (same series, same URL pattern) + */ + router.post('/bulk', requireAuth, async (req, res) => { + try { + const { tmdb_id, media_type, season_number, episode_urls, source_name } = req.body; + const userId = req.user.userId; + const profileId = getProfileId(req); + + if (!profileId) return res.status(400).json({ error: 'Profile ID requis' }); + + const isOwner = await verifyProfileOwnership(userId, req.user.userType, profileId); + if (!isOwner) { + return res.status(403).json({ error: 'Ce profil ne vous appartient pas' }); + } + + if (!tmdb_id || media_type !== 'tv') return res.status(400).json({ error: 'tmdb_id et media_type=tv sont requis' }); + if (!episode_urls || typeof episode_urls !== 'object' || Object.keys(episode_urls).length === 0) return res.status(400).json({ error: 'episode_urls requis (objet {episode_number: url})' }); + if (season_number === undefined || season_number === null) return res.status(400).json({ error: 'season_number requis' }); + + // Validate all URLs + for (const [ep, url] of Object.entries(episode_urls)) { + if (!url || typeof url !== 'string' || !url.trim()) return res.status(400).json({ error: `URL manquante pour l'épisode ${ep}` }); + try { new URL(url.trim()); } catch { return res.status(400).json({ error: `URL invalide pour l'épisode ${ep}` }); } + if (url.trim().length > 2048) return res.status(400).json({ error: `URL trop longue pour l'épisode ${ep}` }); + } + + // Check rate limit (counts as 1 series if not already counted) + const limits = await checkSubmissionLimit(profileId); + const alreadyCounted = await isSeriesAlreadyCounted(profileId, tmdb_id); + if (!alreadyCounted && limits.series.remaining <= 0) { + return res.status(429).json({ error: 'Limite de séries atteinte (10 séries/24h).', limit_reached: true }); + } + + const seasonNum = parseInt(season_number, 10); + const sourceName = source_name ? source_name.trim().substring(0, 100) : null; + let inserted = 0; + let duplicates = 0; + + for (const [epNumStr, epUrl] of Object.entries(episode_urls)) { + const episodeNum = parseInt(epNumStr, 10); + const cleanUrl = String(epUrl).trim(); + // Check duplicate + const [existing] = await mysqlPool.execute( + `SELECT id FROM link_submissions WHERE tmdb_id = ? AND media_type = 'tv' AND season_number = ? AND episode_number = ? AND url = ? AND status != 'rejected'`, + [tmdb_id, seasonNum, episodeNum, cleanUrl] + ); + if (existing.length > 0) { duplicates++; continue; } + + await mysqlPool.execute( + `INSERT INTO link_submissions (user_id, profile_id, tmdb_id, media_type, season_number, episode_number, url, source_name, status) VALUES (?, ?, ?, 'tv', ?, ?, ?, ?, 'pending')`, + [userId, profileId, tmdb_id, seasonNum, episodeNum, cleanUrl, sourceName] + ); + inserted++; + } + + res.status(201).json({ message: `${inserted} épisode(s) soumis`, inserted, duplicates }); + } catch (error) { + console.error('Error bulk submitting:', error); + res.status(500).json({ error: 'Erreur lors de la soumission en masse' }); + } + }); + + /** + * DELETE /api/link-submissions/:id + * User can delete their own pending submission + */ + router.delete('/:id', requireAuth, async (req, res) => { + try { + const submissionId = req.params.id; + const profileId = getProfileId(req); + + if (!profileId) { + return res.status(400).json({ error: 'Profile ID requis' }); + } + + const isOwner = await verifyProfileOwnership(req.user.userId, req.user.userType, profileId); + if (!isOwner) { + return res.status(403).json({ error: 'Ce profil ne vous appartient pas' }); + } + + // Only allow deleting own submissions that are still pending + const [result] = await mysqlPool.execute( + `DELETE FROM link_submissions WHERE id = ? AND profile_id = ? AND status = 'pending'`, + [submissionId, profileId] + ); + + if (result.affectedRows === 0) { + return res.status(404).json({ error: 'Soumission non trouvée ou déjà traitée' }); + } + + res.json({ message: 'Soumission supprimée' }); + } catch (error) { + console.error('Error deleting submission:', error); + res.status(500).json({ error: 'Erreur lors de la suppression' }); + } + }); + + // ===================================== + // ADMIN ENDPOINTS + // ===================================== + + /** + * GET /api/link-submissions/admin + * Admin: list all submissions with filters + */ + router.get('/admin', requireAuth, requireUploaderOrAdmin, async (req, res) => { + try { + const { status = 'pending', media_type, search, page = 1, limit = 50 } = req.query; + const offset = (parseInt(page) - 1) * parseInt(limit); + + let whereConditions = ['1=1']; + let whereParams = []; + + if (status && status !== 'all') { + whereConditions.push('ls.status = ?'); + whereParams.push(status); + } + + if (media_type && media_type !== 'all') { + whereConditions.push('ls.media_type = ?'); + whereParams.push(media_type); + } + + if (search) { + const numSearch = parseInt(search); + if (!isNaN(numSearch)) { + whereConditions.push('(ls.tmdb_id = ? OR ls.id = ?)'); + whereParams.push(numSearch, numSearch); + } else { + whereConditions.push('(ls.url LIKE ? OR ls.source_name LIKE ?)'); + whereParams.push(`%${search}%`, `%${search}%`); + } + } + + const whereClause = whereConditions.join(' AND '); + + const [submissions] = await mysqlPool.execute( + `SELECT ls.* FROM link_submissions ls + WHERE ${whereClause} + ORDER BY ls.created_at DESC + LIMIT ? OFFSET ?`, + [...whereParams, parseInt(limit), offset] + ); + + // Enrich with user data + const enriched = await Promise.all(submissions.map(async (sub) => { + let user = { username: 'Inconnu', avatar: null }; + try { + let userType = 'oauth'; + try { + await fs.access(path.join(__dirname, 'data', 'users', `bip39-${sub.user_id}.json`)); + userType = 'bip39'; + } catch { /* keep oauth */ } + user = await getUserData(sub.user_id, userType, sub.profile_id); + } catch { /* ignore */ } + return { ...sub, user }; + })); + + // Get stats + const [statsResult] = await mysqlPool.execute(` + SELECT + COUNT(*) as total, + SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending, + SUM(CASE WHEN status = 'approved' THEN 1 ELSE 0 END) as approved, + SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected + FROM link_submissions + `); + + // Get total count for pagination + const [countResult] = await mysqlPool.execute( + `SELECT COUNT(*) as total FROM link_submissions ls WHERE ${whereClause}`, + whereParams + ); + + res.json({ + submissions: enriched, + has_more: countResult[0].total > offset + submissions.length, + stats: { + total: statsResult[0].total || 0, + pending: statsResult[0].pending || 0, + approved: statsResult[0].approved || 0, + rejected: statsResult[0].rejected || 0 + } + }); + } catch (error) { + console.error('Error fetching admin submissions:', error); + res.status(500).json({ error: 'Erreur lors de la récupération des soumissions' }); + } + }); + + /** + * PUT /api/link-submissions/admin/:id/approve + * Admin: approve a submission and add the link to films/series table + */ + router.put('/admin/:id/approve', requireAuth, requireUploaderOrAdmin, async (req, res) => { + try { + const submissionId = req.params.id; + + // Get the submission + const [submissions] = await mysqlPool.execute( + 'SELECT * FROM link_submissions WHERE id = ?', + [submissionId] + ); + + if (submissions.length === 0) { + return res.status(404).json({ error: 'Soumission non trouvée' }); + } + + const sub = submissions[0]; + + if (sub.status !== 'pending') { + return res.status(400).json({ error: 'Cette soumission a déjà été traitée' }); + } + + // Add the link to the appropriate table + if (sub.media_type === 'movie') { + // Check if film exists + const [existing] = await mysqlPool.execute('SELECT id, links FROM films WHERE id = ?', [sub.tmdb_id]); + + if (existing.length > 0) { + // Merge link + let currentLinks = []; + try { + currentLinks = JSON.parse(existing[0].links || '[]'); + } catch { currentLinks = []; } + + if (!currentLinks.includes(sub.url)) { + currentLinks.push(sub.url); + } + + await mysqlPool.execute( + 'UPDATE films SET links = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', + [JSON.stringify(currentLinks), sub.tmdb_id] + ); + } else { + // Create new entry + await mysqlPool.execute( + 'INSERT INTO films (id, links) VALUES (?, ?)', + [sub.tmdb_id, JSON.stringify([sub.url])] + ); + } + } else if (sub.media_type === 'tv') { + const seasonNum = sub.season_number; + const episodeNum = sub.episode_number; + + if (seasonNum !== null && episodeNum !== null) { + // Specific episode + const [existing] = await mysqlPool.execute( + 'SELECT id, links FROM series WHERE series_id = ? AND season_number = ? AND episode_number = ?', + [sub.tmdb_id, seasonNum, episodeNum] + ); + + if (existing.length > 0) { + let currentLinks = []; + try { + currentLinks = JSON.parse(existing[0].links || '[]'); + } catch { currentLinks = []; } + + if (!currentLinks.includes(sub.url)) { + currentLinks.push(sub.url); + } + + await mysqlPool.execute( + 'UPDATE series SET links = ? WHERE series_id = ? AND season_number = ? AND episode_number = ?', + [JSON.stringify(currentLinks), sub.tmdb_id, seasonNum, episodeNum] + ); + } else { + await mysqlPool.execute( + 'INSERT INTO series (series_id, season_number, episode_number, links) VALUES (?, ?, ?, ?)', + [sub.tmdb_id, seasonNum, episodeNum, JSON.stringify([sub.url])] + ); + } + } + } + + // Update submission status + await mysqlPool.execute( + `UPDATE link_submissions SET status = 'approved', reviewed_by = ?, reviewed_at = NOW() WHERE id = ?`, + [req.admin.userId, submissionId] + ); + + res.json({ message: 'Lien approuvé et ajouté avec succès' }); + } catch (error) { + console.error('Error approving submission:', error); + res.status(500).json({ error: 'Erreur lors de l\'approbation' }); + } + }); + + /** + * PUT /api/link-submissions/admin/:id/reject + * Admin: reject a submission with optional reason + */ + router.put('/admin/:id/reject', requireAuth, requireUploaderOrAdmin, async (req, res) => { + try { + const submissionId = req.params.id; + const { reason } = req.body; + + const [submissions] = await mysqlPool.execute( + 'SELECT * FROM link_submissions WHERE id = ?', + [submissionId] + ); + + if (submissions.length === 0) { + return res.status(404).json({ error: 'Soumission non trouvée' }); + } + + if (submissions[0].status !== 'pending') { + return res.status(400).json({ error: 'Cette soumission a déjà été traitée' }); + } + + await mysqlPool.execute( + `UPDATE link_submissions SET status = 'rejected', rejection_reason = ?, reviewed_by = ?, reviewed_at = NOW() WHERE id = ?`, + [reason || null, req.admin.userId, submissionId] + ); + + res.json({ message: 'Soumission rejetée' }); + } catch (error) { + console.error('Error rejecting submission:', error); + res.status(500).json({ error: 'Erreur lors du rejet' }); + } + }); + + /** + * PUT /api/link-submissions/admin/bulk-approve + * Admin: approve multiple submissions at once + */ + router.put('/admin/bulk-approve', requireAuth, requireUploaderOrAdmin, async (req, res) => { + try { + const { ids } = req.body; + if (!ids || !Array.isArray(ids) || ids.length === 0) { + return res.status(400).json({ error: 'IDs requis' }); + } + + let approved = 0; + let errors = 0; + + for (const id of ids) { + try { + const [submissions] = await mysqlPool.execute( + 'SELECT * FROM link_submissions WHERE id = ? AND status = ?', + [id, 'pending'] + ); + + if (submissions.length === 0) { + errors++; + continue; + } + + const sub = submissions[0]; + + // Add link to appropriate table + if (sub.media_type === 'movie') { + const [existing] = await mysqlPool.execute('SELECT id, links FROM films WHERE id = ?', [sub.tmdb_id]); + if (existing.length > 0) { + let currentLinks = []; + try { currentLinks = JSON.parse(existing[0].links || '[]'); } catch { currentLinks = []; } + if (!currentLinks.includes(sub.url)) currentLinks.push(sub.url); + await mysqlPool.execute('UPDATE films SET links = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', [JSON.stringify(currentLinks), sub.tmdb_id]); + } else { + await mysqlPool.execute('INSERT INTO films (id, links) VALUES (?, ?)', [sub.tmdb_id, JSON.stringify([sub.url])]); + } + } else if (sub.media_type === 'tv' && sub.season_number !== null && sub.episode_number !== null) { + const [existing] = await mysqlPool.execute('SELECT id, links FROM series WHERE series_id = ? AND season_number = ? AND episode_number = ?', [sub.tmdb_id, sub.season_number, sub.episode_number]); + if (existing.length > 0) { + let currentLinks = []; + try { currentLinks = JSON.parse(existing[0].links || '[]'); } catch { currentLinks = []; } + if (!currentLinks.includes(sub.url)) currentLinks.push(sub.url); + await mysqlPool.execute('UPDATE series SET links = ? WHERE series_id = ? AND season_number = ? AND episode_number = ?', [JSON.stringify(currentLinks), sub.tmdb_id, sub.season_number, sub.episode_number]); + } else { + await mysqlPool.execute('INSERT INTO series (series_id, season_number, episode_number, links) VALUES (?, ?, ?, ?)', [sub.tmdb_id, sub.season_number, sub.episode_number, JSON.stringify([sub.url])]); + } + } + + await mysqlPool.execute( + `UPDATE link_submissions SET status = 'approved', reviewed_by = ?, reviewed_at = NOW() WHERE id = ?`, + [req.admin.userId, id] + ); + approved++; + } catch (err) { + console.error(`Error approving submission ${id}:`, err); + errors++; + } + } + + res.json({ message: `${approved} lien(s) approuvé(s)`, approved, errors }); + } catch (error) { + console.error('Error bulk approving:', error); + res.status(500).json({ error: 'Erreur lors de l\'approbation en masse' }); + } + }); + + /** + * PUT /api/link-submissions/admin/bulk-reject + * Admin: reject multiple submissions at once + */ + router.put('/admin/bulk-reject', requireAuth, requireUploaderOrAdmin, async (req, res) => { + try { + const { ids, reason } = req.body; + if (!ids || !Array.isArray(ids) || ids.length === 0) { + return res.status(400).json({ error: 'IDs requis' }); + } + + const placeholders = ids.map(() => '?').join(','); + await mysqlPool.execute( + `UPDATE link_submissions SET status = 'rejected', rejection_reason = ?, reviewed_by = ?, reviewed_at = NOW() WHERE id IN (${placeholders}) AND status = 'pending'`, + [reason || null, req.admin.userId, ...ids] + ); + + res.json({ message: `${ids.length} soumission(s) rejetée(s)` }); + } catch (error) { + console.error('Error bulk rejecting:', error); + res.status(500).json({ error: 'Erreur lors du rejet en masse' }); + } + }); + + /** + * DELETE /api/link-submissions/admin/:id + * Admin: permanently delete a submission + */ + router.delete('/admin/:id', requireAuth, requireUploaderOrAdmin, async (req, res) => { + try { + const submissionId = req.params.id; + await mysqlPool.execute('DELETE FROM link_submissions WHERE id = ?', [submissionId]); + res.json({ message: 'Soumission supprimée' }); + } catch (error) { + console.error('Error deleting submission:', error); + res.status(500).json({ error: 'Erreur lors de la suppression' }); + } + }); + + return router; +} + +module.exports = { createLinkSubmissionsRouter }; diff --git a/API/Mainapi/liveTvRoutes.js b/API/Mainapi/liveTvRoutes.js new file mode 100644 index 0000000..9c66709 --- /dev/null +++ b/API/Mainapi/liveTvRoutes.js @@ -0,0 +1,4469 @@ +/** + * Live TV Routes - Backend API pour TV en Direct + * + * Ce module gère les requêtes vers l'API Stremio TV Direct + * avec mise en cache et résolution des URLs de streaming. + */ + +const express = require("express"); +const axios = require("axios"); +const path = require("path"); +const fsp = require("fs").promises; +const crypto = require("crypto"); +const cheerio = require("cheerio"); +const { SocksProxyAgent } = require("socks-proxy-agent"); +const { verifyAccessKey, requireVip } = require("./checkVip"); + +// SOCKS5H Proxy configuration pour WITV +const WITV_PROXY_URL = process.env.WITV_SOCKS5_PROXY_URL || ""; +const WITV_PROXY_AGENT = WITV_PROXY_URL + ? new SocksProxyAgent(WITV_PROXY_URL) + : null; + +const router = express.Router(); + +// === CONFIGURATION === +const TVDIRECT_BASE_URL = "https://tvdirect.ddns.net"; +// URL de base pour la source Vavoo (configuration France) +const VAVOO_BASE_URL = "https://tvvoo.hayd.uk/cfg-fr"; +// URL du serveur proxy local (proxiesembed) +const PROXY_SERVER_URL = process.env.PROXY_SERVER_URL; +const M3U_PATH = path.join(__dirname, "france.m3u"); + +// URL de base pour TVMio (Stremio addon) +const TVMIO_BASE_URL = + "https://tvmio.gleeze.com/eyJjb3VudHJpZXMiOlsiRlIiXSwiY2F0ZWdvcmllcyI6eyJGUiI6WyJHZW5lcmFsIPCfk7oiLCJTcG9ydHMg4pq9IiwiRG9jdW1lbnRhaXJlcyDwn4yNIiwiRmlsbXMg8J+OrCIsIkluZm9ybWF0aW9ucyDwn5OwIiwiRW5mYW50cyDwn5G2IiwiTXVzaWMg8J+OtSJdfSwiZW5hYmxlU2VhcmNoIjpmYWxzZX0"; + +// TVMio categories mapping (catalogId -> group-title filter) +const TVMIO_CATEGORIES = { + tvmio_general: { + genre: "FR | General", + remoteGenre: "General 📺", + name: "Généraliste 📺", + emoji: "📺", + }, + tvmio_sports: { + genre: "FR | Sports", + remoteGenre: "Sports ⚽", + name: "Sports ⚽", + emoji: "⚽", + }, + tvmio_documentaires: { + genre: "FR | Documentaires", + remoteGenre: "Documentaires 🌍", + name: "Documentaires 🌍", + emoji: "🌍", + }, + tvmio_films: { + genre: "FR | Films", + remoteGenre: "Films 🎬", + name: "Films 🎬", + emoji: "🎬", + }, + tvmio_informations: { + genre: "FR | Informations", + remoteGenre: "Informations 📰", + name: "Informations 📰", + emoji: "📰", + }, + tvmio_enfants: { + genre: "FR | Enfants", + remoteGenre: "Enfants 👶", + name: "Enfants 👶", + emoji: "👶", + }, + tvmio_music: { + genre: "FR | Musique", + remoteGenre: "Music 🎵", + name: "Musique 🎵", + emoji: "🎵", + }, +}; + +// URL de base pour Wiflix (Witv) +const WITV_BASE_URL = "https://witv.team"; +// Cloudflare proxy for 403 bypass (livehdtv) +const CF_PROXY_403 = process.env.CF_PROXY_403_URL; + +const WITV_CATEGORIES = { + wiflix_generaliste: "/chaines-live/generaliste/", + wiflix_cinema: "/chaines-live/cinema/", + wiflix_sport: "/chaines-live/sport/", + wiflix_documentaire: "/chaines-live/documentaire/", + wiflix_enfants: "/chaines-live/enfants/", + wiflix_info: "/chaines-live/info/", + wiflix_musique: "/chaines-live/musique/", +}; + +// URL de base pour Sosplay +const SOSPLAY_BASE_URL = "https://ligue1live.xyz"; + +// Source Bolaloca/Elitegol (remplace l'ancien catalogue Sosplay pour les chaines) +const BOLALOCA_BASE_URL = "https://bolaloca.my"; +const BOLALOCA_PLAYER_VARIANTS = [2, 4, 3, 1]; +const BOLALOCA_CHANNELS = [ + { + id: "20", + name: "Ligue 1+", + poster: "https://www.lensois.com/wp-content/uploads/2025/07/ligue-1-1.jpg", + }, + { + id: "21", + name: "Ligue 1+ CH2", + poster: + "https://www.monpetitforfait.com/comparateur-box-internet/wp-content/uploads/2025/07/ligue-1-plus-2.png", + }, + { + id: "22", + name: "Ligue 1+ CH3", + poster: + "https://www.monpetitforfait.com/comparateur-box-internet/wp-content/uploads/2025/07/ligue-1plus-3-box-internet-300x95.png", + }, + { + id: "39", + name: "Ligue 1+ CH4", + poster: + "https://www.monpetitforfait.com/comparateur-box-internet/wp-content/uploads/2025/07/ligue-1plus-4-box-internet-300x106.png", + }, + { + id: "40", + name: "Ligue 1+ CH5", + poster: + "https://www.monpetitforfait.com/comparateur-box-internet/wp-content/uploads/2025/07/ligue-1-plus-5.png", + }, + { + id: "11", + name: "Canal+", + poster: + "https://thumb.canalplus.pro/http/unsafe/epg.canal-plus.com/mycanal/img/CHN43FN/PNG/213X160/CHN43FB_301.PNG", + }, + { + id: "12", + name: "Canal+ Foot", + poster: "https://upload.wikimedia.org/wikipedia/fr/3/3b/C%2B_Foot.png", + }, + { + id: "13", + name: "Canal+ Sport", + poster: + "https://upload.wikimedia.org/wikipedia/fr/2/2c/C%2B_Sport_%282023%29.png", + }, + { + id: "14", + name: "Canal+ Sport 360", + poster: "https://upload.wikimedia.org/wikipedia/fr/1/11/C%2B_Sport_360.png", + }, + { + id: "17", + name: "RMC Sport 1", + poster: + "https://i0.wp.com/www.planetecsat.com/wp-content/uploads/2018/07/RMC_SPORT1_PNG_500x500px.png?w=500&ssl=1", + }, + { + id: "18", + name: "RMC Sport 2", + poster: + "https://i0.wp.com/www.planetecsat.com/wp-content/uploads/2018/07/RMC_SPORT2_PNG_500x500px.png?fit=500%2C500&ssl=1", + }, + { + id: "15", + name: "Eurosport 1", + poster: + "https://2.bp.blogspot.com/-qEkUoydNN-E/WvMoKma36fI/AAAAAAAAG_0/ov-d571uhZ443Nai7gdU9sSIV2IBOkquQCLcBGAs/s1600/europsort-1-HD.jpg", + }, + { + id: "16", + name: "Eurosport 2", + poster: + "https://4.bp.blogspot.com/-1bHZ8b5ZnW0/VzDh6KfzayI/AAAAAAAABsI/lKDWcPmyBSk7etoAj2DVr7nvQ5SsMPwzgCLcB/s1600/fhuxmcp92wg1w4y9pd2v4zjz3xs1vmjm.jpg", + }, + { + id: "19", + name: "L'Equipe", + poster: + "https://www.cse.fr/wp-content/uploads/2016/02/LEquipe_logo-300x200-300x150.png", + }, + { + id: "23", + name: "Automoto", + poster: + "https://moto-station.com/wp-content/uploads/2021/05/05/Automoto-La-Chaine-logo_0.png.jpg", + }, + { + id: "31", + name: "Canal+ Live 1", + poster: "https://www.lyngsat.com/logo/tv/cc/canal-plus-live-1-fr.png", + }, + { + id: "32", + name: "Canal+ Live 2", + poster: "https://www.lyngsat.com/logo/tv/cc/canal-plus-live-2-fr.png", + }, + { + id: "33", + name: "Canal+ Live 3", + poster: "https://www.lyngsat.com/logo/tv/cc/canal-plus-live-3-fr.png", + }, + { + id: "1", + name: "beIN Sports 1", + poster: + "https://r2.thesportsdb.com/images/media/channel/logo/BeIn_Sports_1_Australia.png", + }, + { + id: "2", + name: "beIN Sports 2", + poster: + "https://r2.thesportsdb.com/images/media/channel/logo/BeIn_Sports_2_Australia.png", + }, + { + id: "3", + name: "beIN Sports 3", + poster: + "https://r2.thesportsdb.com/images/media/channel/logo/BeIn_Sports_3_Australia.png", + }, + { + id: "4", + name: "beIN Sports MAX 4", + poster: + "https://r2.thesportsdb.com/images/media/channel/logo/BeIn_Sports_Max_4.png", + }, + { + id: "5", + name: "beIN Sports MAX 5", + poster: + "https://r2.thesportsdb.com/images/media/channel/logo/BeIn_Sports_Max_5.png", + }, + { + id: "6", + name: "beIN Sports MAX 6", + poster: + "https://r2.thesportsdb.com/images/media/channel/logo/BeIn_Sports_Max_6.png", + }, + { + id: "7", + name: "beIN Sports MAX 7", + poster: + "https://r2.thesportsdb.com/images/media/channel/logo/BeIn_Sports_Max_7.png", + }, + { + id: "8", + name: "beIN Sports MAX 8", + poster: + "https://r2.thesportsdb.com/images/media/channel/logo/BeIn_Sports_Max_8.png", + }, + { + id: "9", + name: "beIN Sports MAX 9", + poster: + "https://r2.thesportsdb.com/images/media/channel/logo/BeIn_Sports_Max_9.png", + }, + { + id: "10", + name: "beIN Sports MAX 10", + poster: + "https://r2.thesportsdb.com/images/media/channel/logo/BeIn_Sports_Max_10.png", + }, +]; + +const LIVETV_BASE_URL = "https://livetv873.me"; +const LIVETV_EMBED_REFERER = `${LIVETV_BASE_URL}/`; +const LIVETV_ALLUPCOMING_PATHS = ["/frx/allupcoming/", "/frx/ads/"]; +const LIVETV_CATEGORIES = { + livetv_all: { name: "Tous les sports", emoji: "📅", sportKey: "all" }, + livetv_live: { name: "En direct", emoji: "🔴", sportKey: "live" }, + livetv_football: { name: "Football", emoji: "⚽", sportKey: "football" }, + livetv_hockey: { name: "Hockey", emoji: "🏒", sportKey: "hockey" }, + livetv_basketball: { + name: "Basketball", + emoji: "🏀", + sportKey: "basketball", + }, + livetv_tennis: { name: "Tennis", emoji: "🎾", sportKey: "tennis" }, + livetv_volleyball: { + name: "Volley-ball", + emoji: "🏐", + sportKey: "volleyball", + }, + livetv_handball: { name: "Handball", emoji: "🤾", sportKey: "handball" }, + livetv_rugby: { name: "Rugby", emoji: "🏉", sportKey: "rugby" }, + livetv_combat: { name: "Sports de combat", emoji: "🥊", sportKey: "combat" }, + livetv_motorsport: { + name: "Sports mecaniques", + emoji: "🏎️", + sportKey: "motorsport", + }, + livetv_winter: { name: "Sports d'hiver", emoji: "🎿", sportKey: "winter" }, + livetv_athletics: { name: "Athletisme", emoji: "🏃", sportKey: "athletics" }, + livetv_other: { name: "Autres sports", emoji: "🏟️", sportKey: "other" }, +}; +const LIVETV_SPORT_ALIASES = { + football: ["football", "soccer", "futsal"], + hockey: ["hockey sur glace", "ice hockey", "hockey"], + basketball: ["basketball", "basket"], + tennis: ["tennis"], + volleyball: ["volley-ball", "volleyball", "volley ball", "volley"], + handball: ["handball"], + rugby: ["rugby"], + combat: [ + "boxe", + "boxing", + "mma", + "ufc", + "kickboxing", + "muay thai", + "wrestling", + "lutte", + "combat", + ], + motorsport: [ + "courses", + "motogp", + "formula 1", + "formule 1", + "rally", + "rallye", + "nascar", + "indycar", + "motorsport", + "auto racing", + ], + winter: [ + "sport d'hiver", + "sports d'hiver", + "winter sports", + "ski", + "biathlon", + "snowboard", + "curling", + "patinage", + ], + athletics: [ + "course a pied", + "course a pied", + "course à pied", + "athletisme", + "athletism", + "athletisme...", + "athletisme…", + "marathon", + "trail", + "running", + ], +}; +const LIVETV_SPORT_EMOJIS = Object.fromEntries( + Object.values(LIVETV_CATEGORIES) + .filter( + (config) => + config.sportKey && + config.sportKey !== "all" && + config.sportKey !== "live", + ) + .map((config) => [config.sportKey, config.emoji || "🏟️"]), +); + +// Sosplay categories +const SOSPLAY_CATEGORIES = { + sosplay_chaines: "/livetv-sport-france-streaming-gratuit", +}; + +// Sosplay Matches categories (for live sports events) +const SOSPLAY_MATCHES_CATEGORIES = { + matches_football: { + path: "/type.php?type=Football", + name: "Football", + emoji: "⚽", + }, +}; + +// Linkzy configuration (FREE source - no extension/VIP required) +const LINKZY_CATEGORIES = { + general: { id: "linkzy_generaliste", name: "Généraliste", emoji: "📺" }, + sports: { id: "linkzy_sport", name: "Sport", emoji: "⚽" }, + movies: { id: "linkzy_cinema", name: "Cinéma", emoji: "🎬" }, + chaines_info: { id: "linkzy_info", name: "Informations", emoji: "📰" }, + chaines_jeunesse: { id: "linkzy_jeunesse", name: "Jeunesse", emoji: "👶" }, +}; + +// HTTPS Agent for Sosplay — DNS Cloudflare (1.1.1.1) pour contourner le blocage FAI +const https = require("https"); +const dns = require("dns"); +const cloudflareDns = new dns.Resolver(); +cloudflareDns.setServers(["1.1.1.1", "1.0.0.1"]); + +const cloudflareLookup = (hostname, options, callback) => { + if (typeof options === "function") { + callback = options; + options = {}; + } + cloudflareDns.resolve4(hostname, (err, addresses) => { + if (err) return callback(err); + if (options.all) { + callback( + null, + addresses.map((addr) => ({ address: addr, family: 4 })), + ); + } else { + callback(null, addresses[0], 4); + } + }); +}; + +const SOSPLAY_HTTPS_AGENT = new https.Agent({ + rejectUnauthorized: false, + lookup: cloudflareLookup, + maxSockets: 50, + maxFreeSockets: 10, +}); + +const STREAM_PROXY_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"; +const LIVE_PAGE_USER_AGENT = + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36"; + +const CACHE_DIR = path.join(__dirname, "cache", "tvdirect"); +const CACHE_EXPIRATION_HOURS = 24; // Cache expire après 24h + +// Headers Stremio pour les requêtes (principalement TV Direct) +const STREMIO_HEADERS = { + "User-Agent": + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Stremio/4.4.162 Chrome/114.0.0.0 Safari/537.36", + Accept: "application/json, text/plain, */*", + Origin: "https://app.strem.io", + Referer: "https://app.strem.io/", + "Accept-Language": "fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7", + "Accept-Encoding": "gzip, deflate, br", +}; + +// In-memory M3U cache to avoid re-reading/re-parsing on every request +let m3uCache = null; +let m3uCacheTime = 0; +const M3U_CACHE_TTL = 10 * 60 * 1000; // 10 minutes + +/** + * Parse local M3U file (cached) + */ +async function parseM3u() { + // Return cached data if still fresh + if (m3uCache && Date.now() - m3uCacheTime < M3U_CACHE_TTL) { + return m3uCache; + } + try { + const content = await fsp.readFile(M3U_PATH, "utf8"); + const lines = content.split(/\r?\n/); + const channels = []; + let currentChannel = null; + + for (const line of lines) { + const trimmed = line.trim(); + if (!trimmed) continue; + + if (trimmed.startsWith("#EXTINF:")) { + currentChannel = {}; + // Parse attributes + const attrs = trimmed.match(/([a-zA-Z0-9-]+)="([^"]*)"/g); + if (attrs) { + for (const attr of attrs) { + const [key, val] = attr.split("="); + const value = val.replace(/"/g, ""); + if (key === "tvg-id") currentChannel.id = value; + if (key === "tvg-name") currentChannel.name = value; + if (key === "tvg-logo") currentChannel.logo = value; + if (key === "tvg-poster") currentChannel.poster = value; + if (key === "group-title") currentChannel.group = value; + if (key === "tvg-back") currentChannel.background = value; + } + } + + // Name after comma + const commaIndex = trimmed.lastIndexOf(","); + if (commaIndex !== -1) { + currentChannel.title = trimmed.substring(commaIndex + 1).trim(); + } else { + currentChannel.title = currentChannel.name || "Unknown"; + } + } else if (!trimmed.startsWith("#") && currentChannel) { + currentChannel.stream = trimmed; + // If no ID, generate one from title + if (!currentChannel.id) { + currentChannel.id = currentChannel.title.replace(/[^a-zA-Z0-9]/g, ""); + } + channels.push(currentChannel); + currentChannel = null; // Reset for next channel + } + } + // Cache the parsed result + m3uCache = channels; + m3uCacheTime = Date.now(); + return channels; + } catch (error) { + console.error("[M3U] Error parsing france.m3u:", error.message); + return []; + } +} + +function normalizeTvmioImageKey(value) { + if (!value) return ""; + return String(value) + .toLowerCase() + .normalize("NFD") + .replace(/[\u0300-\u036f]/g, "") + .replace(/\.(fr|be|ch|ca|uk|us)$/g, " ") + .replace(/\b(fr|fhd|uhd|hd|sd|4k)\b/g, " ") + .replace(/[|_\-]+/g, " ") + .replace(/[^a-z0-9 ]+/g, " ") + .replace(/\s+/g, " ") + .trim(); +} + +async function fetchTvmioCatalogMetas(catalogId) { + const cacheKey = generateCacheKey(`tvmio_remote_catalog_v2_${catalogId}`); + const cached = await getFromCache(cacheKey, 24); + if (cached) return cached; + + try { + const categoryConfig = TVMIO_CATEGORIES[catalogId]; + if (!categoryConfig?.remoteGenre) { + return []; + } + + const encodedGenre = encodeURIComponent(categoryConfig.remoteGenre); + const url = `${TVMIO_BASE_URL}/catalog/tv/tvmio-fr/genre=${encodedGenre}.json`; + const response = await axios.get(url, { + headers: STREMIO_HEADERS, + timeout: 12000, + }); + + const metas = Array.isArray(response.data?.metas) + ? response.data.metas + : []; + await saveToCache(cacheKey, metas); + return metas; + } catch (error) { + console.warn( + `[TVMIO] Unable to fetch remote catalog images for ${catalogId}: ${error.message}`, + ); + return []; + } +} + +function buildTvmioImagesMap(remoteMetas) { + const imageMap = new Map(); + + for (const meta of remoteMetas) { + const imageData = { + poster: meta?.poster || null, + logo: meta?.logo || null, + background: meta?.background || null, + }; + + const normalizedId = normalizeTvmioImageKey(meta?.id); + const normalizedName = normalizeTvmioImageKey(meta?.name); + + if (normalizedId) imageMap.set(`id:${normalizedId}`, imageData); + if (normalizedName) imageMap.set(`name:${normalizedName}`, imageData); + } + + return imageMap; +} + +function getTvmioRemoteImages(channel, imageMap) { + const idRaw = channel?.id || ""; + const titleRaw = channel?.title || channel?.name || ""; + + const idNormalized = normalizeTvmioImageKey(idRaw); + const idBaseNormalized = normalizeTvmioImageKey(idRaw.split(".")[0]); + const titleNormalized = normalizeTvmioImageKey(titleRaw); + + return ( + imageMap.get(`id:${idNormalized}`) || + imageMap.get(`id:${idBaseNormalized}`) || + imageMap.get(`name:${titleNormalized}`) || { + poster: null, + logo: null, + background: null, + } + ); +} + +// === UTILITAIRES DE CACHE === + +// Créer le dossier de cache s'il n'existe pas +(async () => { + try { + await fsp.access(CACHE_DIR); + } catch { + await fsp.mkdir(CACHE_DIR, { recursive: true }); + console.log("✅ Live TV cache directory created"); + } +})(); + +/** + * Génère une clé de cache MD5 basée sur les paramètres + */ +function generateCacheKey(params) { + const stringParams = + typeof params === "string" ? params : JSON.stringify(params); + return crypto.createHash("md5").update(stringParams).digest("hex"); +} + +/** + * Récupère des données du cache avec vérification d'expiration + */ +async function getFromCache(key, expirationHours = CACHE_EXPIRATION_HOURS) { + try { + const cacheFilePath = path.join(CACHE_DIR, `${key}.json`); + const stats = await fsp.stat(cacheFilePath); + const now = Date.now(); + const fileTime = stats.mtime.getTime(); + const expirationTime = expirationHours * 60 * 60 * 1000; + + if (now - fileTime > expirationTime) { + return null; // Cache expiré + } + + const cacheData = JSON.parse(await fsp.readFile(cacheFilePath, "utf8")); + return cacheData; + } catch (error) { + if (error.code === "ENOENT") { + return null; + } + console.error(`[LIVETV CACHE] Erreur lecture cache ${key}:`, error.message); + return null; + } +} + +/** + * Récupère des données du cache avec expiration en millisecondes + */ +async function getFromCacheMs(key, expirationMs = 30000) { + try { + const cacheFilePath = path.join(CACHE_DIR, `${key}.json`); + const stats = await fsp.stat(cacheFilePath); + const now = Date.now(); + const fileTime = stats.mtime.getTime(); + + if (now - fileTime > expirationMs) { + return null; // Cache expiré + } + + const cacheData = JSON.parse(await fsp.readFile(cacheFilePath, "utf8")); + return cacheData; + } catch (error) { + if (error.code === "ENOENT") { + return null; + } + console.error(`[LIVETV CACHE] Erreur lecture cache ${key}:`, error.message); + return null; + } +} + +/** + * Sauvegarde des données en cache + */ +async function saveToCache(key, data) { + try { + const cacheFilePath = path.join(CACHE_DIR, `${key}.json`); + await fsp.writeFile(cacheFilePath, JSON.stringify(data, null, 2), "utf8"); + return true; + } catch (error) { + console.error( + `[LIVETV CACHE] Erreur sauvegarde cache ${key}:`, + error.message, + ); + return false; + } +} + +/** + * Résout l'URL de lecture pour obtenir le lien m3u8 final + * Suit les redirections et récupère le header Location + */ +async function resolvePlayUrl(playUrl) { + try { + const response = await axios.get(playUrl, { + headers: STREMIO_HEADERS, + timeout: 10000, + maxRedirects: 0, // Ne pas suivre les redirections automatiquement + validateStatus: (status) => status >= 200 && status < 400, // Accepter 2xx et 3xx + }); + + // Si c'est une redirection (302, 301), récupérer le header Location + if (response.status === 302 || response.status === 301) { + return response.headers.location || null; + } + + // Sinon retourner l'URL originale (peut-être déjà un m3u8) + return playUrl; + } catch (error) { + // Si erreur avec response (ex: 302), essayer de récupérer Location + if ( + error.response && + (error.response.status === 302 || error.response.status === 301) + ) { + return error.response.headers.location || null; + } + console.error(`[LIVETV] Erreur résolution URL ${playUrl}:`, error.message); + return null; + } +} + +// === WITV (WIFLIX) SCRAPING FUNCTIONS === + +/** + * Scrape les chaînes disponibles depuis une catégorie Witv + */ +async function scrapeWitvChannels(categoryKey) { + try { + const pathUrl = WITV_CATEGORIES[categoryKey]; + if (!pathUrl) { + console.log(`[WITV] Unknown category: ${categoryKey}`); + return []; + } + + const fullUrl = `${WITV_BASE_URL}${pathUrl}`; + console.log(`[WITV] Scraping category ${categoryKey} from ${fullUrl}`); + + const response = await axios.get(fullUrl, { + headers: { + "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", + Accept: + "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", + }, + timeout: 15000, + httpAgent: WITV_PROXY_AGENT, + httpsAgent: WITV_PROXY_AGENT, + }); + + const $ = cheerio.load(response.data); + const channels = []; + + console.log(`[WITV] Page loaded, length: ${response.data.length} bytes`); + + // Pattern 1: .holographic-card with .ann-short_price for name + $(".holographic-card").each((index, element) => { + const $el = $(element); + + // Name: .ann-short_price + const name = $el.find(".ann-short_price").text().trim(); + + // Link: a href + const link = $el.find("a").attr("href"); + + if (name && link) { + // Extract ID from link (e.g. .../40-mtv.html -> 40) + const idMatch = link.match(/\/(\d+)-/); + if (idMatch) { + const id = idMatch[1]; + // Also extract the slug for the channel page URL + const slugMatch = link.match(/\/(\d+-[^\/]+\.html)$/); + const pageSlug = slugMatch ? slugMatch[1] : null; + channels.push({ + id: `wiflix_${id}`, + type: "tv", + name: name, + poster: null, + genres: [categoryKey.replace("wiflix_", "")], + _pageSlug: pageSlug, // Store for stream resolution + }); + } + } + }); + + console.log( + `[WITV] Pattern 1 (.holographic-card): found ${channels.length} channels`, + ); + + // Pattern 2 fallback: Look for .e-grid-cat or similar grid structures + if (channels.length === 0) { + console.log("[WITV] Trying Pattern 2 (.e-grid-cat)..."); + $(".e-grid-cat a, .grid-item a, .channel-item a").each( + (index, element) => { + const $el = $(element); + const link = $el.attr("href"); + const name = + $el.find(".ann-short_price, .channel-name, .title").text().trim() || + $el.text().trim(); + + if (name && link) { + const idMatch = link.match(/\/(\d+)-/); + if (idMatch) { + const id = idMatch[1]; + if (!channels.find((c) => c.id === `wiflix_${id}`)) { + const slugMatch = link.match(/\/(\d+-[^\/]+\.html)$/); + const pageSlug = slugMatch ? slugMatch[1] : null; + channels.push({ + id: `wiflix_${id}`, + type: "tv", + name: name, + poster: null, + genres: [categoryKey.replace("wiflix_", "")], + _pageSlug: pageSlug, + }); + } + } + } + }, + ); + console.log(`[WITV] Pattern 2: found ${channels.length} channels`); + } + + // Pattern 3: Ultra-simple - find all links with /ID-slug pattern + if (channels.length === 0) { + console.log("[WITV] Trying Pattern 3 (regex on all links)..."); + const html = response.data; + const linkRegex = /href="[^"]*\/(\d+)-([^"\.]+)/gi; + let match; + const seenIds = new Set(); + + while ((match = linkRegex.exec(html)) !== null) { + const id = match[1]; + const slug = match[2]; + + // Convert slug to readable name + const name = slug + .replace(/-/g, " ") + .replace(/\b\w/g, (c) => c.toUpperCase()); + + if (id && !seenIds.has(id)) { + seenIds.add(id); + channels.push({ + id: `wiflix_${id}`, + type: "tv", + name: name, + poster: null, + genres: [categoryKey.replace("wiflix_", "")], + _pageSlug: `${id}-${slug}.html`, + }); + } + } + console.log(`[WITV] Pattern 3: found ${channels.length} channels`); + } + + // Debug: Log HTML preview if no channels found + if (channels.length === 0) { + console.log("[WITV] No channels found! HTML preview:"); + console.log(response.data.substring(0, 2000)); + } + + console.log( + `[WITV] Total scraped ${channels.length} channels for ${categoryKey}`, + ); + return channels; + } catch (error) { + console.error(`[WITV] Error scraping ${categoryKey}:`, error.message); + return []; + } +} + +/** + * Trouve l'URL de la page d'une chaîne Witv à partir de son ID + */ +async function findWitvChannelPageUrl(channelId) { + // channelId format: wiflix_XX (ex: wiflix_23) + const id = channelId.replace("wiflix_", ""); + + // Chercher dans le cache des catalogues + for (const categoryKey of Object.keys(WITV_CATEGORIES)) { + const catalogCacheKey = generateCacheKey(`catalog_tv_${categoryKey}`); + const catalogCache = await getFromCache(catalogCacheKey, 24); + + if (catalogCache && catalogCache.metas) { + const channel = catalogCache.metas.find((m) => m.id === channelId); + if (channel && channel._pageSlug) { + // Déterminer la catégorie pour construire l'URL complète + const categoryPath = WITV_CATEGORIES[categoryKey]; + return `${WITV_BASE_URL}${categoryPath}${channel._pageSlug}`; + } + } + } + + // Fallback: Si pas trouvé dans le cache, chercher dynamiquement + console.log(`[WITV] Channel ${channelId} not found in cache, searching...`); + + for (const [categoryKey, pathUrl] of Object.entries(WITV_CATEGORIES)) { + try { + const fullUrl = `${WITV_BASE_URL}${pathUrl}`; + const response = await axios.get(fullUrl, { + headers: { + "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", + }, + timeout: 10000, + httpAgent: WITV_PROXY_AGENT, + httpsAgent: WITV_PROXY_AGENT, + }); + + // Chercher le lien de la chaîne avec l'ID correspondant + const regex = new RegExp(`href="([^"]*/${id}-[^"\.]+\.html)"`, "i"); + const match = response.data.match(regex); + + if (match) { + const channelPath = match[1]; + return channelPath.startsWith("http") + ? channelPath + : `${WITV_BASE_URL}${channelPath}`; + } + } catch (e) { + console.warn(`[WITV] Error searching in ${categoryKey}: ${e.message}`); + } + } + + return null; +} + +/** + * Résout le lien m3u8 pour une chaîne Witv + * Gère 2 types d'embeds: witv-player.php et livehdtv.com + */ +async function resolveWitvStream(channelId) { + try { + console.log(`[WITV] Resolving stream for channel ${channelId}`); + + // Étape 1: Trouver l'URL de la page de la chaîne + const channelPageUrl = await findWitvChannelPageUrl(channelId); + + if (!channelPageUrl) { + console.warn(`[WITV] Could not find page URL for ${channelId}`); + return null; + } + + console.log(`[WITV] Channel page URL: ${channelPageUrl}`); + + // Étape 2: Récupérer la page de la chaîne + const pageResponse = await axios.get(channelPageUrl, { + headers: { + "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", + Referer: WITV_BASE_URL, + }, + timeout: 15000, + httpAgent: WITV_PROXY_AGENT, + httpsAgent: WITV_PROXY_AGENT, + }); + + const $ = cheerio.load(pageResponse.data); + + // Étape 3: Trouver l'iframe embed + const iframe = $("iframe").first(); + let embedSrc = iframe.attr("src"); + + if (!embedSrc) { + console.warn(`[WITV] No iframe found on page ${channelPageUrl}`); + return null; + } + + console.log(`[WITV] Found embed iframe: ${embedSrc}`); + + // Étape 4: Gérer les différents types d'embeds + + // Type 1: witv-player.php (ex: /player/playerjs/witv-player.php?id=20) + if (embedSrc.includes("witv-player.php")) { + const playerUrl = embedSrc.startsWith("http") + ? embedSrc + : `${WITV_BASE_URL}${embedSrc}`; + console.log(`[WITV] Type 1: witv-player detected, fetching ${playerUrl}`); + + const playerResponse = await axios.get(playerUrl, { + headers: { + "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", + Referer: channelPageUrl, + }, + timeout: 15000, + httpAgent: WITV_PROXY_AGENT, + httpsAgent: WITV_PROXY_AGENT, + }); + + const html = playerResponse.data; + + // Chercher: var streamUrl = "..." + const streamMatch = html.match(/var\s+streamUrl\s*=\s*["']([^"']+)["']/); + if (streamMatch && streamMatch[1]) { + console.log(`[WITV] Found streamUrl: ${streamMatch[1]}`); + return streamMatch[1]; + } + + // Alternative: chercher file: "..." (JWPlayer setup) + const fileMatch = html.match(/file:\s*["']([^"']+\.m3u8[^"']*)["']/); + if (fileMatch && fileMatch[1]) { + console.log(`[WITV] Found JWPlayer file: ${fileMatch[1]}`); + return fileMatch[1]; + } + + console.warn(`[WITV] No stream URL found in witv-player`); + return null; + } + + // Type 2: livehdtv.com (ex: https://www.livehdtv.com/yayin/?kanal=182) + if (embedSrc.includes("livehdtv.com")) { + console.log(`[WITV] Type 2: livehdtv detected, following embed chain...`); + + // Use Cloudflare proxy to bypass 403 + const proxiedLivehdtvUrl = `${CF_PROXY_403}${encodeURIComponent(embedSrc)}`; + + // Étape 4a: Récupérer la page livehdtv/yayin + const livehdtvResponse = await axios.get(proxiedLivehdtvUrl, { + headers: { + "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", + Referer: "https://www.livehdtv.com/", + }, + timeout: 15000, + }); + + const $livehdtv = cheerio.load(livehdtvResponse.data); + const innerIframe = $livehdtv("iframe").first(); + let tokenPhpUrl = innerIframe.attr("src"); + + if (!tokenPhpUrl) { + console.warn(`[WITV] No inner iframe found in livehdtv page`); + return null; + } + + console.log(`[WITV] Found token.php iframe: ${tokenPhpUrl}`); + + // Étape 4b: Récupérer la page token.php (contient le JWPlayer avec le m3u8) + if (!tokenPhpUrl.startsWith("http")) { + tokenPhpUrl = `https://www.livehdtv.com${tokenPhpUrl}`; + } + + // Use got-scraping to bypass Cloudflare protection for token.php + const { gotScraping } = await import("got-scraping"); + const tokenResponse = await gotScraping({ + url: tokenPhpUrl, + headers: { + Referer: embedSrc, // Critical for validation + }, + headerGeneratorOptions: { + browsers: [{ name: "chrome", minVersion: 120 }], + devices: ["desktop"], + locales: ["fr-FR", "en-US"], + operatingSystems: ["windows"], + }, + }); + + const tokenHtml = tokenResponse.body; + + // Extraire: file: "https://livetvde.net/gulli/index.m3u8?token=..." + const fileMatch = tokenHtml.match(/file:\s*["']([^"']+\.m3u8[^"']*)["']/); + if (fileMatch && fileMatch[1]) { + console.log(`[WITV] Found m3u8 from token.php: ${fileMatch[1]}`); + return fileMatch[1]; + } + + console.warn( + `[WITV] No m3u8 URL found in token.php response. Response preview:`, + ); + console.log(tokenHtml.substring(0, 500)); + return null; + } + + // Type inconnu: tenter d'extraire directement un m3u8 + console.log( + `[WITV] Unknown embed type, attempting direct extraction from: ${embedSrc}`, + ); + + const unknownUrl = embedSrc.startsWith("http") + ? embedSrc + : `${WITV_BASE_URL}${embedSrc}`; + const unknownResponse = await axios.get(unknownUrl, { + headers: { + "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", + Referer: channelPageUrl, + }, + timeout: 15000, + httpAgent: WITV_PROXY_AGENT, + httpsAgent: WITV_PROXY_AGENT, + }); + + const unknownHtml = unknownResponse.data; + + // Chercher n'importe quel m3u8 + const m3u8Match = unknownHtml.match( + /["'](https?:\/\/[^"']+\.m3u8[^"']*)["']/, + ); + if (m3u8Match && m3u8Match[1]) { + console.log(`[WITV] Found m3u8 via generic extraction: ${m3u8Match[1]}`); + return m3u8Match[1]; + } + + console.warn(`[WITV] Could not extract stream URL from ${channelId}`); + return null; + } catch (error) { + console.error( + `[WITV] Error resolving stream for ${channelId}:`, + error.message, + ); + return null; + } +} + +// === SOSPLAY SCRAPING FUNCTIONS === + +/** + * Scrape les chaînes disponibles depuis Sosplay + */ +async function scrapeSosplayChannels(categoryKey) { + try { + if (categoryKey !== "sosplay_chaines") { + console.log(`[BOLALOCA] Unknown category: ${categoryKey}`); + return []; + } + + const channels = BOLALOCA_CHANNELS.map((channel) => ({ + id: `sosplay_${channel.id}`, + type: "tv", + name: channel.name, + poster: channel.poster || null, + genres: ["chaines"], + _channelId: channel.id, + })); + + console.log( + `[BOLALOCA] Returning ${channels.length} static channels for ${categoryKey}`, + ); + return channels; + } catch (error) { + console.error(`[BOLALOCA] Error building ${categoryKey}:`, error.message); + return []; + } +} + +/** + * Scrape les matchs disponibles depuis Sosplay (Football, etc.) + */ +async function scrapeSosplayMatches(categoryKey) { + try { + const categoryConfig = SOSPLAY_MATCHES_CATEGORIES[categoryKey]; + if (!categoryConfig) { + console.log(`[SOSPLAY-MATCHES] Unknown category: ${categoryKey}`); + return []; + } + + const fullUrl = `${SOSPLAY_BASE_URL}${categoryConfig.path}`; + console.log(`[SOSPLAY-MATCHES] Scraping matches from ${fullUrl}`); + + const response = await axios.get(fullUrl, { + headers: { + "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", + Accept: + "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", + }, + timeout: 15000, + httpsAgent: SOSPLAY_HTTPS_AGENT, + }); + + const $ = cheerio.load(response.data); + const matches = []; + const now = Date.now(); + + console.log( + `[SOSPLAY-MATCHES] Page loaded, length: ${response.data.length} bytes`, + ); + + // Parse each .row element containing a match + $(".events .row").each((index, element) => { + const $el = $(element); + + // Get match name (team1 - team2) + const name = $el.find(".game-name span").text().trim(); + const link = $el.find(".game-name").attr("href"); + + // Get timestamp from data-timestamp attribute + const timeElement = $el.find("time.DISDATE"); + const timestamp = parseInt(timeElement.attr("data-timestamp")) || 0; + const timeText = timeElement.text().trim(); + + // Get competition/league name + const houreText = $el.find(".houre").text().trim(); + const competitionMatch = houreText.match(/·\s*(.+)$/); + const competition = competitionMatch ? competitionMatch[1].trim() : ""; + + // Check if match is live (timestamp is in the past or has "Direct" link) + const isLive = + timestamp <= now || $el.find(".scdw a").text().includes("Direct"); + + // Get countdown/status + const countdownEl = $el.find(".scdw"); + const countdownText = countdownEl.text().trim(); + const status = countdownText.includes("Direct") ? "live" : "upcoming"; + + // Get country flag from .map class + const flagClass = $el.find(".map").attr("class") || ""; + const countryCode = flagClass.replace("map", "").trim(); + + if (name && link) { + // Create a unique ID from the link + const slugMatch = link.match(/\/regarder-([^/]+)/); + const slug = slugMatch + ? slugMatch[1] + : link.replace(/\//g, "-").replace(/^\//, ""); + + matches.push({ + id: `match_${slug}`, + type: "tv", + name: name, + poster: null, + genres: [categoryConfig.name.toLowerCase()], + _pageUrl: link.startsWith("http") + ? link + : `${SOSPLAY_BASE_URL}${link}`, + _timestamp: timestamp, + _timeText: timeText, + _competition: competition, + _isLive: isLive, + _status: status, + _countryCode: countryCode, + }); + } + }); + + // Sort: Live matches first, then by timestamp (soonest first) + matches.sort((a, b) => { + if (a._isLive && !b._isLive) return -1; + if (!a._isLive && b._isLive) return 1; + return a._timestamp - b._timestamp; + }); + + console.log( + `[SOSPLAY-MATCHES] Scraped ${matches.length} matches (${matches.filter((m) => m._isLive).length} live)`, + ); + return matches; + } catch (error) { + console.error( + `[SOSPLAY-MATCHES] Error scraping ${categoryKey}:`, + error.message, + ); + return []; + } +} + +/** + * Récupère les serveurs disponibles pour un match Sosplay (French first, fallback to other languages) + */ +async function getSosplayMatchServers(matchPageUrl) { + try { + console.log(`[SOSPLAY-MATCHES] Getting servers from: ${matchPageUrl}`); + + const response = await axios.get(matchPageUrl, { + headers: { + "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", + Referer: SOSPLAY_BASE_URL, + }, + timeout: 15000, + httpsAgent: SOSPLAY_HTTPS_AGENT, + }); + + const $ = cheerio.load(response.data); + const frenchServers = []; + const otherServers = []; + + // Language flag to emoji mapping + const langEmojis = { + fr: "🇫🇷", + es: "🇪🇸", + de: "🇩🇪", + pt: "🇵🇹", + it: "🇮🇹", + gb: "🇬🇧", + en: "🇬🇧", + }; + + // Parse .servideo div for server options + $(".servideo .change-video").each((index, element) => { + const $el = $(element); + const name = $el.text().trim(); + const embedPath = $el.attr("data-embed"); + const imgAlt = $el.find("img").attr("alt") || ""; + + if (embedPath) { + // Extract channel and server IDs from path like "/part/Ll.php?id=1/46" + const match = embedPath.match(/id=(\d+)\/(\d+)/); + if (match) { + const serverInfo = { + name: name, + channelNum: match[1], + serverNum: match[2], + embedPath: embedPath, + language: imgAlt, + langEmoji: langEmojis[imgAlt] || `[${imgAlt.toUpperCase()}]`, + }; + + // Separate French and other servers + if (imgAlt === "fr") { + frenchServers.push(serverInfo); + } else { + otherServers.push(serverInfo); + } + } + } + }); + + console.log( + `[SOSPLAY-MATCHES] Found ${frenchServers.length} French servers, ${otherServers.length} other servers`, + ); + + // If we have French servers, return them + if (frenchServers.length > 0) { + return frenchServers; + } + + // Fallback: No French servers, get up to 3 servers from other languages + // Prioritize by getting one of each type (Wigi, Hoca, Obcast) from same language if possible + console.log( + `[SOSPLAY-MATCHES] No French servers, falling back to other languages`, + ); + + // Group other servers by language + const serversByLang = {}; + for (const server of otherServers) { + if (!serversByLang[server.language]) { + serversByLang[server.language] = []; + } + serversByLang[server.language].push(server); + } + + // Find the language with most servers (likely the best coverage) + let bestLang = null; + let maxServers = 0; + for (const [lang, servers] of Object.entries(serversByLang)) { + if (servers.length > maxServers) { + maxServers = servers.length; + bestLang = lang; + } + } + + if (bestLang && serversByLang[bestLang]) { + // Return up to 3 servers from the best language + const fallbackServers = serversByLang[bestLang].slice(0, 3); + console.log( + `[SOSPLAY-MATCHES] Using ${fallbackServers.length} servers from language: ${bestLang}`, + ); + return fallbackServers; + } + + // Last resort: return first 3 servers from any language + return otherServers.slice(0, 3); + } catch (error) { + console.error(`[SOSPLAY-MATCHES] Error getting servers:`, error.message); + return []; + } +} + +/** + * Résout le lien m3u8 pour un match Sosplay + */ +async function resolveSosplayMatchStream(matchId) { + try { + console.log(`[SOSPLAY-MATCHES] Resolving stream for match ${matchId}`); + + // Try to find the match page URL from cache first + let matchPageUrl = null; + + // Check matches_football catalog cache + for (const categoryKey of Object.keys(SOSPLAY_MATCHES_CATEGORIES)) { + const catalogCacheKey = generateCacheKey(`catalog_tv_${categoryKey}`); + const catalogCache = await getFromCache(catalogCacheKey, 1); // 1 hour cache + + if (catalogCache && catalogCache.metas) { + const match = catalogCache.metas.find((m) => m.id === matchId); + if (match && match._pageUrl) { + matchPageUrl = match._pageUrl; + break; + } + } + } + + if (!matchPageUrl) { + // Fallback: reconstruct URL from match ID + const slug = matchId.replace("match_", ""); + matchPageUrl = `${SOSPLAY_BASE_URL}/regarder-${slug}`; + } + + console.log(`[SOSPLAY-MATCHES] Match page URL: ${matchPageUrl}`); + + // Get available servers (French first, fallback to other languages) + const servers = await getSosplayMatchServers(matchPageUrl); + + if (servers.length === 0) { + console.warn(`[SOSPLAY-MATCHES] No servers found for ${matchId}`); + return []; + } + + // Collect streams from all servers + const allStreams = []; + + for (const server of servers) { + try { + console.log(`[SOSPLAY-MATCHES] Trying server: ${server.name}`); + + // Fetch the intermediate embed page (e.g. /part/Ll.php?id=1/20) + const embedUrl = `${SOSPLAY_BASE_URL}${server.embedPath}`; + console.log(`[SOSPLAY-MATCHES] Fetching embed page: ${embedUrl}`); + + const embedPageResponse = await axios.get(embedUrl, { + headers: { + "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", + Referer: matchPageUrl, + }, + timeout: 15000, + httpsAgent: SOSPLAY_HTTPS_AGENT, + }); + + const embedHtml = embedPageResponse.data; + + // Extract iframe src (e.g. /Zoz/1/20 or external URL) + const iframeMatch = embedHtml.match(/]+src=["']([^"']+)/i); + if (!iframeMatch) { + console.warn( + `[SOSPLAY-MATCHES] No iframe found in embed page response`, + ); + continue; + } + + let iframeSrc = iframeMatch[1]; + // Handle relative URLs + if (iframeSrc.startsWith("/")) { + iframeSrc = `${SOSPLAY_BASE_URL}${iframeSrc}`; + } + console.log(`[SOSPLAY-MATCHES] Found iframe: ${iframeSrc}`); + + // Résoudre les iframes imbriqués jusqu'au contenu final + const resolved = await resolveNestedIframes( + iframeSrc, + embedUrl, + 3, + "[SOSPLAY-MATCHES]", + ); + if (!resolved) continue; + + const { html: finalHtml, finalUrl } = resolved; + + // Essayer les deux décodeurs + let m3u8Url = null; + if ( + server.name.toLowerCase().includes("hoca") || + finalUrl.includes("hoca") + ) { + console.log(`[SOSPLAY-MATCHES] Processing Hoca embed`); + m3u8Url = decodeHocaStream(finalHtml); + } + if (!m3u8Url) { + console.log(`[SOSPLAY-MATCHES] Processing Wigi/generic embed`); + m3u8Url = decodeWigiStream(finalHtml); + } + + if (m3u8Url) { + console.log(`[SOSPLAY-MATCHES] Found stream: ${m3u8Url}`); + allStreams.push({ + title: `${server.langEmoji || "🇫🇷"} ${server.name}`, + url: m3u8Url, + referer: finalUrl, + }); + } + } catch (serverError) { + console.warn( + `[SOSPLAY-MATCHES] Error with server ${server.name}:`, + serverError.message, + ); + continue; + } + } + + console.log(`[SOSPLAY-MATCHES] Total streams found: ${allStreams.length}`); + return allStreams; + } catch (error) { + console.error( + `[SOSPLAY-MATCHES] Error resolving stream for ${matchId}:`, + error.message, + ); + return []; + } +} + +/** + * Récupère les serveurs disponibles pour une chaîne Sosplay + */ +async function getSosplayServers(channelPageUrl) { + try { + console.log(`[SOSPLAY] Getting servers from: ${channelPageUrl}`); + + const response = await axios.get(channelPageUrl, { + headers: { + "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", + Referer: SOSPLAY_BASE_URL, + }, + timeout: 15000, + httpsAgent: SOSPLAY_HTTPS_AGENT, + }); + + const $ = cheerio.load(response.data); + const servers = []; + + // Parse .servideo div for server options + $(".servideo .change-video").each((index, element) => { + const $el = $(element); + const name = $el.text().trim(); + const embedPath = $el.attr("data-embed"); + + if (embedPath) { + // Extract channel and server IDs from path like "/part/Ll.php?id=1/20" + const match = embedPath.match(/id=(\d+)\/(\d+)/); + if (match) { + servers.push({ + name: name, + channelNum: match[1], + serverNum: match[2], + embedPath: embedPath, + }); + } + } + }); + + console.log(`[SOSPLAY] Found ${servers.length} servers`); + return servers; + } catch (error) { + console.error(`[SOSPLAY] Error getting servers:`, error.message); + return []; + } +} + +/** + * Dean Edwards Packer unpacker + * Decodes eval(function(p,a,c,k,e,d){...}) obfuscated JavaScript + */ +function unpackPacker(p, a, c, k, e, d) { + e = function (c) { + return ( + (c < a ? "" : e(parseInt(c / a))) + + ((c = c % a) > 35 ? String.fromCharCode(c + 29) : c.toString(36)) + ); + }; + + if (!"".replace(/^/, String)) { + while (c--) { + d[e(c)] = k[c] || e(c); + } + k = [ + function (e) { + return d[e]; + }, + ]; + e = function () { + return "\\w+"; + }; + c = 1; + } + + while (c--) { + if (k[c]) { + p = p.replace(new RegExp("\\b" + e(c) + "\\b", "g"), k[c]); + } + } + return p; +} + +/** + * Résout les iframes imbriqués jusqu'à trouver le contenu final (avec m3u8/player) + * Chaîne: /part/Ll.php → /Zoz/1/20 → @sosplay_...html (contient le player) + */ +async function resolveNestedIframes( + url, + referer, + maxDepth = 3, + logPrefix = "[SOSPLAY]", +) { + let currentUrl = url; + let currentReferer = referer; + + for (let depth = 0; depth < maxDepth; depth++) { + console.log(`${logPrefix} Resolving depth ${depth}: ${currentUrl}`); + + const response = await axios.get(currentUrl, { + headers: { + "User-Agent": + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36", + Referer: currentReferer, + }, + timeout: 15000, + httpsAgent: SOSPLAY_HTTPS_AGENT, + }); + + const html = response.data; + + // Si on trouve un m3u8 ou un player, c'est la page finale + if ( + html.includes(".m3u8") || + html.includes("Clappr") || + html.includes("eval(function(p,a,c,k,e,d)") + ) { + console.log(`${logPrefix} Found final content at depth ${depth}`); + return { html, finalUrl: currentUrl, referer: currentReferer }; + } + + // Sinon chercher un iframe imbriqué + const iframeMatch = html.match(/]+src=["']([^"']+)/i); + if (!iframeMatch) { + console.log( + `${logPrefix} No more iframes at depth ${depth}, returning current content`, + ); + return { html, finalUrl: currentUrl, referer: currentReferer }; + } + + let nextUrl = iframeMatch[1]; + if (nextUrl.startsWith("/")) { + nextUrl = `${SOSPLAY_BASE_URL}${nextUrl}`; + } else if (!nextUrl.startsWith("http")) { + // URL relative au chemin courant + const baseUrl = currentUrl.substring(0, currentUrl.lastIndexOf("/") + 1); + nextUrl = `${baseUrl}${nextUrl}`; + } + + console.log(`${logPrefix} Following nested iframe: ${nextUrl}`); + currentReferer = currentUrl; + currentUrl = nextUrl; + } + + console.warn(`${logPrefix} Max depth reached without finding stream content`); + return null; +} + +function decodeWigiStream(html) { + try { + // Strategy 1: Look for ALL Dean Edwards Packer obfuscated code blocks + const packerRegex = + /eval\(function\(p,a,c,k,e,d\)\{.*?return p\}\('(.*?)',(\d+),(\d+),'(.*?)'\.split\('\|'\),0,\{\}\)\)/gs; + const packerMatches = [...html.matchAll(packerRegex)]; + + for (let i = 0; i < packerMatches.length; i++) { + const packerMatch = packerMatches[i]; + + const payload = packerMatch[1]; + const radix = parseInt(packerMatch[2]); + const count = parseInt(packerMatch[3]); + const keywords = packerMatch[4].split("|"); + + // Create empty dictionary object + const d = {}; + + // Unpack the code + const decodedScript = unpackPacker( + payload, + radix, + count, + keywords, + null, + d, + ); + + // Check if this block contains Clappr/player or m3u8 + if ( + !decodedScript.includes("Clappr") && + !decodedScript.includes(".m3u8") && + !decodedScript.includes("hls") + ) { + continue; + } + + // Extract m3u8 URLs from unpacked code + const urlRegex = /["'](https?:\/\/[^"']+\.m3u8[^"']*)["']/g; + let urlMatch; + const urls = []; + + while ((urlMatch = urlRegex.exec(decodedScript)) !== null) { + let url = urlMatch[1]; + url = url.replace(/\\\//g, "/"); + urls.push(url); + } + + if (urls.length > 0) { + urls.forEach((url, idx) => console.log(` ${idx + 1}. ${url}`)); + + // Prefer vuunov/live URL (backup/direct) over shop/srvagu (P2P) + const backupUrl = urls.find( + (u) => u.includes("vuunov") || u.includes("live"), + ); + const primaryUrl = urls.find( + (u) => u.includes("shop") || u.includes("srvagu"), + ); + + // Return backup if available, otherwise primary + return backupUrl || primaryUrl || urls[0]; + } + } + + if (packerMatches.length === 0) { + } else { + } + + // Strategy 2: Direct src: pattern search + const srcMatch = html.match(/src:\s*["']([^"']+\.m3u8[^"']*)/i); + if (srcMatch) { + let url = srcMatch[1]; + url = url.replace(/\\\//g, "/"); + return url; + } + + // Strategy 3: Direct m3u8 URL search + const streamMatch = html.match(/["'](https?:\/\/[^"']*\.m3u8[^"']*)/); + if (streamMatch) { + let url = streamMatch[1]; + url = url.replace(/\\\//g, "/"); + return url; + } + + // Strategy 4: var src = "..." pattern + const varSrcMatch = html.match(/var\s+src\s*=\s*["']([^"']+)/i); + if (varSrcMatch && varSrcMatch[1].includes(".m3u8")) { + let url = varSrcMatch[1]; + url = url.replace(/\\\//g, "/"); + return url; + } + + return null; + } catch (error) { + return null; + } +} + +// Function to decode Hoca stream +function decodeHocaStream(html) { + try { + // Pattern from hoca.html: atob('...') contains the path + const atobMatch = html.match(/atob\(['"]([^'"]+)['"]\)/); + if (atobMatch) { + const decoded = Buffer.from(atobMatch[1], "base64").toString("utf-8"); + console.log(`[SOSPLAY] Decoded atob: ${decoded}`); + } + + // Look for telgHtrptU function which returns the full URL + // Pattern: array of characters joined together + const urlArrayMatch = html.match(/return\s*\(\[([^\]]+)\]\.join/); + if (urlArrayMatch) { + try { + // Parse the array of characters + const chars = urlArrayMatch[1].match(/"([^"]*)"/g); + if (chars) { + let url = chars.map((c) => c.replace(/"/g, "")).join(""); + // Fix escaped slashes (https:\/\/...) + url = url.replace(/\\\//g, "/"); + + if (url.includes(".m3u8")) { + return url; + } + } + } catch (e) { + console.error("[SOSPLAY] Error parsing Hoca array:", e.message); + } + } + + // Direct m3u8 search + const m3u8Match = html.match(/["'](https?:\/\/[^"']+\.m3u8[^"']*)/); + if (m3u8Match) { + let url = m3u8Match[1]; + // Fix escaped slashes + url = url.replace(/\\\//g, "/"); + return url; + } + + return null; + } catch (error) { + console.error("[SOSPLAY] Error decoding Hoca stream:", error.message); + return null; + } +} + +/** + * Résout le lien m3u8 pour une chaîne Sosplay + */ +function buildLivePageHeaders(referer = null) { + return { + "User-Agent": LIVE_PAGE_USER_AGENT, + Accept: + "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", + ...(referer ? { Referer: referer } : {}), + }; +} + +function buildStreamProxyHeaders( + referer, + fallbackOrigin, + userAgent = STREAM_PROXY_USER_AGENT, +) { + const safeReferer = referer || fallbackOrigin; + let origin = fallbackOrigin; + + try { + origin = new URL(safeReferer).origin; + } catch { + origin = fallbackOrigin; + } + + const headers = { + "User-Agent": userAgent || STREAM_PROXY_USER_AGENT, + }; + + if (safeReferer) { + headers.Referer = safeReferer; + } + + if (origin) { + headers.Origin = origin; + } + + return headers; +} + +function absolutizeLiveUrl(rawUrl, currentUrl = "", fallbackBase = "") { + if (!rawUrl) return null; + + const normalized = String(rawUrl) + .trim() + .replace(/\\u0026/g, "&") + .replace(/\\\//g, "/") + .replace(/\s+/g, ""); + + if (!normalized) return null; + + if (normalized.startsWith("//")) { + const protocol = currentUrl.startsWith("http://") ? "http:" : "https:"; + return `${protocol}${normalized}`; + } + + try { + return new URL(normalized, currentUrl || fallbackBase || undefined).href; + } catch (error) { + return null; + } +} + +function dedupeByKey(items, getKey) { + const seen = new Set(); + const deduped = []; + + for (const item of items) { + const key = getKey(item); + if (!key || seen.has(key)) continue; + seen.add(key); + deduped.push(item); + } + + return deduped; +} + +function encodeUrlToken(value) { + return Buffer.from(String(value), "utf8") + .toString("base64") + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=+$/g, ""); +} + +function decodeUrlToken(value) { + try { + const normalized = String(value).replace(/-/g, "+").replace(/_/g, "/"); + const paddingLength = (4 - (normalized.length % 4 || 4)) % 4; + return Buffer.from( + `${normalized}${"=".repeat(paddingLength)}`, + "base64", + ).toString("utf8"); + } catch (error) { + return null; + } +} + +function revealPipeSplit(html) { + const cleaned = String(html || "").replace(/\\/g, ""); + const results = [ + ...cleaned.matchAll(/return p\}\(([\s\S]*?),'([^']*)'\.split\('\|'\)/g), + ]; + + if (results.length === 0) { + return ""; + } + + const numericMode = !/[a-j]\b/.test(cleaned); + const tokenToInt = (token) => { + if (numericMode) return Number(token); + if (/^[a-z]$/.test(token)) return token.charCodeAt(0) - 87; + if (/^[A-Z]$/.test(token)) return token.charCodeAt(0) - 29; + if (/^\d$/.test(token)) return Number(token); + return Number(token) + 52; + }; + + return results + .map((match) => { + const mask = match[1]; + const keywords = match[2].split("|"); + return mask.replace(/\b[0-9a-zA-Z]+\b/g, (token) => { + const index = tokenToInt(token); + return Number.isInteger(index) && + index < keywords.length && + keywords[index] + ? keywords[index] + : token; + }); + }) + .join("\n"); +} + +function revealCharByCharUrl(html) { + const cleaned = String(html || "").replace(/\\/g, ""); + const match = cleaned.match(/((?:".",)+".")\]\.join\(""\)/); + if (!match) return ""; + + return match[1] + .split(",") + .map((entry) => entry.replace(/"/g, "")) + .join(""); +} + +function extractIframeUrlsFromHtml(html, currentUrl, fallbackBase = "") { + const iframeUrls = []; + const regex = /]+src=["']([^"']+)["']/gi; + let match; + + while ((match = regex.exec(String(html || ""))) !== null) { + const absoluteUrl = absolutizeLiveUrl(match[1], currentUrl, fallbackBase); + if (absoluteUrl && !shouldIgnoreLiveTvIframeUrl(absoluteUrl)) { + iframeUrls.push(absoluteUrl); + } + } + + return dedupeByKey(iframeUrls, (url) => url); +} + +function shouldIgnoreLiveTvIframeUrl(rawUrl) { + const normalizedUrl = String(rawUrl || "").trim(); + if (!normalizedUrl) { + return true; + } + + if (/^(?:about:blank|javascript:|data:)/i.test(normalizedUrl)) { + return true; + } + + try { + const parsed = new URL(normalizedUrl, LIVETV_BASE_URL); + const hostname = parsed.hostname.toLowerCase(); + const pathname = parsed.pathname.toLowerCase(); + const search = parsed.search.toLowerCase(); + const combined = `${hostname}${pathname}${search}`; + + if ( + hostname === "ads.livetv873.me" || + hostname.startsWith("ads.") || + hostname.startsWith("ad.") + ) { + return true; + } + + if (pathname.includes("getbanner.php") || search.includes("zone_id=")) { + return true; + } + + if ( + /(?:^|[./_-])(banner|ads?|popunder|popup)(?:[./_-]|$)/i.test(combined) + ) { + return true; + } + } catch (error) { + return false; + } + + return false; +} + +function shouldTreatLiveTvIframeAsTerminalEmbed( + rawUrl, + fallbackBase = LIVETV_BASE_URL, +) { + const normalizedUrl = String(rawUrl || "").trim(); + if (!normalizedUrl) { + return false; + } + + if (/\.(m3u8|mpd)(?:[?#]|$)/i.test(normalizedUrl)) { + return false; + } + + try { + const parsed = new URL(normalizedUrl, fallbackBase || LIVETV_BASE_URL); + const fallbackHost = new URL(fallbackBase || LIVETV_BASE_URL).hostname + .replace(/^www\./i, "") + .toLowerCase(); + const hostname = parsed.hostname.replace(/^www\./i, "").toLowerCase(); + + if (!hostname || !fallbackHost) { + return false; + } + + return hostname !== fallbackHost && !hostname.endsWith(`.${fallbackHost}`); + } catch (error) { + return false; + } +} + +function isLiveTvExportIframePage(rawUrl, fallbackBase = LIVETV_BASE_URL) { + try { + const parsed = new URL(rawUrl, fallbackBase || LIVETV_BASE_URL); + return /\/export\/webplayer\.iframe\.php$/i.test(parsed.pathname); + } catch (error) { + return false; + } +} + +function shouldFollowLiveTvIframeForExtraction( + iframeUrl, + pageUrl, + fallbackBase = LIVETV_BASE_URL, +) { + try { + const page = new URL(pageUrl, fallbackBase || LIVETV_BASE_URL); + if (!isLiveTvExportIframePage(page.href, fallbackBase)) { + return false; + } + + if ((page.searchParams.get("t") || "").toLowerCase() !== "alieztv") { + return false; + } + + const iframe = new URL(iframeUrl, page.href); + const hostname = iframe.hostname.replace(/^www\./i, "").toLowerCase(); + const pathname = iframe.pathname.toLowerCase(); + + return hostname === "emb.apl395.me" && pathname === "/player/live.php"; + } catch (error) { + return false; + } +} + +function extractDirectMediaCandidatesFromHtml( + html, + referer, + fallbackBase = "", +) { + const candidates = []; + const htmlVariants = [String(html || "")]; + + const addCandidate = (rawUrl, candidateReferer = referer) => { + const absoluteUrl = absolutizeLiveUrl( + rawUrl, + candidateReferer, + fallbackBase, + ); + if (!absoluteUrl) return; + if (!/\.(m3u8|mpd)(?:[?#]|$)/i.test(absoluteUrl)) return; + + candidates.push({ + url: absoluteUrl, + referer: candidateReferer, + }); + }; + + const pipeDecoded = revealPipeSplit(htmlVariants[0]); + if (pipeDecoded) htmlVariants.push(pipeDecoded); + + const charDecoded = revealCharByCharUrl(htmlVariants[0]); + if (charDecoded) addCandidate(charDecoded, referer); + + const packedPattern = + /eval\(function\(p,a,c,k,e,(?:d|r)\)\{[\s\S]*?return p\}\((['"])([\s\S]*?)\1,\s*(\d+),\s*(\d+),\s*(['"])([\s\S]*?)\5\.split\(['"]\|['"]\)\s*(?:,\s*0\s*,\s*\{\})?\s*\)\)/gs; + for (const packedMatch of String(html || "").matchAll(packedPattern)) { + try { + const decoded = unpackPacker( + packedMatch[2], + parseInt(packedMatch[3], 10), + parseInt(packedMatch[4], 10), + packedMatch[6].split("|"), + null, + {}, + ); + if (decoded) htmlVariants.push(decoded); + } catch (error) { + console.warn("[LIVE-TV] Unable to decode packed block:", error.message); + } + } + + for (const fragment of htmlVariants) { + const cleaned = String(fragment || "").replace(/\\\//g, "/"); + + for (const atobMatch of cleaned.matchAll(/atob\(['"]([^'"]+)['"]\)/g)) { + try { + addCandidate( + Buffer.from(atobMatch[1], "base64").toString("utf8"), + referer, + ); + } catch (error) { + // Ignore invalid payloads + } + } + + const mimeTypeMatch = cleaned.match( + /mimeType:\s*"application\/x-mpegURL"[\s\S]*?source:\s*'([^']+)'/i, + ); + if (mimeTypeMatch) addCandidate(mimeTypeMatch[1], referer); + + for (const playerInitMatch of cleaned.matchAll( + /pl\.init\(\s*['"]([^'"]+)['"]\s*\)/gi, + )) { + addCandidate(playerInitMatch[1], referer); + } + + for (const manifestUrlMatch of cleaned.matchAll( + /manifestUrl\s*:\s*['"]([^'"]+)['"]/gi, + )) { + addCandidate(manifestUrlMatch[1], referer); + } + + const loadSourceMatch = cleaned.match( + /player\.load\(\{source:\s*([A-Za-z0-9_$]+)\(/, + ); + if (loadSourceMatch) { + const functionPattern = new RegExp( + `function ${loadSourceMatch[1]}\\(\\)\\s*\\{\\s*return\\(\\[([^\\]]+)`, + "s", + ); + const functionMatch = cleaned.match(functionPattern); + if (functionMatch) { + addCandidate( + functionMatch[1] + .replace(/"/g, "") + .replace(/,/g, "") + .replace(/\\/g, "") + .replace(/\/\/\/\//g, "//"), + referer, + ); + } + } + + const playerMatchA = cleaned.match( + /new Player\("100%","100%","player","(.+?)",\{"(.+?)":/, + ); + if (playerMatchA) + addCandidate( + `https://${playerMatchA[2]}/hls/${playerMatchA[1]}/live.m3u8`, + referer, + ); + + const playerMatchB = cleaned.match( + /new Player\("100%","100%","player","(.+?)".+?,"([^"]+)"/, + ); + if (playerMatchB) + addCandidate( + `https://${playerMatchB[2]}/hls/${playerMatchB[1]}/live.m3u8`, + referer, + ); + + for (const inlineMatch of cleaned.matchAll( + /(?:file|source|src)\s*[:=]\s*["']([^"']+\.(?:m3u8|mpd)[^"']*)["']/gi, + )) { + addCandidate(inlineMatch[1], referer); + } + + for (const quotedMatch of cleaned.matchAll( + /["'](https?:\/\/[^"']+\.(?:m3u8|mpd)[^"']*)["']/gi, + )) { + addCandidate(quotedMatch[1], referer); + } + + for (const varSrcMatch of cleaned.matchAll( + /;var.+?src=["']([^"']+)["']/gi, + )) { + addCandidate(varSrcMatch[1], referer); + } + } + + return dedupeByKey( + candidates, + (item) => `${item.url}__${item.referer || ""}`, + ); +} + +function buildLivetvIframeExportUrl(webplayerUrl, eventUrl = "") { + try { + const parsed = new URL(webplayerUrl, eventUrl || LIVETV_BASE_URL); + + if (/\/export\/webplayer\.iframe\.php$/i.test(parsed.pathname)) { + return parsed.href; + } + + if (!/\/webplayer(?:2)?\.php$/i.test(parsed.pathname)) { + return parsed.href; + } + + let cdnHost = parsed.hostname; + if (!/^cdn\./i.test(cdnHost)) { + const eventHost = new URL(eventUrl || LIVETV_BASE_URL).hostname.replace( + /^www\./i, + "", + ); + cdnHost = `cdn.${eventHost}`; + } + + parsed.protocol = "https:"; + parsed.hostname = cdnHost; + parsed.pathname = "/export/webplayer.iframe.php"; + return parsed.href; + } catch (error) { + return webplayerUrl; + } +} + +function extractLivetvWebplayerEntries(html, eventUrl) { + const rawHtml = String(html || ""); + const $ = cheerio.load(rawHtml); + const entries = []; + const cleanText = (value) => + cheerio + .load(`
${String(value || "")}
`) + .text() + .replace(/\u00a0/g, " ") + .replace(/\s+/g, " ") + .trim(); + + const addEntry = (rawUrl, metadata = {}) => { + const webplayerUrl = absolutizeLiveUrl(rawUrl, eventUrl, LIVETV_BASE_URL); + if (!webplayerUrl) return; + + let streamType = ""; + try { + streamType = new URL(webplayerUrl).searchParams.get("t") || ""; + } catch (error) { + streamType = ""; + } + + if (streamType.toLowerCase() === "acestream") { + return; + } + + const exportUrl = buildLivetvIframeExportUrl(webplayerUrl, eventUrl); + const language = String(metadata.language || "").trim(); + const bitrate = String(metadata.bitrate || "").trim(); + const hoster = String(metadata.hoster || "").trim(); + const sourceType = String(metadata.sourceType || streamType || "").trim(); + const title = String( + metadata.title || + [language, hoster || sourceType, bitrate].filter(Boolean).join(" - ") || + sourceType || + "Stream", + ).trim(); + + entries.push({ + title, + language, + bitrate, + hoster, + sourceType, + webplayerUrl, + exportUrl, + }); + }; + + const rowPattern = /]+class=["']lnktbj["'][\s\S]*?<\/table>/gi; + for (const rowMatch of rawHtml.matchAll(rowPattern)) { + const rowHtml = rowMatch[0]; + const hrefMatch = rowHtml.match( + /href=["']([^"']*\/webplayer(?:2)?\.php[^"']*)["']/i, + ); + if (!hrefMatch) continue; + + const language = + cleanText(rowHtml.match(/]+title=["']([^"']+)["']/i)?.[1] || "") || + ""; + const bitrate = + cleanText( + rowHtml.match(/class=["']bitrate["'][^>]*>([\s\S]*?)<\/td>/i)?.[1] || + "", + ) || ""; + const hoster = + cleanText( + rowHtml.match(/class=["']lnktyt["'][^>]*>([\s\S]*?)<\/td>/i)?.[1] || "", + ) || ""; + const title = [language, hoster, bitrate].filter(Boolean).join(" - "); + + addEntry(hrefMatch[1], { + title, + language, + bitrate, + hoster, + }); + } + + if (entries.length === 0) { + $('#links_block a[href*="/webplayer"]').each((_, link) => { + const href = $(link).attr("href"); + if (!href) return; + + const row = $(link).closest("table.lnktbj"); + const language = row.find("img[title]").first().attr("title") || ""; + const bitrate = row.find("td.bitrate").first().text().trim(); + const hoster = row + .find("td.lnktyt") + .first() + .text() + .replace(/\s+/g, " ") + .trim(); + const title = [language, hoster, bitrate].filter(Boolean).join(" - "); + + addEntry(href, { + title, + language, + bitrate, + hoster, + }); + }); + } + + if (entries.length === 0) { + for (const hrefMatch of rawHtml.matchAll( + /href=["']([^"']*\/webplayer(?:2)?\.php[^"']*)["']/gi, + )) { + addEntry(hrefMatch[1], { + title: "Stream", + }); + } + } + + if (entries.length === 0) { + const onclickPattern = + /show_webplayer\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*['"]([^'"]+)['"]\s*\)/gi; + + for (const match of rawHtml.matchAll(onclickPattern)) { + const [, type, contentId, eventId, linkId, countryId, streamId, lang] = + match; + const fallbackUrl = `/webplayer2.php?t=${encodeURIComponent(type)}&c=${encodeURIComponent(contentId)}&lang=${encodeURIComponent(lang)}&eid=${eventId}&lid=${linkId}&ci=${countryId}&si=${streamId}`; + addEntry(fallbackUrl, { + title: type || "Stream", + language: lang || "", + sourceType: type || "", + }); + } + } + + console.log( + `[LIVETV] Raw parser signals for ${eventUrl}: href=${(rawHtml.match(/\/webplayer(?:2)?\.php/gi) || []).length}, onclick=${(rawHtml.match(/show_webplayer\(/gi) || []).length}`, + ); + + return dedupeByKey( + entries, + (item) => `${item.exportUrl}__${item.webplayerUrl}`, + ); +} + +function buildLivetvSourceOptions(entries) { + return entries.map((entry, index) => ({ + index, + title: entry.title || `Source ${index + 1}`, + language: entry.language || "", + bitrate: entry.bitrate || "", + hoster: entry.hoster || "", + sourceType: entry.sourceType || "", + })); +} + +async function fetchLivetvEventEntries(channelId) { + const encodedPath = channelId.replace("livetv_", ""); + const decodedPath = decodeUrlToken(encodedPath); + if (!decodedPath) { + console.warn(`[LIVETV] Could not decode event id ${channelId}`); + return { eventUrl: "", hosterLinks: [] }; + } + + const eventUrl = absolutizeLiveUrl( + decodedPath, + LIVETV_BASE_URL, + LIVETV_BASE_URL, + ); + if (!eventUrl) { + return { eventUrl: "", hosterLinks: [] }; + } + + const eventResponse = await axios.get(eventUrl, { + headers: buildLivePageHeaders(LIVETV_BASE_URL), + timeout: 15000, + httpsAgent: SOSPLAY_HTTPS_AGENT, + }); + + const eventHtml = String(eventResponse.data || ""); + const hosterLinks = extractLivetvWebplayerEntries(eventHtml, eventUrl); + console.log( + `[LIVETV] Extracted ${hosterLinks.length} webplayer links from ${channelId}`, + ); + + return { eventUrl, hosterLinks }; +} + +async function resolveRecursiveIframeStreams(startUrl, referer, options = {}) { + const { + maxDepth = 4, + visited = new Set(), + fallbackBase = "", + logPrefix = "[LIVE-TV]", + preferEmbedForExternalIframes = false, + embedReferer = null, + } = options; + + const absoluteStartUrl = absolutizeLiveUrl(startUrl, referer, fallbackBase); + if (!absoluteStartUrl || visited.has(absoluteStartUrl)) { + return { streams: [], embeds: [] }; + } + + visited.add(absoluteStartUrl); + + if (/\.(m3u8|mpd)(?:[?#]|$)/i.test(absoluteStartUrl)) { + return { + streams: [ + { url: absoluteStartUrl, referer: referer || absoluteStartUrl }, + ], + embeds: [], + }; + } + + try { + const response = await axios.get(absoluteStartUrl, { + headers: buildLivePageHeaders(referer), + timeout: 15000, + httpsAgent: SOSPLAY_HTTPS_AGENT, + maxRedirects: 5, + transformResponse: [(data) => data], + }); + + const finalUrl = response.request?.res?.responseUrl || absoluteStartUrl; + const html = + typeof response.data === "string" + ? response.data + : String(response.data ?? ""); + let streams = extractDirectMediaCandidatesFromHtml( + html, + finalUrl, + fallbackBase, + ); + let embeds = []; + const iframeUrls = extractIframeUrlsFromHtml(html, finalUrl, fallbackBase); + + if (iframeUrls.length === 0) { + return { streams, embeds }; + } + + if (maxDepth <= 0) { + return { + streams, + embeds: iframeUrls.map((url) => ({ + url, + referer: embedReferer || finalUrl, + })), + }; + } + + for (const iframeUrl of iframeUrls) { + if ( + preferEmbedForExternalIframes && + !shouldFollowLiveTvIframeForExtraction( + iframeUrl, + finalUrl, + fallbackBase, + ) + ) { + embeds.push({ url: iframeUrl, referer: embedReferer || finalUrl }); + continue; + } + + console.log(`${logPrefix} Following iframe: ${iframeUrl}`); + const nested = await resolveRecursiveIframeStreams(iframeUrl, finalUrl, { + maxDepth: maxDepth - 1, + visited, + fallbackBase, + logPrefix, + preferEmbedForExternalIframes, + embedReferer, + }); + + streams = streams.concat(nested.streams); + embeds = embeds.concat(nested.embeds); + + if (nested.streams.length === 0 && nested.embeds.length === 0) { + embeds.push({ url: iframeUrl, referer: embedReferer || finalUrl }); + } + } + + return { + streams: dedupeByKey( + streams, + (item) => `${item.url}__${item.referer || ""}`, + ), + embeds: dedupeByKey( + embeds, + (item) => `${item.url}__${item.referer || ""}`, + ), + }; + } catch (error) { + console.warn( + `${logPrefix} Failed to resolve ${absoluteStartUrl}: ${error.message}`, + ); + return { streams: [], embeds: [] }; + } +} + +async function resolveSosplayStream(channelId) { + try { + const rawChannelId = channelId.replace("sosplay_", ""); + const channelConfig = BOLALOCA_CHANNELS.find( + (channel) => channel.id === rawChannelId, + ); + if (!channelConfig) { + console.warn(`[BOLALOCA] Unknown channel ${channelId}`); + return []; + } + + const resolvedStreams = []; + const resolvedEmbeds = []; + + for (const variant of BOLALOCA_PLAYER_VARIANTS) { + const playerUrl = `${BOLALOCA_BASE_URL}/player/${variant}/${rawChannelId}`; + const resolved = await resolveRecursiveIframeStreams( + playerUrl, + BOLALOCA_BASE_URL, + { + maxDepth: 5, + visited: new Set(), + fallbackBase: BOLALOCA_BASE_URL, + logPrefix: "[BOLALOCA]", + }, + ); + + resolvedStreams.push( + ...resolved.streams.map((stream, index) => ({ + title: `${channelConfig.name} - Lien ${variant}${resolved.streams.length > 1 ? `.${index + 1}` : ""}`, + url: stream.url, + referer: stream.referer || playerUrl, + })), + ); + + resolvedEmbeds.push( + ...resolved.embeds.map((embed, index) => ({ + title: `${channelConfig.name} - Embed ${variant}${resolved.embeds.length > 1 ? `.${index + 1}` : ""}`, + url: embed.url, + referer: embed.referer || playerUrl, + _isEmbed: true, + })), + ); + } + + const uniqueStreams = dedupeByKey( + resolvedStreams, + (item) => `${item.url}__${item.referer || ""}`, + ); + const uniqueEmbeds = dedupeByKey( + resolvedEmbeds, + (item) => `${item.url}__${item.referer || ""}`, + ); + + console.log( + `[BOLALOCA] Resolved ${uniqueStreams.length} direct streams and ${uniqueEmbeds.length} embeds for ${channelId}`, + ); + return uniqueStreams.length > 0 ? uniqueStreams : uniqueEmbeds; + + console.log(`[SOSPLAY] Resolving stream for channel ${channelId}`); + + // Find the channel page URL from cache + const catalogCacheKey = generateCacheKey("catalog_tv_sosplay_chaines"); + const catalogCache = await getFromCache(catalogCacheKey, 24); + + let channelPageUrl = null; + + if (catalogCache && catalogCache.metas) { + const channel = catalogCache.metas.find((m) => m.id === channelId); + if (channel && channel._pageUrl) { + channelPageUrl = channel._pageUrl; + } + } + + if (!channelPageUrl) { + // Fallback: reconstruct URL from channel ID + const slug = channelId.replace("sosplay_", ""); + channelPageUrl = `${SOSPLAY_BASE_URL}/regardertv-${slug}-streaming-direct`; + } + + console.log(`[SOSPLAY] Channel page URL: ${channelPageUrl}`); + + // Get available servers + const servers = await getSosplayServers(channelPageUrl); + + if (servers.length === 0) { + console.warn(`[SOSPLAY] No servers found for ${channelId}`); + return []; + } + + // Collect streams from ALL servers + const allStreams = []; + + for (const server of servers) { + try { + console.log(`[SOSPLAY] Trying server: ${server.name}`); + + // Fetch the intermediate embed page (e.g. /part/Ll.php?id=1/20) + const embedUrl = `${SOSPLAY_BASE_URL}${server.embedPath}`; + console.log(`[SOSPLAY] Fetching embed page: ${embedUrl}`); + + const embedPageResponse = await axios.get(embedUrl, { + headers: { + "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", + Referer: channelPageUrl, + }, + timeout: 15000, + httpsAgent: SOSPLAY_HTTPS_AGENT, + }); + + const embedHtml = embedPageResponse.data; + + // Extract iframe src (e.g. /Zoz/1/20 or external URL) + const iframeMatch = embedHtml.match(/]+src=["']([^"']+)/i); + if (!iframeMatch) { + console.warn(`[SOSPLAY] No iframe found in embed page response`); + continue; + } + + let iframeSrc = iframeMatch[1]; + // Handle relative URLs + if (iframeSrc.startsWith("/")) { + iframeSrc = `${SOSPLAY_BASE_URL}${iframeSrc}`; + } + console.log(`[SOSPLAY] Found iframe: ${iframeSrc}`); + + // Résoudre les iframes imbriqués jusqu'au contenu final + const resolved = await resolveNestedIframes( + iframeSrc, + embedUrl, + 3, + "[SOSPLAY]", + ); + if (!resolved) continue; + + const { html: finalHtml, finalUrl } = resolved; + + // Essayer les deux décodeurs + let m3u8Url = null; + if ( + server.name.toLowerCase().includes("hoca") || + finalUrl.includes("hoca") + ) { + console.log(`[SOSPLAY] Processing Hoca embed`); + m3u8Url = decodeHocaStream(finalHtml); + } + if (!m3u8Url) { + console.log(`[SOSPLAY] Processing Wigi/generic embed`); + m3u8Url = decodeWigiStream(finalHtml); + } + + if (m3u8Url) { + console.log(`[SOSPLAY] Found stream: ${m3u8Url}`); + allStreams.push({ + title: server.name, + url: m3u8Url, + referer: finalUrl, + }); + } + } catch (serverError) { + console.warn( + `[SOSPLAY] Error with server ${server.name}:`, + serverError.message, + ); + continue; + } + } + + console.log(`[SOSPLAY] Total streams found: ${allStreams.length}`); + + if (allStreams.length === 0) { + console.warn( + `[SOSPLAY] Could not find any working stream for ${channelId}`, + ); + return []; + } + + return allStreams; + } catch (error) { + console.error( + `[BOLALOCA] Error resolving stream for ${channelId}:`, + error.message, + ); + return []; + } +} + +function normalizeLiveTvCatalogText(value) { + return cheerio + .load(`
${String(value || "")}
`) + .text() + .replace(/\u00a0/g, " ") + .replace(/\s+/g, " ") + .trim(); +} + +function normalizeLiveTvComparableText(value) { + return normalizeLiveTvCatalogText(value) + .normalize("NFD") + .replace(/[\u0300-\u036f]/g, "") + .replace(/[’']/g, "'") + .toLowerCase(); +} + +function humanizeLiveTvSportKey(sportKey) { + const category = Object.values(LIVETV_CATEGORIES).find( + (entry) => entry.sportKey === sportKey, + ); + return category?.name || "Sport"; +} + +function classifyLiveTvSportKey(...values) { + const normalizedValues = values + .map((value) => normalizeLiveTvComparableText(value)) + .filter(Boolean); + + for (const [sportKey, aliases] of Object.entries(LIVETV_SPORT_ALIASES)) { + if ( + normalizedValues.some((value) => + aliases.some((alias) => value.includes(alias)), + ) + ) { + return sportKey; + } + } + + return "other"; +} + +function extractLiveTvSportInfo(rawSportHint, fallbackText) { + const sportHint = normalizeLiveTvCatalogText(rawSportHint); + const hintParts = sportHint + .split(".") + .map((part) => normalizeLiveTvCatalogText(part)) + .filter(Boolean); + + const sportKey = classifyLiveTvSportKey(sportHint, fallbackText); + const sportLabel = hintParts[0] || humanizeLiveTvSportKey(sportKey); + const competitionFromHint = hintParts.slice(1).join(". ").trim(); + + return { + sportKey, + sportLabel, + competitionFromHint, + }; +} + +function extractLiveTvSectionSportLabel(contextHtml) { + const rawContext = String(contextHtml || ""); + if (!rawContext) { + return ""; + } + + let lastSectionLabel = ""; + const sectionHeaderPattern = + /]*\bclass=["'][^"']*\bmain\b[^"']*["'])(?=[^>]*href=["'][^"']*\/frx\/allupcomingsports\/\d+\/?[^"']*["'])[^>]*>\s*(?:]*>)?([\s\S]*?)(?:<\/b>)?\s*<\/a>/gi; + + for (const match of rawContext.matchAll(sectionHeaderPattern)) { + const candidate = normalizeLiveTvCatalogText(match[1]); + if (candidate) { + lastSectionLabel = candidate; + } + } + + return lastSectionLabel; +} + +function extractLiveTvSectionDateText(rawContext) { + const contextText = normalizeLiveTvCatalogText(rawContext); + if (!contextText) return ""; + + let lastRelativeMatch = null; + const relativePattern = + /(Aujourd'hui|Aujourd’hui|Today|Demain|Tomorrow|Hier|Yesterday)\s*(?:\(([^)]+)\))?/gi; + for (const match of contextText.matchAll(relativePattern)) { + lastRelativeMatch = match; + } + + if (lastRelativeMatch) { + return [ + lastRelativeMatch[1], + lastRelativeMatch[2] ? `(${lastRelativeMatch[2]})` : "", + ] + .filter(Boolean) + .join(" ") + .trim(); + } + + let lastExplicitMatch = null; + const explicitPattern = + /(\d{1,2}\s+(?:janvier|fevrier|février|mars|avril|mai|juin|juillet|aout|août|septembre|octobre|novembre|decembre|décembre|january|february|march|april|may|june|july|august|september|october|november|december))/gi; + for (const match of contextText.matchAll(explicitPattern)) { + lastExplicitMatch = match; + } + + return lastExplicitMatch + ? normalizeLiveTvCatalogText(lastExplicitMatch[1]) + : ""; +} + +function buildLiveTvBaseDate(sectionDateText) { + const normalized = normalizeLiveTvComparableText(sectionDateText); + if (!normalized) return null; + + const now = new Date(); + const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); + + if ( + normalized.includes("aujourd'hui") || + normalized.includes("aujourdhui") || + normalized.includes("today") + ) { + return today; + } + + if (normalized.includes("demain") || normalized.includes("tomorrow")) { + return new Date(today.getTime() + 24 * 60 * 60 * 1000); + } + + if (normalized.includes("hier") || normalized.includes("yesterday")) { + return new Date(today.getTime() - 24 * 60 * 60 * 1000); + } + + const monthMap = { + janvier: 0, + fevrier: 1, + mars: 2, + avril: 3, + mai: 4, + juin: 5, + juillet: 6, + aout: 7, + septembre: 8, + octobre: 9, + novembre: 10, + decembre: 11, + january: 0, + february: 1, + march: 2, + april: 3, + may: 4, + june: 5, + july: 6, + august: 7, + september: 8, + october: 9, + november: 10, + december: 11, + }; + + const dateMatch = normalized.match(/(\d{1,2})\s+([a-z]+)/); + if (!dateMatch) { + return null; + } + + const day = Number.parseInt(dateMatch[1], 10); + const monthIndex = monthMap[dateMatch[2]]; + if (!Number.isFinite(day) || monthIndex === undefined) { + return null; + } + + let year = today.getFullYear(); + let candidate = new Date(year, monthIndex, day); + + if (candidate.getTime() < today.getTime() - 7 * 24 * 60 * 60 * 1000) { + candidate = new Date(year + 1, monthIndex, day); + } + + return candidate; +} + +function buildLiveTvTimestamp(sectionDateText, scheduledTime, isLive = false) { + const timeMatch = String(scheduledTime || "").match(/(\d{1,2}):(\d{2})/); + if (!timeMatch) { + return null; + } + + const now = new Date(); + const baseDate = + buildLiveTvBaseDate(sectionDateText) || + new Date(now.getFullYear(), now.getMonth(), now.getDate()); + baseDate.setHours( + Number.parseInt(timeMatch[1], 10), + Number.parseInt(timeMatch[2], 10), + 0, + 0, + ); + + if ( + !sectionDateText && + !isLive && + baseDate.getTime() < now.getTime() - 6 * 60 * 60 * 1000 + ) { + baseDate.setDate(baseDate.getDate() + 1); + } + + return baseDate.getTime(); +} + +function extractLiveTvTimingInfo(segmentText, anchorHtml, eventBodyHtml = "") { + const timeMatches = Array.from( + segmentText.matchAll(/\b(\d{1,2}:\d{2})\b/g), + ).map((match) => match[1]); + const uniqueTimes = [...new Set(timeMatches)]; + const timeLineMatches = Array.from( + segmentText.matchAll(/(\d{1,2}:\d{2})\s*\(([^)]+)\)/g), + ); + const lastTimeLine = + timeLineMatches.length > 0 + ? timeLineMatches[timeLineMatches.length - 1] + : null; + const scheduledTime = + lastTimeLine?.[1] || uniqueTimes[uniqueTimes.length - 1] || ""; + const competition = normalizeLiveTvCatalogText(lastTimeLine?.[2] || ""); + const liveMarkerHtml = `${eventBodyHtml || ""}${anchorHtml || ""}`; + const rawIsLive = + /]+src=["'][^"']*\/img\/live\.gif(?:\?[^"']*)?["']/i.test( + liveMarkerHtml, + ); + const scoreCandidate = rawIsLive + ? uniqueTimes.find((value) => value !== scheduledTime) || "" + : ""; + + return { + scheduledTime, + competition, + score: scoreCandidate, + isLive: rawIsLive, + }; +} + +function extractLiveTvCatalogEvents(html) { + const rawHtml = String(html || ""); + const linkPattern = + /]+href=["']([^"']*\/frx\/eventinfo\/[^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi; + const linkMatches = Array.from(rawHtml.matchAll(linkPattern)); + const events = []; + + for (let index = 0; index < linkMatches.length; index += 1) { + const match = linkMatches[index]; + const rawHref = match[1]; + const rawName = match[2]; + const name = normalizeLiveTvCatalogText(rawName); + + if (!rawHref || !name || name.length < 3) { + continue; + } + + const pageUrl = absolutizeLiveUrl( + rawHref, + LIVETV_BASE_URL, + LIVETV_BASE_URL, + ); + if (!pageUrl) { + continue; + } + + let pagePath = rawHref; + try { + pagePath = new URL(pageUrl).pathname; + } catch { + pagePath = rawHref; + } + + const matchIndex = match.index || 0; + const nextIndex = linkMatches[index + 1]?.index ?? rawHtml.length; + const segmentStart = Math.max(0, matchIndex - 1200); + const segmentEnd = Math.min(rawHtml.length, nextIndex); + const segmentHtml = rawHtml.slice(segmentStart, segmentEnd); + const eventBodyHtml = rawHtml.slice(matchIndex, segmentEnd); + const beforeHtml = rawHtml.slice( + Math.max(0, matchIndex - 5000), + matchIndex, + ); + const anchorHtml = match[0] || ""; + const segmentText = normalizeLiveTvCatalogText( + segmentHtml + .replace(/<\/(tr|table|div|p|li|td|h\d)>/gi, "\n") + .replace(//gi, "\n"), + ); + + const imgHintMatches = Array.from( + beforeHtml.matchAll( + /<(?:img|span)[^>]+(?:alt|title)=["']([^"']{3,180})["'][^>]*>/gi, + ), + ); + const inlineHint = normalizeLiveTvCatalogText( + imgHintMatches.length > 0 + ? imgHintMatches[imgHintMatches.length - 1][1] + : "", + ); + const sectionSportLabel = extractLiveTvSectionSportLabel(beforeHtml); + const sportHint = sectionSportLabel || inlineHint; + const timingInfo = extractLiveTvTimingInfo( + segmentText, + anchorHtml, + eventBodyHtml, + ); + + if (!timingInfo.scheduledTime && !sportHint) { + continue; + } + + const sectionDateText = extractLiveTvSectionDateText(beforeHtml); + const timestamp = buildLiveTvTimestamp( + sectionDateText, + timingInfo.scheduledTime, + timingInfo.isLive, + ); + const sportInfo = extractLiveTvSportInfo(sportHint, segmentText); + const competition = + timingInfo.competition || sportInfo.competitionFromHint || ""; + const timeText = timingInfo.scheduledTime + ? [timingInfo.scheduledTime, competition ? `(${competition})` : ""] + .filter(Boolean) + .join(" ") + : sectionDateText; + const descriptionParts = [ + sportInfo.sportLabel, + competition, + timingInfo.isLive ? "Live" : timeText, + ].filter(Boolean); + + events.push({ + id: `livetv_${encodeUrlToken(pagePath)}`, + type: "tv", + name, + poster: null, + description: descriptionParts.join(" • "), + genres: [sportInfo.sportKey === "other" ? "sport" : sportInfo.sportKey], + _pagePath: pagePath, + _timestamp: timestamp, + _timeText: timeText, + _competition: competition, + _isLive: timingInfo.isLive, + _status: timingInfo.isLive ? "live" : "upcoming", + _sport: sportInfo.sportLabel, + _sportKey: sportInfo.sportKey, + _score: timingInfo.score, + _emoji: LIVETV_SPORT_EMOJIS[sportInfo.sportKey] || "🏟️", + }); + } + + return dedupeByKey(events, (item) => item.id).sort((a, b) => { + if (a._isLive && !b._isLive) return -1; + if (!a._isLive && b._isLive) return 1; + if (a._timestamp && b._timestamp) return a._timestamp - b._timestamp; + if (a._timestamp) return -1; + if (b._timestamp) return 1; + return String(a.name || "").localeCompare(String(b.name || ""), "fr", { + sensitivity: "base", + }); + }); +} + +async function fetchLiveTvAllUpcomingHtml() { + let bestResponse = null; + + for (const pagePath of LIVETV_ALLUPCOMING_PATHS) { + const pageUrl = `${LIVETV_BASE_URL}${pagePath}`; + + try { + const response = await axios.get(pageUrl, { + headers: buildLivePageHeaders(LIVETV_BASE_URL), + timeout: 15000, + httpsAgent: SOSPLAY_HTTPS_AGENT, + }); + + const html = String(response.data || ""); + const score = (html.match(/\/frx\/eventinfo\//g) || []).length; + if (!bestResponse || score > bestResponse.score) { + bestResponse = { html, pageUrl, score }; + } + } catch (error) { + console.warn( + `[LIVETV] Failed allupcoming page ${pageUrl}:`, + error.message, + ); + } + } + + if (!bestResponse) { + throw new Error("No LiveTV allupcoming page could be fetched"); + } + + return bestResponse; +} + +async function scrapeLivetvChannels(categoryKey) { + try { + const categoryConfig = LIVETV_CATEGORIES[categoryKey]; + if (!categoryConfig) { + console.log(`[LIVETV] Unknown category: ${categoryKey}`); + return []; + } + + const { html, pageUrl, score } = await fetchLiveTvAllUpcomingHtml(); + const events = extractLiveTvCatalogEvents(html); + const filteredEvents = events.filter((event) => { + if (categoryConfig.sportKey === "all") { + return true; + } + + if (categoryConfig.sportKey === "live") { + return Boolean(event._isLive); + } + + if (categoryConfig.sportKey === "other") { + return event._sportKey === "other"; + } + + return event._sportKey === categoryConfig.sportKey; + }); + + console.log( + `[LIVETV] Scraped ${filteredEvents.length}/${events.length} events for ${categoryKey} ` + + `from ${pageUrl} (${score} raw event links, ${filteredEvents.filter((item) => item._isLive).length} live)`, + ); + + return filteredEvents; + } catch (error) { + console.error(`[LIVETV] Error scraping ${categoryKey}:`, error.message); + return []; + } +} + +async function resolveLivetvStream(channelId, options = {}) { + try { + const requestedSourceIndex = + Number.isInteger(options.sourceIndex) && options.sourceIndex >= 0 + ? options.sourceIndex + : null; + const { eventUrl, hosterLinks } = await fetchLivetvEventEntries(channelId); + if (!eventUrl || hosterLinks.length === 0) { + return []; + } + + const selectedHosterLinks = hosterLinks + .map((hoster, index) => ({ + ...hoster, + _sourceIndex: index + 1, + _sourceOffset: index, + })) + .filter( + (hoster) => + requestedSourceIndex === null || + hoster._sourceOffset === requestedSourceIndex, + ); + + const resolvedStreams = []; + const resolvedEmbeds = []; + + for (const hoster of selectedHosterLinks) { + const candidateUrls = dedupeByKey( + [hoster.exportUrl, hoster.webplayerUrl].filter(Boolean), + (url) => url, + ); + + let resolved = { streams: [], embeds: [] }; + + for (const candidateUrl of candidateUrls) { + resolved = await resolveRecursiveIframeStreams(candidateUrl, eventUrl, { + maxDepth: 6, + visited: new Set(), + fallbackBase: LIVETV_BASE_URL, + logPrefix: "[LIVETV]", + preferEmbedForExternalIframes: true, + embedReferer: LIVETV_EMBED_REFERER, + }); + + if (resolved.streams.length > 0 || resolved.embeds.length > 0) { + break; + } + } + + resolvedStreams.push( + ...resolved.streams.map((stream, streamIndex) => ({ + title: `${hoster.title}${resolved.streams.length > 1 ? ` ${streamIndex + 1}` : ""}`, + url: stream.url, + referer: + stream.referer || + hoster.exportUrl || + hoster.webplayerUrl || + eventUrl, + _sourceIndex: hoster._sourceIndex, + })), + ); + + resolvedEmbeds.push( + ...resolved.embeds.map((embed, embedIndex) => ({ + title: `${hoster.title} Embed${resolved.embeds.length > 1 ? ` ${embedIndex + 1}` : ""}`, + url: embed.url, + referer: embed.referer || LIVETV_EMBED_REFERER, + _isEmbed: true, + _sourceIndex: hoster._sourceIndex, + })), + ); + } + + const uniqueStreams = dedupeByKey( + resolvedStreams, + (item) => `${item.url}__${item.referer || ""}`, + ); + const uniqueEmbeds = dedupeByKey( + resolvedEmbeds, + (item) => `${item.url}__${item.referer || ""}`, + ); + + console.log( + `[LIVETV] Resolved ${uniqueStreams.length} direct streams and ${uniqueEmbeds.length} embeds for ${channelId}`, + ); + return uniqueStreams.length > 0 ? uniqueStreams : uniqueEmbeds; + } catch (error) { + console.error( + `[LIVETV] Error resolving stream for ${channelId}:`, + error.message, + ); + return []; + } +} + +async function getLivetvSources(channelId) { + try { + const { eventUrl, hosterLinks } = await fetchLivetvEventEntries(channelId); + if (!eventUrl || hosterLinks.length === 0) { + return []; + } + + return buildLivetvSourceOptions(hosterLinks); + } catch (error) { + console.error( + `[LIVETV] Error fetching source list for ${channelId}:`, + error.message, + ); + return []; + } +} + +// === LINKZY CHANNELS (loaded from linkzy.json) === +const LINKZY_CHANNELS = require("./linkzy.json"); + +/** + * Returns Linkzy channels from linkzy.json (no API call / decryption needed) + */ +function fetchLinkzyChannels() { + return LINKZY_CHANNELS.filter((ch) => ch.active); +} + +/** + * Get Linkzy channels for a specific category + */ +function getLinkzyChannelsByCategory(categoryId) { + try { + // Map catalog ID to API category string + const categoryMap = { + linkzy_generaliste: "general", + linkzy_sport: "sports", + linkzy_cinema: "movies", + linkzy_info: "chaines_info", + linkzy_jeunesse: "chaines_jeunesse", + }; + + const apiCategory = categoryMap[categoryId]; + if (!apiCategory) { + console.error(`[LINKZY] Unknown category: ${categoryId}`); + return []; + } + + const allChannels = fetchLinkzyChannels(); + const filteredChannels = allChannels.filter( + (ch) => ch.category === apiCategory, + ); + + console.log( + `[LINKZY] Category ${categoryId} (${apiCategory}): ${filteredChannels.length} channels`, + ); + + return filteredChannels.map((ch) => ({ + id: `linkzy_${ch.id}`, + type: "tv", + name: ch.name, + poster: ch.logo || null, + })); + } catch (error) { + console.error( + "[LINKZY] Error getting channels by category:", + error.message, + ); + return []; + } +} + +/** + * Get stream URLs for a Linkzy channel (returns array of {label, url}) + */ +function getLinkzyStream(channelId) { + try { + const numericId = parseInt(channelId.replace("linkzy_", "")); + const allChannels = fetchLinkzyChannels(); + const channel = allChannels.find((ch) => ch.id === numericId); + + if (!channel) { + console.error(`[LINKZY] Channel ${channelId} not found`); + return []; + } + + // streamUrl is a JSON string containing an array of {label, url} + let sources = []; + try { + sources = + typeof channel.streamUrl === "string" + ? JSON.parse(channel.streamUrl) + : channel.streamUrl; + } catch (parseErr) { + // Fallback: treat as a plain URL string + console.warn( + `[LINKZY] Could not parse streamUrl as JSON, using as plain URL`, + ); + sources = [{ label: "Principal", url: channel.streamUrl }]; + } + + if (!Array.isArray(sources)) { + sources = [{ label: "Principal", url: String(sources) }]; + } + + console.log( + `[LINKZY] Stream for ${channel.name}: ${sources.length} source(s)`, + ); + return sources; + } catch (error) { + console.error("[LINKZY] Error getting stream:", error.message); + return []; + } +} + +// === ROUTES === + +/** + * GET /api/livetv/resolve-livehdtv + * Resolve a livehdtv.com embed URL to get the m3u8 stream URL + * Uses got-scraping to bypass Cloudflare protection + * Called by the browser extension + */ +router.get("/resolve-livehdtv", async (req, res) => { + try { + const { embedUrl } = req.query; + + if (!embedUrl) { + return res.status(400).json({ error: "Missing embedUrl parameter" }); + } + + console.log(`[LIVEHDTV-API] Resolving embed URL: ${embedUrl}`); + + // Step 1: Fetch the livehdtv/yayin page to find the token.php iframe + const { gotScraping } = await import("got-scraping"); + + const livehdtvResponse = await gotScraping({ + url: embedUrl, + headers: { + Referer: "https://www.livehdtv.com/", + }, + headerGeneratorOptions: { + browsers: [{ name: "chrome", minVersion: 120 }], + devices: ["desktop"], + locales: ["fr-FR", "en-US"], + operatingSystems: ["windows"], + }, + }); + + const livehdtvHtml = livehdtvResponse.body; + console.log(`[LIVEHDTV-API] livehdtv page length: ${livehdtvHtml.length}`); + + // Find the inner iframe (token.php) + const innerIframeMatch = livehdtvHtml.match( + /]*src=["']([^"']+)["']/i, + ); + if (!innerIframeMatch) { + console.error("[LIVEHDTV-API] No inner iframe found in livehdtv page"); + return res.status(404).json({ error: "No token.php iframe found" }); + } + + let tokenPhpUrl = innerIframeMatch[1]; + console.log(`[LIVEHDTV-API] Found token.php iframe: ${tokenPhpUrl}`); + + if (!tokenPhpUrl.startsWith("http")) { + tokenPhpUrl = `https://www.livehdtv.com${tokenPhpUrl}`; + } + + // Step 2: Fetch token.php with got-scraping (to bypass Cloudflare) + const tokenResponse = await gotScraping({ + url: tokenPhpUrl, + headers: { + Referer: embedUrl, // Critical for validation + }, + headerGeneratorOptions: { + browsers: [{ name: "chrome", minVersion: 120 }], + devices: ["desktop"], + locales: ["fr-FR", "en-US"], + operatingSystems: ["windows"], + }, + }); + + const tokenHtml = tokenResponse.body; + console.log( + `[LIVEHDTV-API] token.php response length: ${tokenHtml.length}`, + ); + + // Extract file: "...m3u8..." from JWPlayer setup + const fileMatch = tokenHtml.match(/file:\s*["']([^"']+\.m3u8[^"']*)["']/); + if (!fileMatch) { + console.error("[LIVEHDTV-API] Could not extract m3u8 from token.php"); + console.log( + "[LIVEHDTV-API] token.php preview:", + tokenHtml.substring(0, 500), + ); + return res + .status(404) + .json({ error: "Could not extract m3u8 from token.php" }); + } + + const m3u8Url = fileMatch[1]; + console.log(`[LIVEHDTV-API] Found m3u8: ${m3u8Url}`); + + return res.json({ + success: true, + m3u8Url: m3u8Url, + source: "livehdtv", + }); + } catch (error) { + console.error("[LIVEHDTV-API] Error:", error.message); + return res.status(500).json({ error: error.message }); + } +}); + +/** + * GET /api/livetv/manifest + * Récupère le manifest combiné (TV Direct + Vavoo + Linkzy) + */ +router.get("/manifest", async (req, res) => { + try { + // Nouvelle clé de cache pour la version fusionnée (v4 = added Linkzy) + const cacheKey = generateCacheKey("manifest_combined_v6"); + + // Vérifier le cache + const cached = await getFromCache(cacheKey); + if (cached) { + return res.json(cached); + } + + // Récupérer les deux manifests en parallèle + // On utilise un catch individuel pour ne pas bloquer si l'un échoue + const [tvDirectRes, vavooRes] = await Promise.all([ + axios + .get(`${TVDIRECT_BASE_URL}/manifest.json`, { + headers: STREMIO_HEADERS, + timeout: 5000, + }) + .catch((e) => ({ error: e })), + axios + .get(`${VAVOO_BASE_URL}/manifest.json`, { + timeout: 5000, + }) + .catch((e) => ({ error: e })), + ]); + + // Manifeste de base + const manifest = { + id: "org.stremio.merged", + version: "1.0.0", + name: "Merged Live TV", + description: + "Merged TV sources (TV Direct, Vavoo, WITV, Bolaloca, LiveTV)", + catalogs: [], + resources: ["catalog", "meta", "stream"], + types: ["tv"], + idPrefixes: [], + }; + + // Fusionner TV Direct (User request: Don't use default tv-general etc.) + // We only keep idPrefixes/resources if needed, but not catalogs + if (tvDirectRes && !tvDirectRes.error && tvDirectRes.data) { + const data = tvDirectRes.data; + // if (data.catalogs) manifest.catalogs.push(...data.catalogs); + if (data.idPrefixes) manifest.idPrefixes.push(...data.idPrefixes); + } + + // Fusionner Vavoo + if (vavooRes && !vavooRes.error && vavooRes.data) { + const data = vavooRes.data; + if (data.catalogs) { + // Ajouter les catalogues Vavoo (TvVoo France) + manifest.catalogs.push(...data.catalogs); + } + if (data.idPrefixes) { + manifest.idPrefixes.push(...data.idPrefixes); + } else { + // Préfixe par défaut pour Vavoo si absent + manifest.idPrefixes.push("vavoo_"); + } + } + + // Ajouter les catalogues WITV (Wiflix) + const wiflixNames = { + wiflix_generaliste: "Généraliste", + wiflix_cinema: "Cinéma", + wiflix_sport: "Sport", + wiflix_documentaire: "Documentaire", + wiflix_enfants: "Enfants", + wiflix_info: "Info", + wiflix_musique: "Musique", + }; + + for (const [key, name] of Object.entries(wiflixNames)) { + manifest.catalogs.push({ + type: "tv", + id: key, + name: name, + }); + } + manifest.idPrefixes.push("wiflix_"); + + // Ajouter les catalogues Sosplay + const sosplayNames = { + sosplay_chaines: "Bolaloca", + }; + + for (const [key, name] of Object.entries(sosplayNames)) { + manifest.catalogs.push({ + type: "tv", + id: key, + name: name, + }); + } + manifest.idPrefixes.push("sosplay_"); + + for (const [key, config] of Object.entries(LIVETV_CATEGORIES)) { + manifest.catalogs.push({ + type: "tv", + id: key, + name: `${config.emoji || "📺"} ${config.name}`, + }); + } + manifest.idPrefixes.push("livetv_"); + + // Ajouter les catalogues Matches (FIRST in vavoo source - before vavoo_tv_fr) + // Insert at the beginning of catalogs array so it appears first + const matchesCatalogs = []; + for (const [key, config] of Object.entries(SOSPLAY_MATCHES_CATEGORIES)) { + matchesCatalogs.push({ + type: "tv", + id: key, + name: config.name, + }); + } + // Prepend matches catalogs to the beginning + manifest.catalogs = [...matchesCatalogs, ...manifest.catalogs]; + manifest.idPrefixes.push("match_"); + + // Ajouter les catalogues TVMio + for (const [catId, config] of Object.entries(TVMIO_CATEGORIES)) { + manifest.catalogs.push({ + type: "tv", + id: catId, + name: config.name, + }); + } + manifest.idPrefixes.push("tvmio-"); + + // [DÉSACTIVÉ] Linkzy temporairement désactivé + // for (const [catId, config] of Object.entries(LINKZY_CATEGORIES)) { + // manifest.catalogs.push({ + // type: 'tv', + // id: config.id, + // name: config.name, + // _free: true, + // }); + // } + // manifest.idPrefixes.push('linkzy_'); + + // Sauvegarder en cache + await saveToCache(cacheKey, manifest); + + res.json(manifest); + } catch (error) { + console.error("[LIVETV] Erreur manifest:", error.message); + res.status(500).json({ error: "Impossible de charger le manifest" }); + } +}); + +/** + * GET /api/livetv/catalog/:type/:catalogId + * Récupère un catalogue de chaînes + */ +router.get("/catalog/:type/:catalogId", async (req, res) => { + const { type, catalogId } = req.params; + + try { + const catalogCacheVersion = + catalogId.startsWith("tvmio_") || + catalogId.startsWith("sosplay_") || + catalogId.startsWith("livetv_") + ? "v5" + : "v1"; + const cacheKey = generateCacheKey( + `catalog_${type}_${catalogId}_${catalogCacheVersion}`, + ); + const isMatchesCatalog = catalogId.startsWith("matches_"); + const isDynamicCatalog = + isMatchesCatalog || catalogId.startsWith("livetv_"); + + // Vérifier le cache (1 minute pour matches/LiveTV, 24h pour le reste) + const cached = isDynamicCatalog + ? await getFromCacheMs(cacheKey, 60000) // 1 minute pour matches/LiveTV + : await getFromCache(cacheKey); + if (cached) { + return res.json(cached); + } + + let catalog = null; + + // Déterminer la source en fonction de l'ID du catalogue + if (catalogId.startsWith("tvmio_")) { + // Source TVMio (Local M3U) + console.log(`[LIVETV] Fetching TVMio (M3U) catalog: ${catalogId}`); + const tvmioConfig = TVMIO_CATEGORIES[catalogId]; + + if (tvmioConfig) { + const allChannels = await parseM3u(); + const remoteMetas = await fetchTvmioCatalogMetas(catalogId); + const tvmioImagesMap = buildTvmioImagesMap(remoteMetas); + const targetGroup = tvmioConfig.genre; // e.g. "FR | General" + + // Filter by group + let filtered = allChannels.filter((ch) => ch.group === targetGroup); + + // Deduplicate by ID (pick first one for the catalog entry) + const unique = []; + const seen = new Set(); + for (const ch of filtered) { + if (!seen.has(ch.id)) { + seen.add(ch.id); + const remoteImages = getTvmioRemoteImages(ch, tvmioImagesMap); + unique.push({ + id: `tvmio-${ch.id}`, // Prefix for routing + type: "tv", + name: ch.title, + poster: remoteImages.poster, + logo: remoteImages.logo, + background: remoteImages.background, + description: ch.group, + }); + } + } + + catalog = { metas: unique }; + } else { + catalog = { metas: [] }; + } + console.log( + `[TVMIO] Result: ${catalog.metas ? catalog.metas.length : 0} channels`, + ); + // [DÉSACTIVÉ] Linkzy temporairement désactivé + // } else if (catalogId.startsWith('linkzy_')) { + // const channels = await getLinkzyChannelsByCategory(catalogId); + // catalog = { metas: channels }; + } else if (catalogId.startsWith("matches_")) { + // Source Matches (Sosplay matches) + console.log(`[LIVETV] Fetching Matches catalog: ${catalogId}`); + const matches = await scrapeSosplayMatches(catalogId); + console.log(`[LIVETV] Matches result: ${matches.length} matches`); + catalog = { + metas: matches, + }; + } else if (catalogId.startsWith("sosplay_")) { + // Source Bolaloca/Elitegol (compat prefix sosplay_) + console.log(`[LIVETV] Fetching Bolaloca catalog: ${catalogId}`); + const channels = await scrapeSosplayChannels(catalogId); + console.log( + `[LIVETV] Bolaloca channels result: ${channels.length} channels`, + ); + catalog = { + metas: channels, + }; + } else if (catalogId.startsWith("livetv_")) { + console.log(`[LIVETV] Fetching LiveTV catalog: ${catalogId}`); + const channels = await scrapeLivetvChannels(catalogId); + console.log(`[LIVETV] LiveTV channels result: ${channels.length} events`); + catalog = { + metas: channels, + }; + } else if (catalogId.startsWith("wiflix_")) { + // Source Witv (Wiflix) + console.log(`[LIVETV] Fetching Wiflix catalog: ${catalogId}`); + const channels = await scrapeWitvChannels(catalogId); + console.log( + `[LIVETV] Wiflix channels result: ${channels.length} channels`, + ); + catalog = { + metas: channels, + }; + console.log( + `[LIVETV] Wiflix catalog response: ${JSON.stringify(catalog).substring(0, 500)}`, + ); + } else if (catalogId.startsWith("vavoo_")) { + // Source Vavoo + const url = `${VAVOO_BASE_URL}/catalog/${type}/${catalogId}.json`; + const response = await axios.get(url, { timeout: 10000 }); + catalog = response.data; + + // Note: Si on doit supprimer les images comme demandé ("sans image"), + // on pourrait effectuer un map ici sur catalog.metas + } else { + // Source TV Direct (Défaut) + const url = `${TVDIRECT_BASE_URL}/catalog/${type}/${catalogId}.json`; + const response = await axios.get(url, { + headers: STREMIO_HEADERS, + timeout: 10000, + }); + catalog = response.data; + } + + // Sauvegarder en cache + await saveToCache(cacheKey, catalog); + + res.json(catalog); + } catch (error) { + console.error(`[LIVETV] Erreur catalog ${catalogId}:`, error.message); + res.status(500).json({ error: "Impossible de charger le catalogue" }); + } +}); + +/** + * GET /api/livetv/stream/:type/:channelId + * Récupère les flux d'une chaîne + */ +router.get("/stream/:type/:channelId", async (req, res) => { + const { type, channelId } = req.params; + const mode = + String(req.query.mode || "").toLowerCase() === "sources" + ? "sources" + : "stream"; + const parsedSourceIndex = Number.parseInt( + String(req.query.sourceIndex ?? ""), + 10, + ); + const sourceIndex = + Number.isInteger(parsedSourceIndex) && parsedSourceIndex >= 0 + ? parsedSourceIndex + : null; + + try { + const accessKey = req.headers["x-access-key"]; + + let isVip = { vip: false }; + if (accessKey) { + isVip = await verifyAccessKey(accessKey); + } + + // Block VIP-only sources immediately if not VIP + if ( + (channelId.startsWith("matches_") || + channelId.startsWith("tvmio-") || + channelId.startsWith("iptv_")) && + !isVip.vip + ) { + return res.status(403).json({ error: "Réservé aux membres VIP" }); + } + + // IPTV Xtream — return proxified m3u8 URL directly + if (channelId.startsWith("iptv_")) { + const streamId = channelId.replace("iptv_", ""); + const directUrl = `${XTREAM_URL}/live/${XTREAM_USER}/${XTREAM_PASS}/${streamId}.m3u8`; + const proxiedUrl = `${IPTV_STREAM_PROXY}/${directUrl}`; + return res.json({ + streams: [ + { + url: proxiedUrl, + title: "IPTV Stream", + behaviorHints: { notWebReady: false }, + }, + ], + }); + } + + const skipOuterCache = channelId.startsWith("livetv_"); + const cacheKey = generateCacheKey( + `stream_${type}_${channelId}_${mode}_${sourceIndex ?? "all"}_v6_${isVip.vip ? "vip" : "free"}`, + ); + const streamCacheVariant = isVip.vip ? "vip" : "free"; + + // Vérifier le cache (expiration plus courte pour les streams: 1h) + const cached = skipOuterCache ? null : await getFromCache(cacheKey, 1); + if (cached) { + return res.json(cached); + } + + let streamData = null; + + if (channelId.startsWith("tvmio-")) { + // === SOURCE TVMIO (Local M3U) === + console.log(`[TVMIO] Getting stream for ${channelId}`); + + const targetId = channelId.replace("tvmio-", ""); + const allChannels = await parseM3u(); + + // Find all entries for this ID (support multiple qualities/sources) + const matches = allChannels.filter((ch) => ch.id === targetId); + + if (matches.length > 0) { + console.log( + `[TVMIO] Found ${matches.length} stream(s) for ${channelId}`, + ); + + const streams = matches.map((match, index) => { + // Try to guess quality/label from title + // Pattern: "FR | TF1 FHD" + let title = match.title || `Source ${index + 1}`; + // Simplify title if it contains common quality markers, + // otherwise keep full title or index + if (title.includes("FHD")) title = "FHD"; + else if (title.includes("HD") && !title.includes("UHD")) title = "HD"; + else if (title.includes("4K") || title.includes("UHD")) title = "4K"; + else if (title.includes("SD")) title = "SD"; + else if (index > 0 && title === matches[0].title) + title = `Source ${index + 1}`; + + const originalUrl = match.stream; + const encodedUrl = encodeURIComponent(originalUrl); + // Use proxy server to help with CORS on some players (only if VIP) + const proxyUrl = isVip.vip + ? `${PROXY_SERVER_URL}?url=${encodedUrl}` + : originalUrl; + + return { + title: title, + url: proxyUrl, + originalUrl: originalUrl, + _isTvmio: true, + behaviorHints: { + notWebReady: false, + }, + }; + }); + + streamData = { streams: streams }; + } else { + console.log(`[TVMIO] No streams found for ${channelId} in M3U`); + streamData = { streams: [] }; + } + // [DÉSACTIVÉ] Linkzy temporairement désactivé + // } else if (channelId.startsWith('linkzy_')) { + // const sources = await getLinkzyStream(channelId); + // if (sources && sources.length > 0) { + // streamData = { + // streams: sources.map(source => ({ + // title: `${source.label || 'Linkzy Stream'}`, + // url: source.url, + // behaviorHints: { notWebReady: false } + // })) + // }; + // } else { + // streamData = { streams: [] }; + // } + } else if (channelId.startsWith("match_")) { + // === SOURCE MATCHES (Sosplay matches) === + const matchCacheKey = generateCacheKey( + `match_stream_${channelId}_ua2_${streamCacheVariant}`, + ); + + // Check for fresh cache (30 seconds) + const cachedMatch = await getFromCacheMs(matchCacheKey, 30000); + + if (cachedMatch) { + console.log(`[SOSPLAY-MATCHES] Serving cached stream for ${channelId}`); + return res.json(cachedMatch); + } + + // No cache or expired - fetch fresh + console.log(`[SOSPLAY-MATCHES] Fetching fresh stream for ${channelId}`); + const matchStreams = await resolveSosplayMatchStream(channelId); + + if (!matchStreams || matchStreams.length === 0) { + return res.status(404).json({ error: "Flux match introuvable" }); + } + + // Build streams array with all French servers + const streams = matchStreams.map((stream) => { + const encodedUrl = encodeURIComponent(stream.url); + + const headers = JSON.stringify( + buildStreamProxyHeaders( + stream.referer || "https://dishtrainer.net/", + "https://dishtrainer.net", + stream.userAgent || STREAM_PROXY_USER_AGENT, + ), + ); + const encodedHeaders = encodeURIComponent(headers); + // Only proxyify if VIP + const proxyUrl = isVip.vip + ? `${PROXY_SERVER_URL}?url=${encodedUrl}&headers=${encodedHeaders}` + : stream.url; + + return { + title: stream.title, + url: proxyUrl, + originalUrl: stream.url, + referer: stream.referer, + userAgent: stream.userAgent || STREAM_PROXY_USER_AGENT, + behaviorHints: { + notWebReady: false, + }, + }; + }); + + streamData = { + streams: streams, + _cacheTime: Date.now(), + }; + + // Save to cache with timestamp + await saveToCache(matchCacheKey, streamData); + } else if (channelId.startsWith("sosplay_")) { + // === SOURCE BOLALOCA (compat prefix sosplay_) === + const sosplayCacheKey = generateCacheKey( + `sosplay_stream_${channelId}_ua2_${streamCacheVariant}`, + ); + + // Check for fresh cache (30 seconds) - stale-while-revalidate pattern + const cachedSosplay = await getFromCacheMs(sosplayCacheKey, 30000); + + if (cachedSosplay) { + console.log(`[BOLALOCA] Serving cached stream for ${channelId}`); + return res.json(cachedSosplay); + } + + // No cache or expired - fetch fresh + console.log(`[BOLALOCA] Fetching fresh stream for ${channelId}`); + const sosplayStreams = await resolveSosplayStream(channelId); + + if (!sosplayStreams || sosplayStreams.length === 0) { + return res.status(404).json({ error: "Flux Bolaloca introuvable" }); + } + + // Build streams array with all servers + const streams = sosplayStreams.map((stream) => { + if (stream._isEmbed) { + return { + title: `Bolaloca - ${stream.title}`, + url: stream.url, + originalUrl: stream.url, + referer: stream.referer, + userAgent: stream.userAgent || LIVE_PAGE_USER_AGENT, + _isEmbed: true, + behaviorHints: { + notWebReady: false, + }, + }; + } + + const encodedUrl = encodeURIComponent(stream.url); + const headers = JSON.stringify( + buildStreamProxyHeaders( + stream.referer || BOLALOCA_BASE_URL, + BOLALOCA_BASE_URL, + stream.userAgent || LIVE_PAGE_USER_AGENT, + ), + ); + const encodedHeaders = encodeURIComponent(headers); + // Only proxyify if VIP + const proxyUrl = isVip.vip + ? `${PROXY_SERVER_URL}?url=${encodedUrl}&headers=${encodedHeaders}` + : stream.url; + + return { + title: `Bolaloca - ${stream.title}`, + url: proxyUrl, + originalUrl: stream.url, + referer: stream.referer, // Pass referer for extension + userAgent: stream.userAgent || LIVE_PAGE_USER_AGENT, + behaviorHints: { + notWebReady: false, + }, + }; + }); + + streamData = { + streams: streams, + _cacheTime: Date.now(), + }; + + // Save to cache with timestamp + await saveToCache(sosplayCacheKey, streamData); + } else if (channelId.startsWith("livetv_")) { + if (mode === "sources") { + const livetvSourcesCacheKey = generateCacheKey( + `livetv_sources_${channelId}_v1`, + ); + const cachedLiveTvSources = await getFromCacheMs( + livetvSourcesCacheKey, + 30000, + ); + + if (cachedLiveTvSources) { + console.log(`[LIVETV] Serving cached source list for ${channelId}`); + return res.json(cachedLiveTvSources); + } + + console.log(`[LIVETV] Fetching source list for ${channelId}`); + const sources = await getLivetvSources(channelId); + + if (!sources || sources.length === 0) { + return res.status(404).json({ error: "Sources LiveTV introuvables" }); + } + + streamData = { + sources, + _cacheTime: Date.now(), + }; + + await saveToCache(livetvSourcesCacheKey, streamData); + } else { + const livetvCacheKey = generateCacheKey( + `livetv_stream_${channelId}_source_${sourceIndex ?? "all"}_ua3_${streamCacheVariant}`, + ); + const cachedLiveTv = await getFromCacheMs(livetvCacheKey, 30000); + + if (cachedLiveTv) { + console.log( + `[LIVETV] Serving cached stream for ${channelId} (source ${sourceIndex ?? "all"})`, + ); + return res.json(cachedLiveTv); + } + + console.log( + `[LIVETV] Fetching fresh stream for ${channelId}${sourceIndex !== null ? ` (source ${sourceIndex + 1})` : ""}`, + ); + const livetvStreams = await resolveLivetvStream(channelId, { + sourceIndex, + }); + + if (!livetvStreams || livetvStreams.length === 0) { + return res.status(404).json({ error: "Flux LiveTV introuvable" }); + } + + const streams = livetvStreams.map((stream) => { + if (stream._isEmbed) { + return { + title: `LiveTV - ${stream.title}`, + url: stream.url, + originalUrl: stream.url, + referer: stream.referer, + userAgent: stream.userAgent || LIVE_PAGE_USER_AGENT, + _isEmbed: true, + _sourceIndex: stream._sourceIndex, + behaviorHints: { + notWebReady: false, + }, + }; + } + + const encodedUrl = encodeURIComponent(stream.url); + const headers = JSON.stringify( + buildStreamProxyHeaders( + stream.referer || LIVETV_BASE_URL, + LIVETV_BASE_URL, + stream.userAgent || LIVE_PAGE_USER_AGENT, + ), + ); + const encodedHeaders = encodeURIComponent(headers); + const proxyUrl = isVip.vip + ? `${PROXY_SERVER_URL}?url=${encodedUrl}&headers=${encodedHeaders}` + : stream.url; + + return { + title: `LiveTV - ${stream.title}`, + url: proxyUrl, + originalUrl: stream.url, + referer: stream.referer, + userAgent: stream.userAgent || LIVE_PAGE_USER_AGENT, + _sourceIndex: stream._sourceIndex, + behaviorHints: { + notWebReady: false, + }, + }; + }); + + streamData = { + streams, + _cacheTime: Date.now(), + }; + + await saveToCache(livetvCacheKey, streamData); + } + } else if (channelId.startsWith("wiflix_")) { + // === SOURCE WITV (WIFLIX) === + const wiflixCacheKey = generateCacheKey( + `wiflix_stream_${channelId}_${streamCacheVariant}`, + ); + + // Check for fresh cache (30 seconds) - stale-while-revalidate pattern + const cachedWiflix = await getFromCacheMs(wiflixCacheKey, 30000); // 30 seconds in ms + + if (cachedWiflix) { + console.log(`[WITV] Serving cached stream for ${channelId}`); + + // Trigger background update if cache is older than 30 seconds + const cacheAge = Date.now() - (cachedWiflix._cacheTime || 0); + if (cacheAge > 30000) { + // 30 seconds + console.log( + `[WITV] Cache is ${cacheAge}ms old, triggering background update`, + ); + // Background update - don't await + (async () => { + try { + const freshM3u8 = await resolveWitvStream(channelId); + if (freshM3u8) { + const encodedUrl = encodeURIComponent(freshM3u8); + const proxyUrl = isVip.vip + ? `${PROXY_SERVER_URL}?url=${encodedUrl}` + : freshM3u8; + const freshData = { + streams: [ + { + title: "Orca", + url: proxyUrl, + originalUrl: freshM3u8, + behaviorHints: { notWebReady: false }, + }, + ], + _cacheTime: Date.now(), + }; + await saveToCache(wiflixCacheKey, freshData); + console.log(`[WITV] Background cache updated for ${channelId}`); + } + } catch (e) { + console.error(`[WITV] Background update failed: ${e.message}`); + } + })(); + } + + return res.json(cachedWiflix); + } + + // No cache or expired - fetch fresh + console.log(`[WITV] Fetching fresh stream for ${channelId}`); + const m3u8Url = await resolveWitvStream(channelId); + + if (!m3u8Url) { + return res.status(404).json({ error: "Flux Wiflix introuvable" }); + } + + // For API access (VIP users), wrap URL in proxiesembed proxy + // Extension users will use originalUrl to handle extraction themselves + // Only proxyify if VIP + const encodedUrl = encodeURIComponent(m3u8Url); + const proxyUrl = isVip.vip + ? `${PROXY_SERVER_URL}?url=${encodedUrl}` + : m3u8Url; // Non-VIPs get raw URL (will fail without extension) + + streamData = { + streams: [ + { + title: "Orca", + url: proxyUrl, + originalUrl: m3u8Url, // Keep original for debugging/extension use + behaviorHints: { + notWebReady: false, + }, + }, + ], + _cacheTime: Date.now(), + }; + + // Save to cache with timestamp + await saveToCache(wiflixCacheKey, streamData); + } else if (channelId.startsWith("vavoo_") || channelId.includes("vavoo")) { + // === SOURCE VAVOO === + // Requiert un proxy via proxiesembed + const url = `${VAVOO_BASE_URL}/stream/${type}/${channelId}.json`; + const response = await axios.get(url, { timeout: 10000 }); + streamData = response.data; + + if (streamData.streams) { + // Wrapper les URLs dans le proxy local + streamData.streams = streamData.streams.map((stream) => { + if (stream.url) { + // Encoder l'URL destination + const encodedUrl = encodeURIComponent(stream.url); + + // Préparer les headers (User-Agent Vavoo) pour le proxy + const headers = JSON.stringify({ "User-Agent": "VAVOO/2.6" }); + const encodedHeaders = encodeURIComponent(headers); + + // Créer l'URL pointant vers notre serveur proxy (only if VIP) + const proxyUrl = isVip.vip + ? `${PROXY_SERVER_URL}?url=${encodedUrl}&headers=${encodedHeaders}` + : stream.url; + + return { + ...stream, + url: proxyUrl, // L'URL que le lecteur utilisera + originalUrl: stream.url, // Conserver l'URL originale au cas où + behaviorHints: { + ...stream.behaviorHints, + notWebReady: false, + }, + }; + } + return stream; + }); + } + } else { + // === SOURCE TV DIRECT === + const url = `${TVDIRECT_BASE_URL}/stream/${type}/${channelId}.json`; + const response = await axios.get(url, { + headers: STREMIO_HEADERS, + timeout: 10000, + }); + streamData = response.data; + + if (streamData.streams) { + // Résoudre les URLs (spécifique TV Direct) + const resolvedStreams = await Promise.all( + streamData.streams.map(async (stream) => { + if (stream.url) { + const resolvedUrl = await resolvePlayUrl(stream.url); + return { + ...stream, + url: resolvedUrl || stream.url, + originalUrl: stream.url, + }; + } + return stream; + }), + ); + streamData.streams = resolvedStreams.filter((s) => { + // Filter out invalid streams + if (!s.url) return false; + + // Filter out ALL FamilyRestream sources (User Request: "non fonctionnel") + if ( + s.url.includes("familyrestream.com") || + (s.originalUrl && s.originalUrl.includes("familyrestream.com")) + ) { + return false; + } + + return true; + }); + } + } + + if ( + mode !== "sources" && + (!streamData.streams || streamData.streams.length === 0) + ) { + return res.status(404).json({ error: "Aucun flux disponible" }); + } + + // Sauvegarder en cache + if (!skipOuterCache) { + await saveToCache(cacheKey, streamData); + } + + res.json(streamData); + } catch (error) { + console.error(`[LIVETV] Erreur stream ${channelId}:`, error.message); + res.status(500).json({ error: "Impossible de charger les flux" }); + } +}); + +/** + * GET /api/livetv/resolve/:playId + * Résout une URL de lecture spécifique (TV Direct) + */ +router.get("/resolve/:playId", async (req, res) => { + const { playId } = req.params; + + try { + const playUrl = `${TVDIRECT_BASE_URL}/play/${playId}`; + const resolvedUrl = await resolvePlayUrl(playUrl); + + if (!resolvedUrl) { + return res.status(404).json({ error: "Impossible de résoudre l'URL" }); + } + + res.json({ + originalUrl: playUrl, + resolvedUrl: resolvedUrl, + }); + } catch (error) { + console.error(`[LIVETV] Erreur resolve ${playId}:`, error.message); + res.status(500).json({ error: "Erreur lors de la résolution" }); + } +}); + +/** + * DELETE /api/livetv/cache + * Nettoie le cache Live TV (admin only) + */ +router.delete("/cache", async (req, res) => { + try { + const files = await fsp.readdir(CACHE_DIR); + let deletedCount = 0; + + for (const file of files) { + if (file.endsWith(".json")) { + await fsp.unlink(path.join(CACHE_DIR, file)); + deletedCount++; + } + } + + res.json({ + success: true, + message: `Cache Live TV nettoyé: ${deletedCount} fichiers supprimés`, + }); + } catch (error) { + console.error("[LIVETV] Erreur nettoyage cache:", error.message); + res.status(500).json({ error: "Erreur lors du nettoyage du cache" }); + } +}); + +// === IPTV WEB (Xtream API) — VIP ONLY === +const XTREAM_URL = (process.env.XTREAM_URL || "").replace(/\/+$/, ""); +const XTREAM_USER = process.env.XTREAM_USER || ""; +const XTREAM_PASS = process.env.XTREAM_PASS || ""; +const IPTV_IMAGE_PROXY = "https://proxy.movix.blog/proxy"; +const IPTV_STREAM_PROXY = "https://proxiesembed.movix.blog/proxy"; + +// Cache catégories IPTV en mémoire (change rarement) +let iptvCategoriesCache = null; +let iptvCategoriesCacheTime = 0; +const IPTV_CATEGORIES_TTL = 30 * 60 * 1000; // 30 min + +// Auto-clear IPTV cache after TTL to free memory when not actively used +setInterval(() => { + if ( + iptvCategoriesCache && + Date.now() - iptvCategoriesCacheTime > IPTV_CATEGORIES_TTL + ) { + iptvCategoriesCache = null; + } +}, IPTV_CATEGORIES_TTL).unref(); + +/** + * GET /api/livetv/iptv/categories + * Récupère les catégories live de l'API Xtream (VIP only) + */ +router.get("/iptv/categories", requireVip, async (req, res) => { + try { + const now = Date.now(); + if ( + iptvCategoriesCache && + now - iptvCategoriesCacheTime < IPTV_CATEGORIES_TTL + ) { + return res.json(iptvCategoriesCache); + } + + const response = await axios.get(`${XTREAM_URL}/player_api.php`, { + params: { + username: XTREAM_USER, + password: XTREAM_PASS, + action: "get_live_categories", + }, + timeout: 15000, + }); + + const categories = (response.data || []).map((cat) => ({ + category_id: cat.category_id, + category_name: cat.category_name, + parent_id: cat.parent_id || 0, + })); + + iptvCategoriesCache = { categories }; + iptvCategoriesCacheTime = now; + + res.json({ categories }); + } catch (error) { + console.error("[IPTV] Erreur get_live_categories:", error.message); + res + .status(500) + .json({ error: "Erreur lors de la récupération des catégories IPTV" }); + } +}); + +/** + * GET /api/livetv/iptv/streams/:categoryId + * Récupère les chaînes d'une catégorie Xtream (VIP only) + * Images proxifiées via proxy.movix.blog + */ +router.get("/iptv/streams/:categoryId", requireVip, async (req, res) => { + const { categoryId } = req.params; + + try { + const response = await axios.get(`${XTREAM_URL}/player_api.php`, { + params: { + username: XTREAM_USER, + password: XTREAM_PASS, + action: "get_live_streams", + category_id: categoryId, + }, + timeout: 15000, + }); + + const streams = (response.data || []).map((stream) => ({ + stream_id: stream.stream_id, + name: stream.name, + stream_icon: stream.stream_icon + ? `${IPTV_IMAGE_PROXY}/${stream.stream_icon}` + : null, + epg_channel_id: stream.epg_channel_id || null, + category_id: stream.category_id, + })); + + res.json({ streams }); + } catch (error) { + console.error( + `[IPTV] Erreur get_live_streams cat=${categoryId}:`, + error.message, + ); + res + .status(500) + .json({ error: "Erreur lors de la récupération des chaînes IPTV" }); + } +}); + +/** + * GET /api/livetv/iptv/stream-url/:streamId + * Construit l'URL m3u8 proxifiée pour un stream Xtream (VIP only) + */ +router.get("/iptv/stream-url/:streamId", requireVip, async (req, res) => { + const { streamId } = req.params; + + try { + const directUrl = `${XTREAM_URL}/live/${XTREAM_USER}/${XTREAM_PASS}/${streamId}.m3u8`; + const proxiedUrl = `${IPTV_STREAM_PROXY}/${directUrl}`; + + res.json({ + streams: [ + { + url: proxiedUrl, + title: "IPTV Stream", + behaviorHints: { notWebReady: false }, + }, + ], + }); + } catch (error) { + console.error(`[IPTV] Erreur stream-url ${streamId}:`, error.message); + res.status(500).json({ error: "Erreur lors de la construction de l'URL" }); + } +}); + +module.exports = router; diff --git a/API/Mainapi/middleware/auth.js b/API/Mainapi/middleware/auth.js new file mode 100644 index 0000000..bf02bd9 --- /dev/null +++ b/API/Mainapi/middleware/auth.js @@ -0,0 +1,213 @@ +/** + * Authentication middleware and helpers. + * Extracted from server.js -- JWT setup, admin checks, session validation. + */ + +const jwt = require('jsonwebtoken'); +const { getPool } = require('../mysqlPool'); +const AUTH_METHODS = ['discord', 'google', 'bip39']; + +// Lazy pool getter -- avoids requiring the pool at module load time +let _pool = null; +function getDbPool() { + if (!_pool) _pool = getPool(); + return _pool; +} + +// === JWT Setup === +const JWT_SECRET = process.env.JWT_SECRET; +if (!JWT_SECRET) { + console.error("FATAL: JWT_SECRET is not defined in .env"); + process.exit(1); +} + +function issueJwt(userType, userId, sessionId, authMethod = null) { + // Issue a token without expiration (no exp claim) + const payload = { sub: userId, userType, sessionId }; + if (AUTH_METHODS.includes(authMethod)) { + payload.authMethod = authMethod; + } + return jwt.sign(payload, JWT_SECRET, { algorithm: 'HS256' }); +} + +// === Auth validation === + +async function getAuthIfValid(req) { + try { + const authHeader = req.headers['authorization'] || req.headers['Authorization']; + if (!authHeader || !authHeader.toLowerCase().startsWith('bearer ')) return null; + const token = authHeader.split(' ')[1]; + const payload = jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] }); + const { userType, sub: userId, sessionId } = payload; + const authMethod = AUTH_METHODS.includes(payload?.authMethod) + ? payload.authMethod + : (userType === 'bip39' ? 'bip39' : null); + if (!['oauth', 'bip39'].includes(userType) || !userId || !sessionId) return null; + + // Vérification de session via MySQL avec 3 tentatives + let hasSession = false; + const pool = getDbPool(); + + for (let attempt = 1; attempt <= 3; attempt++) { + try { + if (!pool) { + console.warn('[AUTH] MySQL pool not ready, attempt', attempt); + if (attempt < 3) { + await new Promise(resolve => setTimeout(resolve, 500)); + continue; + } + return null; + } + + const [rows] = await pool.execute( + 'SELECT id FROM user_sessions WHERE id = ? AND user_id = ? AND user_type = ?', + [sessionId, userId, userType] + ); + hasSession = rows.length > 0; + + if (hasSession) { + break; // Session trouvée, sortir de la boucle + } + + if (attempt < 3) { + console.log(`[AUTH] Tentative ${attempt}/3 échouée pour userType=${userType}, userId=${userId}, sessionId=${sessionId} - nouvelle tentative dans 0.5s`); + await new Promise(resolve => setTimeout(resolve, 500)); + } + } catch (error) { + console.error(`[AUTH] Erreur lors de la tentative ${attempt}/3:`, error.message); + if (attempt < 3) { + await new Promise(resolve => setTimeout(resolve, 500)); + } + } + } + + if (!hasSession) { + console.warn(`[AUTH] Session manquante après 3 tentatives pour userType=${userType}, userId=${userId}, sessionId=${sessionId}`); + return null; + } + + // Update last access as activity signal (fire-and-forget, pas de await) + updateSessionAccess(userType, userId, sessionId); + return { userType, userId, sessionId, authMethod }; + } catch { + return null; + } +} + +// === Session access updater (fire-and-forget) === + +const updateSessionAccess = async (userType, userId, sessionId) => { + try { + const pool = getDbPool(); + if (!pool) { + return false; + } + + // Fire-and-forget: ne pas bloquer le flux principal + pool.execute( + 'UPDATE user_sessions SET accessed_at = NOW() WHERE id = ? AND user_id = ? AND user_type = ?', + [sessionId, userId, userType] + ).catch(err => console.error('Error updating session access:', err)); + + return true; + } catch (error) { + console.error('Error updating session access:', error); + return false; + } +}; + +// === Admin middleware === + +// Middleware pour vérifier si l'utilisateur est admin +async function isAdmin(req, res, next) { + try { + const pool = getDbPool(); + // Vérifier si le pool MySQL est initialisé + if (!pool) { + console.error('❌ MySQL pool not initialized'); + return res.status(503).json({ success: false, error: 'Service temporairement indisponible - Base de données en cours d\'initialisation' }); + } + + // Vérifier le JWT + const auth = await getAuthIfValid(req); + if (!auth) { + return res.status(401).json({ success: false, error: 'Non autorisé - Token invalide' }); + } + + const { userId, userType } = auth; + + // Vérifier si l'utilisateur est dans la table admins + const [rows] = await pool.execute( + 'SELECT * FROM admins WHERE user_id = ? AND auth_type = ?', + [userId, userType === 'bip39' ? 'bip-39' : userType] + ); + + if (rows.length === 0) { + return res.status(403).json({ success: false, error: 'Accès refusé - Droits admin requis' }); + } + + // Récupérer le rôle (par défaut 'admin' si non défini) + const role = rows[0].role || 'admin'; + + // Ajouter les infos admin à la requête (avec le rôle) + req.admin = { userId, userType, adminId: rows[0].id, role }; + next(); + } catch (error) { + console.error('❌ Admin verification error:', error); + return res.status(500).json({ success: false, error: 'Erreur lors de la vérification admin' }); + } +} + +// Middleware pour vérifier si l'utilisateur est uploader ou admin (pour les liens de streaming) +async function isUploaderOrAdmin(req, res, next) { + try { + const pool = getDbPool(); + // Vérifier si le pool MySQL est initialisé + if (!pool) { + console.error('❌ MySQL pool not initialized'); + return res.status(503).json({ success: false, error: 'Service temporairement indisponible - Base de données en cours d\'initialisation' }); + } + + // Vérifier le JWT + const auth = await getAuthIfValid(req); + if (!auth) { + return res.status(401).json({ success: false, error: 'Non autorisé - Token invalide' }); + } + + const { userId, userType } = auth; + + // Vérifier si l'utilisateur est dans la table admins (admin ou uploader) + const [rows] = await pool.execute( + 'SELECT * FROM admins WHERE user_id = ? AND auth_type = ?', + [userId, userType === 'bip39' ? 'bip-39' : userType] + ); + + if (rows.length === 0) { + return res.status(403).json({ success: false, error: 'Accès refusé - Droits requis' }); + } + + // Récupérer le rôle (par défaut 'admin' si non défini) + const role = rows[0].role || 'admin'; + + // Autoriser les rôles 'admin' et 'uploader' + if (role !== 'admin' && role !== 'uploader') { + return res.status(403).json({ success: false, error: 'Accès refusé - Droits insuffisants' }); + } + + // Ajouter les infos admin à la requête (avec le rôle) + req.admin = { userId, userType, adminId: rows[0].id, role }; + next(); + } catch (error) { + console.error('❌ Admin/Uploader verification error:', error); + return res.status(500).json({ success: false, error: 'Erreur lors de la vérification des droits' }); + } +} + +module.exports = { + JWT_SECRET, + issueJwt, + isAdmin, + isUploaderOrAdmin, + getAuthIfValid, + updateSessionAccess +}; diff --git a/API/Mainapi/middleware/cors.js b/API/Mainapi/middleware/cors.js new file mode 100644 index 0000000..1299917 --- /dev/null +++ b/API/Mainapi/middleware/cors.js @@ -0,0 +1,63 @@ +/** + * CORS middleware configuration. + * Extracted from server.js -- restricted origin policy. + */ + +const cors = require("cors"); + +const corsMiddleware = cors({ + origin: (origin, callback) => { + const allowedDomains = [ + "movix.blog", + "movix.rodeo", + "movix.club", + "movix.site", + "movix11.pages.dev", + "nakios.site", + "cinezo.site", + "filmib.cc" + ]; + + // Allow requests with no origin (like mobile apps or curl requests) + if (!origin) return callback(null, true); + + // Allow all localhost requests (http and https) + if (origin.match(/^https?:\/\/localhost(:[0-9]+)?$/)) { + return callback(null, true); + } + + // Check if origin matches allowed domains (allows http, https, and subdomains) + const isAllowed = allowedDomains.some((domain) => { + // Allow exact match (http/s) or subdomain + return ( + origin === `https://${domain}` || + origin === `http://${domain}` || + origin.endsWith(`.${domain}`) + ); + }); + + if (isAllowed) { + callback(null, true); + } else { + callback(new Error("Not allowed by CORS")); + } + }, + methods: ["GET", "POST", "OPTIONS", "PUT", "DELETE", "PATCH", "HEAD"], + allowedHeaders: [ + "Content-Type", + "Authorization", + "X-Requested-With", + "Accept", + "Origin", + "X-No-Compression", + "Access-Control-Request-Headers", + "baggage", + "sentry-trace", + "x-profile-id", + "x-access-key", + ], + credentials: true, + optionsSuccessStatus: 204, +}); + +module.exports = corsMiddleware; diff --git a/API/Mainapi/middleware/security.js b/API/Mainapi/middleware/security.js new file mode 100644 index 0000000..ae41f81 --- /dev/null +++ b/API/Mainapi/middleware/security.js @@ -0,0 +1,171 @@ +/** + * Security middleware collection. + * Extracted from server.js -- security headers, keep-alive, domain restriction, + * and JSON parse error handler. + */ + +// Security headers (minimal set -- replaces Helmet) +function securityHeaders(req, res, next) { + res.setHeader('X-Content-Type-Options', 'nosniff'); + res.setHeader('X-Frame-Options', 'DENY'); + res.setHeader('X-XSS-Protection', '0'); // Disabled per OWASP recommendation (use CSP instead) + res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin'); + res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()'); + next(); +} + +// Middleware pour ajouter les headers Keep-Alive +function keepAliveHeaders(req, res, next) { + res.setHeader('Connection', 'keep-alive'); + res.setHeader('Keep-Alive', 'timeout=60, max=1000'); + next(); +} + +// Middleware de restriction de domaine et réponse fake pour route spécifique +function domainRestriction(req, res, next) { + // Autoriser les endpoints LiveTV pour l'extension + if (req.path.startsWith('/api/livetv/')) { + return next(); + } + + // Autoriser le callback serveur-à-serveur PayGate sans dépendre d'un Origin/Referer navigateur + if (req.path === '/api/vip/paygate/callback') { + return next(); + } + + const allowedDomains = [ + 'localhost:3000', + 'movix.blog', + 'movix.rodeo', + 'movix.club', + 'movix.site', + 'movix11.pages.dev', + 'nakios.site', + 'cinezo.site', + 'filmib.cc' + ]; + + const origin = req.get('origin'); + const referer = req.get('referer'); + + let isAllowed = false; + + // Strict domain verification + const checkDomain = (url) => { + try { + if (!url) return false; + const hostname = new URL(url).hostname; + // Allow exact matches or subdomains if needed (here we list full domains) + return allowedDomains.some(domain => { + // Handle localhost with port special case if needed, or just match hostname + if (domain.includes(':')) return url.includes(domain); + return hostname === domain || hostname.endsWith('.' + domain); + }); + } catch (e) { + return false; + } + }; + + if (origin) { + if (checkDomain(origin)) isAllowed = true; + } else if (referer) { + if (checkDomain(referer)) isAllowed = true; + } + + // Si autorisé, on continue + if (isAllowed) { + return next(); + } + + // Si non autorisé + // Route spécifique accessible mais avec fausse réponse + if (req.path.startsWith('/api/imdb/movie')) { + return res.json({ + "iframe_src": "https://movixfakesite.vercel.app/", + "player_links": [ + { + "player": "supervideo", + "link": "https://movixfakesite.vercel.app/", + "is_hd": false + }, + { + "player": "dropload", + "link": "https://movixfakesite.vercel.app/", + "is_hd": false + }, + { + "player": "mixdrop", + "link": "https://movixfakesite.vercel.app/", + "is_hd": false + } + ] + }); + } else if (req.path.startsWith('/api/imdb/tv')) { + return res.json({ + "type": "tv", + "series": [ + { + "title": "Stranger Things - Saison 5", + "audio_type": "VF", + "episode_count": 1, + "release_date": "2016", + "summary": "Quand un jeune garçon disparaît, une petite ville découvre une affaire mystérieuse, des expériences secrètes, des forces surnaturelles terrifiantes... et une fillette.", + "tmdb_data": { + "id": 66732, + "name": "Stranger Things", + "overview": "When a young boy vanishes, a small town uncovers a mystery involving secret experiments, terrifying supernatural forces, and one strange little girl.", + "first_air_date": "2016-07-15", + "poster_path": "/uOOtwVbSr4QDjAGIifLDwpb2Pdl.jpg", + "backdrop_path": "/8zbAoryWbtH0DKdev8abFAjdufy.jpg", + "vote_average": 8.59, + "match_score": 0.8818181818181817 + }, + "seasons": [ + { + "number": 1, + "title": "Saison 1", + "episodes": [ + { + "number": "1", + "versions": { + "vf": { + "title": "Episode 1", + "players": [ + { + "name": "Supervideo", + "link": "https://movixfakesite.vercel.app/" + } + ] + } + } + } + ] + } + ] + } + ] + }); + } + + // Bloquer toutes les autres routes + return res.status(404).json({ error: 'Not Found' }); +} + +// Error handler for JSON parsing errors (malformed requests like URL-encoded form data) +function jsonParseErrorHandler(err, req, res, next) { + if (err.type === 'entity.parse.failed') { + // Silently handle malformed JSON requests (likely bots or scanners) + return res.status(400).json({ + success: false, + error: 'Invalid JSON body' + }); + } + next(err); +} + +module.exports = { + securityHeaders, + keepAliveHeaders, + domainRestriction, + jsonParseErrorHandler +}; diff --git a/API/Mainapi/mysqlPool.js b/API/Mainapi/mysqlPool.js new file mode 100644 index 0000000..c09199a --- /dev/null +++ b/API/Mainapi/mysqlPool.js @@ -0,0 +1,66 @@ +const mysql = require('mysql2/promise'); +require('dotenv').config(); + +// Configuration de la connexion MySQL — credentials from environment variables +const dbConfig = { + host: process.env.DB_HOST, + port: parseInt(process.env.DB_PORT || '3306'), + user: process.env.DB_USER, + password: process.env.DB_PASSWORD, + database: process.env.DB_NAME, + waitForConnections: true, + connectionLimit: 20, // 20 × 6 workers = 120 connexions max (avant: 300 × 2 pools × 6 = 3600) + maxIdle: 5, // Libère les connexions inactives au-delà de 5 + idleTimeout: 60000, // Ferme les connexions idle après 60s + queueLimit: 200, // Limite la file d'attente en mémoire (avant: illimité) + enableKeepAlive: true, + keepAliveInitialDelay: 10000 +}; + +// Pool de connexions MySQL partagé — single instance per worker +let pool = null; +let poolInitializing = false; + +// Initialiser le pool (async, with connection test) +const initPool = async () => { + if (pool) return pool; + if (poolInitializing) { + // Prevent double-creation race: wait for existing init + return new Promise((resolve) => { + const check = setInterval(() => { + if (pool) { clearInterval(check); resolve(pool); } + }, 50); + }); + } + poolInitializing = true; + try { + pool = mysql.createPool(dbConfig); + console.log('✅ MySQL connection pool created successfully'); + + // Test de connexion + const connection = await pool.getConnection(); + console.log('✅ MySQL connection test successful'); + connection.release(); + } catch (error) { + console.error('❌ MySQL connection error:', error.message); + } finally { + poolInitializing = false; + } + return pool; +}; + +// Getter pour le pool (initialise si nécessaire — uses existing pool if already created) +const getPool = () => { + if (!pool) { + console.warn('⚠️ MySQL pool not initialized yet, initializing synchronously...'); + pool = mysql.createPool(dbConfig); + } + return pool; +}; + +module.exports = { + initPool, + getPool, + dbConfig +}; + diff --git a/API/Mainapi/package-lock.json b/API/Mainapi/package-lock.json new file mode 100644 index 0000000..987d2c7 --- /dev/null +++ b/API/Mainapi/package-lock.json @@ -0,0 +1,5632 @@ +{ + "name": "movix-api", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "movix-api", + "dependencies": { + "@fastify/compress": "^8.3.1", + "@fastify/cookie": "^11.0.2", + "@fastify/cors": "^11.2.0", + "@fastify/express": "^4.0.2", + "@fastify/formbody": "^8.0.2", + "@fastify/middie": "^9.1.0", + "@ffmpeg-installer/ffmpeg": "^1.1.0", + "axios": "^1.11.0", + "axios-cookiejar-support": "^6.0.4", + "better-sqlite3": "^12.5.0", + "bip32": "^5.0.1", + "bip39": "^3.1.0", + "bitcoinjs-lib": "^7.0.1", + "chardet": "^2.0.0", + "cheerio": "^1.1.2", + "compression": "^1.8.1", + "cors": "^2.8.5", + "crypto-js": "^4.2.0", + "cycletls": "^1.0.27", + "dotenv": "^17.2.1", + "express": "^4.21.2", + "express-list-endpoints": "^7.1.1", + "express-rate-limit": "^8.2.1", + "fastify": "^5.6.2", + "got-scraping": "^4.1.3", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.6", + "impit": "^0.9.2", + "ioredis": "^5.9.2", + "jsonwebtoken": "^9.0.2", + "mysql2": "^3.15.0", + "openai": "^6.15.0", + "proper-lockfile": "^4.1.2", + "socket.io": "^4.8.3", + "socks-proxy-agent": "^8.0.5", + "sqlite3": "^5.1.7", + "tiny-secp256k1": "^2.2.4", + "tough-cookie": "^5.1.2", + "uuid": "^11.1.0", + "write-file-atomic": "^6.0.0" + } + }, + "node_modules/@fastify/accept-negotiator": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@fastify/accept-negotiator/-/accept-negotiator-2.0.1.tgz", + "integrity": "sha512-/c/TW2bO/v9JeEgoD/g1G5GxGeCF1Hafdf79WPmUlgYiBXummY0oX3VVq4yFkKKVBKDNlaDUYoab7g38RpPqCQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/@fastify/ajv-compiler": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@fastify/ajv-compiler/-/ajv-compiler-4.0.5.tgz", + "integrity": "sha512-KoWKW+MhvfTRWL4qrhUwAAZoaChluo0m0vbiJlGMt2GXvL4LVPQEjt8kSpHI3IBq5Rez8fg+XeH3cneztq+C7A==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "ajv": "^8.12.0", + "ajv-formats": "^3.0.1", + "fast-uri": "^3.0.0" + } + }, + "node_modules/@fastify/compress": { + "version": "8.3.1", + "resolved": "https://registry.npmjs.org/@fastify/compress/-/compress-8.3.1.tgz", + "integrity": "sha512-BUpItLr6MUX9e9ukg5Y6xekyA/7pBFG8QWtFCrUDm9ctoBc3R2/nA16yOaOWtVoccpXGjdDEYA/MxAb5+8cxag==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/accept-negotiator": "^2.0.0", + "fastify-plugin": "^5.0.0", + "mime-db": "^1.52.0", + "minipass": "^7.0.4", + "peek-stream": "^1.1.3", + "pump": "^3.0.0", + "pumpify": "^2.0.1", + "readable-stream": "^4.5.2" + } + }, + "node_modules/@fastify/compress/node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, + "node_modules/@fastify/compress/node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/@fastify/compress/node_modules/readable-stream": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz", + "integrity": "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==", + "license": "MIT", + "dependencies": { + "abort-controller": "^3.0.0", + "buffer": "^6.0.3", + "events": "^3.3.0", + "process": "^0.11.10", + "string_decoder": "^1.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/@fastify/cookie": { + "version": "11.0.2", + "resolved": "https://registry.npmjs.org/@fastify/cookie/-/cookie-11.0.2.tgz", + "integrity": "sha512-GWdwdGlgJxyvNv+QcKiGNevSspMQXncjMZ1J8IvuDQk0jvkzgWWZFNC2En3s+nHndZBGV8IbLwOI/sxCZw/mzA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "cookie": "^1.0.0", + "fastify-plugin": "^5.0.0" + } + }, + "node_modules/@fastify/cookie/node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/@fastify/cors": { + "version": "11.2.0", + "resolved": "https://registry.npmjs.org/@fastify/cors/-/cors-11.2.0.tgz", + "integrity": "sha512-LbLHBuSAdGdSFZYTLVA3+Ch2t+sA6nq3Ejc6XLAKiQ6ViS2qFnvicpj0htsx03FyYeLs04HfRNBsz/a8SvbcUw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "fastify-plugin": "^5.0.0", + "toad-cache": "^3.7.0" + } + }, + "node_modules/@fastify/error": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@fastify/error/-/error-4.2.0.tgz", + "integrity": "sha512-RSo3sVDXfHskiBZKBPRgnQTtIqpi/7zhJOEmAxCiBcM7d0uwdGdxLlsCaLzGs8v8NnxIRlfG0N51p5yFaOentQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/@fastify/express": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@fastify/express/-/express-4.0.2.tgz", + "integrity": "sha512-lzu9MLdjlsK4Q2RiqEAwTgwQPrWQVP0kmbgAi/w9rIUqtnacjKvj3EHVTR6PIvXDs6Ut1jnTHiGbuNxHTsZwHQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "express": "^4.18.3", + "fastify-plugin": "^5.0.0" + } + }, + "node_modules/@fastify/fast-json-stringify-compiler": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/@fastify/fast-json-stringify-compiler/-/fast-json-stringify-compiler-5.0.3.tgz", + "integrity": "sha512-uik7yYHkLr6fxd8hJSZ8c+xF4WafPK+XzneQDPU+D10r5X19GW8lJcom2YijX2+qtFF1ENJlHXKFM9ouXNJYgQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "fast-json-stringify": "^6.0.0" + } + }, + "node_modules/@fastify/formbody": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@fastify/formbody/-/formbody-8.0.2.tgz", + "integrity": "sha512-84v5J2KrkXzjgBpYnaNRPqwgMsmY7ZDjuj0YVuMR3NXCJRCgKEZy/taSP1wUYGn0onfxJpLyRGDLa+NMaDJtnA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "fast-querystring": "^1.1.2", + "fastify-plugin": "^5.0.0" + } + }, + "node_modules/@fastify/forwarded": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@fastify/forwarded/-/forwarded-3.0.1.tgz", + "integrity": "sha512-JqDochHFqXs3C3Ml3gOY58zM7OqO9ENqPo0UqAjAjH8L01fRZqwX9iLeX34//kiJubF7r2ZQHtBRU36vONbLlw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/@fastify/merge-json-schemas": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/@fastify/merge-json-schemas/-/merge-json-schemas-0.2.1.tgz", + "integrity": "sha512-OA3KGBCy6KtIvLf8DINC5880o5iBlDX4SxzLQS8HorJAbqluzLRn80UXU0bxZn7UOFhFgpRJDasfwn9nG4FG4A==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "dequal": "^2.0.3" + } + }, + "node_modules/@fastify/middie": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/@fastify/middie/-/middie-9.1.0.tgz", + "integrity": "sha512-cObruXSFB5CCqn2m9sF5ktf6pNQX+QQth2N39FGXXV+8M4O+dWzkvqjqzwpIWvwvIffP9+O7KaLN+5xVgFFdWw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/error": "^4.0.0", + "fastify-plugin": "^5.0.0", + "find-my-way": "^9.4.0", + "path-to-regexp": "^8.1.0", + "reusify": "^1.0.4" + } + }, + "node_modules/@fastify/middie/node_modules/path-to-regexp": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.3.0.tgz", + "integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/@fastify/proxy-addr": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@fastify/proxy-addr/-/proxy-addr-5.1.0.tgz", + "integrity": "sha512-INS+6gh91cLUjB+PVHfu1UqcB76Sqtpyp7bnL+FYojhjygvOPA9ctiD/JDKsyD9Xgu4hUhCSJBPig/w7duNajw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/forwarded": "^3.0.0", + "ipaddr.js": "^2.1.0" + } + }, + "node_modules/@fastify/proxy-addr/node_modules/ipaddr.js": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.3.0.tgz", + "integrity": "sha512-Zv/pA+ciVFbCSBBjGfaKUya/CcGmUHzTydLMaTwrUUEM2DIEO3iZvueGxmacvmN50fGpGVKeTXpb2LcYQxeVdg==", + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/@ffmpeg-installer/darwin-arm64": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/darwin-arm64/-/darwin-arm64-4.1.5.tgz", + "integrity": "sha512-hYqTiP63mXz7wSQfuqfFwfLOfwwFChUedeCVKkBtl/cliaTM7/ePI9bVzfZ2c+dWu3TqCwLDRWNSJ5pqZl8otA==", + "cpu": [ + "arm64" + ], + "hasInstallScript": true, + "license": "https://git.ffmpeg.org/gitweb/ffmpeg.git/blob_plain/HEAD:/LICENSE.md", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@ffmpeg-installer/darwin-x64": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/darwin-x64/-/darwin-x64-4.1.0.tgz", + "integrity": "sha512-Z4EyG3cIFjdhlY8wI9aLUXuH8nVt7E9SlMVZtWvSPnm2sm37/yC2CwjUzyCQbJbySnef1tQwGG2Sx+uWhd9IAw==", + "cpu": [ + "x64" + ], + "hasInstallScript": true, + "license": "LGPL-2.1", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@ffmpeg-installer/ffmpeg": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/ffmpeg/-/ffmpeg-1.1.0.tgz", + "integrity": "sha512-Uq4rmwkdGxIa9A6Bd/VqqYbT7zqh1GrT5/rFwCwKM70b42W5gIjWeVETq6SdcL0zXqDtY081Ws/iJWhr1+xvQg==", + "license": "LGPL-2.1", + "optionalDependencies": { + "@ffmpeg-installer/darwin-arm64": "4.1.5", + "@ffmpeg-installer/darwin-x64": "4.1.0", + "@ffmpeg-installer/linux-arm": "4.1.3", + "@ffmpeg-installer/linux-arm64": "4.1.4", + "@ffmpeg-installer/linux-ia32": "4.1.0", + "@ffmpeg-installer/linux-x64": "4.1.0", + "@ffmpeg-installer/win32-ia32": "4.1.0", + "@ffmpeg-installer/win32-x64": "4.1.0" + } + }, + "node_modules/@ffmpeg-installer/linux-arm": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/linux-arm/-/linux-arm-4.1.3.tgz", + "integrity": "sha512-NDf5V6l8AfzZ8WzUGZ5mV8O/xMzRag2ETR6+TlGIsMHp81agx51cqpPItXPib/nAZYmo55Bl2L6/WOMI3A5YRg==", + "cpu": [ + "arm" + ], + "hasInstallScript": true, + "license": "GPLv3", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@ffmpeg-installer/linux-arm64": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/linux-arm64/-/linux-arm64-4.1.4.tgz", + "integrity": "sha512-dljEqAOD0oIM6O6DxBW9US/FkvqvQwgJ2lGHOwHDDwu/pX8+V0YsDL1xqHbj1DMX/+nP9rxw7G7gcUvGspSoKg==", + "cpu": [ + "arm64" + ], + "hasInstallScript": true, + "license": "GPLv3", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@ffmpeg-installer/linux-ia32": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/linux-ia32/-/linux-ia32-4.1.0.tgz", + "integrity": "sha512-0LWyFQnPf+Ij9GQGD034hS6A90URNu9HCtQ5cTqo5MxOEc7Rd8gLXrJvn++UmxhU0J5RyRE9KRYstdCVUjkNOQ==", + "cpu": [ + "ia32" + ], + "hasInstallScript": true, + "license": "GPLv3", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@ffmpeg-installer/linux-x64": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/linux-x64/-/linux-x64-4.1.0.tgz", + "integrity": "sha512-Y5BWhGLU/WpQjOArNIgXD3z5mxxdV8c41C+U15nsE5yF8tVcdCGet5zPs5Zy3Ta6bU7haGpIzryutqCGQA/W8A==", + "cpu": [ + "x64" + ], + "hasInstallScript": true, + "license": "GPLv3", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@ffmpeg-installer/win32-ia32": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/win32-ia32/-/win32-ia32-4.1.0.tgz", + "integrity": "sha512-FV2D7RlaZv/lrtdhaQ4oETwoFUsUjlUiasiZLDxhEUPdNDWcH1OU9K1xTvqz+OXLdsmYelUDuBS/zkMOTtlUAw==", + "cpu": [ + "ia32" + ], + "license": "GPLv3", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@ffmpeg-installer/win32-x64": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/win32-x64/-/win32-x64-4.1.0.tgz", + "integrity": "sha512-Drt5u2vzDnIONf4ZEkKtFlbvwj6rI3kxw1Ck9fpudmtgaZIHD4ucsWB2lCZBXRxJgXR+2IMSti+4rtM4C4rXgg==", + "cpu": [ + "x64" + ], + "license": "GPLv3", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@gar/promisify": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@gar/promisify/-/promisify-1.1.3.tgz", + "integrity": "sha512-k2Ty1JcVojjJFwrg/ThKi2ujJ7XNLYaFGNB/bWT9wGR+oSMJHMa5w+CUq6p/pVrKeNNgA7pCqEcjSnHVoqJQFw==", + "license": "MIT", + "optional": true + }, + "node_modules/@ioredis/commands": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@ioredis/commands/-/commands-1.5.0.tgz", + "integrity": "sha512-eUgLqrMf8nJkZxT24JvVRrQya1vZkQh8BBeYNwGDqa5I0VUi8ACx7uFvAaLxintokpTenkK6DASvo/bvNbBGow==", + "license": "MIT" + }, + "node_modules/@keyv/serialize": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@keyv/serialize/-/serialize-1.1.1.tgz", + "integrity": "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==", + "license": "MIT" + }, + "node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@npmcli/fs": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-1.1.1.tgz", + "integrity": "sha512-8KG5RD0GVP4ydEzRn/I4BNDuxDtqVbOdm8675T49OIG/NGhaK0pjPX7ZcDlvKYbA+ulvVK3ztfcF4uBdOxuJbQ==", + "license": "ISC", + "optional": true, + "dependencies": { + "@gar/promisify": "^1.0.1", + "semver": "^7.3.5" + } + }, + "node_modules/@npmcli/move-file": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@npmcli/move-file/-/move-file-1.1.2.tgz", + "integrity": "sha512-1SUf/Cg2GzGDyaf15aR9St9TWlb+XvbZXWpDx8YKs7MLzMH/BCeopv+y9vzrzgkfykCGuWOlSu3mZhj2+FQcrg==", + "deprecated": "This functionality has been moved to @npmcli/fs", + "license": "MIT", + "optional": true, + "dependencies": { + "mkdirp": "^1.0.4", + "rimraf": "^3.0.2" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@pinojs/redact": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz", + "integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==", + "license": "MIT" + }, + "node_modules/@scure/base": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@scure/base/-/base-1.2.6.tgz", + "integrity": "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg==", + "license": "MIT", + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@sec-ant/readable-stream": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@sec-ant/readable-stream/-/readable-stream-0.4.1.tgz", + "integrity": "sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg==", + "license": "MIT" + }, + "node_modules/@sindresorhus/is": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz", + "integrity": "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sindresorhus/is?sponsor=1" + } + }, + "node_modules/@socket.io/component-emitter": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz", + "integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==", + "license": "MIT" + }, + "node_modules/@tootallnate/once": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-1.1.2.tgz", + "integrity": "sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 6" + } + }, + "node_modules/@types/cors": { + "version": "2.8.19", + "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.19.tgz", + "integrity": "sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/http-cache-semantics": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.0.4.tgz", + "integrity": "sha512-1m0bIFVc7eJWyve9S0RnuRgcQqF/Xd5QsUZAZeQFr1Q3/p9JWoQQEqmVy+DPTNpGXwhgIetAoYF8JSc33q29QA==", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "25.0.3", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.0.3.tgz", + "integrity": "sha512-W609buLVRVmeW693xKfzHeIV6nJGGz98uCPfeXI1ELMLXVeKYZ9m15fAMSaUPBHYLGFsVRcMmSCksQOrZV9BYA==", + "license": "MIT", + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/abbrev": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==", + "license": "ISC", + "optional": true + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "license": "MIT", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, + "node_modules/abstract-logging": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/abstract-logging/-/abstract-logging-2.0.1.tgz", + "integrity": "sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==", + "license": "MIT" + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/adm-zip": { + "version": "0.5.16", + "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.16.tgz", + "integrity": "sha512-TGw5yVi4saajsSEgz25grObGHEUaDrniwvA2qwSC060KfqGPdglhvPMA2lPIoxs3PQIItj2iag35fONcQqgUaQ==", + "license": "MIT", + "engines": { + "node": ">=12.0" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/agentkeepalive": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.6.0.tgz", + "integrity": "sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "humanize-ms": "^1.2.1" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/aggregate-error": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.1.0.tgz", + "integrity": "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==", + "license": "MIT", + "optional": true, + "dependencies": { + "clean-stack": "^2.0.0", + "indent-string": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ajv": { + "version": "8.17.1", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz", + "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/aproba": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.1.0.tgz", + "integrity": "sha512-tLIEcj5GuR2RSTnxNKdkK0dJ/GrC7P38sUkiDmDuHfsHmbagTFAxDVIBltoklXEVIQ/f14IL8IMJ5pn9Hez1Ew==", + "license": "ISC", + "optional": true + }, + "node_modules/are-we-there-yet": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-3.0.1.tgz", + "integrity": "sha512-QZW4EDmGwlYur0Yyf/b2uGucHQMa8aFUP7eu9ddR73vvhFyt4V0Vl3QHPcTNJ8l6qYOBdxgXdnBXQrHilfRQBg==", + "deprecated": "This package is no longer supported.", + "license": "ISC", + "optional": true, + "dependencies": { + "delegates": "^1.0.0", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", + "license": "MIT" + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, + "node_modules/atomic-sleep": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz", + "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/avvio": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/avvio/-/avvio-9.1.0.tgz", + "integrity": "sha512-fYASnYi600CsH/j9EQov7lECAniYiBFiiAtBNuZYLA2leLe9qOvZzqYHFjtIj6gD2VMoMLP14834LFWvr4IfDw==", + "license": "MIT", + "dependencies": { + "@fastify/error": "^4.0.0", + "fastq": "^1.17.1" + } + }, + "node_modules/aws-ssl-profiles": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz", + "integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==", + "license": "MIT", + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/axios": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.12.2.tgz", + "integrity": "sha512-vMJzPewAlRyOgxV2dU0Cuz2O8zzzx9VYtbJOaBgXFeLc4IV/Eg50n4LowmehOOR61S8ZMpc2K5Sa7g6A4jfkUw==", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.15.6", + "form-data": "^4.0.4", + "proxy-from-env": "^1.1.0" + } + }, + "node_modules/axios-cookiejar-support": { + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/axios-cookiejar-support/-/axios-cookiejar-support-6.0.4.tgz", + "integrity": "sha512-4Bzj+l63eGwnWDBFdJHeGS6Ij3ytpyqvo//ocsb5kCLN/rKthzk27Afh2iSkZtuudOBkHUWWIcyCb4GKhXqovQ==", + "license": "MIT", + "dependencies": { + "http-cookie-agent": "^7.0.2" + }, + "engines": { + "node": ">=20.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/3846masa" + }, + "peerDependencies": { + "axios": ">=0.20.0", + "tough-cookie": ">=4.0.0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT", + "optional": true + }, + "node_modules/base-x": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/base-x/-/base-x-5.0.1.tgz", + "integrity": "sha512-M7uio8Zt++eg3jPj+rHMfCC+IuygQHHCOU+IYsVtik6FWjuYpVt/+MRKcgsAMHh8mMFAwnB+Bs+mTrFiXjMzKg==", + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/base64id": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/base64id/-/base64id-2.0.0.tgz", + "integrity": "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==", + "license": "MIT", + "engines": { + "node": "^4.5.0 || >= 5.9" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.9.15", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.15.tgz", + "integrity": "sha512-kX8h7K2srmDyYnXRIppo4AH/wYgzWVCs+eKr3RusRSQ5PvRYoEFmR/I0PbdTjKFAoKqp5+kbxnNTFO9jOfSVJg==", + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.js" + } + }, + "node_modules/bech32": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/bech32/-/bech32-2.0.0.tgz", + "integrity": "sha512-LcknSilhIGatDAsY1ak2I8VtGaHNhgMSYVxFrGLXv+xLHytaKZKcaUJJUE7qmBr7h33o5YQwP55pMI0xmkpJwg==", + "license": "MIT" + }, + "node_modules/better-sqlite3": { + "version": "12.5.0", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.5.0.tgz", + "integrity": "sha512-WwCZ/5Diz7rsF29o27o0Gcc1Du+l7Zsv7SYtVPG0X3G/uUI1LqdxrQI7c9Hs2FWpqXXERjW9hp6g3/tH7DlVKg==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "bindings": "^1.5.0", + "prebuild-install": "^7.1.1" + }, + "engines": { + "node": "20.x || 22.x || 23.x || 24.x || 25.x" + } + }, + "node_modules/bindings": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", + "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "license": "MIT", + "dependencies": { + "file-uri-to-path": "1.0.0" + } + }, + "node_modules/bip174": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/bip174/-/bip174-3.0.0.tgz", + "integrity": "sha512-N3vz3rqikLEu0d6yQL8GTrSkpYb35NQKWMR7Hlza0lOj6ZOlvQ3Xr7N9Y+JPebaCVoEUHdBeBSuLxcHr71r+Lw==", + "license": "MIT", + "dependencies": { + "uint8array-tools": "^0.0.9", + "varuint-bitcoin": "^2.0.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/bip174/node_modules/uint8array-tools": { + "version": "0.0.9", + "resolved": "https://registry.npmjs.org/uint8array-tools/-/uint8array-tools-0.0.9.tgz", + "integrity": "sha512-9vqDWmoSXOoi+K14zNaf6LBV51Q8MayF0/IiQs3GlygIKUYtog603e6virExkjjFosfJUBI4LhbQK1iq8IG11A==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/bip32": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/bip32/-/bip32-5.0.1.tgz", + "integrity": "sha512-PWlHIAgYCfVhwqNpZyeakHXuLAGyN6rEQZnhxHxKI3BoFJRVWLl26455fhRlHsmbYcV986HqtPnt33Edu5sTCw==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "^1.2.0", + "@scure/base": "^1.1.1", + "uint8array-tools": "^0.0.8", + "valibot": "^1.2.0", + "wif": "^5.0.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/bip39": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/bip39/-/bip39-3.1.0.tgz", + "integrity": "sha512-c9kiwdk45Do5GL0vJMe7tS95VjCii65mYAH7DfWl3uW8AVzXKQVUm64i3hzVybBDMp9r7j9iNxR85+ul8MdN/A==", + "license": "ISC", + "dependencies": { + "@noble/hashes": "^1.2.0" + } + }, + "node_modules/bitcoinjs-lib": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/bitcoinjs-lib/-/bitcoinjs-lib-7.0.1.tgz", + "integrity": "sha512-vwEmpL5Tpj0I0RBdNkcDMXePoaYSTeKY6mL6/l5esbnTs+jGdPDuLp4NY1hSh6Zk5wSgePygZ4Wx5JJao30Pww==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "^1.2.0", + "bech32": "^2.0.0", + "bip174": "^3.0.0", + "bs58check": "^4.0.0", + "uint8array-tools": "^0.0.9", + "valibot": "^1.2.0", + "varuint-bitcoin": "^2.0.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/bitcoinjs-lib/node_modules/uint8array-tools": { + "version": "0.0.9", + "resolved": "https://registry.npmjs.org/uint8array-tools/-/uint8array-tools-0.0.9.tgz", + "integrity": "sha512-9vqDWmoSXOoi+K14zNaf6LBV51Q8MayF0/IiQs3GlygIKUYtog603e6virExkjjFosfJUBI4LhbQK1iq8IG11A==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "license": "MIT", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/body-parser": { + "version": "1.20.4", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.4.tgz", + "integrity": "sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "~1.2.0", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "on-finished": "~2.4.1", + "qs": "~6.14.0", + "raw-body": "~2.5.3", + "type-is": "~1.6.18", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/body-parser/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/body-parser/node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/body-parser/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/boolbase": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", + "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==", + "license": "ISC" + }, + "node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "license": "MIT", + "optional": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/browserslist": { + "version": "4.28.1", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.1.tgz", + "integrity": "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.9.0", + "caniuse-lite": "^1.0.30001759", + "electron-to-chromium": "^1.5.263", + "node-releases": "^2.0.27", + "update-browserslist-db": "^1.2.0" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/bs58": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/bs58/-/bs58-6.0.0.tgz", + "integrity": "sha512-PD0wEnEYg6ijszw/u8s+iI3H17cTymlrwkKhDhPZq+Sokl3AU4htyBFTjAeNAlCCmg0f53g6ih3jATyCKftTfw==", + "license": "MIT", + "dependencies": { + "base-x": "^5.0.0" + } + }, + "node_modules/bs58check": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/bs58check/-/bs58check-4.0.0.tgz", + "integrity": "sha512-FsGDOnFg9aVI9erdriULkd/JjEWONV/lQE5aYziB5PoBsXRind56lh8doIZIc9X4HoxT5x4bLjMWN1/NB8Zp5g==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "^1.2.0", + "bs58": "^6.0.0" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "license": "MIT" + }, + "node_modules/byte-counter": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/byte-counter/-/byte-counter-0.1.0.tgz", + "integrity": "sha512-jheRLVMeUKrDBjVw2O5+k4EvR4t9wtxHL+bo/LxfkxsVeuGMy3a5SEGgXdAFA4FSzTrU8rQXQIrsZ3oBq5a0pQ==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/cacache": { + "version": "15.3.0", + "resolved": "https://registry.npmjs.org/cacache/-/cacache-15.3.0.tgz", + "integrity": "sha512-VVdYzXEn+cnbXpFgWs5hTT7OScegHVmLhJIR8Ufqk3iFD6A6j5iSX1KuBTfNEv4tdJWE2PzA6IVFtcLC7fN9wQ==", + "license": "ISC", + "optional": true, + "dependencies": { + "@npmcli/fs": "^1.0.0", + "@npmcli/move-file": "^1.0.1", + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "glob": "^7.1.4", + "infer-owner": "^1.0.4", + "lru-cache": "^6.0.0", + "minipass": "^3.1.1", + "minipass-collect": "^1.0.2", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.2", + "mkdirp": "^1.0.3", + "p-map": "^4.0.0", + "promise-inflight": "^1.0.1", + "rimraf": "^3.0.2", + "ssri": "^8.0.1", + "tar": "^6.0.2", + "unique-filename": "^1.1.1" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/cacache/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "license": "ISC", + "optional": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/cacheable-lookup": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-7.0.0.tgz", + "integrity": "sha512-+qJyx4xiKra8mZrcwhjMRMUhD5NR1R8esPkzIYxX96JiecFoxAXFuz/GpR3+ev4PE1WamHip78wV0vcmPQtp8w==", + "license": "MIT", + "engines": { + "node": ">=14.16" + } + }, + "node_modules/cacheable-request": { + "version": "13.0.18", + "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-13.0.18.tgz", + "integrity": "sha512-rFWadDRKJs3s2eYdXlGggnBZKG7MTblkFBB0YllFds+UYnfogDp2wcR6JN97FhRkHTvq59n2vhNoHNZn29dh/Q==", + "license": "MIT", + "dependencies": { + "@types/http-cache-semantics": "^4.0.4", + "get-stream": "^9.0.1", + "http-cache-semantics": "^4.2.0", + "keyv": "^5.5.5", + "mimic-response": "^4.0.0", + "normalize-url": "^8.1.1", + "responselike": "^4.0.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/cacheable-request/node_modules/mimic-response": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-4.0.0.tgz", + "integrity": "sha512-e5ISH9xMYU0DzrT+jl8q2ze9D6eWBto+I8CNpe+VI+K2J/F/k3PdkdTdz4wvGVH4NTpo+NRYTVIuMQEMMcsLqg==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/callsites": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-4.2.0.tgz", + "integrity": "sha512-kfzR4zzQtAE9PC7CzZsjl3aBNbXWuXiSeOCdLcPpBfGW8YuCqQHcRPFDbr/BPVmd3EEPVpuFzLyuT/cUhPr4OQ==", + "license": "MIT", + "engines": { + "node": ">=12.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001764", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001764.tgz", + "integrity": "sha512-9JGuzl2M+vPL+pz70gtMF9sHdMFbY9FJaQBi186cHKH3pSzDvzoUJUPV6fqiKIMyXbud9ZLg4F3Yza1vJ1+93g==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chardet": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-2.1.0.tgz", + "integrity": "sha512-bNFETTG/pM5ryzQ9Ad0lJOTa6HWD/YsScAR3EnCPZRPlQh77JocYktSHOUHelyhm8IARL+o4c4F1bP5KVOjiRA==", + "license": "MIT" + }, + "node_modules/cheerio": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.1.2.tgz", + "integrity": "sha512-IkxPpb5rS/d1IiLbHMgfPuS0FgiWTtFIm/Nj+2woXDLTZ7fOT2eqzgYbdMlLweqlHbsZjxEChoVK+7iph7jyQg==", + "license": "MIT", + "dependencies": { + "cheerio-select": "^2.1.0", + "dom-serializer": "^2.0.0", + "domhandler": "^5.0.3", + "domutils": "^3.2.2", + "encoding-sniffer": "^0.2.1", + "htmlparser2": "^10.0.0", + "parse5": "^7.3.0", + "parse5-htmlparser2-tree-adapter": "^7.1.0", + "parse5-parser-stream": "^7.1.2", + "undici": "^7.12.0", + "whatwg-mimetype": "^4.0.0" + }, + "engines": { + "node": ">=20.18.1" + }, + "funding": { + "url": "https://github.com/cheeriojs/cheerio?sponsor=1" + } + }, + "node_modules/cheerio-select": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/cheerio-select/-/cheerio-select-2.1.0.tgz", + "integrity": "sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==", + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0", + "css-select": "^5.1.0", + "css-what": "^6.1.0", + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3", + "domutils": "^3.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/chownr": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", + "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/clean-stack": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", + "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/cluster-key-slot": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz", + "integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/color-support": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", + "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", + "license": "ISC", + "optional": true, + "bin": { + "color-support": "bin.js" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/compressible": { + "version": "2.0.18", + "resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.18.tgz", + "integrity": "sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==", + "license": "MIT", + "dependencies": { + "mime-db": ">= 1.43.0 < 2" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/compression": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/compression/-/compression-1.8.1.tgz", + "integrity": "sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "compressible": "~2.0.18", + "debug": "2.6.9", + "negotiator": "~0.6.4", + "on-headers": "~1.1.0", + "safe-buffer": "5.2.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/compression/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/compression/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/compression/node_modules/negotiator": { + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.4.tgz", + "integrity": "sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "license": "MIT", + "optional": true + }, + "node_modules/console-control-strings": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", + "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==", + "license": "ISC", + "optional": true + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz", + "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz", + "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==", + "license": "MIT" + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "license": "MIT" + }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/crypto-js": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.2.0.tgz", + "integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==", + "license": "MIT" + }, + "node_modules/css-select": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/css-select/-/css-select-5.2.2.tgz", + "integrity": "sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==", + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0", + "css-what": "^6.1.0", + "domhandler": "^5.0.2", + "domutils": "^3.0.1", + "nth-check": "^2.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/css-what": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.2.2.tgz", + "integrity": "sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">= 6" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/cycletls": { + "version": "1.0.27", + "resolved": "https://registry.npmjs.org/cycletls/-/cycletls-1.0.27.tgz", + "integrity": "sha512-LZPyuj32BZm/rIt35dmim2ykb1hodwkFXc7K4zXei2p/ykcb7qNOf+JeBK0Ls5lyCbmyDyYkHYQmkHfow0JmNw==", + "license": "GPL3", + "dependencies": { + "@types/node": "^20.11.5", + "ws": "^7.5.7" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/cycletls/node_modules/@types/node": { + "version": "20.19.35", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.35.tgz", + "integrity": "sha512-Uarfe6J91b9HAUXxjvSOdiO2UPOKLm07Q1oh0JHxoZ1y8HoqxDAu3gVrsrOHeiio0kSsoVBt4wFrKOm0dKxVPQ==", + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/cycletls/node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "license": "MIT" + }, + "node_modules/cycletls/node_modules/ws": { + "version": "7.5.10", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.10.tgz", + "integrity": "sha512-+dbF1tHwZpXcbOJdVOkzLDxZP1ailvSxM6ZweXTegylPny803bFhA+vqBYw4s31NSAk4S2Qz+AKXK9a4wkdjcQ==", + "license": "MIT", + "engines": { + "node": ">=8.3.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/debug": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz", + "integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "license": "MIT", + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/delegates": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==", + "license": "MIT", + "optional": true + }, + "node_modules/denque": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz", + "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/detect-libc": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.0.tgz", + "integrity": "sha512-vEtk+OcP7VBRtQZ1EJ3bdgzSfBjgnEalLTp5zjJrS+2Z1w2KZly4SBdac/WDU3hhsNAZ9E8SC96ME4Ey8MZ7cg==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/dom-serializer": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz", + "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==", + "license": "MIT", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.2", + "entities": "^4.2.0" + }, + "funding": { + "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" + } + }, + "node_modules/domelementtype": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", + "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "BSD-2-Clause" + }, + "node_modules/domhandler": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz", + "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==", + "license": "BSD-2-Clause", + "dependencies": { + "domelementtype": "^2.3.0" + }, + "engines": { + "node": ">= 4" + }, + "funding": { + "url": "https://github.com/fb55/domhandler?sponsor=1" + } + }, + "node_modules/domutils": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz", + "integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==", + "license": "BSD-2-Clause", + "dependencies": { + "dom-serializer": "^2.0.0", + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3" + }, + "funding": { + "url": "https://github.com/fb55/domutils?sponsor=1" + } + }, + "node_modules/dot-prop": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-7.2.0.tgz", + "integrity": "sha512-Ol/IPXUARn9CSbkrdV4VJo7uCy1I3VuSiWCaFSg+8BdUOzF9n3jefIpcgAydvUZbTdEBZs2vEiTiS9m61ssiDA==", + "license": "MIT", + "dependencies": { + "type-fest": "^2.11.2" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/dot-prop/node_modules/type-fest": { + "version": "2.19.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-2.19.0.tgz", + "integrity": "sha512-RAH822pAdBgcNMAfWnCBU3CFZcfZ/i1eZjwFU/dsLKumyuuP3niueg2UAukXYF0E2AAoc82ZSSf9J0WQBinzHA==", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=12.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/dotenv": { + "version": "17.2.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.2.1.tgz", + "integrity": "sha512-kQhDYKZecqnM0fCnzI5eIv5L4cAe/iRI+HqMbO/hbRdTAeXDG+M9FjipUxNfbARuEg4iHIbhnhs78BCHNbSxEQ==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/duplexify": { + "version": "3.7.1", + "resolved": "https://registry.npmjs.org/duplexify/-/duplexify-3.7.1.tgz", + "integrity": "sha512-07z8uv2wMyS51kKhD1KsdXJg5WQ6t93RneqRxUHnskXVtlYYkLqM0gqStQZ3pj073g687jPCHrqNfCzawLYh5g==", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.0.0", + "inherits": "^2.0.1", + "readable-stream": "^2.0.0", + "stream-shift": "^1.0.0" + } + }, + "node_modules/duplexify/node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/duplexify/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/duplexify/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/electron-to-chromium": { + "version": "1.5.267", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.267.tgz", + "integrity": "sha512-0Drusm6MVRXSOJpGbaSVgcQsuB4hEkMpHXaVstcPmhu5LIedxs1xNK/nIxmQIU/RPC0+1/o0AVZfBTkTNJOdUw==", + "license": "ISC" + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT", + "optional": true + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/encoding": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.13.tgz", + "integrity": "sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==", + "license": "MIT", + "optional": true, + "dependencies": { + "iconv-lite": "^0.6.2" + } + }, + "node_modules/encoding-sniffer": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/encoding-sniffer/-/encoding-sniffer-0.2.1.tgz", + "integrity": "sha512-5gvq20T6vfpekVtqrYQsSCFZ1wEg5+wW0/QaZMWkFr6BqD3NfKs0rLCx4rrVlSWJeZb5NBJgVLswK/w2MWU+Gw==", + "license": "MIT", + "dependencies": { + "iconv-lite": "^0.6.3", + "whatwg-encoding": "^3.1.1" + }, + "funding": { + "url": "https://github.com/fb55/encoding-sniffer?sponsor=1" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/engine.io": { + "version": "6.6.5", + "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.6.5.tgz", + "integrity": "sha512-2RZdgEbXmp5+dVbRm0P7HQUImZpICccJy7rN7Tv+SFa55pH+lxnuw6/K1ZxxBfHoYpSkHLAO92oa8O4SwFXA2A==", + "license": "MIT", + "dependencies": { + "@types/cors": "^2.8.12", + "@types/node": ">=10.0.0", + "accepts": "~1.3.4", + "base64id": "2.0.0", + "cookie": "~0.7.2", + "cors": "~2.8.5", + "debug": "~4.4.1", + "engine.io-parser": "~5.2.1", + "ws": "~8.18.3" + }, + "engines": { + "node": ">=10.2.0" + } + }, + "node_modules/engine.io-parser": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz", + "integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/engine.io/node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/env-paths": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", + "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/err-code": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/err-code/-/err-code-2.0.3.tgz", + "integrity": "sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==", + "license": "MIT", + "optional": true + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "license": "MIT", + "engines": { + "node": ">=0.8.x" + } + }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "license": "(MIT OR WTFPL)", + "engines": { + "node": ">=6" + } + }, + "node_modules/express": { + "version": "4.22.1", + "resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz", + "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "~1.20.3", + "content-disposition": "~0.5.4", + "content-type": "~1.0.4", + "cookie": "~0.7.1", + "cookie-signature": "~1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "~1.3.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "~0.1.12", + "proxy-addr": "~2.0.7", + "qs": "~6.14.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "~0.19.0", + "serve-static": "~1.16.2", + "setprototypeof": "1.2.0", + "statuses": "~2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-list-endpoints": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/express-list-endpoints/-/express-list-endpoints-7.1.1.tgz", + "integrity": "sha512-SA6YHH1r6DrioJ4fFJNqiwu1FweGFqJZO9KBApMzwPosoSGPOX2AW0wiMepOXjojjEXDuP9whIvckomheErbJA==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/express-rate-limit": { + "version": "8.2.1", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.2.1.tgz", + "integrity": "sha512-PCZEIEIxqwhzw4KF0n7QF4QqruVTcF73O5kFKUnGOyjbCCgizBBiFaYpd/fnBLUMPw/BWw9OsiN7GgrNYr7j6g==", + "license": "MIT", + "dependencies": { + "ip-address": "10.0.1" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, + "node_modules/express/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/express/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/fast-decode-uri-component": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/fast-decode-uri-component/-/fast-decode-uri-component-1.0.1.tgz", + "integrity": "sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg==", + "license": "MIT" + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-json-stringify": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/fast-json-stringify/-/fast-json-stringify-6.1.1.tgz", + "integrity": "sha512-DbgptncYEXZqDUOEl4krff4mUiVrTZZVI7BBrQR/T3BqMj/eM1flTC1Uk2uUoLcWCxjT95xKulV/Lc6hhOZsBQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/merge-json-schemas": "^0.2.0", + "ajv": "^8.12.0", + "ajv-formats": "^3.0.1", + "fast-uri": "^3.0.0", + "json-schema-ref-resolver": "^3.0.0", + "rfdc": "^1.2.0" + } + }, + "node_modules/fast-querystring": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/fast-querystring/-/fast-querystring-1.1.2.tgz", + "integrity": "sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg==", + "license": "MIT", + "dependencies": { + "fast-decode-uri-component": "^1.0.1" + } + }, + "node_modules/fast-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz", + "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/fastify": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/fastify/-/fastify-5.6.2.tgz", + "integrity": "sha512-dPugdGnsvYkBlENLhCgX8yhyGCsCPrpA8lFWbTNU428l+YOnLgYHR69hzV8HWPC79n536EqzqQtvhtdaCE0dKg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/ajv-compiler": "^4.0.0", + "@fastify/error": "^4.0.0", + "@fastify/fast-json-stringify-compiler": "^5.0.0", + "@fastify/proxy-addr": "^5.0.0", + "abstract-logging": "^2.0.1", + "avvio": "^9.0.0", + "fast-json-stringify": "^6.0.0", + "find-my-way": "^9.0.0", + "light-my-request": "^6.0.0", + "pino": "^10.1.0", + "process-warning": "^5.0.0", + "rfdc": "^1.3.1", + "secure-json-parse": "^4.0.0", + "semver": "^7.6.0", + "toad-cache": "^3.7.0" + } + }, + "node_modules/fastify-plugin": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/fastify-plugin/-/fastify-plugin-5.1.0.tgz", + "integrity": "sha512-FAIDA8eovSt5qcDgcBvDuX/v0Cjz0ohGhENZ/wpc3y+oZCY2afZ9Baqql3g/lC+OHRnciQol4ww7tuthOb9idw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/fastq": { + "version": "1.19.1", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.1.tgz", + "integrity": "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==", + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/file-uri-to-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", + "license": "MIT" + }, + "node_modules/finalhandler": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz", + "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "statuses": "~2.0.2", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/finalhandler/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/finalhandler/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/find-my-way": { + "version": "9.4.0", + "resolved": "https://registry.npmjs.org/find-my-way/-/find-my-way-9.4.0.tgz", + "integrity": "sha512-5Ye4vHsypZRYtS01ob/iwHzGRUDELlsoCftI/OZFhcLs1M0tkGPcXldE80TAZC5yYuJMBPJQQ43UHlqbJWiX2w==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-querystring": "^1.0.0", + "safe-regex2": "^5.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/follow-redirects": { + "version": "1.15.11", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", + "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz", + "integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/form-data-encoder": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-4.1.0.tgz", + "integrity": "sha512-G6NsmEW15s0Uw9XnCg+33H3ViYRyiM0hMrMhhqQOR8NFc5GhYrI+6I3u7OTw7b91J2g8rtvMBZJDbcGb2YUniw==", + "license": "MIT", + "engines": { + "node": ">= 18" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "license": "MIT" + }, + "node_modules/fs-minipass": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", + "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", + "license": "ISC", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "license": "ISC", + "optional": true + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gauge": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/gauge/-/gauge-4.0.4.tgz", + "integrity": "sha512-f9m+BEN5jkg6a0fZjleidjN51VE1X+mPFQ2DJ0uv1V39oCLCbsGe6yjbBnp7eK7z/+GAon99a3nHuqbuuthyPg==", + "deprecated": "This package is no longer supported.", + "license": "ISC", + "optional": true, + "dependencies": { + "aproba": "^1.0.3 || ^2.0.0", + "color-support": "^1.1.3", + "console-control-strings": "^1.1.0", + "has-unicode": "^2.0.1", + "signal-exit": "^3.0.7", + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1", + "wide-align": "^1.1.5" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + } + }, + "node_modules/gauge/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "license": "ISC", + "optional": true + }, + "node_modules/generate-function": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz", + "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==", + "license": "MIT", + "dependencies": { + "is-property": "^1.0.2" + } + }, + "node_modules/generative-bayesian-network": { + "version": "2.1.79", + "resolved": "https://registry.npmjs.org/generative-bayesian-network/-/generative-bayesian-network-2.1.79.tgz", + "integrity": "sha512-aPH+V2wO+HE0BUX1LbsM8Ak99gmV43lgh+D7GDteM0zgnPqiAwcK9JZPxMPZa3aJUleFtFaL1lAei8g9zNrDIA==", + "license": "Apache-2.0", + "dependencies": { + "adm-zip": "^0.5.9", + "tslib": "^2.4.0" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/get-stream": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-9.0.1.tgz", + "integrity": "sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA==", + "license": "MIT", + "dependencies": { + "@sec-ant/readable-stream": "^0.4.1", + "is-stream": "^4.0.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "license": "MIT" + }, + "node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Glob versions prior to v9 are no longer supported", + "license": "ISC", + "optional": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/got": { + "version": "14.6.6", + "resolved": "https://registry.npmjs.org/got/-/got-14.6.6.tgz", + "integrity": "sha512-QLV1qeYSo5l13mQzWgP/y0LbMr5Plr5fJilgAIwgnwseproEbtNym8xpLsDzeZ6MWXgNE6kdWGBjdh3zT/Qerg==", + "license": "MIT", + "dependencies": { + "@sindresorhus/is": "^7.0.1", + "byte-counter": "^0.1.0", + "cacheable-lookup": "^7.0.0", + "cacheable-request": "^13.0.12", + "decompress-response": "^10.0.0", + "form-data-encoder": "^4.0.2", + "http2-wrapper": "^2.2.1", + "keyv": "^5.5.3", + "lowercase-keys": "^3.0.0", + "p-cancelable": "^4.0.1", + "responselike": "^4.0.2", + "type-fest": "^4.26.1" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sindresorhus/got?sponsor=1" + } + }, + "node_modules/got-scraping": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/got-scraping/-/got-scraping-4.1.3.tgz", + "integrity": "sha512-PTXcxbuWg631hbRNZRa7p0JKCTLDVAy5AMbJtrxkiNHLVb9Fkn5ghOELaxjNXU5axrriPhEhV4/N/omhaOWJeg==", + "license": "Apache-2.0", + "dependencies": { + "got": "^14.2.1", + "header-generator": "^2.1.41", + "http2-wrapper": "^2.2.0", + "mimic-response": "^4.0.0", + "ow": "^1.1.1", + "quick-lru": "^7.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/got-scraping/node_modules/mimic-response": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-4.0.0.tgz", + "integrity": "sha512-e5ISH9xMYU0DzrT+jl8q2ze9D6eWBto+I8CNpe+VI+K2J/F/k3PdkdTdz4wvGVH4NTpo+NRYTVIuMQEMMcsLqg==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/got/node_modules/decompress-response": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-10.0.0.tgz", + "integrity": "sha512-oj7KWToJuuxlPr7VV0vabvxEIiqNMo+q0NueIiL3XhtwC6FVOX7Hr1c0C4eD0bmf7Zr+S/dSf2xvkH3Ad6sU3Q==", + "license": "MIT", + "dependencies": { + "mimic-response": "^4.0.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/got/node_modules/mimic-response": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-4.0.0.tgz", + "integrity": "sha512-e5ISH9xMYU0DzrT+jl8q2ze9D6eWBto+I8CNpe+VI+K2J/F/k3PdkdTdz4wvGVH4NTpo+NRYTVIuMQEMMcsLqg==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "license": "ISC" + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-unicode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", + "integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==", + "license": "ISC", + "optional": true + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/header-generator": { + "version": "2.1.79", + "resolved": "https://registry.npmjs.org/header-generator/-/header-generator-2.1.79.tgz", + "integrity": "sha512-YvHx8teq4QmV5mz7wdPMsj9n1OZBPnZxA4QE+EOrtx7xbmGvd1gBvDNKCb5XqS4GR/TL75MU5hqMqqqANdILRg==", + "license": "Apache-2.0", + "dependencies": { + "browserslist": "^4.21.1", + "generative-bayesian-network": "^2.1.79", + "ow": "^0.28.1", + "tslib": "^2.4.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/header-generator/node_modules/@sindresorhus/is": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz", + "integrity": "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/is?sponsor=1" + } + }, + "node_modules/header-generator/node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/header-generator/node_modules/dot-prop": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-6.0.1.tgz", + "integrity": "sha512-tE7ztYzXHIeyvc7N+hR3oi7FIbf/NIjVP9hmAt3yMXzrQ072/fpjGLx2GxNxGxUl5V73MEqYzioOMoVhGMJ5cA==", + "license": "MIT", + "dependencies": { + "is-obj": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/header-generator/node_modules/ow": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/ow/-/ow-0.28.2.tgz", + "integrity": "sha512-dD4UpyBh/9m4X2NVjA+73/ZPBRF+uF4zIMFvvQsabMiEK8x41L3rQ8EENOi35kyyoaJwNxEeJcP6Fj1H4U409Q==", + "license": "MIT", + "dependencies": { + "@sindresorhus/is": "^4.2.0", + "callsites": "^3.1.0", + "dot-prop": "^6.0.1", + "lodash.isequal": "^4.5.0", + "vali-date": "^1.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/htmlparser2": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.0.0.tgz", + "integrity": "sha512-TwAZM+zE5Tq3lrEHvOlvwgj1XLWQCtaaibSN11Q+gGBAS7Y1uZSWwXXRe4iF6OXnaq1riyQAPFOBtYc77Mxq0g==", + "funding": [ + "https://github.com/fb55/htmlparser2?sponsor=1", + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "MIT", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3", + "domutils": "^3.2.1", + "entities": "^6.0.0" + } + }, + "node_modules/htmlparser2/node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/http-cache-semantics": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz", + "integrity": "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==", + "license": "BSD-2-Clause" + }, + "node_modules/http-cookie-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-cookie-agent/-/http-cookie-agent-7.0.2.tgz", + "integrity": "sha512-aHaES6SOFtnSlmWu0yEaaQvu+QexUG2gscSAvMhJ7auzW8r/jYOgGrzuAm9G9nHbksuhz7Lw4zOwDHmfQaxZvw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.4" + }, + "engines": { + "node": ">=20.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/3846masa" + }, + "peerDependencies": { + "tough-cookie": "^4.0.0 || ^5.0.0", + "undici": "^7.0.0" + }, + "peerDependenciesMeta": { + "undici": { + "optional": true + } + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/http2-wrapper": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/http2-wrapper/-/http2-wrapper-2.2.1.tgz", + "integrity": "sha512-V5nVw1PAOgfI3Lmeaj2Exmeg7fenjhRUgz1lPSezy1CuhPYbgQtbQj4jZfEAEMlaL+vupsvhjqCyjzob0yxsmQ==", + "license": "MIT", + "dependencies": { + "quick-lru": "^5.1.1", + "resolve-alpn": "^1.2.0" + }, + "engines": { + "node": ">=10.19.0" + } + }, + "node_modules/http2-wrapper/node_modules/quick-lru": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz", + "integrity": "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/humanize-ms": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz", + "integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "ms": "^2.0.0" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/impit": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/impit/-/impit-0.9.2.tgz", + "integrity": "sha512-flHQYxC16o7H+OKrO0zXv8Ob8Hs/E1Z1CfjGUHkN+6qqQksi1/2KMnZZEeSWfB9fM4b8SQVL6aQha/K6qVKqng==", + "license": "Apache-2.0", + "engines": { + "node": ">= 20" + }, + "optionalDependencies": { + "impit-darwin-arm64": "0.9.2", + "impit-darwin-x64": "0.9.2", + "impit-linux-arm64-gnu": "0.9.2", + "impit-linux-arm64-musl": "0.9.2", + "impit-linux-x64-gnu": "0.9.2", + "impit-linux-x64-musl": "0.9.2", + "impit-win32-arm64-msvc": "0.9.2", + "impit-win32-x64-msvc": "0.9.2" + } + }, + "node_modules/impit-darwin-arm64": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/impit-darwin-arm64/-/impit-darwin-arm64-0.9.2.tgz", + "integrity": "sha512-YHfrBeWwwI6je3OLBK8kgxR49bLbYGLkF/HFUHjPnhZxR821zd0NNPsYMX/1Rrasx0Zpu3skhN68ofudilhHdg==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/impit-darwin-x64": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/impit-darwin-x64/-/impit-darwin-x64-0.9.2.tgz", + "integrity": "sha512-FPH7gE0YdHfYRjX9qGKIvfQ6hdgo9GM+/wD1ktUC2UiEwKbwjpmrBhdXt0bSudrw9D28T4KR1w4TmX4X+uBYEA==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/impit-linux-arm64-gnu": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/impit-linux-arm64-gnu/-/impit-linux-arm64-gnu-0.9.2.tgz", + "integrity": "sha512-9Va4WmklAWwjJYT5M74u6HHzmRA8Tw8tdwzsrhIBmEyJ/gzCD6TJD0sE0mgFGd8v/mEB/WfMX1VnpOQmPm1gDQ==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/impit-linux-arm64-musl": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/impit-linux-arm64-musl/-/impit-linux-arm64-musl-0.9.2.tgz", + "integrity": "sha512-eiZs4C4vOPRi5A/V/bNTpX9Ays1m1trMfDXRH/Bnulo7XPngP6AEGW0SaKBznfDhiFOfO7hcDPupkGvSfX5rpw==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/impit-linux-x64-gnu": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/impit-linux-x64-gnu/-/impit-linux-x64-gnu-0.9.2.tgz", + "integrity": "sha512-KXkc6A0jh6c1ymxbcxgMbjNwr7YCm48froJaQWzXHg9nRSepJxprHtlWoFcz9HG/D9+eBQXTpMAJMAqXMs+NtA==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/impit-linux-x64-musl": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/impit-linux-x64-musl/-/impit-linux-x64-musl-0.9.2.tgz", + "integrity": "sha512-GWXqohv79LgOF0YUP/rwVGZ4uQZWK/NJUhGZR4PgKRMb1HHH2S2wrGtSP7AHyW+GT27Tv9yrRcyidVK+FYxOVw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/impit-win32-arm64-msvc": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/impit-win32-arm64-msvc/-/impit-win32-arm64-msvc-0.9.2.tgz", + "integrity": "sha512-ta82EKAMjCXhnCs6n9jr7hzbjX3wBWhW21AdAwZEiX4RaJNmE6j0oH0ZrTZuCDJumxAV+1pJapB4q/BCuoP1IQ==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/impit-win32-x64-msvc": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/impit-win32-x64-msvc/-/impit-win32-x64-msvc-0.9.2.tgz", + "integrity": "sha512-S1F8b4sKYwd0FORJWir4rrU0iZbQwebY+U/lkSJOK316P46sH8wu8wHB4TLVLLNpAUI0bp4sBgXlholqtlDAQw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/infer-owner": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/infer-owner/-/infer-owner-1.0.4.tgz", + "integrity": "sha512-IClj+Xz94+d7irH5qRyfJonOdfTzuDaifE6ZPWfx0N0+/ATZCbuTPq2prFl526urkQd90WyUKIh1DfBQ2hMz9A==", + "license": "ISC", + "optional": true + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", + "license": "ISC", + "optional": true, + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "license": "ISC" + }, + "node_modules/ioredis": { + "version": "5.9.2", + "resolved": "https://registry.npmjs.org/ioredis/-/ioredis-5.9.2.tgz", + "integrity": "sha512-tAAg/72/VxOUW7RQSX1pIxJVucYKcjFjfvj60L57jrZpYCHC3XN0WCQ3sNYL4Gmvv+7GPvTAjc+KSdeNuE8oWQ==", + "license": "MIT", + "dependencies": { + "@ioredis/commands": "1.5.0", + "cluster-key-slot": "^1.1.0", + "debug": "^4.3.4", + "denque": "^2.1.0", + "lodash.defaults": "^4.2.0", + "lodash.isarguments": "^3.1.0", + "redis-errors": "^1.2.0", + "redis-parser": "^3.0.0", + "standard-as-callback": "^2.1.0" + }, + "engines": { + "node": ">=12.22.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/ioredis" + } + }, + "node_modules/ip-address": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.0.1.tgz", + "integrity": "sha512-NWv9YLW4PoW2B7xtzaS3NCot75m6nK7Icdv0o3lfMceJVRfSoQwqD4wEH5rLwoKJwUiZ/rfpiVBhnaF0FK4HoA==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-lambda": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-lambda/-/is-lambda-1.0.1.tgz", + "integrity": "sha512-z7CMFGNrENq5iFB9Bqo64Xk6Y9sg+epq1myIcdHaGnbMTYOxvzsEtdYqQUylB7LxfkvgrrjP32T6Ywciio9UIQ==", + "license": "MIT", + "optional": true + }, + "node_modules/is-obj": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-2.0.0.tgz", + "integrity": "sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-property": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", + "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==", + "license": "MIT" + }, + "node_modules/is-stream": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-4.0.1.tgz", + "integrity": "sha512-Dnz92NInDqYckGEUJv689RbRiTSEHCQ7wOVeALbkOz999YpqT46yMRIGtSNl2iCL1waAZSx40+h59NV/EwzV/A==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC", + "optional": true + }, + "node_modules/json-schema-ref-resolver": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/json-schema-ref-resolver/-/json-schema-ref-resolver-3.0.0.tgz", + "integrity": "sha512-hOrZIVL5jyYFjzk7+y7n5JDzGlU8rfWDuYyHwGa2WA8/pcmMHezp2xsVwxrebD/Q9t8Nc5DboieySDpCp4WG4A==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "dequal": "^2.0.3" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/jsonwebtoken": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz", + "integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==", + "license": "MIT", + "dependencies": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=12", + "npm": ">=6" + } + }, + "node_modules/jwa": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.2.tgz", + "integrity": "sha512-eeH5JO+21J78qMvTIDdBXidBd6nG2kZjg5Ohz/1fpa28Z4CcsWUzJ1ZZyFq/3z3N17aZy+ZuBoHljASbL1WfOw==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.3.tgz", + "integrity": "sha512-byiJ0FLRdLdSVSReO/U4E7RoEyOCKnEnEPMjq3HxWtvzLsV08/i5RQKsFVNkCldrCaPr2vDNAOMsfs8T/Hze7g==", + "license": "MIT", + "dependencies": { + "jwa": "^1.4.2", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/keyv": { + "version": "5.5.5", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.5.5.tgz", + "integrity": "sha512-FA5LmZVF1VziNc0bIdCSA1IoSVnDCqE8HJIZZv2/W8YmoAM50+tnUgJR/gQZwEeIMleuIOnRnHA/UaZRNeV4iQ==", + "license": "MIT", + "dependencies": { + "@keyv/serialize": "^1.1.1" + } + }, + "node_modules/light-my-request": { + "version": "6.6.0", + "resolved": "https://registry.npmjs.org/light-my-request/-/light-my-request-6.6.0.tgz", + "integrity": "sha512-CHYbu8RtboSIoVsHZ6Ye4cj4Aw/yg2oAFimlF7mNvfDV192LR7nDiKtSIfCuLT7KokPSTn/9kfVLm5OGN0A28A==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause", + "dependencies": { + "cookie": "^1.0.1", + "process-warning": "^4.0.0", + "set-cookie-parser": "^2.6.0" + } + }, + "node_modules/light-my-request/node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/light-my-request/node_modules/process-warning": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-4.0.1.tgz", + "integrity": "sha512-3c2LzQ3rY9d0hc1emcsHhfT9Jwz0cChib/QN89oME2R451w5fy3f0afAhERFZAwrbDU43wk12d0ORBpDVME50Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/lodash.defaults": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz", + "integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==", + "license": "MIT" + }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==", + "license": "MIT" + }, + "node_modules/lodash.isarguments": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz", + "integrity": "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==", + "license": "MIT" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==", + "license": "MIT" + }, + "node_modules/lodash.isequal": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz", + "integrity": "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==", + "deprecated": "This package is deprecated. Use require('node:util').isDeepStrictEqual instead.", + "license": "MIT" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==", + "license": "MIT" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==", + "license": "MIT" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", + "license": "MIT" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==", + "license": "MIT" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==", + "license": "MIT" + }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, + "node_modules/lowercase-keys": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-3.0.0.tgz", + "integrity": "sha512-ozCC6gdQ+glXOQsveKD0YsDy8DSQFjDTz4zyzEHNV5+JP5D62LmfDZ6o1cycFx9ouG940M5dE8C8CTewdj2YWQ==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lru-cache": { + "version": "7.18.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.18.3.tgz", + "integrity": "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/lru.min": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.2.tgz", + "integrity": "sha512-Nv9KddBcQSlQopmBHXSsZVY5xsdlZkdH/Iey0BlcBYggMd4two7cZnKOK9vmy3nY0O5RGH99z1PCeTpPqszUYg==", + "license": "MIT", + "engines": { + "bun": ">=1.0.0", + "deno": ">=1.30.0", + "node": ">=8.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wellwelwel" + } + }, + "node_modules/make-fetch-happen": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-9.1.0.tgz", + "integrity": "sha512-+zopwDy7DNknmwPQplem5lAZX/eCOzSvSNNcSKm5eVwTkOBzoktEfXsa9L23J/GIRhxRsaxzkPEhrJEpE2F4Gg==", + "license": "ISC", + "optional": true, + "dependencies": { + "agentkeepalive": "^4.1.3", + "cacache": "^15.2.0", + "http-cache-semantics": "^4.1.0", + "http-proxy-agent": "^4.0.1", + "https-proxy-agent": "^5.0.0", + "is-lambda": "^1.0.1", + "lru-cache": "^6.0.0", + "minipass": "^3.1.3", + "minipass-collect": "^1.0.2", + "minipass-fetch": "^1.3.2", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "negotiator": "^0.6.2", + "promise-retry": "^2.0.1", + "socks-proxy-agent": "^6.0.0", + "ssri": "^8.0.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/make-fetch-happen/node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/make-fetch-happen/node_modules/http-proxy-agent": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-4.0.1.tgz", + "integrity": "sha512-k0zdNgqWTGA6aeIRVpvfVob4fL52dTfaehylg0Y4UvSySvOq/Y+BOyPrgpUrA7HylqvU8vIZGsRuXmspskV0Tg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@tootallnate/once": "1", + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/make-fetch-happen/node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "license": "MIT", + "optional": true, + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/make-fetch-happen/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "license": "ISC", + "optional": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/make-fetch-happen/node_modules/socks-proxy-agent": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-6.2.1.tgz", + "integrity": "sha512-a6KW9G+6B3nWZ1yB8G7pJwL3ggLy1uTzKAgCb7ttblwqdz9fMGJUuTy3uFzEP48FAs9FLILlmzDlE2JJhVQaXQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "agent-base": "^6.0.2", + "debug": "^4.3.3", + "socks": "^2.6.2" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "license": "ISC", + "optional": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-collect": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/minipass-collect/-/minipass-collect-1.0.2.tgz", + "integrity": "sha512-6T6lH0H8OG9kITm/Jm6tdooIbogG9e0tLgpY6mphXSm/A9u8Nq1ryBG+Qspiub9LjWlBPsPS3tWQ/Botq4FdxA==", + "license": "ISC", + "optional": true, + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/minipass-fetch": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-1.4.1.tgz", + "integrity": "sha512-CGH1eblLq26Y15+Azk7ey4xh0J/XfJfrCox5LDJiKqI2Q2iwOLOKrlmIaODiSQS8d18jalF6y2K2ePUm0CmShw==", + "license": "MIT", + "optional": true, + "dependencies": { + "minipass": "^3.1.0", + "minipass-sized": "^1.0.3", + "minizlib": "^2.0.0" + }, + "engines": { + "node": ">=8" + }, + "optionalDependencies": { + "encoding": "^0.1.12" + } + }, + "node_modules/minipass-flush": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/minipass-flush/-/minipass-flush-1.0.5.tgz", + "integrity": "sha512-JmQSYYpPUqX5Jyn1mXaRwOda1uQ8HP5KAT/oDSLCzt1BYRhQU0/hDtsB1ufZfEEzMZ9aAVmsBw8+FWsIXlClWw==", + "license": "ISC", + "optional": true, + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/minipass-pipeline": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/minipass-pipeline/-/minipass-pipeline-1.2.4.tgz", + "integrity": "sha512-xuIq7cIOt09RPRJ19gdi4b+RiNvDFYe5JH+ggNvBqGqpQXcru3PcRmOZuHBKWK1Txf9+cQ+HMVN4d6z46LZP7A==", + "license": "ISC", + "optional": true, + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-sized": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/minipass-sized/-/minipass-sized-1.0.3.tgz", + "integrity": "sha512-MbkQQ2CTiBMlA2Dm/5cY+9SWFEN8pzzOXi6rlM5Xxq0Yqbda5ZQy9sU75a673FE9ZK0Zsbr6Y5iP6u9nktfg2g==", + "license": "ISC", + "optional": true, + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minizlib": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", + "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", + "license": "MIT", + "dependencies": { + "minipass": "^3.0.0", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "license": "MIT", + "bin": { + "mkdirp": "bin/cmd.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "license": "MIT" + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/mysql2": { + "version": "3.15.0", + "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.15.0.tgz", + "integrity": "sha512-tT6pomf5Z/I7Jzxu8sScgrYBMK9bUFWd7Kbo6Fs1L0M13OOIJ/ZobGKS3Z7tQ8Re4lj+LnLXIQVZZxa3fhYKzA==", + "license": "MIT", + "dependencies": { + "aws-ssl-profiles": "^1.1.1", + "denque": "^2.1.0", + "generate-function": "^2.3.1", + "iconv-lite": "^0.7.0", + "long": "^5.2.1", + "lru.min": "^1.0.0", + "named-placeholders": "^1.1.3", + "seq-queue": "^0.0.5", + "sqlstring": "^2.3.2" + }, + "engines": { + "node": ">= 8.0" + } + }, + "node_modules/mysql2/node_modules/iconv-lite": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.0.tgz", + "integrity": "sha512-cf6L2Ds3h57VVmkZe+Pn+5APsT7FpqJtEhhieDCvrE2MK5Qk9MyffgQyuxQTm6BChfeZNtcOLHp9IcWRVcIcBQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/named-placeholders": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.3.tgz", + "integrity": "sha512-eLoBxg6wE/rZkJPhU/xRX1WTpkFEwDJEN96oxFrTsqBdbT5ec295Q+CoHrL9IT0DipqKhmGcaZmwOt8OON5x1w==", + "license": "MIT", + "dependencies": { + "lru-cache": "^7.14.1" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/napi-build-utils": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", + "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-abi": { + "version": "3.77.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.77.0.tgz", + "integrity": "sha512-DSmt0OEcLoK4i3NuscSbGjOf3bqiDEutejqENSplMSFA/gmB8mkED9G4pKWnPl7MDU4rSHebKPHeitpDfyH0cQ==", + "license": "MIT", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/node-addon-api": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz", + "integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==", + "license": "MIT" + }, + "node_modules/node-gyp": { + "version": "8.4.1", + "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-8.4.1.tgz", + "integrity": "sha512-olTJRgUtAb/hOXG0E93wZDs5YiJlgbXxTwQAFHyNlRsXQnYzUaF2aGgujZbw+hR8aF4ZG/rST57bWMWD16jr9w==", + "license": "MIT", + "optional": true, + "dependencies": { + "env-paths": "^2.2.0", + "glob": "^7.1.4", + "graceful-fs": "^4.2.6", + "make-fetch-happen": "^9.1.0", + "nopt": "^5.0.0", + "npmlog": "^6.0.0", + "rimraf": "^3.0.2", + "semver": "^7.3.5", + "tar": "^6.1.2", + "which": "^2.0.2" + }, + "bin": { + "node-gyp": "bin/node-gyp.js" + }, + "engines": { + "node": ">= 10.12.0" + } + }, + "node_modules/node-releases": { + "version": "2.0.27", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.27.tgz", + "integrity": "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==", + "license": "MIT" + }, + "node_modules/nopt": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz", + "integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==", + "license": "ISC", + "optional": true, + "dependencies": { + "abbrev": "1" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/normalize-url": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-8.1.1.tgz", + "integrity": "sha512-JYc0DPlpGWB40kH5g07gGTrYuMqV653k3uBKY6uITPWds3M0ov3GaWGp9lbE3Bzngx8+XkfzgvASb9vk9JDFXQ==", + "license": "MIT", + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/npmlog": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-6.0.2.tgz", + "integrity": "sha512-/vBvz5Jfr9dT/aFWd0FIRf+T/Q2WBsLENygUaFUqstqsycmZAP/t5BvFJTK0viFmSUxiUKTUplWy5vt+rvKIxg==", + "deprecated": "This package is no longer supported.", + "license": "ISC", + "optional": true, + "dependencies": { + "are-we-there-yet": "^3.0.0", + "console-control-strings": "^1.1.0", + "gauge": "^4.0.3", + "set-blocking": "^2.0.0" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + } + }, + "node_modules/nth-check": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz", + "integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==", + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0" + }, + "funding": { + "url": "https://github.com/fb55/nth-check?sponsor=1" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-exit-leak-free": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", + "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/on-headers": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.1.0.tgz", + "integrity": "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/openai": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/openai/-/openai-6.15.0.tgz", + "integrity": "sha512-F1Lvs5BoVvmZtzkUEVyh8mDQPPFolq4F+xdsx/DO8Hee8YF3IGAlZqUIsF+DVGhqf4aU0a3bTghsxB6OIsRy1g==", + "license": "Apache-2.0", + "bin": { + "openai": "bin/cli" + }, + "peerDependencies": { + "ws": "^8.18.0", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "ws": { + "optional": true + }, + "zod": { + "optional": true + } + } + }, + "node_modules/ow": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ow/-/ow-1.1.1.tgz", + "integrity": "sha512-sJBRCbS5vh1Jp9EOgwp1Ws3c16lJrUkJYlvWTYC03oyiYVwS/ns7lKRWow4w4XjDyTrA2pplQv4B2naWSR6yDA==", + "license": "MIT", + "dependencies": { + "@sindresorhus/is": "^5.3.0", + "callsites": "^4.0.0", + "dot-prop": "^7.2.0", + "lodash.isequal": "^4.5.0", + "vali-date": "^1.0.0" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ow/node_modules/@sindresorhus/is": { + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-5.6.0.tgz", + "integrity": "sha512-TV7t8GKYaJWsn00tFDqBw8+Uqmr8A0fRU1tvTQhyZzGv0sJCGRQL3JGMI3ucuKo3XIZdUP+Lx7/gh2t3lewy7g==", + "license": "MIT", + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sindresorhus/is?sponsor=1" + } + }, + "node_modules/p-cancelable": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-4.0.1.tgz", + "integrity": "sha512-wBowNApzd45EIKdO1LaU+LrMBwAcjfPaYtVzV3lmfM3gf8Z4CHZsiIqlM8TZZ8okYvh5A1cP6gTfCRQtwUpaUg==", + "license": "MIT", + "engines": { + "node": ">=14.16" + } + }, + "node_modules/p-map": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/p-map/-/p-map-4.0.0.tgz", + "integrity": "sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "aggregate-error": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parse5": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5-htmlparser2-tree-adapter": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/parse5-htmlparser2-tree-adapter/-/parse5-htmlparser2-tree-adapter-7.1.0.tgz", + "integrity": "sha512-ruw5xyKs6lrpo9x9rCZqZZnIUntICjQAd0Wsmp396Ul9lN/h+ifgVV1x1gZHi8euej6wTfpqX8j+BFQxF0NS/g==", + "license": "MIT", + "dependencies": { + "domhandler": "^5.0.3", + "parse5": "^7.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5-parser-stream": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/parse5-parser-stream/-/parse5-parser-stream-7.1.2.tgz", + "integrity": "sha512-JyeQc9iwFLn5TbvvqACIF/VXG6abODeB3Fwmv/TGdLk2LfbWkaySGY72at4+Ty7EkPZj854u4CrICqNk2qIbow==", + "license": "MIT", + "dependencies": { + "parse5": "^7.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5/node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz", + "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==", + "license": "MIT" + }, + "node_modules/peek-stream": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/peek-stream/-/peek-stream-1.1.3.tgz", + "integrity": "sha512-FhJ+YbOSBb9/rIl2ZeE/QHEsWn7PqNYt8ARAY3kIgNGOk13g9FGyIY6JIl/xB/3TFRVoTv5as0l11weORrTekA==", + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "duplexify": "^3.5.0", + "through2": "^2.0.3" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/pino": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/pino/-/pino-10.1.0.tgz", + "integrity": "sha512-0zZC2ygfdqvqK8zJIr1e+wT1T/L+LF6qvqvbzEQ6tiMAoTqEVK9a1K3YRu8HEUvGEvNqZyPJTtb2sNIoTkB83w==", + "license": "MIT", + "dependencies": { + "@pinojs/redact": "^0.4.0", + "atomic-sleep": "^1.0.0", + "on-exit-leak-free": "^2.1.0", + "pino-abstract-transport": "^2.0.0", + "pino-std-serializers": "^7.0.0", + "process-warning": "^5.0.0", + "quick-format-unescaped": "^4.0.3", + "real-require": "^0.2.0", + "safe-stable-stringify": "^2.3.1", + "sonic-boom": "^4.0.1", + "thread-stream": "^3.0.0" + }, + "bin": { + "pino": "bin.js" + } + }, + "node_modules/pino-abstract-transport": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-2.0.0.tgz", + "integrity": "sha512-F63x5tizV6WCh4R6RHyi2Ml+M70DNRXt/+HANowMflpgGFMAym/VKm6G7ZOQRjqN7XbGxK1Lg9t6ZrtzOaivMw==", + "license": "MIT", + "dependencies": { + "split2": "^4.0.0" + } + }, + "node_modules/pino-std-serializers": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.0.0.tgz", + "integrity": "sha512-e906FRY0+tV27iq4juKzSYPbUj2do2X2JX4EzSca1631EB2QJQUqGbDuERal7LCtOpxl6x3+nvo9NPZcmjkiFA==", + "license": "MIT" + }, + "node_modules/prebuild-install": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", + "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^2.0.0", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/process": { + "version": "0.11.10", + "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", + "integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==", + "license": "MIT", + "engines": { + "node": ">= 0.6.0" + } + }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "license": "MIT" + }, + "node_modules/process-warning": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.0.0.tgz", + "integrity": "sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/promise-inflight": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/promise-inflight/-/promise-inflight-1.0.1.tgz", + "integrity": "sha512-6zWPyEOFaQBJYcGMHBKTKJ3u6TBsnMFOIZSa6ce1e/ZrrsOlnHRHbabMjLiBYKp+n44X9eUI6VUPaukCXHuG4g==", + "license": "ISC", + "optional": true + }, + "node_modules/promise-retry": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/promise-retry/-/promise-retry-2.0.1.tgz", + "integrity": "sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g==", + "license": "MIT", + "optional": true, + "dependencies": { + "err-code": "^2.0.2", + "retry": "^0.12.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/proper-lockfile": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz", + "integrity": "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==", + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "retry": "^0.12.0", + "signal-exit": "^3.0.2" + } + }, + "node_modules/proper-lockfile/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "license": "ISC" + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==", + "license": "MIT" + }, + "node_modules/pump": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.3.tgz", + "integrity": "sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA==", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/pumpify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pumpify/-/pumpify-2.0.1.tgz", + "integrity": "sha512-m7KOje7jZxrmutanlkS1daj1dS6z6BgslzOXmcSEpIlCxM3VJH7lG5QLeck/6hgF6F4crFf01UtQmNsJfweTAw==", + "license": "MIT", + "dependencies": { + "duplexify": "^4.1.1", + "inherits": "^2.0.3", + "pump": "^3.0.0" + } + }, + "node_modules/pumpify/node_modules/duplexify": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/duplexify/-/duplexify-4.1.3.tgz", + "integrity": "sha512-M3BmBhwJRZsSx38lZyhE53Csddgzl5R7xGJNk7CVddZD6CcmwMCH8J+7AprIrQKH7TonKxaCjcv27Qmf+sQ+oA==", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.4.1", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1", + "stream-shift": "^1.0.2" + } + }, + "node_modules/qs": { + "version": "6.14.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.1.tgz", + "integrity": "sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/quick-format-unescaped": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz", + "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==", + "license": "MIT" + }, + "node_modules/quick-lru": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-7.3.0.tgz", + "integrity": "sha512-k9lSsjl36EJdK7I06v7APZCbyGT2vMTsYSRX1Q2nbYmnkBqgUhRkAuzH08Ciotteu/PLJmIF2+tti7o3C/ts2g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", + "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/raw-body/node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/real-require": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz", + "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==", + "license": "MIT", + "engines": { + "node": ">= 12.13.0" + } + }, + "node_modules/redis-errors": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/redis-errors/-/redis-errors-1.2.0.tgz", + "integrity": "sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/redis-parser": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/redis-parser/-/redis-parser-3.0.0.tgz", + "integrity": "sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A==", + "license": "MIT", + "dependencies": { + "redis-errors": "^1.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve-alpn": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/resolve-alpn/-/resolve-alpn-1.2.1.tgz", + "integrity": "sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g==", + "license": "MIT" + }, + "node_modules/responselike": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/responselike/-/responselike-4.0.2.tgz", + "integrity": "sha512-cGk8IbWEAnaCpdAt1BHzJ3Ahz5ewDJa0KseTsE3qIRMJ3C698W8psM7byCeWVpd/Ha7FUYzuRVzXoKoM6nRUbA==", + "license": "MIT", + "dependencies": { + "lowercase-keys": "^3.0.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ret": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/ret/-/ret-0.5.0.tgz", + "integrity": "sha512-I1XxrZSQ+oErkRR4jYbAyEEu2I0avBvvMM5JN+6EBprOGRCs63ENqZ3vjavq8fBw2+62G5LF5XelKwuJpcvcxw==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/retry": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz", + "integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/reusify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/rfdc": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", + "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", + "license": "MIT" + }, + "node_modules/rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "deprecated": "Rimraf versions prior to v4 are no longer supported", + "license": "ISC", + "optional": true, + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safe-regex2": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/safe-regex2/-/safe-regex2-5.0.0.tgz", + "integrity": "sha512-YwJwe5a51WlK7KbOJREPdjNrpViQBI3p4T50lfwPuDhZnE3XGVTlGvi+aolc5+RvxDD6bnUmjVsU9n1eboLUYw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "ret": "~0.5.0" + } + }, + "node_modules/safe-stable-stringify": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz", + "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/secure-json-parse": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-4.1.0.tgz", + "integrity": "sha512-l4KnYfEyqYJxDwlNVyRfO2E4NTHfMKAWdUuA8J0yve2Dz/E/PdBepY03RvyJpssIpRFwJoCD55wA+mEDs6ByWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/semver": { + "version": "7.7.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz", + "integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz", + "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.1", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "~2.4.1", + "range-parser": "~1.2.1", + "statuses": "~2.0.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/send/node_modules/debug/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/seq-queue": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/seq-queue/-/seq-queue-0.0.5.tgz", + "integrity": "sha512-hr3Wtp/GZIc/6DAGPDcV4/9WoZhjrkXsi5B/07QgX8tsdc6ilr7BFM6PM6rbdAX1kFSDYeZGLipIZZKyQP0O5Q==" + }, + "node_modules/serve-static": { + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz", + "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==", + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "~0.19.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "license": "ISC", + "optional": true + }, + "node_modules/set-cookie-parser": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz", + "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==", + "license": "MIT" + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "license": "MIT", + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socket.io": { + "version": "4.8.3", + "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.8.3.tgz", + "integrity": "sha512-2Dd78bqzzjE6KPkD5fHZmDAKRNe3J15q+YHDrIsy9WEkqttc7GY+kT9OBLSMaPbQaEd0x1BjcmtMtXkfpc+T5A==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.4", + "base64id": "~2.0.0", + "cors": "~2.8.5", + "debug": "~4.4.1", + "engine.io": "~6.6.0", + "socket.io-adapter": "~2.5.2", + "socket.io-parser": "~4.2.4" + }, + "engines": { + "node": ">=10.2.0" + } + }, + "node_modules/socket.io-adapter": { + "version": "2.5.6", + "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.6.tgz", + "integrity": "sha512-DkkO/dz7MGln0dHn5bmN3pPy+JmywNICWrJqVWiVOyvXjWQFIv9c2h24JrQLLFJ2aQVQf/Cvl1vblnd4r2apLQ==", + "license": "MIT", + "dependencies": { + "debug": "~4.4.1", + "ws": "~8.18.3" + } + }, + "node_modules/socket.io-parser": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.5.tgz", + "integrity": "sha512-bPMmpy/5WWKHea5Y/jYAP6k74A+hvmRCQaJuJB6I/ML5JZq/KfNieUVo/3Mh7SAqn7TyFdIo6wqYHInG1MU1bQ==", + "license": "MIT", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.4.1" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/socks": { + "version": "2.8.7", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.7.tgz", + "integrity": "sha512-HLpt+uLy/pxB+bum/9DzAgiKS8CX1EvbWxI4zlmgGCExImLdiad2iCwXT5Z4c9c3Eq8rP2318mPW2c+QbtjK8A==", + "license": "MIT", + "dependencies": { + "ip-address": "^10.0.1", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks-proxy-agent": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz", + "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "^4.3.4", + "socks": "^2.8.3" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/sonic-boom": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.0.tgz", + "integrity": "sha512-INb7TM37/mAcsGmc9hyyI6+QR3rR1zVRu36B0NeGXKnOOLiZOfER5SA+N7X7k3yUYRzLWafduTDvJAfDswwEww==", + "license": "MIT", + "dependencies": { + "atomic-sleep": "^1.0.0" + } + }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, + "node_modules/sqlite3": { + "version": "5.1.7", + "resolved": "https://registry.npmjs.org/sqlite3/-/sqlite3-5.1.7.tgz", + "integrity": "sha512-GGIyOiFaG+TUra3JIfkI/zGP8yZYLPQ0pl1bH+ODjiX57sPhrLU5sQJn1y9bDKZUFYkX1crlrPfSYt0BKKdkog==", + "hasInstallScript": true, + "license": "BSD-3-Clause", + "dependencies": { + "bindings": "^1.5.0", + "node-addon-api": "^7.0.0", + "prebuild-install": "^7.1.1", + "tar": "^6.1.11" + }, + "optionalDependencies": { + "node-gyp": "8.x" + }, + "peerDependencies": { + "node-gyp": "8.x" + }, + "peerDependenciesMeta": { + "node-gyp": { + "optional": true + } + } + }, + "node_modules/sqlstring": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.3.tgz", + "integrity": "sha512-qC9iz2FlN7DQl3+wjwn3802RTyjCx7sDvfQEXchwa6CWOx07/WVfh91gBmQ9fahw8snwGEWU3xGzOt4tFyHLxg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ssri": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/ssri/-/ssri-8.0.1.tgz", + "integrity": "sha512-97qShzy1AiyxvPNIkLWoGua7xoQzzPjQ0HAH4B0rWKo7SZ6USuPcrUiAFrws0UH8RrbWmgq3LMTObhPIHbbBeQ==", + "license": "ISC", + "optional": true, + "dependencies": { + "minipass": "^3.1.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/standard-as-callback": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/standard-as-callback/-/standard-as-callback-2.1.0.tgz", + "integrity": "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==", + "license": "MIT" + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/stream-shift": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.3.tgz", + "integrity": "sha512-76ORR0DO1o1hlKwTbi/DM3EXWGf3ZJYO8cXX5RJwnul2DEg2oyoZyjLNoQM8WsvZiFKCRfC1O0J7iCvie3RZmQ==", + "license": "MIT" + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "optional": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "optional": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tar": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz", + "integrity": "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==", + "license": "ISC", + "dependencies": { + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "minipass": "^5.0.0", + "minizlib": "^2.1.1", + "mkdirp": "^1.0.3", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/tar-fs": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz", + "integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==", + "license": "MIT", + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/tar-fs/node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "license": "ISC" + }, + "node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "license": "MIT", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tar/node_modules/minipass": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz", + "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==", + "license": "ISC", + "engines": { + "node": ">=8" + } + }, + "node_modules/thread-stream": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.1.0.tgz", + "integrity": "sha512-OqyPZ9u96VohAyMfJykzmivOrY2wfMSf3C5TtFJVgN+Hm6aj+voFhlK+kZEIv2FBh1X6Xp3DlnCOfEQ3B2J86A==", + "license": "MIT", + "dependencies": { + "real-require": "^0.2.0" + } + }, + "node_modules/through2": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", + "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", + "license": "MIT", + "dependencies": { + "readable-stream": "~2.3.6", + "xtend": "~4.0.1" + } + }, + "node_modules/through2/node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/through2/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/through2/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/tiny-secp256k1": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/tiny-secp256k1/-/tiny-secp256k1-2.2.4.tgz", + "integrity": "sha512-FoDTcToPqZE454Q04hH9o2EhxWsm7pOSpicyHkgTwKhdKWdsTUuqfP5MLq3g+VjAtl2vSx6JpXGdwA2qpYkI0Q==", + "license": "MIT", + "dependencies": { + "uint8array-tools": "0.0.7" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tiny-secp256k1/node_modules/uint8array-tools": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/uint8array-tools/-/uint8array-tools-0.0.7.tgz", + "integrity": "sha512-vrrNZJiusLWoFWBqz5Y5KMCgP9W9hnjZHzZiZRT8oNAkq3d5Z5Oe76jAvVVSRh4U8GGR90N2X1dWtrhvx6L8UQ==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tldts": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz", + "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==", + "license": "MIT", + "dependencies": { + "tldts-core": "^6.1.86" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz", + "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==", + "license": "MIT" + }, + "node_modules/toad-cache": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/toad-cache/-/toad-cache-3.7.0.tgz", + "integrity": "sha512-/m8M+2BJUpoJdgAHoG+baCwBT+tf2VraSfkBgl0Y00qIWt41DJ8R5B8nsEw0I58YwF5IZH6z24/2TobDKnqSWw==", + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tough-cookie": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz", + "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==", + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^6.1.32" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/type-fest": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz", + "integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/uint8array-tools": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/uint8array-tools/-/uint8array-tools-0.0.8.tgz", + "integrity": "sha512-xS6+s8e0Xbx++5/0L+yyexukU7pz//Yg6IHg3BKhXotg1JcYtgxVcUctQ0HxLByiJzpAkNFawz1Nz5Xadzo82g==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/undici": { + "version": "7.13.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.13.0.tgz", + "integrity": "sha512-l+zSMssRqrzDcb3fjMkjjLGmuiiK2pMIcV++mJaAc9vhjSGpvM7h43QgP+OAMb1GImHmbPyG2tBXeuyG5iY4gA==", + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/undici-types": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "license": "MIT" + }, + "node_modules/unique-filename": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/unique-filename/-/unique-filename-1.1.1.tgz", + "integrity": "sha512-Vmp0jIp2ln35UTXuryvjzkjGdRyf9b2lTXuSYUiPmzRcl3FDtYqAwOnTJkAngD9SWhnoJzDbTKwaOrZ+STtxNQ==", + "license": "ISC", + "optional": true, + "dependencies": { + "unique-slug": "^2.0.0" + } + }, + "node_modules/unique-slug": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/unique-slug/-/unique-slug-2.0.2.tgz", + "integrity": "sha512-zoWr9ObaxALD3DOPfjPSqxt4fnZiWblxHIgeWqW8x7UqDzEtHEQLzji2cuJYQFCU6KmoJikOYAZlrTHHebjx2w==", + "license": "ISC", + "optional": true, + "dependencies": { + "imurmurhash": "^0.1.4" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/uuid": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz", + "integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/esm/bin/uuid" + } + }, + "node_modules/vali-date": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/vali-date/-/vali-date-1.0.0.tgz", + "integrity": "sha512-sgECfZthyaCKW10N0fm27cg8HYTFK5qMWgypqkXMQ4Wbl/zZKx7xZICgcoxIIE+WFAP/MBL2EFwC/YvLxw3Zeg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/valibot": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/valibot/-/valibot-1.3.1.tgz", + "integrity": "sha512-sfdRir/QFM0JaF22hqTroPc5xy4DimuGQVKFrzF1YfGwaS1nJot3Y8VqMdLO2Lg27fMzat2yD3pY5PbAYO39Gg==", + "license": "MIT", + "peerDependencies": { + "typescript": ">=5" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/varuint-bitcoin": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/varuint-bitcoin/-/varuint-bitcoin-2.0.0.tgz", + "integrity": "sha512-6QZbU/rHO2ZQYpWFDALCDSRsXbAs1VOEmXAxtbtjLtKuMJ/FQ8YbhfxlaiKv5nklci0M6lZtlZyxo9Q+qNnyog==", + "license": "MIT", + "dependencies": { + "uint8array-tools": "^0.0.8" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/whatwg-encoding": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", + "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "optional": true, + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/wide-align": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz", + "integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==", + "license": "ISC", + "optional": true, + "dependencies": { + "string-width": "^1.0.2 || 2 || 3 || 4" + } + }, + "node_modules/wif": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/wif/-/wif-5.0.0.tgz", + "integrity": "sha512-iFzrC/9ne740qFbNjTZ2FciSRJlHIXoxqk/Y5EnE08QOXu1WjJyCCswwDTYbohAOEnlCtLaAAQBhyaLRFh2hMA==", + "license": "MIT", + "dependencies": { + "bs58check": "^4.0.0" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/write-file-atomic": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-6.0.0.tgz", + "integrity": "sha512-GmqrO8WJ1NuzJ2DrziEI2o57jKAVIQNf8a18W3nCYU3H7PNWqCCVTeH6/NQE93CIllIgQS98rrmVkYgTX9fFJQ==", + "license": "ISC", + "dependencies": { + "imurmurhash": "^0.1.4", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/ws": { + "version": "8.18.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz", + "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "license": "MIT", + "engines": { + "node": ">=0.4" + } + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "license": "ISC" + } + } +} diff --git a/API/Mainapi/package.json b/API/Mainapi/package.json new file mode 100644 index 0000000..3108620 --- /dev/null +++ b/API/Mainapi/package.json @@ -0,0 +1,52 @@ +{ + "name": "movix-api", + "private": true, + "type": "commonjs", + "scripts": { + "start": "node server.js", + "dev": "node server.js", + "start-new": "node server-new.js" + }, + "dependencies": { + "@fastify/compress": "^8.3.1", + "@fastify/cookie": "^11.0.2", + "@fastify/cors": "^11.2.0", + "@fastify/express": "^4.0.2", + "@fastify/formbody": "^8.0.2", + "@fastify/middie": "^9.1.0", + "@ffmpeg-installer/ffmpeg": "^1.1.0", + "axios": "^1.11.0", + "axios-cookiejar-support": "^6.0.4", + "better-sqlite3": "^12.5.0", + "bip32": "^5.0.1", + "bip39": "^3.1.0", + "bitcoinjs-lib": "^7.0.1", + "chardet": "^2.0.0", + "cheerio": "^1.1.2", + "compression": "^1.8.1", + "cors": "^2.8.5", + "crypto-js": "^4.2.0", + "cycletls": "^1.0.27", + "dotenv": "^17.2.1", + "express": "^4.21.2", + "express-list-endpoints": "^7.1.1", + "express-rate-limit": "^8.2.1", + "fastify": "^5.6.2", + "got-scraping": "^4.1.3", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.6", + "impit": "^0.9.2", + "ioredis": "^5.9.2", + "jsonwebtoken": "^9.0.2", + "mysql2": "^3.15.0", + "openai": "^6.15.0", + "proper-lockfile": "^4.1.2", + "socket.io": "^4.8.3", + "socks-proxy-agent": "^8.0.5", + "sqlite3": "^5.1.7", + "tiny-secp256k1": "^2.2.4", + "tough-cookie": "^5.1.2", + "uuid": "^11.1.0", + "write-file-atomic": "^6.0.0" + } +} diff --git a/API/Mainapi/routes/admin.js b/API/Mainapi/routes/admin.js new file mode 100644 index 0000000..76d51ca --- /dev/null +++ b/API/Mainapi/routes/admin.js @@ -0,0 +1,872 @@ +/** + * Admin routes. + * Extracted from server.js -- streaming links CRUD, VIP key management, admin checks, anime cache. + * Mount point: app.use('/api', router) + */ + +const express = require('express'); +const router = express.Router(); +const path = require('path'); +const fsp = require('fs').promises; +const rateLimit = require('express-rate-limit'); +const { ipKeyGenerator } = require('express-rate-limit'); + +const { isAdmin, isUploaderOrAdmin } = require('../middleware/auth'); +const { getPool } = require('../mysqlPool'); +const { verifyAccessKey, invalidateVipCache } = require('../checkVip'); +const { ANIME_SAMA_CACHE_DIR } = require('../utils/cacheManager'); +const { createRedisRateLimitStore } = require('../utils/redisRateLimitStore'); + +function parseAccessKeyExpiresAt(value) { + if (value === undefined || value === null || value === '') { + return null; + } + + if (typeof value === 'number' && Number.isFinite(value)) { + return Math.trunc(value); + } + + const normalizedValue = String(value).trim(); + if (!normalizedValue) { + return null; + } + + if (/^\d+$/.test(normalizedValue)) { + return Number(normalizedValue); + } + + const parsed = new Date( + normalizedValue.includes('T') + ? normalizedValue + : normalizedValue.replace(' ', 'T') + ); + const timestamp = parsed.getTime(); + + if (!Number.isFinite(timestamp)) { + throw new Error('Date d\'expiration invalide'); + } + + return timestamp; +} + +function buildAccessKeyExpiryFromDuration(durationLabel) { + if (!durationLabel) { + return null; + } + + const now = new Date(); + const match = durationLabel.match(/(\d+)\s*(min|minute|minutes|h|hour|hours|heure|heures|d|day|days|jour|jours|m|month|months|mois|y|year|years|an|ans)/i); + + if (!match) { + return null; + } + + const duration = parseInt(match[1], 10); + const unit = match[2].toLowerCase(); + + if (unit.startsWith('min')) { + now.setMinutes(now.getMinutes() + duration); + } else if (unit.startsWith('h')) { + now.setHours(now.getHours() + duration); + } else if (unit.startsWith('d') || unit.startsWith('j')) { + now.setDate(now.getDate() + duration); + } else if (unit.startsWith('m')) { + now.setMonth(now.getMonth() + duration); + } else if (unit.startsWith('y') || unit.startsWith('an')) { + now.setFullYear(now.getFullYear() + duration); + } + + return now.getTime(); +} + +// Rate limiter pour la vérification de codes VIP +// 5 tentatives par IP toutes les 15 minutes (plus strict car code bruteforceable) +const vipCodeRateLimit = rateLimit({ + windowMs: 15 * 60 * 1000, + max: 5, + store: createRedisRateLimitStore({ prefix: 'rate-limit:admin:vip-code-check:' }), + passOnStoreError: true, + standardHeaders: true, + legacyHeaders: false, + message: { + success: false, + error: 'Trop de tentatives de vérification. Réessayez dans 15 minutes.' + }, + keyGenerator: (req) => req.headers['cf-connecting-ip'] || req.headers['x-forwarded-for']?.split(',')[0].trim() || ipKeyGenerator(req.ip), + validate: { xForwardedForHeader: false, ip: false } +}); + +// === PUBLIC ROUTES (no authentication) === + +/** + * GET /links/:type/:id + * Retrieve streaming links for a movie or series + * Params: type (movie/tv), id (TMDB ID) + * Query: season (optional for series), episode (optional for series) + */ +router.get('/links/:type/:id', async (req, res) => { + try { + const { type, id } = req.params; + const { season, episode } = req.query; + + // Validation + if (!['movie', 'tv'].includes(type)) { + return res.status(400).json({ success: false, error: 'Type invalide. Utilisez "movie" ou "tv"' }); + } + + const pool = getPool(); + let query, params; + + if (type === 'movie') { + query = 'SELECT id, links FROM films WHERE id = ?'; + params = [id]; + } else { + // Pour les séries + if (!season || !episode) { + // Retourner tous les épisodes de la série + query = 'SELECT id, series_id, season_number, episode_number, links FROM series WHERE series_id = ? ORDER BY season_number, episode_number'; + params = [id]; + } else { + // Retourner un épisode spécifique + query = 'SELECT id, series_id, season_number, episode_number, links FROM series WHERE series_id = ? AND season_number = ? AND episode_number = ?'; + params = [id, parseInt(season), parseInt(episode)]; + } + } + + const [rows] = await pool.execute(query, params); + + if (rows.length === 0) { + return res.status(404).json({ + success: false, + error: 'Aucun lien trouvé', + type, + id, + ...(season && { season }), + ...(episode && { episode }) + }); + } + + // Parser les liens JSON + const result = rows.map(row => ({ + ...row, + links: typeof row.links === 'string' ? JSON.parse(row.links) : row.links + })); + + res.json({ + success: true, + type, + data: type === 'movie' ? result[0] : result + }); + + } catch (error) { + console.error('Error fetching streaming links:', error); + res.status(500).json({ + success: false, + error: 'Erreur lors de la récupération des liens', + message: error.message + }); + } +}); + +/** + * POST /verify-access-code + * Verify a VIP access code (used during initial code entry) + * Body: { code: string } + */ +router.post('/verify-access-code', vipCodeRateLimit, async (req, res) => { + try { + const { code } = req.body; + + if (!code) { + return res.status(400).json({ + success: false, + error: 'Code d\'accès requis' + }); + } + + // Utiliser le module centralisé checkVip + const vipStatus = await verifyAccessKey(code); + + if (!vipStatus.vip) { + if (vipStatus.reason === 'key_expired') { + return res.status(410).json({ + success: false, + error: 'Code d\'accès expiré' + }); + } + if (vipStatus.reason === 'key_inactive') { + return res.status(403).json({ + success: false, + error: 'Code d\'accès désactivé' + }); + } + return res.status(404).json({ + success: false, + error: 'Code d\'accès invalide ou expiré' + }); + } + + return res.json({ + success: true, + message: 'Code d\'accès valide', + data: { + key: code, + duration: vipStatus.duration, + expiresAt: vipStatus.expiresAt + } + }); + + } catch (error) { + console.error('Error verifying access code:', error); + return res.status(500).json({ + success: false, + error: 'Erreur lors de la vérification du code d\'accès' + }); + } +}); + +/** + * GET /check-vip + * Server-side VIP status check via x-access-key header. + * Called periodically by the frontend to ensure the key is still valid. + * If the key is no longer valid, the frontend must revoke the local VIP status. + */ +router.get('/check-vip', async (req, res) => { + try { + const accessKey = req.headers['x-access-key']; + + if (!accessKey) { + return res.json({ vip: false, reason: 'no_key' }); + } + + const vipStatus = await verifyAccessKey(accessKey); + + return res.json({ + vip: vipStatus.vip, + expiresAt: vipStatus.expiresAt || null, + duration: vipStatus.duration || null, + reason: vipStatus.reason || null + }); + + } catch (error) { + console.error('Error checking VIP status:', error); + return res.status(500).json({ vip: false, error: 'Erreur interne' }); + } +}); + +// === ADMIN ROUTES (with authentication) === + +/** + * POST /admin/links + * Add or update streaming links + * Body: { type: 'movie'|'tv', id: string, links: array, season?: number, episode?: number } + */ +router.post('/admin/links', isUploaderOrAdmin, async (req, res) => { + try { + const { type, id, links, season, episode } = req.body; + + // Validation + if (!type || !id || !links || !Array.isArray(links)) { + return res.status(400).json({ + success: false, + error: 'Paramètres invalides. Required: type, id, links (array)' + }); + } + + if (!['movie', 'tv'].includes(type)) { + return res.status(400).json({ success: false, error: 'Type invalide. Utilisez "movie" ou "tv"' }); + } + + if (type === 'tv' && (season === undefined || season === null || episode === undefined || episode === null)) { + return res.status(400).json({ + success: false, + error: 'Pour les séries, season et episode sont requis' + }); + } + + const pool = getPool(); + + if (type === 'movie') { + // Récupérer les liens existants + const [existing] = await pool.execute( + 'SELECT links FROM films WHERE id = ?', + [id] + ); + + let finalLinks = links; + if (existing.length > 0 && existing[0].links) { + // Parse existing links + const existingLinks = typeof existing[0].links === 'string' + ? JSON.parse(existing[0].links) + : existing[0].links; + + // Merge with new links, avoiding duplicates + const existingUrls = new Set(existingLinks.map(link => + typeof link === 'string' ? link : link.url || JSON.stringify(link) + )); + + const newLinksToAdd = links.filter(link => { + const url = typeof link === 'string' ? link : link.url || JSON.stringify(link); + return !existingUrls.has(url); + }); + + finalLinks = [...existingLinks, ...newLinksToAdd]; + } + + const linksJson = JSON.stringify(finalLinks); + + // Insérer ou mettre à jour le film + await pool.execute( + 'INSERT INTO films (id, links) VALUES (?, ?) ON DUPLICATE KEY UPDATE links = VALUES(links), updated_at = CURRENT_TIMESTAMP', + [id, linksJson] + ); + + res.json({ + success: true, + message: 'Liens de film ajoutés/mis à jour avec succès', + type: 'movie', + id, + linksCount: finalLinks.length + }); + + } else { + // Insérer ou mettre à jour l'épisode de série + // Vérifier si l'épisode existe déjà + const [existing] = await pool.execute( + 'SELECT id, links FROM series WHERE series_id = ? AND season_number = ? AND episode_number = ?', + [id, season, episode] + ); + + let finalLinks = links; + if (existing.length > 0 && existing[0].links) { + // Parse existing links + const existingLinks = typeof existing[0].links === 'string' + ? JSON.parse(existing[0].links) + : existing[0].links; + + // Merge with new links, avoiding duplicates + const existingUrls = new Set(existingLinks.map(link => + typeof link === 'string' ? link : link.url || JSON.stringify(link) + )); + + const newLinksToAdd = links.filter(link => { + const url = typeof link === 'string' ? link : link.url || JSON.stringify(link); + return !existingUrls.has(url); + }); + + finalLinks = [...existingLinks, ...newLinksToAdd]; + } + + const linksJson = JSON.stringify(finalLinks); + + if (existing.length > 0) { + // Mise à jour + await pool.execute( + 'UPDATE series SET links = ? WHERE series_id = ? AND season_number = ? AND episode_number = ?', + [linksJson, id, season, episode] + ); + } else { + // Insertion + await pool.execute( + 'INSERT INTO series (series_id, season_number, episode_number, links) VALUES (?, ?, ?, ?)', + [id, season, episode, linksJson] + ); + } + + res.json({ + success: true, + message: 'Liens d\'épisode ajoutés/mis à jour avec succès', + type: 'tv', + id, + season, + episode, + linksCount: finalLinks.length + }); + } + + } catch (error) { + console.error('Error adding streaming links:', error); + res.status(500).json({ + success: false, + error: 'Erreur lors de l\'ajout des liens', + message: error.message + }); + } +}); + +/** + * DELETE /admin/links + * Delete streaming links + * Body: { type: 'movie'|'tv', id: string, season?: number, episode?: number } + */ +router.delete('/admin/links', isUploaderOrAdmin, async (req, res) => { + try { + const { type, id, season, episode } = req.body; + + // Validation + if (!type || !id) { + return res.status(400).json({ + success: false, + error: 'Paramètres invalides. Required: type, id' + }); + } + + if (!['movie', 'tv'].includes(type)) { + return res.status(400).json({ success: false, error: 'Type invalide. Utilisez "movie" ou "tv"' }); + } + + const pool = getPool(); + + if (type === 'movie') { + const [result] = await pool.execute('DELETE FROM films WHERE id = ?', [id]); + + if (result.affectedRows === 0) { + return res.status(404).json({ success: false, error: 'Film non trouvé' }); + } + + res.json({ + success: true, + message: 'Film supprimé avec succès', + type: 'movie', + id + }); + + } else { + // Pour les séries + let query, params; + + if (season && episode) { + // Supprimer un épisode spécifique + query = 'DELETE FROM series WHERE series_id = ? AND season_number = ? AND episode_number = ?'; + params = [id, season, episode]; + } else if (season) { + // Supprimer toute une saison + query = 'DELETE FROM series WHERE series_id = ? AND season_number = ?'; + params = [id, season]; + } else { + // Supprimer toute la série + query = 'DELETE FROM series WHERE series_id = ?'; + params = [id]; + } + + const [result] = await pool.execute(query, params); + + if (result.affectedRows === 0) { + return res.status(404).json({ success: false, error: 'Aucune donnée trouvée à supprimer' }); + } + + res.json({ + success: true, + message: `${result.affectedRows} épisode(s) supprimé(s) avec succès`, + type: 'tv', + id, + ...(season && { season }), + ...(episode && { episode }), + deletedCount: result.affectedRows + }); + } + + } catch (error) { + console.error('Error deleting streaming links:', error); + res.status(500).json({ + success: false, + error: 'Erreur lors de la suppression des liens', + message: error.message + }); + } +}); + +/** + * PUT /admin/links + * Modify streaming links (complete replacement) + * Body: { type: 'movie'|'tv', id: string, links: array, season?: number, episode?: number } + */ +router.put('/admin/links', isUploaderOrAdmin, async (req, res) => { + try { + const { type, id, links, season, episode } = req.body; + + // Validation + if (!type || !id || !links || !Array.isArray(links)) { + return res.status(400).json({ + success: false, + error: 'Paramètres invalides. Required: type, id, links (array)' + }); + } + + if (!['movie', 'tv'].includes(type)) { + return res.status(400).json({ success: false, error: 'Type invalide. Utilisez "movie" ou "tv"' }); + } + + if (type === 'tv' && (season === undefined || season === null || episode === undefined || episode === null)) { + return res.status(400).json({ + success: false, + error: 'Pour les séries, season et episode sont requis' + }); + } + + const pool = getPool(); + const linksJson = JSON.stringify(links); + + if (type === 'movie') { + const [result] = await pool.execute( + 'UPDATE films SET links = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', + [linksJson, id] + ); + + if (result.affectedRows === 0) { + return res.status(404).json({ success: false, error: 'Film non trouvé' }); + } + + res.json({ + success: true, + message: 'Liens de film modifiés avec succès', + type: 'movie', + id, + linksCount: links.length + }); + + } else { + const [result] = await pool.execute( + 'UPDATE series SET links = ? WHERE series_id = ? AND season_number = ? AND episode_number = ?', + [linksJson, id, season, episode] + ); + + if (result.affectedRows === 0) { + return res.status(404).json({ success: false, error: 'Épisode non trouvé' }); + } + + res.json({ + success: true, + message: 'Liens d\'épisode modifiés avec succès', + type: 'tv', + id, + season, + episode, + linksCount: links.length + }); + } + + } catch (error) { + console.error('Error updating streaming links:', error); + res.status(500).json({ + success: false, + error: 'Erreur lors de la modification des liens', + message: error.message + }); + } +}); + +// === ADMIN ROUTES - VIP KEY MANAGEMENT === + +/** + * GET /admin/check + * Verify admin rights (admin or uploader) + */ +router.get('/admin/check', isUploaderOrAdmin, async (req, res) => { + try { + res.json({ + success: true, + message: 'Droits d\'administration confirmés', + admin: { + userId: req.admin.userId, + userType: req.admin.userType, + adminId: req.admin.adminId, + role: req.admin.role // Inclure le rôle dans la réponse + } + }); + } catch (error) { + console.error('Admin check error:', error); + res.status(500).json({ success: false, error: 'Erreur lors de la vérification admin' }); + } +}); + +/** + * GET /admin/vip-keys + * Retrieve all VIP keys + * Query: active (optional, true/false), used (optional, true/false), search, page, limit + */ +router.get('/admin/vip-keys', isAdmin, async (req, res) => { + try { + const { active, used } = req.query; + const search = String(req.query.search || '').trim(); + const page = Math.max(1, parseInt(String(req.query.page || '1'), 10) || 1); + const limit = Math.min(100, Math.max(1, parseInt(String(req.query.limit || '30'), 10) || 30)); + const offset = (page - 1) * limit; + + const conditions = []; + const params = []; + + if (active !== undefined) { + conditions.push('active = ?'); + params.push(active === 'true' ? 1 : 0); + } + + if (used !== undefined) { + conditions.push('used = ?'); + params.push(used === 'true' ? 1 : 0); + } + + if (search) { + const likeSearch = `%${search}%`; + conditions.push(`( + key_value LIKE ? + OR COALESCE(duree_validite, '') LIKE ? + OR COALESCE(CAST(expires_at AS CHAR), '') LIKE ? + OR COALESCE(DATE_FORMAT(FROM_UNIXTIME(expires_at / 1000), '%Y-%m-%d %H:%i:%s'), '') LIKE ? + OR COALESCE(DATE_FORMAT(created_at, '%Y-%m-%d %H:%i:%s'), '') LIKE ? + )`); + params.push(likeSearch, likeSearch, likeSearch, likeSearch, likeSearch); + } + + let whereClause = ''; + if (conditions.length > 0) { + whereClause = ` WHERE ${conditions.join(' AND ')}`; + } + + const pool = getPool(); + const [[countRow]] = await pool.execute( + `SELECT COUNT(*) AS total FROM access_keys${whereClause}`, + params + ); + const total = Number(countRow?.total || 0); + + const [rows] = await pool.execute( + `SELECT * FROM access_keys${whereClause} ORDER BY created_at DESC LIMIT ? OFFSET ?`, + [...params, limit, offset] + ); + + res.json({ + success: true, + keys: rows, + count: rows.length, + total, + page, + limit, + hasMore: offset + rows.length < total + }); + + } catch (error) { + console.error('Error fetching VIP keys:', error); + res.status(500).json({ + success: false, + error: 'Erreur lors de la récupération des clés VIP', + message: error.message + }); + } +}); + +/** + * POST /admin/vip-keys + * Add a new VIP key + * Body: { key: string, duree_validite?: string, expires_at?: string } + */ +router.post('/admin/vip-keys', isAdmin, async (req, res) => { + try { + const { key, duree_validite, expires_at } = req.body; + + // Validation + if (!key || key.trim().length === 0) { + return res.status(400).json({ + success: false, + error: 'La clé est requise et ne peut pas être vide' + }); + } + + if (key.length > 255) { + return res.status(400).json({ + success: false, + error: 'La clé ne peut pas dépasser 255 caractères' + }); + } + + const pool = getPool(); + + // Vérifier si la clé existe déjà + const [existing] = await pool.execute( + 'SELECT key_value FROM access_keys WHERE key_value = ?', + [key] + ); + + if (existing.length > 0) { + return res.status(409).json({ + success: false, + error: 'Cette clé existe déjà' + }); + } + + // Calculer la date d'expiration si duree_validite est fournie + let expiresAtValue = parseAccessKeyExpiresAt(expires_at); + + if (duree_validite && !expires_at) { + expiresAtValue = buildAccessKeyExpiryFromDuration(duree_validite); + } + + // Insérer la nouvelle clé + await pool.execute( + 'INSERT INTO access_keys (key_value, active, used, duree_validite, expires_at, created_at) VALUES (?, 1, 0, ?, ?, NOW())', + [key, duree_validite || null, expiresAtValue || null] + ); + + // Invalider le cache VIP pour cette clé + invalidateVipCache(key); + + res.status(201).json({ + success: true, + message: 'Clé VIP créée avec succès', + key: { + key_value: key, + duree_validite: duree_validite || null, + expires_at: expiresAtValue || null, + active: true, + used: false + } + }); + + } catch (error) { + console.error('Error adding VIP key:', error); + res.status(500).json({ + success: false, + error: 'Erreur lors de l\'ajout de la clé VIP', + message: error.message + }); + } +}); + +/** + * PUT /admin/vip-keys/:key + * Modify a VIP key (expiration, duration, status) + * Body: { duree_validite?: string, expires_at?: string, active?: boolean, used?: boolean } + */ +router.put('/admin/vip-keys/:key', isAdmin, async (req, res) => { + try { + const { key } = req.params; + const { duree_validite, expires_at, active, used } = req.body; + + const pool = getPool(); + + // Vérifier si la clé existe + const [existing] = await pool.execute( + 'SELECT * FROM access_keys WHERE key_value = ?', + [key] + ); + + if (existing.length === 0) { + return res.status(404).json({ + success: false, + error: 'Clé VIP non trouvée' + }); + } + + // Construire la requête de mise à jour dynamiquement + const updates = []; + const params = []; + + if (duree_validite !== undefined) { + updates.push('duree_validite = ?'); + params.push(duree_validite || null); + + // Si duree_validite est fournie, calculer la nouvelle date d'expiration + if (duree_validite && expires_at === undefined) { + const computedExpiresAt = buildAccessKeyExpiryFromDuration(duree_validite); + if (computedExpiresAt !== null) { + updates.push('expires_at = ?'); + params.push(computedExpiresAt); + } + } + } + + if (expires_at !== undefined) { + updates.push('expires_at = ?'); + params.push(parseAccessKeyExpiresAt(expires_at)); + } + + if (active !== undefined) { + updates.push('active = ?'); + params.push(active ? 1 : 0); + } + + if (used !== undefined) { + updates.push('used = ?'); + params.push(used ? 1 : 0); + } + + if (updates.length === 0) { + return res.status(400).json({ + success: false, + error: 'Aucune modification fournie' + }); + } + + params.push(key); + + await pool.execute( + `UPDATE access_keys SET ${updates.join(', ')}, updated_at = CURRENT_TIMESTAMP WHERE key_value = ?`, + params + ); + + // Invalider le cache VIP pour cette clé + invalidateVipCache(key); + + // Récupérer la clé mise à jour + const [updated] = await pool.execute( + 'SELECT * FROM access_keys WHERE key_value = ?', + [key] + ); + + res.json({ + success: true, + message: 'Clé VIP modifiée avec succès', + key: updated[0] + }); + + } catch (error) { + console.error('Error updating VIP key:', error); + res.status(500).json({ + success: false, + error: 'Erreur lors de la modification de la clé VIP', + message: error.message + }); + } +}); + +/** + * DELETE /admin/vip-keys/:key + * Delete a VIP key + */ +router.delete('/admin/vip-keys/:key', isAdmin, async (req, res) => { + try { + const { key } = req.params; + + const pool = getPool(); + const [result] = await pool.execute( + 'DELETE FROM access_keys WHERE key_value = ?', + [key] + ); + + if (result.affectedRows === 0) { + return res.status(404).json({ + success: false, + error: 'Clé VIP non trouvée' + }); + } + + // Invalider le cache VIP pour cette clé + invalidateVipCache(key); + + res.json({ + success: true, + message: 'Clé VIP supprimée avec succès', + key + }); + + } catch (error) { + console.error('Error deleting VIP key:', error); + res.status(500).json({ + success: false, + error: 'Erreur lors de la suppression de la clé VIP', + message: error.message + }); + } +}); + +module.exports = router; diff --git a/API/Mainapi/routes/animeSama.js b/API/Mainapi/routes/animeSama.js new file mode 100644 index 0000000..dcce0cb --- /dev/null +++ b/API/Mainapi/routes/animeSama.js @@ -0,0 +1,1085 @@ +/** + * AnimeSama route module. + * Extracted from server.js -- handles anime search, season/episode scraping, and caching. + * + * Mounted as: app.use('/anime', require('./routes/animeSama')); + * Route paths are relative to the mount point. + */ + +const express = require('express'); +const router = express.Router(); +const cheerio = require('cheerio'); +const fsp = require('fs').promises; +const path = require('path'); +const axios = require('axios'); +const writeFileAtomic = require('write-file-atomic'); + +const { ANIME_SAMA_CACHE_DIR, generateCacheKey } = require('../utils/cacheManager'); +const { memoryCache } = require('../config/redis'); + +// ---- Lazy-bound dependencies injected via configure() ---- +let deps = { + ANIME_SAMA_URL: '', + axiosAnimeSama: null, + axiosAnimeSamaRequest: async () => { throw new Error('animeSama not configured'); }, + getFromCacheNoExpiration: async () => null, + saveToCache: async () => false, + normalizeAnimeSamaUrls: (data) => data, + mergeStreamingLinks: () => [], + cleanupOldCacheFiles: async () => {}, + migrateOldCacheFiles: async () => {}, + limitConcurrency10: async (fn) => fn() +}; + +function configure(injected) { + Object.assign(deps, injected); + // Re-bind normalizeAnimeSamaUrls with the current ANIME_SAMA_URL + deps.normalizeAnimeSamaUrls = normalizeAnimeSamaUrls; +} + +// ---- normalizeAnimeSamaUrls (was inline in server.js) ---- +const normalizeAnimeSamaUrls = (data) => { + if (!data) return data; + const currentDomain = (deps.ANIME_SAMA_URL || '').replace(/\/$/, ''); + + const isValidPlayerUrl = (url) => { + if (typeof url !== 'string' || url.length === 0) return false; + if (!url.startsWith('http://') && !url.startsWith('https://')) return false; + if (!url.includes('.')) return false; + const invalidPatterns = ['_self', 'containerSamedi', '\u00e9lite', 'Sectes', 'prouesses', 'discord.gg']; + if (invalidPatterns.some(pattern => url.includes(pattern))) return false; + return true; + }; + + const replaceUrls = (obj, key = null) => { + if (typeof obj === 'string') { + let cleanedUrl = obj.replace(/https:\/\/proxy\.movix\.(blog|club|site)\/proxy\//gi, ''); + return cleanedUrl.replace(/https?:\/\/anime-sama\.[a-z]+/gi, currentDomain); + } + if (Array.isArray(obj)) { + if (key === 'players') { + return obj.map(item => replaceUrls(item)).filter(item => { + if (item && typeof item === 'object' && item.link) return true; + return isValidPlayerUrl(item); + }); + } + if (key === 'streaming_links') { + return obj.map(item => replaceUrls(item)).filter(item => item && item.players && item.players.length > 0); + } + return obj.map(item => replaceUrls(item)); + } + if (obj && typeof obj === 'object') { + const newObj = {}; + for (const [k, value] of Object.entries(obj)) { + newObj[k] = replaceUrls(value, k); + } + return newObj; + } + return obj; + }; + + return replaceUrls(data); +}; + +// ---- Utility functions ---- + +const zipVarlen = (...arrays) => { + const maxLength = Math.max(...arrays.map(arr => arr.length)); + const result = []; + + for (let i = 0; i < maxLength; i++) { + result.push(arrays.map(arr => i < arr.length ? arr[i] : [])); + } + + return result; +}; + +const splitAndStrip = (str, delimiter) => { + return str.split(delimiter).map(item => item.trim()).filter(item => item); +}; + +const removeQuotes = (str) => { + if (typeof str !== 'string') return str; + return str.replace(/^["'](.*)["']$/, '$1'); +}; + +const safeFilename = (str) => { + return str.replace(/[^a-zA-Z0-9\s\-_]/g, '').trim(); +}; + +// Language constants +const LANG = { + VOSTFR: 'VOSTFR', + VF: 'VF', + VOST_ENG: 'VOSTEng', + VOST_SPA: 'VOSTSpa', + VJ: 'VJ' +}; + +const LANG_ID = { + VOSTFR: 'vostfr', + VF: 'vf', + VOST_ENG: 'vosteng', + VOST_SPA: 'vostspa', + VJ: 'vj' +}; + +const flags = { + 'VOSTFR': '\ud83c\uddef\ud83c\uddf5', + 'VF': '\ud83c\uddeb\ud83c\uddf7', + 'VOSTEng': '\ud83c\uddec\ud83c\udde7', + 'VOSTSpa': '\ud83c\uddea\ud83c\uddf8', + 'VJ': '\ud83c\uddef\ud83c\uddf5' +}; + +const id2lang = { + 'vostfr': LANG.VOSTFR, + 'vf': LANG.VF, + 'vosteng': LANG.VOST_ENG, + 'vostspa': LANG.VOST_SPA, + 'vj': LANG.VJ +}; + +const lang2ids = { + [LANG.VOSTFR]: [LANG_ID.VOSTFR], + [LANG.VF]: [LANG_ID.VF], + [LANG.VOST_ENG]: [LANG_ID.VOST_ENG], + [LANG.VOST_SPA]: [LANG_ID.VOST_SPA], + [LANG.VJ]: [LANG_ID.VJ] +}; + +const langIds = ['vostfr', 'vf', 'vosteng', 'vostspa', 'vj', 'va', 'vf1', 'vf2', 'vkr']; + +// Helper function to validate player URLs +const isValidPlayerUrl = (url) => { + if (typeof url !== 'string' || url.length === 0) return false; + if (!url.startsWith('http://') && !url.startsWith('https://')) return false; + if (!url.includes('.')) return false; + const invalidPatterns = ['_self', 'containerSamedi', '\u00e9lite', 'Sectes', 'prouesses', 'discord.gg']; + if (invalidPatterns.some(pattern => url.includes(pattern))) return false; + return true; +}; + +// ---- Classes ---- + +class Players { + constructor(availables = []) { + this.availables = availables; + this._best = null; + this.index = 1; + } + + get best() { + if (!this._best) { + this.setBest(); + } + return this._best; + } + + setBest(prefers = [], bans = []) { + if (!this.availables.length) { + return; + } + + for (const prefer of prefers) { + for (const player of this.availables) { + if (player.includes(prefer)) { + this._best = player; + return; + } + } + } + + for (let i = this.index; i < this.availables.length + this.index; i++) { + const candidate = this.availables[i % this.availables.length]; + if (bans.every(ban => !candidate.includes(ban))) { + this._best = candidate; + return; + } + } + + if (!this._best) { + console.warn(`WARNING: No suitable player found. Defaulting to ${this.availables[0]}`); + this._best = this.availables[0]; + } + } +} + +class Languages { + constructor(players, preferLanguages = []) { + this.players = players; + this.preferLanguages = preferLanguages; + + Object.keys(this.players).forEach(langId => { + if (!this.players[langId].availables.length) { + delete this.players[langId]; + } + }); + + if (Object.keys(this.players).length === 0) { + console.warn('WARNING: No player available'); + } + + this.availables = {}; + for (const langId in this.players) { + const lang = id2lang[langId]; + if (!this.availables[lang]) { + this.availables[lang] = []; + } + this.availables[lang].push(this.players[langId]); + } + } + + get best() { + for (const preferLanguage of this.preferLanguages) { + if (this.availables[preferLanguage]) { + for (const player of this.availables[preferLanguage]) { + if (player.availables.length) { + return player.best; + } + } + } + } + + for (const language in this.availables) { + for (const player of this.availables[language]) { + if (player.availables.length) { + console.warn(`WARNING: Language preference not respected. Defaulting to ${language}`); + return player.best; + } + } + } + + return null; + } + + setBest(...args) { + for (const langId in this.players) { + this.players[langId].setBest(...args); + } + } +} + +class Episode { + constructor(languages, serieName = "", seasonName = "", episodeName = "", index = 1) { + this.languages = languages; + this.serieName = serieName; + this.seasonName = seasonName; + this.episodeName = episodeName; + this._index = index; + + this.name = this.episodeName; + this.fancyName = this.name; + + for (const lang in this.languages.availables) { + this.fancyName += ` ${flags[lang]}`; + } + + this.index = this._index; + + const seasonNumberMatch = seasonName.match(/\d+/); + this.seasonNumber = seasonNumberMatch ? parseInt(seasonNumberMatch[0]) : 0; + + this.longName = `${this.seasonName} - ${this.episodeName}`; + this.shortName = `${this.serieName} S${this.seasonNumber.toString().padStart(2, '0')}E${this.index.toString().padStart(2, '0')}`; + } + + get index() { + return this._index; + } + + set index(value) { + this._index = value; + for (const langId in this.languages.players) { + this.languages.players[langId].index = this._index; + } + } + + toString() { + return this.fancyName; + } +} + +class Season { + constructor(url, name = "", serieName = "", client = null) { + const normalizedUrl = url.endsWith('/') ? url : url + '/'; + this.pages = langIds.map(lang => normalizedUrl + lang + "/"); + this.siteUrl = url.split('/').slice(0, 3).join('/') + '/'; + + this.name = name || url.split('/').slice(-2)[0]; + this.serieName = serieName || url.split('/').slice(-3)[0]; + + this.client = client || deps.axiosAnimeSama; + } + + async _getPlayersLinksFrom(page) { + try { + const episodesUrl = page + 'episodes.js'; + const episodesJsResponse = await deps.axiosAnimeSamaRequest({ + method: 'get', + url: episodesUrl, + timeout: 10000 + }); + + if (episodesJsResponse.status !== 200) { + return []; + } + + const episodesJs = episodesJsResponse.data; + + if (typeof episodesJs === 'string' && ( + episodesJs.includes('') || + episodesJs.includes('') || + episodesJs.includes(' { + const matches = player.match(/'(.+?)'/g); + if (!matches) return []; + + const allLinks = matches.map(link => { + let cleanLink = link.replace(/'/g, ''); + const proxyPrefix = 'https://proxy.liyao.space/------'; + if (cleanLink.startsWith(proxyPrefix)) { + cleanLink = cleanLink.substring(proxyPrefix.length); + } + return cleanLink; + }); + + const validLinks = allLinks.filter(isValidPlayerUrl); + return validLinks; + }); + + const result = zipVarlen(...playersListLinks); + return result; + } catch (error) { + if (!error.response || error.response.status !== 404) { + // Non-404 error + } + return []; + } + } + + async episodes(existingEpisodes = null) { + const episodesPagesPromises = this.pages.map(page => this._getPlayersLinksFrom(page)); + const episodesPages = await Promise.all(episodesPagesPromises); + const episodesInSeason = Math.max(...episodesPages.map(ep => ep.length)); + + const padding = episodesInSeason.toString().length; + const episodeNames = Array.from({ length: episodesInSeason }, (_, i) => + `Episode ${(i + 1).toString().padStart(padding, '0')}` + ); + + const episodeObjs = episodeNames.map((name, index) => { + const playersLinks = episodesPages.map(pages => pages[index] || []); + + const languages = new Languages( + Object.fromEntries( + langIds.map((langId, i) => [langId, new Players(playersLinks[i])]) + ) + ); + return new Episode(languages, this.serieName, this.name, name, index + 1); + }); + + if (!existingEpisodes) { + return episodeObjs.map(ep => ({ + name: ep.name, + serie_name: ep.serieName, + season_name: ep.seasonName, + index: ep.index, + streaming_links: Object.entries(ep.languages.players).map(([langId, players]) => ({ + language: langId, + players: (Array.isArray(players.availables) ? players.availables : []).filter(isValidPlayerUrl) + })).filter(link => link.players.length > 0) + })); + } + + return episodeObjs.map((ep, idx) => { + const oldEp = existingEpisodes[idx]; + if (!oldEp) { + return { + name: ep.name, + serie_name: ep.serieName, + season_name: ep.seasonName, + index: ep.index, + streaming_links: Object.entries(ep.languages.players).map(([langId, players]) => ({ + language: langId, + players: (Array.isArray(players.availables) ? players.availables : []).filter(isValidPlayerUrl) + })).filter(link => link.players.length > 0) + }; + } + const oldLinks = oldEp.streaming_links || []; + const newLinks = Object.entries(ep.languages.players).map(([langId, players]) => ({ + language: langId, + players: (Array.isArray(players.availables) ? players.availables : []).filter(isValidPlayerUrl) + })); + const mergedLinks = deps.mergeStreamingLinks(oldLinks, newLinks); + return { + name: ep.name, + serie_name: ep.serieName, + season_name: ep.seasonName, + index: ep.index, + streaming_links: mergedLinks.filter(link => link.players && link.players.length > 0) + }; + }); + } +} + +class Catalogue { + constructor(url, name = "", client = null, additionalData = null) { + if (url.startsWith('/')) { + this.url = deps.ANIME_SAMA_URL + url.substring(1); + } else if (url.startsWith('http')) { + try { + const urlObj = new URL(url); + let urlPath = urlObj.pathname; + if (urlPath.startsWith('/')) urlPath = urlPath.substring(1); + this.url = deps.ANIME_SAMA_URL + urlPath + urlObj.search; + } catch (e) { + console.error("Error parsing URL in Catalogue constructor:", url); + this.url = url; + } + } else { + this.url = url.endsWith('/') ? url : url + '/'; + } + this.name = name || url.split('/').slice(-2)[0]; + this.siteUrl = url.split('/').slice(0, 3).join('/') + '/'; + this.client = client || deps.axiosAnimeSama; + + if (additionalData) { + this.image = additionalData.image || ''; + this.alternative_names = additionalData.alternative_names || []; + this.alternative_names_string = additionalData.alternative_names_string || ''; + } else { + this.image = ''; + this.alternative_names = []; + this.alternative_names_string = ''; + } + } + + async seasons() { + try { + const response = await deps.axiosAnimeSamaRequest({ + method: 'get', + url: this.url + }); + const responseData = response.data; + + const seasonsMatches = responseData.match(/panneauAnime\("(.+?)", *"(.+?)(?:vostfr|vf)"\);/g) || []; + + const seasons = []; + for (const match of seasonsMatches) { + const [_, name, link] = match.match(/panneauAnime\("(.+?)", *"(.+?)(?:vostfr|vf)"\);/) || []; + + if (name && link) { + const urlParts = this.url.split('/'); + const animeNameFromUrl = urlParts[urlParts.length - 2] || urlParts[urlParts.length - 1]; + + let normalizedLink = link; + if (animeNameFromUrl && normalizedLink.startsWith(animeNameFromUrl)) { + normalizedLink = normalizedLink.substring(animeNameFromUrl.length); + } + + if (!normalizedLink.startsWith('/')) { + normalizedLink = '/' + normalizedLink; + } + + const baseUrl = this.url.endsWith('/') ? this.url.slice(0, -1) : this.url; + const seasonUrl = baseUrl + normalizedLink; + + seasons.push( + new Season( + seasonUrl, + name, + this.name, + this.client + ) + ); + } + } + + return seasons; + } catch (error) { + console.error(`Error getting seasons for ${this.name}:`, error.message); + return []; + } + } +} + +class AnimeSama { + constructor(siteUrl) { + this.siteUrl = siteUrl; + this.client = deps.axiosAnimeSama; + } + + async search(query, forceNoCache = false) { + try { + const cacheKey = generateCacheKey(query); + if (!forceNoCache) { + const cachedResults = await deps.getFromCacheNoExpiration(ANIME_SAMA_CACHE_DIR, cacheKey); + if (cachedResults) { + return cachedResults.map(result => + new Catalogue(result.url, result.name, this.client, result) + ); + } + } + + const requestUrl = `${this.siteUrl}template-php/defaut/fetch.php`; + const requestData = `query=${encodeURIComponent(query)}`; + console.log(`\n[AnimeSama Search] DEBUG INFO:`); + console.log(`[AnimeSama Search] Query: ${query}`); + console.log(`[AnimeSama Search] URL: ${requestUrl}`); + console.log(`[AnimeSama Search] Payload: ${requestData}`); + + const response = await deps.axiosAnimeSamaRequest({ + method: 'post', + url: requestUrl, + data: requestData, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + } + }); + + if (response.status !== 200) { + return []; + } + + const responseData = response.data; + const results = this.parseSearchResults(responseData); + + await deps.saveToCache(ANIME_SAMA_CACHE_DIR, cacheKey, results); + + return results.map(result => + new Catalogue(result.url, result.name, this.client, result) + ); + } catch (error) { + console.error(`\n[AnimeSama Search] ERROR FAIL:`); + console.error(`[AnimeSama Search] Query: ${query}`); + console.error(`[AnimeSama Search] Error Message: ${error.message}`); + if (error.response) { + console.error(`[AnimeSama Search] Status Code: ${error.response.status}`); + console.error(`[AnimeSama Search] Response Data:`, JSON.stringify(error.response.data, null, 2)); + } + if (error.config) { + console.error(`[AnimeSama Search] Request Config URL:`, error.config.url); + } + return []; + } + } + + parseSearchResults(htmlData) { + const results = []; + + try { + const $ = cheerio.load(htmlData); + + $('a').each((_, element) => { + const $link = $(element); + const href = $link.attr('href'); + + if (!href || !href.includes('/catalogue/')) { + return; + } + + // Only accept valid anime catalogue URLs: /catalogue/[slug]/ with at least 2 chars + const catalogueSlugMatch = href.match(/\/catalogue\/([a-zA-Z0-9][a-zA-Z0-9\-_.]+)/); + if (!catalogueSlugMatch) { + return; + } + + const $img = $link.find('img'); + const imageUrl = $img.attr('src') || ''; + + const $title = $link.find('h3'); + const mainTitle = $title.text().trim(); + + const $altNames = $link.find('p'); + const alternativeNames = $altNames.text().trim(); + + const altNamesArray = alternativeNames + ? alternativeNames.split(',').map(name => name.trim()).filter(name => name.length > 0) + : []; + + if (mainTitle && href) { + results.push({ + url: href, + name: mainTitle, + image: imageUrl, + alternative_names: altNamesArray, + alternative_names_string: alternativeNames + }); + } + }); + + if (results.length === 0) { + console.log('Cheerio parsing returned no results, falling back to regex parsing'); + return this.parseSearchResultsRegex(htmlData); + } + + console.log(`Parsed ${results.length} anime results with enhanced data`); + return results; + + } catch (error) { + console.error('Error parsing search results with cheerio:', error.message); + return this.parseSearchResultsRegex(htmlData); + } + } + + parseSearchResultsRegex(htmlData) { + try { + const links = (htmlData.match(/href="(.+?)"/g) || []).map(link => + link.replace(/href="|"/g, '') + ).filter(link => link.includes('/catalogue/')); + + const names = (htmlData.match(/>(.+?)<\/h3>/g) || []).map(name => + name.replace(/>(.*?)<\/h3>/g, '$1') + ); + + return links.map((link, index) => ({ + url: link, + name: names[index] || '', + image: '', + alternative_names: [], + alternative_names_string: '' + })).filter(result => result.name.length > 0); + } catch (error) { + console.error('Error in regex parsing fallback:', error.message); + return []; + } + } +} + +// Episode cache for Anime Sama +class EpisodeCache { + constructor(cacheDir = ANIME_SAMA_CACHE_DIR, ttl = 3600) { + this.cacheDir = cacheDir; + this.ttl = ttl * 1000; + } + + _getCachePath(serieName) { + const safeSerie = safeFilename(serieName); + return path.join(this.cacheDir, `${safeSerie}.json`); + } + + async getAnimeData(serieName) { + const cachePath = this._getCachePath(serieName); + + try { + const fileContent = await fsp.readFile(cachePath, 'utf-8'); + const data = deps.normalizeAnimeSamaUrls(JSON.parse(fileContent)); + + if (Date.now() - data.timestamp > this.ttl) { + return null; + } + + return data.seasons || {}; + } catch (error) { + if (error.code !== 'ENOENT') { + console.error('Error reading cache:', error); + } + return null; + } + } + + async getEpisodes(serieName, seasonName) { + const animeData = await this.getAnimeData(serieName); + if (!animeData) return null; + + const seasonData = animeData[seasonName]; + return seasonData ? seasonData.episodes : null; + } + + async saveAnimeData(serieName, seasonsData) { + const cachePath = this._getCachePath(serieName); + + const data = { + timestamp: Date.now(), + seasons: seasonsData + }; + + try { + await writeFileAtomic(cachePath, JSON.stringify(data), 'utf-8'); + await memoryCache.set(`anime:${serieName}`, data); + } catch (error) { + console.error('Error saving cache:', error); + } + } + + async saveEpisodes(serieName, seasonName, episodesData) { + let animeData = await this.getAnimeData(serieName) || {}; + + animeData[seasonName] = { + timestamp: Date.now(), + episodes: episodesData + }; + + await this.saveAnimeData(serieName, animeData); + } +} + +// ---- Routes ---- + +router.get('/search/:query', async (req, res) => { + try { + const { query } = req.params; + const cacheKey = generateCacheKey(query); + const animeCacheDir = ANIME_SAMA_CACHE_DIR; + let cachedResults = await deps.getFromCacheNoExpiration(animeCacheDir, cacheKey); + let dataReturned = false; + + if (!cachedResults || !Array.isArray(cachedResults) || cachedResults.length === 0) { + try { + const client = new AnimeSama(deps.ANIME_SAMA_URL); + const searchResults = await client.search(query, false); + const serializedResults = searchResults.map(cat => ({ + url: cat.url, + name: cat.name, + image: cat.image, + alternative_names: cat.alternative_names, + alternative_names_string: cat.alternative_names_string + })); + await deps.saveToCache(animeCacheDir, cacheKey, serializedResults); + cachedResults = serializedResults; + } catch (err) { + console.error('Erreur scraping Anime Sama:', err); + return res.status(500).json({ error: 'Erreur lors de la recherche Anime Sama' }); + } + } + + const allCacheFiles = await fsp.readdir(animeCacheDir).catch(() => []); + + const animesWithSeasons = await Promise.all(cachedResults.map(async (anime) => { + const safeAnimeName = anime.name.replace(/[^a-zA-Z0-9\s\-_]/g, '').trim(); + const animeFile = `${safeAnimeName}.json`; + + let saisons = []; + + if (allCacheFiles.includes(animeFile)) { + try { + const animeContent = await fsp.readFile(path.join(animeCacheDir, animeFile), 'utf-8'); + const animeCache = deps.normalizeAnimeSamaUrls(JSON.parse(animeContent)); + + if (animeCache.seasons) { + saisons = Object.entries(animeCache.seasons).map(([seasonName, seasonData]) => ({ + name: seasonName, + episodes: seasonData.episodes || [], + episodeCount: (seasonData.episodes || []).length, + cacheFile: animeFile, + timestamp: seasonData.timestamp || animeCache.timestamp || null + })); + } + } catch (e) { + console.error(`Error reading unified cache for ${anime.name}:`, e.message); + } + } else { + const seasonFiles = allCacheFiles.filter(f => f.startsWith(safeAnimeName + '_') && f !== cacheKey + '.json'); + + saisons = (await Promise.all(seasonFiles.map(async seasonFile => { + try { + const seasonContent = await fsp.readFile(path.join(animeCacheDir, seasonFile), 'utf-8'); + const seasonCache = deps.normalizeAnimeSamaUrls(JSON.parse(seasonContent)); + return { + name: seasonFile.replace(safeAnimeName + '_', '').replace('.json', ''), + episodes: seasonCache.episodes || [], + episodeCount: (seasonCache.episodes || []).length, + cacheFile: seasonFile, + timestamp: seasonCache.timestamp || null + }; + } catch (e) { + return null; + } + }))).filter(Boolean); + } + + const sortSeasons = (seasons) => { + return seasons; + }; + + return { + ...anime, + seasons: sortSeasons(saisons) + }; + })); + + // --- Filtering unwanted URLs before response --- + const unwantedUrls = [ + 'https://video.sibnet.ru/shell.php?videoid=', + 'https://vidmoly.to/embed-.html', + 'https://sendvid.com/embed/', + 'https://vk.com/video_ext.php?oid=&hd=3' + ]; + animesWithSeasons.forEach(anime => { + if (anime.seasons && Array.isArray(anime.seasons)) { + anime.seasons.forEach(season => { + if (season.episodes && Array.isArray(season.episodes)) { + season.episodes.forEach(ep => { + if (ep.streaming_links && Array.isArray(ep.streaming_links)) { + ep.streaming_links.forEach(linkObj => { + if (linkObj.players && Array.isArray(linkObj.players)) { + linkObj.players = linkObj.players.filter(url => !unwantedUrls.includes(url)); + } + }); + } + }); + season.episodes = season.episodes.filter(ep => + Array.isArray(ep.streaming_links) && + ep.streaming_links.some(linkObj => Array.isArray(linkObj.players) && linkObj.players.length > 0) + ); + season.episodeCount = season.episodes.length; + } + }); + + anime.seasons = anime.seasons.filter(season => + Array.isArray(season.episodes) && season.episodes.length > 0 + ); + } + }); + + res.json(animesWithSeasons); + dataReturned = true; + + // --- Background update --- + (async () => { + const client = new AnimeSama(deps.ANIME_SAMA_URL); + + for (const anime of animesWithSeasons) { + // Skip entries without valid catalogue URLs + if (!anime.url || !anime.url.includes('/catalogue/') || !anime.name) { + continue; + } + let catalogueObj = null; + try { + catalogueObj = new Catalogue(anime.url, anime.name, client.client, anime); + } catch (e) { + continue; + } + if (!catalogueObj) continue; + + let seasonsList = []; + try { + seasonsList = await catalogueObj.seasons(); + } catch (e) { + continue; + } + + const safeAnimeName = anime.name.replace(/[^a-zA-Z0-9\s\-_]/g, '').trim(); + const animeCacheFile = `${safeAnimeName}.json`; + const animeCachePath = path.join(animeCacheDir, animeCacheFile); + + let existingAnimeCache = {}; + try { + const animeContent = await fsp.readFile(animeCachePath, 'utf-8'); + const animeData = JSON.parse(animeContent); + existingAnimeCache = animeData.seasons || {}; + } catch (e) { + // No existing cache + } + + const RECENT_UPDATE_THRESHOLD = 1 * 60 * 60 * 1000; + let shouldSkipAnime = false; + try { + const stats = await fsp.stat(animeCachePath); + const timeSinceLastUpdate = Date.now() - stats.mtime.getTime(); + if (timeSinceLastUpdate < RECENT_UPDATE_THRESHOLD) { + shouldSkipAnime = true; + } + } catch (e) { + // File doesn't exist + } + + if (shouldSkipAnime) continue; + + let animeDataUpdated = false; + const updatedAnimeCache = { ...existingAnimeCache }; + + for (const seasonObj of seasonsList) { + const safeSeasonName = seasonObj.name.replace(/[^a-zA-Z0-9\s\-_]/g, '').trim(); + let cachedEpisodes = null; + let shouldUpdate = false; + + try { + const seasonCache = existingAnimeCache[seasonObj.name]; + if (seasonCache && seasonCache.episodes) { + cachedEpisodes = seasonCache.episodes; + + const scrapedEpisodes = await seasonObj.episodes(cachedEpisodes); + + const hasNewEpisodes = scrapedEpisodes.length > cachedEpisodes.length; + const hasNewLang = scrapedEpisodes.some((ep, idx) => { + const oldEp = cachedEpisodes[idx]; + if (!oldEp) return true; + const oldLangs = (oldEp.streaming_links || []).map(l => l.language); + const newLangs = (ep.streaming_links || []).map(l => l.language); + return newLangs.some(l => !oldLangs.includes(l)); + }); + + const hasNewPlayers = scrapedEpisodes.some((ep, idx) => { + const oldEp = cachedEpisodes[idx]; + if (!oldEp) return false; + + return (ep.streaming_links || []).some(newLink => { + const oldLink = (oldEp.streaming_links || []).find(ol => ol.language === newLink.language); + if (!oldLink) return false; + + const oldPlayers = Array.isArray(oldLink.players) ? oldLink.players : []; + const newPlayers = Array.isArray(newLink.players) ? newLink.players : []; + return newPlayers.length > oldPlayers.length || + newPlayers.some(player => !oldPlayers.includes(player)); + }); + }); + + if (hasNewEpisodes || hasNewLang || hasNewPlayers) { + shouldUpdate = true; + cachedEpisodes = scrapedEpisodes; + } + } else { + shouldUpdate = true; + cachedEpisodes = await seasonObj.episodes(); + } + } catch (e) { + shouldUpdate = true; + cachedEpisodes = await seasonObj.episodes(); + } + + if (shouldUpdate) { + try { + const unwantedUrlsForCache = [ + 'https://video.sibnet.ru/shell.php?videoid=', + 'https://vidmoly.to/embed-.html', + 'https://sendvid.com/embed/', + 'https://vk.com/video_ext.php?oid=&hd=3' + ]; + const episodesData = cachedEpisodes.map(episode => ({ + name: episode.name, + serie_name: episode.serie_name || episode.serieName, + season_name: episode.season_name || episode.seasonName, + index: episode.index, + streaming_links: (episode.streaming_links || []).map(linkObj => ({ + language: linkObj.language, + players: Array.isArray(linkObj.players) + ? linkObj.players.filter(url => !unwantedUrlsForCache.includes(url)) + : linkObj.players + })) + })); + + updatedAnimeCache[seasonObj.name] = { + timestamp: Date.now(), + episodes: episodesData + }; + animeDataUpdated = true; + + } catch (e) { + console.error(`Erreur lors du scraping de la saison ${seasonObj.name} (${anime.name}):`, e.message); + } + } + } + + if (animeDataUpdated) { + try { + const unifiedCacheData = { + timestamp: Date.now(), + seasons: updatedAnimeCache + }; + await writeFileAtomic(animeCachePath, JSON.stringify(unifiedCacheData), 'utf-8'); + + await deps.cleanupOldCacheFiles(safeAnimeName, animeCacheDir); + } catch (e) { + // ignore + } + } else if (Object.keys(existingAnimeCache).length === 0) { + await deps.migrateOldCacheFiles(safeAnimeName, animeCacheDir); + } + } + })(); + + } catch (error) { + console.error('Erreur /anime/search/:query:', error); + return res.status(500).json({ error: 'Erreur serveur' }); + } +}); + +// Delete anime cache +router.delete('/search/:query/cache', async (req, res) => { + try { + const { query } = req.params; + const cacheKey = generateCacheKey(query); + const animeCacheDir = ANIME_SAMA_CACHE_DIR; + + let deletedFiles = []; + let errors = []; + + // 1. Delete search cache file + try { + const searchCacheFile = path.join(animeCacheDir, `${cacheKey}.json`); + await fsp.unlink(searchCacheFile); + deletedFiles.push(`search cache: ${cacheKey}.json`); + } catch (err) { + if (err.code !== 'ENOENT') { + errors.push(`Erreur suppression cache de recherche: ${err.message}`); + } + } + + // 2. Delete unified anime cache + try { + const decodedQuery = decodeURIComponent(query); + const safeAnimeName = decodedQuery.replace(/[^a-zA-Z0-9\s\-_]/g, '').trim(); + const animeFile = path.join(animeCacheDir, `${safeAnimeName}.json`); + + try { + await fsp.unlink(animeFile); + deletedFiles.push(`unified cache: ${safeAnimeName}.json`); + } catch (err) { + if (err.code !== 'ENOENT') { + errors.push(`Erreur suppression cache unifie: ${err.message}`); + } + } + + // 3. Delete old separate cache files + const allCacheFiles = await fsp.readdir(animeCacheDir).catch(() => []); + const oldSeasonFiles = allCacheFiles.filter(f => + f.startsWith(safeAnimeName + '_') && f.endsWith('.json') + ); + + for (const oldFile of oldSeasonFiles) { + try { + await fsp.unlink(path.join(animeCacheDir, oldFile)); + deletedFiles.push(`old season cache: ${oldFile}`); + } catch (err) { + errors.push(`Erreur suppression ancien cache ${oldFile}: ${err.message}`); + } + } + } catch (err) { + errors.push(`Erreur lors de la recherche des fichiers: ${err.message}`); + } + + if (deletedFiles.length > 0) { + return res.status(200).json({ + success: true, + message: `Cache anime "${decodeURIComponent(query)}" supprime.`, + deletedFiles, + errors: errors.length > 0 ? errors : undefined + }); + } else { + return res.status(404).json({ + success: false, + error: 'Aucun cache trouve pour cet anime.', + errors: errors.length > 0 ? errors : undefined + }); + } + } catch (err) { + console.error('Erreur suppression cache anime:', err); + return res.status(500).json({ success: false, error: 'Erreur serveur.' }); + } +}); + +module.exports = router; +module.exports.configure = configure; diff --git a/API/Mainapi/routes/authRoutes.js b/API/Mainapi/routes/authRoutes.js new file mode 100644 index 0000000..5b1fa9b --- /dev/null +++ b/API/Mainapi/routes/authRoutes.js @@ -0,0 +1,730 @@ +/** + * Authentication routes. + * Extracted from server.js -- BIP39, Discord, and Google authentication. + * Mount point: app.use('/api/auth', router) + */ + +const express = require('express'); +const router = express.Router(); +const axios = require('axios'); +const crypto = require('crypto'); +const bip39 = require('bip39'); +const { v4: uuidv4 } = require('uuid'); +const rateLimit = require('express-rate-limit'); +const { ipKeyGenerator } = require('express-rate-limit'); + +const { issueJwt, getAuthIfValid } = require('../middleware/auth'); +const { getPool } = require('../mysqlPool'); +const { createRedisRateLimitStore } = require('../utils/redisRateLimitStore'); +const { verifyTurnstileFromRequest } = require('../utils/turnstile'); +const { + SUPPORTED_PROVIDERS, + isSupportedProvider, + getLinkedTarget, + getLinksForTarget, + setLink, + removeLinksForTargetProvider, +} = require('../utils/accountLinks'); + +// Rate limiter pour les endpoints d'authentification +// 10 tentatives par IP toutes les 15 minutes +const authRateLimit = rateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 10, // 10 requêtes max par fenêtre + store: createRedisRateLimitStore({ prefix: 'rate-limit:auth:login:' }), + passOnStoreError: true, + standardHeaders: true, // Retourne les headers RateLimit-* standard + legacyHeaders: false, // Désactive X-RateLimit-* + message: { + success: false, + error: 'Trop de tentatives de connexion. Réessayez dans 15 minutes.' + }, + keyGenerator: (req) => req.headers['cf-connecting-ip'] || req.headers['x-forwarded-for']?.split(',')[0].trim() || ipKeyGenerator(req.ip), + validate: { xForwardedForHeader: false, ip: false } +}); + +// Récupération de la liste de mots française +const frenchWordlist = bip39.wordlists.french; +const DEFAULT_AVATAR = 'https://as2.ftcdn.net/v2/jpg/05/89/93/27/1000_F_589932782_vQAEAZhHnq1QCGu5ikwrYaQD0Mmurm0N.webp'; + +// Lazy imports from sync module +let _syncModule = null; +function getSyncModule() { + if (!_syncModule) _syncModule = require('./sync'); + return _syncModule; +} + +// === Session helpers === +const generateDeviceFingerprint = (userAgent, ip) => { + const fingerprint = crypto.createHash('sha256') + .update(`${userAgent}-${ip || 'unknown'}-${Date.now()}`) + .digest('hex') + .substring(0, 32); + return fingerprint; +}; + +const encryptDeviceInfo = (deviceInfo) => { + const algorithm = 'aes-256-cbc'; + const salt = crypto.randomBytes(16); + const key = crypto.scryptSync(process.env.JWT_SECRET, salt, 32); + const iv = crypto.randomBytes(16); + const cipher = crypto.createCipheriv(algorithm, key, iv); + let encrypted = cipher.update(deviceInfo, 'utf8', 'base64'); + encrypted += cipher.final('base64'); + return `${salt.toString('base64')}.${iv.toString('base64')}.${encrypted}`; +}; + +const createUserSession = async (userType, userId, req) => { + try { + const pool = getPool(); + if (!pool) { console.error('MySQL pool not ready for session creation'); return null; } + + const userAgent = req.headers['user-agent'] || 'Unknown'; + const ip = req.ip || req.connection.remoteAddress || 'Unknown'; + const sessionId = uuidv4(); + const deviceInfo = generateDeviceFingerprint(userAgent, ip); + const encryptedDevice = encryptDeviceInfo(deviceInfo); + + await pool.execute( + 'INSERT INTO user_sessions (id, user_id, user_type, device, user_agent) VALUES (?, ?, ?, ?, ?)', + [sessionId, userId, userType, encryptedDevice, userAgent] + ); + + console.log(`[SESSION] Created new session ${sessionId} for ${userType}:${userId}`); + return sessionId; + } catch (error) { + console.error('Error creating user session:', error); + return null; + } +}; + +// === Helpers === + +function normalizeMnemonic(mnemonic) { + return mnemonic.normalize('NFKD').toLowerCase().trim().replace(/\s+/g, ' '); +} + +function validateBip39Mnemonic(mnemonic) { + return bip39.validateMnemonic(mnemonic, frenchWordlist) || bip39.validateMnemonic(mnemonic); +} + +function createBip39UserId(normalizedMnemonic) { + return crypto.createHash('sha256').update(normalizedMnemonic).digest('hex').substring(0, 16); +} + +function buildBip39Profile(userId, username, avatar, existingProfile = null) { + return { + id: userId, + username: (username || existingProfile?.username || `Utilisateur-${userId.substring(0, 8)}`).trim(), + avatar: avatar || existingProfile?.avatar || DEFAULT_AVATAR, + provider: 'bip39', + createdAt: existingProfile?.createdAt || new Date().toISOString(), + }; +} + +function buildDiscordProfile(user) { + return { + id: String(user.id), + username: user.username || `Discord-${user.id}`, + avatar: user.avatar + ? `https://cdn.discordapp.com/avatars/${user.id}/${user.avatar}.png` + : DEFAULT_AVATAR, + provider: 'discord', + createdAt: new Date().toISOString(), + }; +} + +function buildGoogleProfile(user) { + return { + id: String(user.sub), + username: user.name || user.email || `Google-${user.sub}`, + avatar: user.picture || DEFAULT_AVATAR, + provider: 'google', + createdAt: new Date().toISOString(), + }; +} + +function parseStoredAuth(userData) { + if (!userData?.auth || typeof userData.auth !== 'string') return null; + try { + const authData = JSON.parse(userData.auth); + if (authData && authData.userProfile) return authData; + } catch (error) { + console.error('Error parsing stored auth data:', error.message); + } + return null; +} + +async function ensureStoredAuthData(userType, userId, authData, extraFields = {}) { + const { readUserData, writeUserData } = getSyncModule(); + const userData = await readUserData(userType, userId) || {}; + let shouldWrite = false; + + if (!parseStoredAuth(userData)) { + userData.auth = JSON.stringify(authData); + shouldWrite = true; + } + + for (const [key, value] of Object.entries(extraFields)) { + if (userData[key] !== value) { + userData[key] = value; + shouldWrite = true; + } + } + + if (shouldWrite) { + userData.lastUpdated = Date.now(); + await writeUserData(userType, userId, userData); + } + + return userData; +} + +async function getResolvedAuthData(userType, userId, fallbackProfile, fallbackProvider) { + const { readUserData } = getSyncModule(); + const userData = await readUserData(userType, userId) || {}; + const storedAuth = parseStoredAuth(userData); + + if (storedAuth?.userProfile) { + return { + userData, + authData: { + ...storedAuth, + provider: storedAuth.provider || storedAuth.userProfile.provider || fallbackProvider, + } + }; + } + + return { + userData, + authData: { + userProfile: fallbackProfile, + provider: fallbackProvider, + } + }; +} + +function getProviderLabel(provider) { + if (provider === 'discord') return 'Discord'; + if (provider === 'google') return 'Google'; + if (provider === 'bip39') return 'BIP39'; + return 'ce moyen de connexion'; +} + +async function getAccountPrimaryProvider(userType, userId) { + const fallbackProvider = userType === 'bip39' ? 'bip39' : 'oauth'; + const { userData, authData } = await getResolvedAuthData( + userType, + userId, + { id: String(userId), provider: fallbackProvider }, + fallbackProvider + ); + + const providerCandidates = [ + authData?.userProfile?.provider, + authData?.provider, + userData?.oauth_provider, + ]; + + for (const candidate of providerCandidates) { + if (isSupportedProvider(candidate)) { + return candidate; + } + } + + return userType === 'bip39' ? 'bip39' : null; +} + +async function ensureLinkManagementAccess(auth) { + const accountProvider = await getAccountPrimaryProvider(auth.userType, auth.userId); + if (!accountProvider) { + return { + allowed: false, + status: 403, + error: 'Impossible de déterminer le provider principal de ce compte. Reconnectez-vous avec le compte d’origine.', + }; + } + + if (auth.authMethod !== accountProvider) { + return { + allowed: false, + status: 403, + error: `Reconnectez-vous avec ${getProviderLabel(accountProvider)} pour gérer les liaisons de ce compte.`, + }; + } + + return { allowed: true, accountProvider }; +} + +async function getOrCreateBip39Account({ mnemonic, username = null, avatar = null, overwriteProfile = false }) { + const normalizedMnemonic = normalizeMnemonic(mnemonic); + if (!validateBip39Mnemonic(normalizedMnemonic)) { + return { success: false, error: 'Phrase secrète invalide' }; + } + + const userId = createBip39UserId(normalizedMnemonic); + const { readUserData, writeUserData } = getSyncModule(); + const userData = await readUserData('bip39', userId) || {}; + const storedAuth = parseStoredAuth(userData); + const existingProfile = storedAuth?.userProfile || null; + + const shouldWriteProfile = overwriteProfile || !existingProfile; + const userProfile = buildBip39Profile(userId, username, avatar, existingProfile); + + if (shouldWriteProfile) { + userData.auth = JSON.stringify({ userProfile, provider: 'bip39' }); + userData.bip39_auth = 'true'; + userData.lastUpdated = Date.now(); + await writeUserData('bip39', userId, userData); + } + + return { success: true, normalizedMnemonic, userId, userProfile }; +} + +async function verifyDiscordAccessToken(accessToken) { + const resp = await axios.get('https://discord.com/api/users/@me', { + headers: { Authorization: `Bearer ${accessToken}` }, + timeout: 10000, + }); + + const user = resp.data; + if (!user || !user.id) { + throw new Error('Token Discord invalide'); + } + + return user; +} + +async function verifyGoogleAccessToken(accessToken) { + const resp = await axios.get('https://www.googleapis.com/oauth2/v3/userinfo', { + headers: { Authorization: `Bearer ${accessToken}` }, + timeout: 10000, + }); + + const user = resp.data; + if (!user || !user.sub) { + throw new Error('Token Google invalide'); + } + + return user; +} + +async function finalizeResolvedSession(req, { + provider, + providerUserId, + fallbackUserType, + sourceAuthData, + externalUser, +}) { + const sourceExtraFields = provider === 'bip39' + ? { bip39_auth: 'true' } + : { oauth_provider: provider }; + + await ensureStoredAuthData(fallbackUserType, providerUserId, sourceAuthData, sourceExtraFields); + + const linkedTarget = await getLinkedTarget(provider, providerUserId); + const resolvedUserType = linkedTarget?.targetUserType || fallbackUserType; + const resolvedUserId = linkedTarget?.targetUserId || String(providerUserId); + + const sessionId = await createUserSession(resolvedUserType, resolvedUserId, req); + const token = issueJwt(resolvedUserType, resolvedUserId, sessionId, provider); + + const fallbackResolvedProvider = resolvedUserType === 'bip39' + ? 'bip39' + : sourceAuthData?.provider || provider; + + const fallbackResolvedProfile = { + ...(sourceAuthData?.userProfile || {}), + id: resolvedUserId, + provider: fallbackResolvedProvider, + }; + + const { authData } = await getResolvedAuthData( + resolvedUserType, + resolvedUserId, + fallbackResolvedProfile, + fallbackResolvedProvider + ); + + return { + success: true, + sessionId, + token, + user: externalUser, + account: { + userType: resolvedUserType, + userId: resolvedUserId, + linked: Boolean(linkedTarget), + linkProvider: linkedTarget?.provider || null, + }, + authData, + }; +} + +async function resolveProviderIdentity(provider, body) { + switch (provider) { + case 'discord': { + const accessToken = body?.access_token; + if (!accessToken) { + return { success: false, status: 400, error: 'access_token requis' }; + } + const user = await verifyDiscordAccessToken(accessToken); + return { + success: true, + provider, + providerUserId: String(user.id), + authData: { userProfile: buildDiscordProfile(user), provider: 'discord' }, + externalUser: user, + }; + } + case 'google': { + const accessToken = body?.access_token; + if (!accessToken) { + return { success: false, status: 400, error: 'access_token requis' }; + } + const user = await verifyGoogleAccessToken(accessToken); + return { + success: true, + provider, + providerUserId: String(user.sub), + authData: { userProfile: buildGoogleProfile(user), provider: 'google' }, + externalUser: user, + }; + } + case 'bip39': { + const mnemonic = body?.mnemonic; + if (!mnemonic) { + return { success: false, status: 400, error: 'Phrase secrète requise' }; + } + const account = await getOrCreateBip39Account({ mnemonic }); + if (!account.success) { + return { success: false, status: 400, error: account.error }; + } + return { + success: true, + provider, + providerUserId: account.userId, + authData: { userProfile: account.userProfile, provider: 'bip39' }, + externalUser: { + id: account.userId, + username: account.userProfile.username, + avatar: account.userProfile.avatar, + }, + }; + } + default: + return { success: false, status: 400, error: 'Provider non supporté' }; + } +} + +function getProviderStatusMap(records) { + return SUPPORTED_PROVIDERS.reduce((acc, provider) => { + const record = records.find((item) => item.provider === provider) || null; + acc[provider] = record ? { + linked: true, + providerUserId: record.providerUserId, + linkedAt: record.linkedAt, + updatedAt: record.updatedAt, + } : { + linked: false, + providerUserId: null, + linkedAt: null, + updatedAt: null, + }; + return acc; + }, {}); +} + +// === Routes === + +// GET /bip39/generate +router.get('/bip39/generate', (req, res) => { + try { + const mnemonic = bip39.generateMnemonic(128, undefined, frenchWordlist); + res.status(200).json({ success: true, mnemonic }); + } catch (error) { + console.error('Error generating mnemonic:', error); + res.status(500).json({ success: false, error: 'Erreur lors de la génération de la phrase secrète' }); + } +}); + +// POST /bip39/create +router.post('/bip39/create', authRateLimit, async (req, res) => { + try { + const { mnemonic, username, avatar, turnstileToken } = req.body; + if (!mnemonic || !username) { + return res.status(400).json({ success: false, error: 'Phrase secrète et nom d\'utilisateur requis' }); + } + + const turnstileResult = await verifyTurnstileFromRequest(req, turnstileToken); + if (!turnstileResult.valid) { + return res.status(turnstileResult.status).json({ success: false, error: turnstileResult.error }); + } + + const account = await getOrCreateBip39Account({ + mnemonic, + username, + avatar, + overwriteProfile: true, + }); + + if (!account.success) { + return res.status(400).json({ success: false, error: account.error }); + } + + const payload = await finalizeResolvedSession(req, { + provider: 'bip39', + providerUserId: account.userId, + fallbackUserType: 'bip39', + sourceAuthData: { userProfile: account.userProfile, provider: 'bip39' }, + externalUser: { + id: account.userId, + username: account.userProfile.username, + avatar: account.userProfile.avatar, + }, + }); + + return res.status(200).json({ + ...payload, + userId: payload.account.userId, + userProfile: payload.authData.userProfile, + message: 'Compte créé avec succès', + }); + } catch (error) { + console.error('Error creating BIP39 account:', error); + res.status(500).json({ success: false, error: 'Erreur lors de la création du compte' }); + } +}); + +// POST /bip39/login +router.post('/bip39/login', authRateLimit, async (req, res) => { + try { + const { mnemonic, turnstileToken } = req.body; + if (!mnemonic) { + return res.status(400).json({ success: false, error: 'Phrase secrète requise' }); + } + + const turnstileResult = await verifyTurnstileFromRequest(req, turnstileToken); + if (!turnstileResult.valid) { + return res.status(turnstileResult.status).json({ success: false, error: turnstileResult.error }); + } + + const account = await getOrCreateBip39Account({ mnemonic }); + if (!account.success) { + return res.status(400).json({ success: false, error: account.error }); + } + + const payload = await finalizeResolvedSession(req, { + provider: 'bip39', + providerUserId: account.userId, + fallbackUserType: 'bip39', + sourceAuthData: { userProfile: account.userProfile, provider: 'bip39' }, + externalUser: { + id: account.userId, + username: account.userProfile.username, + avatar: account.userProfile.avatar, + }, + }); + + return res.status(200).json({ + ...payload, + userId: payload.account.userId, + userProfile: payload.authData.userProfile, + message: 'Connexion réussie', + }); + } catch (error) { + console.error('Error logging in with BIP39:', error); + res.status(500).json({ success: false, error: 'Erreur lors de la connexion' }); + } +}); + +// POST /discord/verify +router.post('/discord/verify', authRateLimit, async (req, res) => { + try { + const { access_token: accessToken } = req.body || {}; + if (!accessToken) { + return res.status(400).json({ success: false, error: 'access_token requis' }); + } + + const user = await verifyDiscordAccessToken(accessToken); + const payload = await finalizeResolvedSession(req, { + provider: 'discord', + providerUserId: String(user.id), + fallbackUserType: 'oauth', + sourceAuthData: { userProfile: buildDiscordProfile(user), provider: 'discord' }, + externalUser: user, + }); + + return res.status(200).json(payload); + } catch (error) { + console.error('Discord verify error:', error.response?.status || error.message); + return res.status(401).json({ success: false, error: 'Échec de la vérification Discord' }); + } +}); + +// POST /google/verify +router.post('/google/verify', authRateLimit, async (req, res) => { + try { + const { access_token: accessToken } = req.body || {}; + if (!accessToken) { + return res.status(400).json({ success: false, error: 'access_token requis' }); + } + + const user = await verifyGoogleAccessToken(accessToken); + const payload = await finalizeResolvedSession(req, { + provider: 'google', + providerUserId: String(user.sub), + fallbackUserType: 'oauth', + sourceAuthData: { userProfile: buildGoogleProfile(user), provider: 'google' }, + externalUser: user, + }); + + return res.status(200).json(payload); + } catch (error) { + console.error('Google verify error:', error.response?.status || error.message); + return res.status(401).json({ success: false, error: 'Échec de la vérification Google' }); + } +}); + +// GET /links +router.get('/links', async (req, res) => { + try { + const auth = await getAuthIfValid(req); + if (!auth || !['oauth', 'bip39'].includes(auth.userType)) { + return res.status(401).json({ success: false, error: 'Non autorisé' }); + } + + const records = await getLinksForTarget(auth.userType, auth.userId); + const fallbackProvider = auth.userType === 'bip39' ? 'bip39' : 'oauth'; + const { authData } = await getResolvedAuthData( + auth.userType, + auth.userId, + { id: String(auth.userId), provider: fallbackProvider }, + fallbackProvider + ); + const resolvedProviderCandidate = authData?.userProfile?.provider || authData?.provider; + const accountProvider = await getAccountPrimaryProvider(auth.userType, auth.userId) + || (isSupportedProvider(resolvedProviderCandidate) ? resolvedProviderCandidate : null) + || (auth.userType === 'bip39' ? 'bip39' : null); + + return res.status(200).json({ + success: true, + account: { + userType: auth.userType, + userId: auth.userId, + provider: accountProvider, + authMethod: isSupportedProvider(auth.authMethod) ? auth.authMethod : null, + canManageLinks: Boolean(accountProvider && auth.authMethod && auth.authMethod === accountProvider), + manageWithProvider: accountProvider, + }, + links: getProviderStatusMap(records), + }); + } catch (error) { + console.error('Error getting account links:', error); + return res.status(500).json({ success: false, error: 'Erreur lors de la récupération des liaisons' }); + } +}); + +// POST /links/:provider +router.post('/links/:provider', authRateLimit, async (req, res) => { + try { + const auth = await getAuthIfValid(req); + if (!auth || !['oauth', 'bip39'].includes(auth.userType)) { + return res.status(401).json({ success: false, error: 'Non autorisé' }); + } + + const accessCheck = await ensureLinkManagementAccess(auth); + if (!accessCheck.allowed) { + return res.status(accessCheck.status || 403).json({ success: false, error: accessCheck.error }); + } + + const provider = String(req.params.provider || '').toLowerCase(); + if (!isSupportedProvider(provider)) { + return res.status(400).json({ success: false, error: 'Provider non supporté' }); + } + + const resolved = await resolveProviderIdentity(provider, req.body); + if (!resolved.success) { + return res.status(resolved.status || 400).json({ success: false, error: resolved.error }); + } + + const isSelfLink = + ((provider === 'google' || provider === 'discord') && auth.userType === 'oauth' && String(auth.userId) === String(resolved.providerUserId)) || + (provider === 'bip39' && auth.userType === 'bip39' && String(auth.userId) === String(resolved.providerUserId)); + + if (isSelfLink) { + return res.status(400).json({ + success: false, + error: 'Ce moyen de connexion correspond déjà à ce compte.', + }); + } + + const extraFields = provider === 'bip39' + ? { bip39_auth: 'true' } + : { oauth_provider: provider }; + + await ensureStoredAuthData( + provider === 'bip39' ? 'bip39' : 'oauth', + resolved.providerUserId, + resolved.authData, + extraFields + ); + + const link = await setLink({ + provider, + providerUserId: resolved.providerUserId, + targetUserType: auth.userType, + targetUserId: auth.userId, + }); + + return res.status(200).json({ + success: true, + link: { + provider: link.provider, + providerUserId: link.providerUserId, + linkedAt: link.linkedAt, + updatedAt: link.updatedAt, + targetUserType: link.targetUserType, + targetUserId: link.targetUserId, + }, + message: 'Compte lié avec succès', + }); + } catch (error) { + console.error('Error linking account:', error); + return res.status(500).json({ success: false, error: 'Erreur lors de la liaison du compte' }); + } +}); + +// DELETE /links/:provider +router.delete('/links/:provider', async (req, res) => { + try { + const auth = await getAuthIfValid(req); + if (!auth || !['oauth', 'bip39'].includes(auth.userType)) { + return res.status(401).json({ success: false, error: 'Non autorisé' }); + } + + const accessCheck = await ensureLinkManagementAccess(auth); + if (!accessCheck.allowed) { + return res.status(accessCheck.status || 403).json({ success: false, error: accessCheck.error }); + } + + const provider = String(req.params.provider || '').toLowerCase(); + if (!isSupportedProvider(provider)) { + return res.status(400).json({ success: false, error: 'Provider non supporté' }); + } + + const removed = await removeLinksForTargetProvider(auth.userType, auth.userId, provider); + return res.status(200).json({ + success: true, + removed, + message: removed + ? 'Liaison supprimée avec succès' + : 'Aucune liaison active à supprimer', + }); + } catch (error) { + console.error('Error unlinking account:', error); + return res.status(500).json({ success: false, error: 'Erreur lors de la suppression de la liaison' }); + } +}); + +module.exports = router; diff --git a/API/Mainapi/routes/coflix.js b/API/Mainapi/routes/coflix.js new file mode 100644 index 0000000..1a10e62 --- /dev/null +++ b/API/Mainapi/routes/coflix.js @@ -0,0 +1,682 @@ +/** + * Coflix helper module. + * Extracted from server.js -- provides Coflix search and data extraction functions. + * + * This is NOT a router. It exports plain functions used by tmdb.js and others. + */ + +const cheerio = require('cheerio'); +const { Buffer } = require('buffer'); + +const { CACHE_DIR, generateCacheKey } = require('../utils/cacheManager'); + +// ---- Lazy-bound dependencies injected via configure() ---- +let deps = { + axiosCoflixRequest: async () => { throw new Error('coflix not configured'); }, + axiosLecteurVideoRequest: async () => { throw new Error('coflix not configured'); }, + makeCoflixRequest: async () => { throw new Error('coflix not configured'); }, + coflixHeaders: {}, + getFromCacheNoExpiration: async () => null, + saveToCache: async () => false, + formatCoflixError: (error) => (error && error.message ? error.message : String(error)) +}; + +function configure(injected) { + Object.assign(deps, injected); +} + +// ---- Functions ---- + +// Fonction pour normaliser les caracteres speciaux pour les requetes Coflix +function normalizeCoflixQuery(query) { + if (!query) return query; + + const replacements = { + '\u00e0': 'a', '\u00e1': 'a', '\u00e2': 'a', '\u00e3': 'a', '\u00e4': 'a', '\u00e5': 'a', + '\u00e8': 'e', '\u00e9': 'e', '\u00ea': 'e', '\u00eb': 'e', + '\u00ec': 'i', '\u00ed': 'i', '\u00ee': 'i', '\u00ef': 'i', + '\u00f2': 'o', '\u00f3': 'o', '\u00f4': 'o', '\u00f5': 'o', '\u00f6': 'o', + '\u00f9': 'u', '\u00fa': 'u', '\u00fb': 'u', '\u00fc': 'u', + '\u00fd': 'y', '\u00ff': 'y', + '\u00f1': 'n', + '\u00e7': 'c', + '\u0153': 'oe', '\u00e6': 'ae', + '\u00c0': 'A', '\u00c1': 'A', '\u00c2': 'A', '\u00c3': 'A', '\u00c4': 'A', '\u00c5': 'A', + '\u00c8': 'E', '\u00c9': 'E', '\u00ca': 'E', '\u00cb': 'E', + '\u00cc': 'I', '\u00cd': 'I', '\u00ce': 'I', '\u00cf': 'I', + '\u00d2': 'O', '\u00d3': 'O', '\u00d4': 'O', '\u00d5': 'O', '\u00d6': 'O', + '\u00d9': 'U', '\u00da': 'U', '\u00db': 'U', '\u00dc': 'U', + '\u00dd': 'Y', '\u0178': 'Y', + '\u00d1': 'N', + '\u00c7': 'C', + '\u0152': 'OE', '\u00c6': 'AE' + }; + + let normalized = query; + for (const [special, normal] of Object.entries(replacements)) { + normalized = normalized.split(special).join(normal); + } + + return normalized; +} + +// Fonction pour rechercher un contenu sur Coflix par titre +async function searchCoflixByTitle(title, mediaType, releaseYear) { + try { + const normalizedTitle = normalizeCoflixQuery(title); + + const response = await deps.axiosCoflixRequest({ method: 'get', url: `/suggest.php?query=${encodeURIComponent(normalizedTitle)}` }); + + if (!Array.isArray(response.data)) { + console.error(`La reponse de l'API Coflix n'est pas un tableau: ${deps.formatCoflixError(response.data)}`); + return []; + } + + const results = response.data.map(item => { + const similarity = calculateTitleSimilarity(title, item.title); + const resultYear = item.year ? parseInt(item.year) : null; + + return { + title: item.title, + url: item.url, + similarity: similarity, + year: resultYear, + id: item.ID, + excerpt: item.excerpt, + post_type: item.post_type, + rating: item.rating + }; + }); + + let coflixTypes = []; + + if (mediaType === 'movie') { + coflixTypes = ['movies']; + } else if (mediaType === 'tv') { + coflixTypes = ['series', 'animes', 'doramas']; + } else if (mediaType === 'anime') { + coflixTypes = ['animes']; + } else { + coflixTypes = ['movies', 'series', 'animes', 'doramas']; + } + + let filteredResults = mediaType + ? results.filter(item => coflixTypes.includes(item.post_type)) + : results; + + filteredResults.sort((a, b) => b.similarity - a.similarity); + + if (releaseYear) { + const yearMatchedResults = filteredResults.filter(r => r.year === releaseYear); + + if (mediaType === 'movie') { + if (yearMatchedResults.length > 0 && yearMatchedResults[0].similarity >= 0.80) { + filteredResults = [yearMatchedResults[0]]; + } else { + filteredResults = []; + } + } else if (mediaType === 'tv') { + if (yearMatchedResults.length > 0 && yearMatchedResults[0].similarity >= 0.70) { + filteredResults = [yearMatchedResults[0]]; + } else { + filteredResults = []; + } + } else { + if (yearMatchedResults.length > 0 && yearMatchedResults[0].similarity >= 0.80) { + filteredResults = [yearMatchedResults[0]]; + } else { + filteredResults = []; + } + } + } else { + if (filteredResults.length > 0 && filteredResults[0].similarity > 0.80) { + filteredResults = [filteredResults[0]]; + } else { + filteredResults = []; + } + } + + return filteredResults; + + } catch (error) { + console.error(`Erreur lors de la recherche sur Coflix pour ${title}: ${deps.formatCoflixError(error)}`); + throw error; + } +} + +// Fonction utilitaire pour calculer la similarite entre deux titres +function calculateTitleSimilarity(title1, title2) { + if (!title1 || !title2) return 0; + + const t1 = title1.toLowerCase(); + const t2 = title2.toLowerCase(); + + const normalize = (str) => str + .normalize("NFD") + .replace(/[\u0300-\u036f]/g, "") + .replace(/[\u00ae\u2122\u00a9]/g, "") + .replace(/[^\p{L}\p{N}\s]/gu, " ") + .replace(/\s+/g, " ") + .trim(); + const norm1 = normalize(t1); + const norm2 = normalize(t2); + + if (norm1 === norm2) { + return 1.0; + } + + const extractNumbers = (str) => { + const numbers = str.match(/\b\d+\b/g); + return numbers ? numbers.map(n => parseInt(n)) : []; + }; + + const numbers1 = extractNumbers(norm1); + const numbers2 = extractNumbers(norm2); + + if (numbers1.length > 0 || numbers2.length > 0) { + const hasCommonNumbers = numbers1.length > 0 && numbers2.length > 0 && + numbers1.some(n1 => numbers2.some(n2 => n1 === n2)); + + if (!hasCommonNumbers) { + return 0.2; + } + } + + const extractSubtitles = (str) => { + const parts = str.split(/[:|]/); + return parts.length > 1 ? parts[1].trim() : ""; + }; + + const subtitle1 = extractSubtitles(norm1); + const subtitle2 = extractSubtitles(norm2); + + if (subtitle1 && subtitle2 && subtitle1 !== subtitle2) { + const subtitleWords1 = subtitle1.split(/\s+/).filter(w => w.length > 2); + const subtitleWords2 = subtitle2.split(/\s+/).filter(w => w.length > 2); + const commonSubtitleWords = subtitleWords1.filter(w1 => + subtitleWords2.some(w2 => w1.includes(w2) || w2.includes(w1)) + ); + + if (commonSubtitleWords.length === 0) { + return 0.3; + } + } + + const locationKeywords = ['londres', 'paris', 'new york', 'tokyo', 'berlin', 'rome', 'madrid', 'barcelone']; + const hasLocation1 = locationKeywords.some(keyword => norm1.includes(keyword)); + const hasLocation2 = locationKeywords.some(keyword => norm2.includes(keyword)); + + if (hasLocation1 !== hasLocation2) { + return 0.25; + } + + // Short titles + if (norm1.length <= 10 || norm2.length <= 10) { + if (norm2.includes(norm1) || norm1.includes(norm2)) { + const shorter = norm1.length <= norm2.length ? norm1 : norm2; + const longer = norm1.length <= norm2.length ? norm2 : norm1; + const lengthRatio = shorter.length / longer.length; + + if (lengthRatio >= 0.8) { + return 0.85; + } else if (lengthRatio >= 0.6) { + return 0.7; + } else if (lengthRatio >= 0.4) { + return 0.5; + } + return 0.2; + } + } + + // Boost if searched title is a head token + if (norm2.startsWith(norm1 + " ") || norm1.startsWith(norm2 + " ")) { + return 0.9; + } + + if (norm2.includes(norm1) || norm1.includes(norm2)) { + if (norm1.length < norm2.length && norm2.includes(norm1)) { + const lengthRatio = norm1.length / norm2.length; + if (lengthRatio >= 0.6) { + return 0.8 * lengthRatio; + } else if (lengthRatio >= 0.4) { + return 0.6 * lengthRatio; + } + return 0.3; + } + else if (norm2.length < norm1.length && norm1.includes(norm2)) { + const lengthRatio = norm2.length / norm1.length; + if (lengthRatio >= 0.6) { + return 0.75 * lengthRatio; + } else if (lengthRatio >= 0.4) { + return 0.55 * lengthRatio; + } + return 0.3; + } + return 0.6; + } + + const filterShortWords = words => words.filter(w => w.length > 3); + const words1 = filterShortWords(norm1.split(/\s+/)); + const words2 = filterShortWords(norm2.split(/\s+/)); + + const finalWords1 = words1.length ? words1 : norm1.split(/\s+/); + const finalWords2 = words2.length ? words2 : norm2.split(/\s+/); + + let matches = 0; + let orderBonus = 0; + + finalWords1.forEach((word, index) => { + const matchIndex = finalWords2.findIndex(w => w.includes(word) || word.includes(w)); + if (matchIndex !== -1) { + matches++; + if (Math.abs(index - matchIndex) < 2) { + orderBonus += 0.1; + } + } + }); + + const baseScore = matches / Math.max(finalWords1.length, finalWords2.length, 1); + return Math.min(baseScore + orderBonus, 0.95); +} + +// Fonction pour filtrer les lecteurs lecteur1.xtremestream.xyz des donnees +function filterEmmmmbedReaders(data) { + if (!data) return data; + + function filterObject(obj) { + if (Array.isArray(obj)) { + return obj.map(item => filterObject(item)); + } else if (obj && typeof obj === 'object') { + const filtered = {}; + for (const [key, value] of Object.entries(obj)) { + if (key === 'player_links' && Array.isArray(value)) { + filtered[key] = value.filter(link => + !link.decoded_url || + !link.decoded_url.includes('lecteur1.xtremestream.xyz') + ); + } else { + filtered[key] = filterObject(value); + } + } + return filtered; + } + return obj; + } + + return filterObject(data); +} + +// Fonction pour extraire les donnees des films depuis Coflix +async function getMovieDataFromCoflix(url) { + let cachedData = null; + let hadCache = false; + try { + const cacheKey = generateCacheKey({ url: url, type: 'movie' }); + + cachedData = await deps.getFromCacheNoExpiration(CACHE_DIR.COFLIX, cacheKey); + hadCache = !!cachedData; + if (cachedData) { + // Ne pas utiliser le cache si player_links est vide — re-fetcher + if (!cachedData.player_links || cachedData.player_links.length === 0) { + console.log(`[COFLIX MOVIE] Cache ignoré (player_links vide) pour ${url} — re-fetch en cours`); + } else { + return cachedData; + } + } + + const relativePath = url.replace(/^https?:\/\/(?:www\.)?coflix\.[^/]+/i, ''); + const response = await deps.axiosCoflixRequest({ method: 'get', url: relativePath }); + const $ = cheerio.load(response.data); + + let iframe = $('main div div div article div:nth-child(2) div:nth-child(1) aside div div iframe'); + if (!iframe.length) { + iframe = $('article iframe'); + } + if (!iframe.length) { + iframe = $('iframe'); + } + + let iframeSrc = null; + let playerLinks = []; + + if (iframe.length > 0) { + iframeSrc = iframe.attr('src'); + + if (iframeSrc) { + try { + const iframePageResponse = await deps.axiosLecteurVideoRequest({ method: 'get', url: iframeSrc }); + const iframePage$ = cheerio.load(iframePageResponse.data); + + let playerItems = iframePage$('li[onclick*="showVideo"]'); + if (!playerItems.length) { + playerItems = iframePage$('div li[onclick]'); + } + + if (playerItems.length === 0) { + const bodyHtml = iframePage$('body').html() || ''; + console.warn(`[COFLIX MOVIE] ⚠️ Aucun playerItem — iframe: ${iframeSrc}, status: ${iframePageResponse.status}, taille: ${(iframePageResponse.data || '').length} chars, aperçu HTML: ${bodyHtml.substring(0, 500)}`); + } + + playerItems.each((i, element) => { + try { + const $element = iframePage$(element); + const onClickAttr = $element.attr('onclick') || ''; + + const base64Match = onClickAttr.match(/showVideo\(['"]([^'\"]+)['"]/); + + if (base64Match && base64Match[1]) { + const base64Url = base64Match[1]; + + let decodedUrl; + try { + decodedUrl = Buffer.from(base64Url, 'base64').toString('utf-8'); + } catch (decodeError) { + decodedUrl = null; + } + + const quality = $element.find('span').text().trim(); + + let language = 'Unknown'; + const info = $element.find('p').text().trim(); + if (info.toLowerCase().includes('french')) { + language = 'French'; + } else if (info.toLowerCase().includes('english')) { + language = 'English'; + } else if (info.toLowerCase().includes('vostfr')) { + language = 'VOSTFR'; + } + + playerLinks.push({ + decoded_url: decodedUrl, + quality: quality, + language: language + }); + } + } catch (playerError) { + const errorCode = playerError.response?.status || playerError.code || 'unknown'; + console.error(`[COFLIX MOVIE] ❌ Erreur extraction player: ${errorCode}`); + } + }); + } catch (iframePageError) { + const errorCode = iframePageError.response?.status || iframePageError.code || 'unknown'; + console.error(`[COFLIX MOVIE] ❌ Erreur requête iframe ${iframeSrc} — code: ${errorCode}, message: ${iframePageError.message}`); + } + } + } else { + console.log(`Aucun iframe trouve pour l'URL ${url}`); + } + + const result = { + iframe_src: iframeSrc && !iframeSrc.includes('coflix') ? iframeSrc : null, + player_links: playerLinks + }; + + await deps.saveToCache(CACHE_DIR.COFLIX, cacheKey, result); + + return result; + } catch (error) { + if (error && (error.isAxiosError || (error.response && error.response.status))) { + console.error(`Erreur lors de la recuperation des donnees du film Coflix: ${deps.formatCoflixError(error)}`); + if (hadCache) { + console.log(`[COFLIX] Cache preserve malgre l'erreur pour ${url}`); + return cachedData; + } + throw error; + } + console.error(`Erreur lors de la recuperation des donnees du film Coflix: ${deps.formatCoflixError(error)}`); + if (hadCache) { + console.log(`[COFLIX] Cache preserve malgre l'erreur pour ${url}`); + return cachedData; + } + return { iframe_src: null, player_links: [] }; + } +} + +// Nouvelle fonction pour recuperer les episodes via l'API Coflix +async function fetchCoflixSeriesEpisodes(postId, seasonNumber) { + try { + const response = await deps.axiosCoflixRequest({ method: 'get', url: `/wp-json/apiflix/v1/series/${postId}/${seasonNumber}` }); + if (response.data && Array.isArray(response.data.episodes)) { + return response.data; + } + return null; + } catch (error) { + console.error(`Erreur lors de la recuperation des episodes Coflix: ${deps.formatCoflixError(error)}`); + return null; + } +} + +// Fonction pour extraire les donnees des series depuis Coflix +async function getTvDataFromCoflix(url, seasonNumber, episodeNumber) { + let cachedData = null; + let hadCache = false; + try { + const cacheKey = generateCacheKey({ url: url, season: seasonNumber, episode: episodeNumber, type: 'tv' }); + + cachedData = await deps.getFromCacheNoExpiration(CACHE_DIR.COFLIX, cacheKey); + hadCache = !!cachedData; + if (cachedData) { + return cachedData; + } + + const relativePath = url.replace(/^https?:\/\/(?:www\.)?coflix\.[^/]+/i, ''); + const response = await deps.axiosCoflixRequest({ method: 'get', url: relativePath }); + const $ = cheerio.load(response.data); + + const seasonItems = $('article section div aside div ul li'); + + if (!seasonItems.length) { + console.log(`[ERROR] Aucune saison trouvee pour ${url}`); + + const altSelectors = [ + 'ul li', + '.seasons li', + '.season-list li', + '[data-season]', + 'input[data-season]' + ]; + + for (const selector of altSelectors) { + const altItems = $(selector); + if (altItems.length > 0) { + // found items with alternative selector + } + } + + return { + seasons: [], + current_episode: null + }; + } + + const seasons = []; + let targetSeason = null; + let postId = null; + + for (let i = 0; i < seasonItems.length; i++) { + const $seasonElement = $(seasonItems[i]); + const $label = $seasonElement.find('label'); + const $input = $label.find('input'); + + const sNumber = $input.attr('data-season'); + const seriesId = $input.attr('data-id'); + const currentPostId = $input.attr('post-id'); + const seasonName = $label.find('span').text().trim(); + + const season = { + season_number: parseInt(sNumber), + name: seasonName, + data_id: seriesId, + post_id: currentPostId, + episodes: [] + }; + + seasons.push(season); + + if (parseInt(sNumber) === seasonNumber) { + targetSeason = season; + postId = currentPostId; + } + } + + const slugMatch = url.match(/\/serie\/([^/]+)/); + const animeMatch = url.match(/\/animes\/([^/]+)/); + const seriesSlug = slugMatch ? slugMatch[1] : (animeMatch ? animeMatch[1] : ''); + + if (targetSeason && episodeNumber) { + let episodeApiData = null; + let episodeUrl = null; + + if (postId) { + const apiData = await fetchCoflixSeriesEpisodes(postId, seasonNumber); + if (apiData && apiData.episodes) { + const episode = apiData.episodes.find(ep => parseInt(ep.number) === parseInt(episodeNumber)); + if (episode && episode.links) { + episodeUrl = episode.links.startsWith('https://coflix.space') + ? `${episode.links}` + : episode.links; + } + } + } + + if (!episodeUrl) { + episodeUrl = `https://coflix.space/episode/${seriesSlug}-${seasonNumber}x${episodeNumber}/`; + } + + try { + const episodePageResponse = await deps.makeCoflixRequest(episodeUrl, { headers: deps.coflixHeaders, timeout: 15000 }); + const episodePage$ = cheerio.load(episodePageResponse.data); + + const episodeTitle = episodePage$('article header h1').text().trim(); + const episodePlayerLinks = []; + + let episodeIframe = episodePage$('main div div div article div iframe'); + if (!episodeIframe.length) { + episodeIframe = episodePage$('article iframe'); + } + if (!episodeIframe.length) { + episodeIframe = episodePage$('iframe'); + } + + let episodeIframeSrc = null; + + if (episodeIframe.length > 0) { + episodeIframeSrc = episodeIframe.attr('src'); + + if (episodeIframeSrc) { + try { + const iframePageResponse = await deps.axiosLecteurVideoRequest({ method: 'get', url: episodeIframeSrc }); + const iframePage$ = cheerio.load(iframePageResponse.data); + + let playerItems = iframePage$('li[onclick*="showVideo"]'); + if (!playerItems.length) { + playerItems = iframePage$('div li[onclick]'); + } + + if (playerItems.length === 0) { + const bodyHtml = iframePage$('body').html() || ''; + console.warn(`[COFLIX TV] ⚠️ Aucun playerItem — iframe: ${episodeIframeSrc}, status: ${iframePageResponse.status}, taille: ${(iframePageResponse.data || '').length} chars, aperçu HTML: ${bodyHtml.substring(0, 500)}`); + } + + playerItems.each((i, element) => { + try { + const $element = iframePage$(element); + const onClickAttr = $element.attr('onclick') || ''; + + const base64Match = onClickAttr.match(/showVideo\(['"]([^'\"]+)['"]/); + + if (base64Match && base64Match[1]) { + const base64Url = base64Match[1]; + + let decodedUrl; + try { + decodedUrl = Buffer.from(base64Url, 'base64').toString('utf-8'); + } catch (decodeError) { + decodedUrl = null; + } + + const quality = $element.find('span').text().trim(); + + let language = 'Unknown'; + const info = $element.find('p').text().trim(); + if (info.toLowerCase().includes('french')) { + language = 'French'; + } else if (info.toLowerCase().includes('english')) { + language = 'English'; + } else if (info.toLowerCase().includes('vostfr')) { + language = 'VOSTFR'; + } + + episodePlayerLinks.push({ + decoded_url: decodedUrl, + quality: quality, + language: language + }); + } + } catch (playerError) { + const errorCode = playerError.response?.status || playerError.code || 'unknown'; + console.error(`[COFLIX TV] ❌ Erreur extraction player: ${errorCode}`); + } + }); + } catch (iframePageError) { + const errorCode = iframePageError.response?.status || iframePageError.code || 'unknown'; + console.error(`[COFLIX TV] ❌ Erreur requête iframe ${episodeIframeSrc} — code: ${errorCode}, message: ${iframePageError.message}`); + } + } + } + + return { + seasons: seasons, + current_episode: { + season_number: seasonNumber, + episode_number: episodeNumber, + title: episodeTitle, + iframe_src: episodeIframeSrc && !episodeIframeSrc.includes('coflix') ? episodeIframeSrc : null, + player_links: episodePlayerLinks + } + }; + } catch (episodeError) { + console.error(`Erreur lors de la recuperation des donnees de l'episode: ${deps.formatCoflixError(episodeError)}`); + return { + seasons: seasons, + current_episode: null + }; + } + } + + const result = { + seasons: seasons, + current_episode: null + }; + + await deps.saveToCache(CACHE_DIR.COFLIX, cacheKey, result); + + return result; + } catch (error) { + if (error && (error.isAxiosError || (error.response && error.response.status))) { + console.error(`Erreur lors de la recuperation des donnees de la serie Coflix: ${deps.formatCoflixError(error)}`); + if (hadCache) { + console.log(`[COFLIX] Cache preserve malgre l'erreur pour ${url}`); + return cachedData; + } + throw error; + } + console.error(`Erreur lors de la recuperation des donnees de la serie Coflix: ${deps.formatCoflixError(error)}`); + if (hadCache) { + console.log(`[COFLIX] Cache preserve malgre l'erreur pour ${url}`); + return cachedData; + } + return { seasons: [], current_episode: null }; + } +} + +module.exports = { + configure, + normalizeCoflixQuery, + searchCoflixByTitle, + calculateTitleSimilarity, + filterEmmmmbedReaders, + getMovieDataFromCoflix, + fetchCoflixSeriesEpisodes, + getTvDataFromCoflix +}; diff --git a/API/Mainapi/routes/cpasmal.js b/API/Mainapi/routes/cpasmal.js new file mode 100644 index 0000000..800a6ff --- /dev/null +++ b/API/Mainapi/routes/cpasmal.js @@ -0,0 +1,820 @@ +/** + * Cpasmal route module. + * Extracted from server.js — handles Cpasmal search, link extraction, and caching. + * + * Mounted as: app.use('/api/cpasmal', require('./routes/cpasmal')); + * Route paths are relative to the mount point. + */ + +const express = require('express'); +const router = express.Router(); +const cheerio = require('cheerio'); +const fsp = require('fs').promises; +const path = require('path'); +const axios = require('axios'); + +const { CACHE_DIR, generateCacheKey } = require('../utils/cacheManager'); +const { memoryCache } = require('../config/redis'); +const { fetchTmdbDetails } = require('../utils/tmdbCache'); + +// ---- Lazy-bound dependencies injected via configure() ---- +let deps = { + CPASMAL_BASE_URL: '', + TMDB_API_URL: '', + TMDB_API_KEY: '', + axiosCpasmalRequest: async () => { throw new Error('cpasmal not configured'); }, + DARKINO_PROXIES: [], + getDarkinoHttpProxyAgent: () => null, + getFromCacheNoExpiration: async () => null, + shouldUpdateCache: async () => true +}; + +/** + * Crée une fonction de requête scopée qui utilise toujours le même proxy HTTP (DARKINO_PROXIES). + * Garantit que tout le scraping d'un même film/série passe par la même IP. + * Un proxy est obligatoire — si aucun n'est disponible, une erreur est levée. + */ +function _createScopedRequest() { + const proxies = deps.DARKINO_PROXIES; + if (!proxies || proxies.length === 0) { + throw new Error('Cpasmal: aucun proxy HTTP configuré (DARKINO_PROXIES vide)'); + } + const proxy = proxies[Math.floor(Math.random() * proxies.length)]; + const agents = deps.getDarkinoHttpProxyAgent(proxy); + if (!agents) { + throw new Error(`Cpasmal: impossible de créer l'agent proxy pour ${proxy.host}:${proxy.port}`); + } + agents._label = `${proxy.host}:${proxy.port}`; + return (config) => deps.axiosCpasmalRequest({ ...config, _cpasmalAgents: agents }); +} + +function configure(injected) { + Object.assign(deps, injected); +} + +// ---- Helper: log 403 errors ---- +function _log403(context, error) { + const status = error.response?.status; + if (status === 403) { + const proxy = error.cpasmalProxy || 'unknown'; + const url = error.cpasmalUrl || error.config?.url || ''; + console.log(`[Cpasmal] 403 Forbidden — ${context} | proxy=${proxy} | url=${url}`); + } +} + +// ---- Helper functions ---- + +function hasEmptyLinks(data) { + if (!data || !data.links) return true; + return data.links.vf.length === 0 && data.links.vostfr.length === 0; +} + +function sortCpasmalLinks(links) { + const priority = ['voe', 'uqload']; + return links.sort((a, b) => { + const indexA = priority.indexOf(a.server); + const indexB = priority.indexOf(b.server); + + if (indexA !== -1 && indexB !== -1) return indexA - indexB; + if (indexA !== -1) return -1; + if (indexB !== -1) return 1; + return 0; + }); +} + +// Helper to get TMDB details (cached via Redis) +async function getTmdbDetails(tmdbId, type) { + return fetchTmdbDetails(deps.TMDB_API_URL, deps.TMDB_API_KEY, tmdbId, type, 'fr-FR'); +} + +// Scores search results from a single search query and returns { bestMatch, bestScore } +function _scoreCpasmalResults($, items, title, year, type, normalize) { + let bestMatch = null; + let bestScore = -1; + + items.each((i, el) => { + const $el = $(el); + const link = $el.find('a.th-img').attr('href'); + const titleText = $el.find('.th-desc .th-capt').text().trim(); + const yearText = $el.find('.th-desc .th-year').text().trim(); + const isSerie = $el.find('.th-Serie').length > 0; + const isMovie = $el.find('.th-Film').length > 0; + + // Check type - strict filtering + if (type === 'movie' && !isMovie) return; + if (type === 'tv' && !isSerie) return; + + const normTitle = normalize(title); + // Retirer l'annee entre parentheses du titre (deja capturee dans yearText) + const cleanedTitleText = titleText.replace(/\s*\(\d{4}\)\s*/g, '').trim(); + const normTitleText = normalize(cleanedTitleText); + + // Calculate match score + let score = 0; + let titleMatchQuality = 'none'; + + // Exact title match (highest priority) - 100 points + if (normTitleText === normTitle) { + score += 100; + titleMatchQuality = 'exact'; + } + // Title starts with search term (good match) + else if (normTitleText.startsWith(normTitle + ' ')) { + const lengthRatio = normTitle.length / normTitleText.length; + if (lengthRatio >= 0.75) { + score += 50; + titleMatchQuality = 'strong'; + } else if (lengthRatio >= 0.60) { + score += 25; + titleMatchQuality = 'moderate'; + } else { + score += 5; + titleMatchQuality = 'weak'; + } + } + // Title ends with search term + else if (normTitleText.endsWith(' ' + normTitle)) { + const lengthRatio = normTitle.length / normTitleText.length; + if (lengthRatio >= 0.75) { + score += 50; + titleMatchQuality = 'strong'; + } else if (lengthRatio >= 0.60) { + score += 25; + titleMatchQuality = 'moderate'; + } else { + score += 5; + titleMatchQuality = 'weak'; + } + } + // Search term is contained but not at start/end + else if (normTitleText.includes(normTitle)) { + score += 5; + titleMatchQuality = 'weak'; + } + // Search term contains the result title + else if (normTitle.includes(normTitleText)) { + score += 3; + titleMatchQuality = 'weak'; + } + // No match at all - skip + else { + return; + } + + // Year matching bonus points + if (year && yearText) { + const yearDiff = Math.abs(parseInt(yearText) - parseInt(year)); + const isWeakTitle = (titleMatchQuality === 'weak'); + if (yearDiff === 0) { + score += isWeakTitle ? 10 : 50; + } else if (yearDiff === 1) { + score += isWeakTitle ? 5 : 20; + } else if (yearDiff > 5) { + // Forte penalite: empecher un exact title match avec mauvaise annee de battre + // un match partiel avec bonne annee (ex: "Magnum" 1980 vs "Magnum, P.I." 2018) + score -= 100; + } else { + score -= 30; + } + } + + if (score > bestScore && score > 0) { + bestScore = score; + bestMatch = link; + } + }); + + return { bestMatch, bestScore }; +} + +// Run a single cpasmal search query across multiple pages, return { bestMatch, bestScore } +async function _runCpasmalSearch(searchQuery, title, year, type, normalize, maxPages, requestFn) { + const doRequest = requestFn || deps.axiosCpasmalRequest; + let bestMatch = null; + let bestScore = -1; + let page = 1; + + while (page <= maxPages) { + try { + const searchUrl = `${deps.CPASMAL_BASE_URL}/index.php?do=search&subaction=search&search_start=${page}&full_search=0&story=${encodeURIComponent(searchQuery)}`; + const response = await doRequest({ method: 'get', url: searchUrl }); + const $ = cheerio.load(response.data); + + const items = $('div.thumb'); + if (items.length === 0) break; + + const result = _scoreCpasmalResults($, items, title, year, type, normalize); + if (result.bestScore > bestScore) { + bestScore = result.bestScore; + bestMatch = result.bestMatch; + } + + // Only stop early if we have title + year confirmed match + if (bestScore >= 140) break; + + page++; + } catch (error) { + _log403('search', error); + break; + } + } + + return { bestMatch, bestScore }; +} + +async function searchCpasmal(title, year, type, requestFn) { + const doRequest = requestFn || deps.axiosCpasmalRequest; + // Prepare search query: normalize spaces and keep colons + let searchQuery = title.replace(/\u00A0/g, ' ').replace(/\s+/g, ' ').trim(); + + // Normalize function for title comparison + const normalize = (str) => str.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[:\s\-.,!?'"()]+/g, ' ').replace(/\s+/g, ' ').trim(); + + // === Strategy 1: Search by title only (2 pages) === + let { bestMatch, bestScore } = await _runCpasmalSearch(searchQuery, title, year, type, normalize, 2, doRequest); + + // === Strategy 2: If no year-confirmed match, retry with "title year" === + if (bestScore < 140 && year) { + const searchQueryWithYear = `${searchQuery} ${year}`; + const result2 = await _runCpasmalSearch(searchQueryWithYear, title, year, type, normalize, 1, doRequest); + if (result2.bestScore > bestScore) { + bestScore = result2.bestScore; + bestMatch = result2.bestMatch; + } + } + + // === Strategy 3: If still no good match, try full_search=1 === + if (bestScore < 20) { + try { + const fullSearchUrl = `${deps.CPASMAL_BASE_URL}/index.php?do=search&subaction=search&search_start=1&full_search=1&story=${encodeURIComponent(searchQuery)}`; + const response = await doRequest({ method: 'get', url: fullSearchUrl }); + const $ = cheerio.load(response.data); + const items = $('div.thumb'); + if (items.length > 0) { + const result3 = _scoreCpasmalResults($, items, title, year, type, normalize); + if (result3.bestScore > bestScore) { + bestScore = result3.bestScore; + bestMatch = result3.bestMatch; + } + } + } catch (error) { + _log403('full_search', error); + } + } + + return bestScore >= 20 ? bestMatch : null; +} + +// Helper to extract links from a movie page +async function extractMovieLinks(url, requestFn) { + const doRequest = requestFn || deps.axiosCpasmalRequest; + if (process.env.DEBUG_CPASMAL) console.time(`[Cpasmal] ExtractMovieLinks ${url}`); + try { + const response = await doRequest({ method: 'get', url: url }); + const $ = cheerio.load(response.data); + const links = { vf: [], vostfr: [] }; + let cpasmalYear = null; + + // Extraire l'annee de sortie depuis la page cpasmal + $('article ul li').each((i, el) => { + const $el = $(el); + const infoLabel = $el.find('span.info').text().trim().toLowerCase(); + if (infoLabel.includes('date de sortie') || infoLabel.includes('ann\u00e9e') || infoLabel.includes('annee')) { + const infoValue = $el.find('span.infos').text().trim(); + const yearMatch = infoValue.match(/(\d{4})/); + if (yearMatch) { + cpasmalYear = yearMatch[1]; + } + } + }); + + // Si pas trouve, chercher avec d'autres selecteurs + if (!cpasmalYear) { + const infosList = $('div.content-info ul li, div.shortpost-info ul li, .fx-info ul li'); + infosList.each((i, el) => { + const text = $(el).text().toLowerCase(); + if (text.includes('date de sortie') || text.includes('ann\u00e9e') || text.includes('annee')) { + const yearMatch = text.match(/(\d{4})/); + if (yearMatch) { + cpasmalYear = yearMatch[1]; + } + } + }); + } + + const linkElements = $('.liens-c .lien'); + + // Collect all tasks first + const tasks = []; + + for (let i = 0; i < linkElements.length; i++) { + const el = linkElements[i]; + const onclick = $(el).attr('onclick'); + if (onclick && onclick.includes('getxfield')) { + const match = onclick.match(/getxfield\('([^']*)',\s*'([^']*)',\s*'([^']*)'\)/); + if (match) { + const [_, id, xfield, token] = match; + const isVostfr = xfield.includes('vostfr'); + const isVf = xfield.includes('vf'); + + const ajaxUrl = `${deps.CPASMAL_BASE_URL}/engine/ajax/getxfield.php?id=${id}&xfield=${xfield}&token=${token}`; + tasks.push({ ajaxUrl, xfield, isVostfr, isVf }); + } + } + } + + // Execute requests sequentially + for (const task of tasks) { + try { + const ajaxResponse = await doRequest({ method: 'get', url: task.ajaxUrl }); + const iframeMatch = ajaxResponse.data.match(/src="([^"]+)"/); + if (iframeMatch) { + const linkData = { server: task.xfield.split('_')[0], url: iframeMatch[1] }; + if (task.isVostfr) links.vostfr.push(linkData); + if (task.isVf) links.vf.push(linkData); + } + } catch (err) { + _log403('getxfield', err); + } + } + + links.vf = sortCpasmalLinks(links.vf); + links.vostfr = sortCpasmalLinks(links.vostfr); + if (process.env.DEBUG_CPASMAL) { + console.timeEnd(`[Cpasmal] ExtractMovieLinks ${url}`); + console.log(`[Cpasmal] Found ${links.vf.length} VF and ${links.vostfr.length} VOSTFR links`); + } + return { links, cpasmalYear }; + } catch (error) { + _log403('extractMovieLinks', error); + return { links: { vf: [], vostfr: [] }, cpasmalYear: null }; + } +} + +// Helper to extract links from a series episode +async function extractSeriesLinks(seriesUrl, seasonNumber, episodeNumber, requestFn) { + const doRequest = requestFn || deps.axiosCpasmalRequest; + if (process.env.DEBUG_CPASMAL) console.time(`[Cpasmal] ExtractSeriesLinks ${seriesUrl}`); + try { + const response = await doRequest({ method: 'get', url: seriesUrl }); + let $ = cheerio.load(response.data); + + // Find season link + let seasonUrl = null; + $('.th-seas').each((i, el) => { + const text = $(el).find('.th-count').text().trim(); + if (text.toLowerCase().includes(`saison ${seasonNumber}`)) { + seasonUrl = $(el).closest('a').attr('href'); + } + }); + + if (!seasonUrl) { + return { vf: [], vostfr: [] }; + } + + // Construct episode URL + const episodeUrl = `${seasonUrl.replace('.html', '')}/${episodeNumber}-episode.html`; + + // Fetch episode page + const epResponse = await doRequest({ method: 'get', url: episodeUrl }); + $ = cheerio.load(epResponse.data); + + const links = { vf: [], vostfr: [] }; + const linkElements = $('.liens-c .lien'); + + // Collect all tasks first + const tasks = []; + + for (let i = 0; i < linkElements.length; i++) { + const el = linkElements[i]; + const onclick = $(el).attr('onclick'); + if (onclick && onclick.includes('playEpisode')) { + const match = onclick.match(/playEpisode\(this,\s*'([^']*)',\s*'([^']*)'\)/); + if (match) { + const [_, id, xfield] = match; + const isVostfr = xfield.includes('vostfr'); + const isVf = xfield.includes('vf'); + + const ajaxUrl = `${deps.CPASMAL_BASE_URL}/engine/inc/serial/app/ajax/Season.php`; + const params = new URLSearchParams(); + params.append('id', id); + params.append('xfield', xfield); + params.append('action', 'playEpisode'); + + tasks.push({ ajaxUrl, data: params.toString(), xfield, isVostfr, isVf }); + } + } + } + + // Execute requests sequentially + for (const task of tasks) { + try { + const ajaxResponse = await doRequest({ + method: 'post', + url: task.ajaxUrl, + data: task.data, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-Requested-With': 'XMLHttpRequest' + } + }); + + const iframeMatch = ajaxResponse.data.match(/src="([^"]+)"/); + if (iframeMatch) { + const linkData = { server: task.xfield.split('_')[0], url: iframeMatch[1] }; + if (task.isVostfr) links.vostfr.push(linkData); + if (task.isVf) links.vf.push(linkData); + } + } catch (err) { + _log403('playEpisode', err); + } + } + + links.vf = sortCpasmalLinks(links.vf); + links.vostfr = sortCpasmalLinks(links.vostfr); + if (process.env.DEBUG_CPASMAL) { + console.timeEnd(`[Cpasmal] ExtractSeriesLinks ${seriesUrl}`); + console.log(`[Cpasmal] Found ${links.vf.length} VF and ${links.vostfr.length} VOSTFR links`); + } + return links; + + } catch (error) { + _log403('extractSeriesLinks', error); + return { vf: [], vostfr: [] }; + } +} + +// === DATA FETCHING FUNCTIONS === + +async function fetchCpasmalMovieData(tmdbId, throwOnError = true) { + const requestFn = _createScopedRequest(); + + const tmdbData = await getTmdbDetails(tmdbId, 'movie'); + if (!tmdbData) { + if (throwOnError) throw new Error('Movie not found on TMDB'); + return null; + } + + const title = tmdbData.title; + const tmdbYear = tmdbData.release_date ? tmdbData.release_date.split('-')[0] : null; + + const cpasmalUrl = await searchCpasmal(title, tmdbYear, 'movie', requestFn); + if (!cpasmalUrl) { + if (throwOnError) throw new Error('Movie not found on Cpasmal'); + return null; + } + let { links, cpasmalYear } = await extractMovieLinks(cpasmalUrl, requestFn); + let finalCpasmalUrl = cpasmalUrl; + + // Validation post-match: reject if year mismatch, retry with explicit year search + if (cpasmalYear && tmdbYear && cpasmalYear !== tmdbYear) { + // Retry: search specifically with "title year" + const normalize = (str) => str.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[:\s\-.,!?'"()]+/g, ' ').replace(/\s+/g, ' ').trim(); + const searchQueryWithYear = `${title.replace(/\u00A0/g, ' ').replace(/\s+/g, ' ').trim()} ${tmdbYear}`; + const retryResult = await _runCpasmalSearch(searchQueryWithYear, title, tmdbYear, 'movie', normalize, 2, requestFn); + + if (retryResult.bestMatch && retryResult.bestMatch !== cpasmalUrl) { + const retryExtract = await extractMovieLinks(retryResult.bestMatch, requestFn); + // Accept if year matches or if year is not available on the page + if (!retryExtract.cpasmalYear || retryExtract.cpasmalYear === tmdbYear) { + links = retryExtract.links; + cpasmalYear = retryExtract.cpasmalYear; + finalCpasmalUrl = retryResult.bestMatch; + } else { + if (throwOnError) throw new Error('Movie not found on Cpasmal (year mismatch)'); + return null; + } + } else { + if (throwOnError) throw new Error('Movie not found on Cpasmal (year mismatch)'); + return null; + } + } + + const year = cpasmalYear || tmdbYear; + return { title, year, cpasmalUrl: finalCpasmalUrl, links }; +} + +async function fetchCpasmalTvData(tmdbId, season, episode, throwOnError = true) { + const requestFn = _createScopedRequest(); + + const tmdbData = await getTmdbDetails(tmdbId, 'tv'); + if (!tmdbData) { + if (throwOnError) throw new Error('TV Show not found on TMDB'); + return null; + } + + const title = tmdbData.name; + const year = tmdbData.first_air_date ? tmdbData.first_air_date.split('-')[0] : null; + + const cpasmalUrl = await searchCpasmal(title, year, 'tv', requestFn); + if (!cpasmalUrl) { + if (throwOnError) throw new Error('TV Show not found on Cpasmal'); + return null; + } + + // Validation post-match: verifier l'annee sur la page de la serie + if (year) { + try { + const pageResponse = await requestFn({ method: 'get', url: cpasmalUrl }); + const $page = cheerio.load(pageResponse.data); + let cpasmalYear = null; + + $page('article ul li').each((i, el) => { + const $el = $page(el); + const infoLabel = $el.find('span.info').text().trim().toLowerCase(); + if (infoLabel.includes('date de sortie') || infoLabel.includes('ann\u00e9e') || infoLabel.includes('annee')) { + const infoValue = $el.find('span.infos').text().trim(); + const yearMatch = infoValue.match(/(\d{4})/); + if (yearMatch) cpasmalYear = yearMatch[1]; + } + }); + + if (!cpasmalYear) { + const infosList = $page('div.content-info ul li, div.shortpost-info ul li, .fx-info ul li'); + infosList.each((i, el) => { + const text = $page(el).text().toLowerCase(); + if (text.includes('date de sortie') || text.includes('ann\u00e9e') || text.includes('annee')) { + const ym = text.match(/(\d{4})/); + if (ym) cpasmalYear = ym[1]; + } + }); + } + + if (cpasmalYear && cpasmalYear !== year) { + console.log(`[CPASMAL TV] Annee non correspondante: TMDB=${year}, Cpasmal=${cpasmalYear} pour "${title}" (${cpasmalUrl})`); + // Retry avec "title year" + const normalize = (str) => str.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[:\s\-.,!?'"()]+/g, ' ').replace(/\s+/g, ' ').trim(); + const searchQueryWithYear = `${title.replace(/\u00A0/g, ' ').replace(/\s+/g, ' ').trim()} ${year}`; + const retryResult = await _runCpasmalSearch(searchQueryWithYear, title, year, 'tv', normalize, 2, requestFn); + + if (retryResult.bestMatch && retryResult.bestMatch !== cpasmalUrl) { + const links = await extractSeriesLinks(retryResult.bestMatch, season, episode, requestFn); + return { title, year, cpasmalUrl: retryResult.bestMatch, links }; + } else { + if (throwOnError) throw new Error('TV Show not found on Cpasmal (year mismatch)'); + return null; + } + } + } catch (error) { + if (error.message && error.message.includes('year mismatch')) throw error; + // Erreur de validation non bloquante — continuer normalement + console.log(`[CPASMAL TV] Erreur lors de la validation d'annee: ${error.message}`); + } + } + + const links = await extractSeriesLinks(cpasmalUrl, season, episode, requestFn); + return { title, year, cpasmalUrl, links }; +} + +// === CPASMAL REQUEST DEDUPLICATION === +const ongoingCpasmalRequests = new Map(); +const CPASMAL_REQUEST_TIMEOUT = 15000; +const CPASMAL_STALE_CLEANUP_MS = 10 * 60 * 1000; + +const getOrCreateCpasmalRequest = async (cacheKey, requestFunction) => { + if (ongoingCpasmalRequests.has(cacheKey)) { + const existing = ongoingCpasmalRequests.get(cacheKey); + let dedupTimer; + return Promise.race([ + existing.promise.finally(() => clearTimeout(dedupTimer)), + new Promise((_, reject) => { dedupTimer = setTimeout(() => reject(new Error('Cpasmal dedup timeout')), CPASMAL_REQUEST_TIMEOUT); }) + ]); + } + + const requestPromise = (async () => { + let timeoutTimer; + try { + const result = await Promise.race([ + requestFunction().finally(() => clearTimeout(timeoutTimer)), + new Promise((_, reject) => { + timeoutTimer = setTimeout(() => { + ongoingCpasmalRequests.delete(cacheKey); + reject(new Error('Cpasmal request timeout')); + }, CPASMAL_REQUEST_TIMEOUT); + }) + ]); + return result; + } finally { + clearTimeout(timeoutTimer); + ongoingCpasmalRequests.delete(cacheKey); + } + })(); + + ongoingCpasmalRequests.set(cacheKey, { promise: requestPromise, createdAt: Date.now() }); + return requestPromise; +}; + +// Nettoyage périodique des requêtes Cpasmal bloquées +setInterval(() => { + const now = Date.now(); + let cleaned = 0; + for (const [key, entry] of ongoingCpasmalRequests) { + if (entry.createdAt && (now - entry.createdAt > CPASMAL_STALE_CLEANUP_MS)) { + ongoingCpasmalRequests.delete(key); + cleaned++; + } + } + if (cleaned > 0) console.log(`[CPASMAL DEDUP] Nettoyage: ${cleaned} requêtes expirées supprimées`); +}, 5 * 60 * 1000).unref(); + +// === BACKGROUND UPDATE === + +const updateCpasmalCache = async (cacheKey, type, ...args) => { + try { + const shouldUpdate = await deps.shouldUpdateCache(CACHE_DIR.CPASMAL, cacheKey); + if (!shouldUpdate) { + return; + } + + // background update + const existingCache = await deps.getFromCacheNoExpiration(CACHE_DIR.CPASMAL, cacheKey); + + let newData; + if (type === 'movie') { + newData = await fetchCpasmalMovieData(args[0], false); + } else if (type === 'tv') { + newData = await fetchCpasmalTvData(args[0], args[1], args[2], false); + } + + if (newData) { + await fsp.writeFile(path.join(CACHE_DIR.CPASMAL, `${cacheKey}.json`), JSON.stringify(newData), 'utf-8'); + const memKey = `${CACHE_DIR.CPASMAL}:${cacheKey}`; + await memoryCache.set(memKey, newData); + + // Si les liens sont vides, antidater le fichier pour forcer un re-fetch au prochain appel + if (hasEmptyLinks(newData)) { + const cacheFilePath = path.join(CACHE_DIR.CPASMAL, `${cacheKey}.json`); + try { + const oldTime = new Date(Date.now() - 30 * 60 * 1000); + await fsp.utimes(cacheFilePath, oldTime, oldTime); + } catch (e) { /* ignore */ } + } + } else if (existingCache && !existingCache.notFound) { + // On a déjà un cache valide — ne PAS le remplacer par notFound (erreur 403, timeout, etc.) + // On touche juste le fichier pour repousser le prochain check + const cacheFilePath = path.join(CACHE_DIR.CPASMAL, `${cacheKey}.json`); + try { + const now = new Date(); + await fsp.utimes(cacheFilePath, now, now); + } catch (e) { /* ignore */ } + } else { + // Pas de cache existant ou cache déjà notFound → on met à jour le notFound + const notFoundData = { notFound: true, timestamp: Date.now() }; + await fsp.writeFile(path.join(CACHE_DIR.CPASMAL, `${cacheKey}.json`), JSON.stringify(notFoundData), 'utf-8'); + const memKey = `${CACHE_DIR.CPASMAL}:${cacheKey}`; + await memoryCache.set(memKey, notFoundData); + } + } catch (error) { + // silent + } +}; + +// ---- Routes ---- + +router.get('/movie/:tmdbid', async (req, res) => { + const { tmdbid } = req.params; + const cacheKey = generateCacheKey(`movie_${tmdbid}`); + + if (process.env.DEBUG_CPASMAL) { + const used = process.memoryUsage().heapUsed / 1024 / 1024; + console.log(`[Cpasmal API] Start /movie/${tmdbid} - Memory: ${Math.round(used * 100) / 100} MB`); + console.time(`[Cpasmal API] Total /movie/${tmdbid}`); + } + + try { + // 1. Try cache + const cachedData = await deps.getFromCacheNoExpiration(CACHE_DIR.CPASMAL, cacheKey); + if (cachedData) { + const cacheFilePath = path.join(CACHE_DIR.CPASMAL, `${cacheKey}.json`); + + if (cachedData.notFound) { + res.status(404).json({ error: 'Movie not found on Cpasmal (Cached)' }); + } else { + // Calculer la prochaine mise à jour + let prochaineMiseAJour = null; + try { + const stats = await fsp.stat(cacheFilePath); + const nextUpdateTime = stats.mtime.getTime() + 40 * 60 * 1000; + if (nextUpdateTime <= Date.now()) { + prochaineMiseAJour = 'immédiate'; + } else { + prochaineMiseAJour = new Date(nextUpdateTime).toISOString(); + } + } catch (e) { /* ignore */ } + res.json({ ...cachedData, prochaineMiseAJour }); + } + + // Background update if old OR if links are empty + try { + const stats = await fsp.stat(cacheFilePath); + const age = Date.now() - stats.mtime.getTime(); + if (age > 20 * 60 * 1000 || hasEmptyLinks(cachedData)) { + updateCpasmalCache(cacheKey, 'movie', tmdbid); + } + } catch (e) { /* ignore */ } + return; + } + + // 2. Fetch fresh with deduplication + const data = await getOrCreateCpasmalRequest(cacheKey, () => fetchCpasmalMovieData(tmdbid, false)); + + if (!data) { + const notFoundData = { notFound: true, tmdbId: tmdbid, timestamp: Date.now() }; + await fsp.writeFile(path.join(CACHE_DIR.CPASMAL, `${cacheKey}.json`), JSON.stringify(notFoundData), 'utf-8'); + return res.status(404).json({ error: 'Movie not found on Cpasmal' }); + } + + await fsp.writeFile(path.join(CACHE_DIR.CPASMAL, `${cacheKey}.json`), JSON.stringify(data), 'utf-8'); + await memoryCache.set(`${CACHE_DIR.CPASMAL}:${cacheKey}`, data); + const prochaineMiseAJour = new Date(Date.now() + 40 * 60 * 1000).toISOString(); + res.json({ ...data, prochaineMiseAJour }); + if (process.env.DEBUG_CPASMAL) console.timeEnd(`[Cpasmal API] Total /movie/${tmdbid}`); + + } catch (error) { + if (error.message && error.message.includes('not found')) { + return res.status(404).json({ error: error.message }); + } + res.status(500).json({ error: 'Internal Server Error' }); + } +}); + +// Route pour supprimer le cache d'un film cpasmal +router.get('/movie/:tmdbid/clear-cache', async (req, res) => { + const { tmdbid } = req.params; + const cacheKey = generateCacheKey(`movie_${tmdbid}`); + const cacheFilePath = path.join(CACHE_DIR.CPASMAL, `${cacheKey}.json`); + + try { + await fsp.unlink(cacheFilePath); + res.json({ success: true, message: `Cache cleared for movie ${tmdbid}` }); + } catch (error) { + if (error.code === 'ENOENT') { + res.status(404).json({ error: `No cache found for movie ${tmdbid}` }); + } else { + res.status(500).json({ error: 'Failed to clear cache' }); + } + } +}); + +router.get('/tv/:tmdbid/:season/:episode', async (req, res) => { + const { tmdbid, season, episode } = req.params; + const cacheKey = generateCacheKey(`tv_${tmdbid}_s${season}_e${episode}`); + + try { + // 1. Try cache + const cachedData = await deps.getFromCacheNoExpiration(CACHE_DIR.CPASMAL, cacheKey); + if (cachedData) { + const cacheFilePath = path.join(CACHE_DIR.CPASMAL, `${cacheKey}.json`); + + if (cachedData.notFound) { + res.status(404).json({ error: 'TV Show not found on Cpasmal (Cached)' }); + } else { + // Calculer la prochaine mise à jour + let prochaineMiseAJour = null; + try { + const stats = await fsp.stat(cacheFilePath); + const nextUpdateTime = stats.mtime.getTime() + 40 * 60 * 1000; + if (nextUpdateTime <= Date.now()) { + prochaineMiseAJour = 'immédiate'; + } else { + prochaineMiseAJour = new Date(nextUpdateTime).toISOString(); + } + } catch (e) { /* ignore */ } + res.json({ ...cachedData, prochaineMiseAJour }); + } + + // Background update if old OR if links are empty + try { + const stats = await fsp.stat(cacheFilePath); + const age = Date.now() - stats.mtime.getTime(); + if (age > 20 * 60 * 1000 || hasEmptyLinks(cachedData)) { + updateCpasmalCache(cacheKey, 'tv', tmdbid, season, episode); + } + } catch (e) { /* ignore */ } + return; + } + + // 2. Fetch fresh with deduplication + const data = await getOrCreateCpasmalRequest(cacheKey, () => fetchCpasmalTvData(tmdbid, season, episode, false)); + + if (!data) { + const notFoundData = { notFound: true, tmdbId: tmdbid, season, episode, timestamp: Date.now() }; + await fsp.writeFile(path.join(CACHE_DIR.CPASMAL, `${cacheKey}.json`), JSON.stringify(notFoundData), 'utf-8'); + return res.status(404).json({ error: 'TV Show not found on Cpasmal' }); + } + + await fsp.writeFile(path.join(CACHE_DIR.CPASMAL, `${cacheKey}.json`), JSON.stringify(data), 'utf-8'); + await memoryCache.set(`${CACHE_DIR.CPASMAL}:${cacheKey}`, data); + const prochaineMiseAJour = new Date(Date.now() + 40 * 60 * 1000).toISOString(); + res.json({ ...data, prochaineMiseAJour }); + + } catch (error) { + if (error.message && error.message.includes('not found')) { + return res.status(404).json({ error: error.message }); + } + res.status(500).json({ error: 'Internal Server Error' }); + } +}); + +module.exports = router; +module.exports.configure = configure; diff --git a/API/Mainapi/routes/darkiworld.js b/API/Mainapi/routes/darkiworld.js new file mode 100644 index 0000000..bc44c20 --- /dev/null +++ b/API/Mainapi/routes/darkiworld.js @@ -0,0 +1,834 @@ +/** + * DarkiWorld routes module. + * Extracted from server.js -- handles DarkiWorld download links, decoding, + * seasons and episodes retrieval. + * + * Mounted at /api/darkiworld (paths below are relative to that prefix). + */ + +const express = require('express'); +const router = express.Router(); +const path = require('path'); +const fsp = require('fs').promises; +const { generateCacheKey } = require('../utils/cacheManager'); +const { getAuthIfValid } = require('../middleware/auth'); + +// --------------------------------------------------------------------------- +// Dependencies injected via configure() +// --------------------------------------------------------------------------- +let DARKINO_MAINTENANCE; +let DOWNLOAD_CACHE_DIR; +let darkiHeaders; +let axiosDarkinoRequest; +let getFromCacheNoExpiration; +let saveToCache; +let shouldUpdateCache; +let shouldUpdateCache24h; +let refreshDarkinoSessionIfNeeded; + +/** + * Inject runtime dependencies that still live in server.js. + */ +function configure(deps) { + if (deps.DARKINO_MAINTENANCE !== undefined) DARKINO_MAINTENANCE = deps.DARKINO_MAINTENANCE; + if (deps.DOWNLOAD_CACHE_DIR) DOWNLOAD_CACHE_DIR = deps.DOWNLOAD_CACHE_DIR; + if (deps.darkiHeaders) darkiHeaders = deps.darkiHeaders; + if (deps.axiosDarkinoRequest) axiosDarkinoRequest = deps.axiosDarkinoRequest; + if (deps.getFromCacheNoExpiration) getFromCacheNoExpiration = deps.getFromCacheNoExpiration; + if (deps.saveToCache) saveToCache = deps.saveToCache; + if (deps.shouldUpdateCache) shouldUpdateCache = deps.shouldUpdateCache; + if (deps.shouldUpdateCache24h) shouldUpdateCache24h = deps.shouldUpdateCache24h; + if (deps.refreshDarkinoSessionIfNeeded) refreshDarkinoSessionIfNeeded = deps.refreshDarkinoSessionIfNeeded; +} + +function parsePositiveInt(value, fallback) { + const parsed = Number.parseInt(value, 10); + return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback; +} + +async function fetchLegacySeasonsPage(titleId, page, perPage) { + const response = await axiosDarkinoRequest({ + method: 'get', + url: `/api/v1/titles/${titleId}/seasons?perPage=${perPage}&query=&page=${page}` + }); + + return { + success: true, + mode: 'legacy', + ...response.data + }; +} + +async function fetchSeasonPageForCount(titleId, seasonNumbers = []) { + const attemptedSeasonNumbers = new Set(); + + for (const rawSeasonNumber of seasonNumbers) { + const seasonNumber = parsePositiveInt(rawSeasonNumber, null); + if (!seasonNumber || attemptedSeasonNumbers.has(seasonNumber)) { + continue; + } + + attemptedSeasonNumbers.add(seasonNumber); + + try { + const response = await axiosDarkinoRequest({ + method: 'get', + url: `/api/v1/titles/${titleId}/seasons/${seasonNumber}?loader=seasonPage` + }); + + const seasonsCount = parsePositiveInt(response.data?.title?.seasons_count, 0); + if (seasonsCount > 0) { + return { + seasonsCount, + data: response.data + }; + } + } catch (error) { + const status = error.response?.status; + if (status !== 404 && status !== 422) { + console.warn(`[DARKIWORLD][SEASONS] seasonPage indisponible pour titleId=${titleId}, season=${seasonNumber}: ${error.message}`); + } + } + } + + return null; +} + +function buildSyntheticSeasonsResponse(titleId, page, perPage, seasonPagePayload) { + const currentPage = parsePositiveInt(page, 1); + const itemsPerPage = parsePositiveInt(perPage, 8); + const seasonsCount = parsePositiveInt(seasonPagePayload?.title?.seasons_count, 0); + const selectedSeason = seasonPagePayload?.season || null; + const selectedSeasonNumber = parsePositiveInt(selectedSeason?.number, 0); + const lastPage = seasonsCount > 0 ? Math.ceil(seasonsCount / itemsPerPage) : 1; + const safePage = Math.min(currentPage, lastPage); + const startIndex = seasonsCount > 0 ? (safePage - 1) * itemsPerPage : 0; + + const allSeasons = Array.from({ length: seasonsCount }, (_, index) => { + const seasonNumber = index + 1; + const isSelectedSeason = selectedSeasonNumber === seasonNumber; + + return { + id: isSelectedSeason && selectedSeason?.id ? selectedSeason.id : seasonNumber, + poster: isSelectedSeason ? (selectedSeason?.poster || '') : '', + release_date: isSelectedSeason + ? (selectedSeason?.release_date || seasonPagePayload?.title?.release_date || '') + : '', + number: seasonNumber, + title_id: isSelectedSeason && selectedSeason?.title_id + ? selectedSeason.title_id + : parsePositiveInt(titleId, 0), + episodes_count: isSelectedSeason + ? parsePositiveInt(selectedSeason?.episodes_count ?? selectedSeason?.episode_count, 0) + : 0, + model_type: isSelectedSeason ? (selectedSeason?.model_type || 'season') : 'season', + first_episode: isSelectedSeason ? (selectedSeason?.first_episode || null) : null + }; + }); + + const data = allSeasons.slice(startIndex, startIndex + itemsPerPage); + const from = data.length > 0 ? startIndex + 1 : 0; + const to = data.length > 0 ? startIndex + data.length : 0; + + return { + success: true, + mode: 'seasonPage', + title: seasonPagePayload?.title || null, + loader: seasonPagePayload?.loader || 'seasonPage', + pagination: { + current_page: safePage, + data, + from, + last_page: lastPage, + next_page: safePage < lastPage ? safePage + 1 : null, + per_page: itemsPerPage, + prev_page: safePage > 1 ? safePage - 1 : null, + to, + total: seasonsCount + } + }; +} + +async function fetchSeasonsCountResponse(titleId, page, perPage) { + let seasonPageResult = await fetchSeasonPageForCount(titleId, [1]); + + if (!seasonPageResult) { + try { + const legacyBootstrap = await fetchLegacySeasonsPage(titleId, 1, 1); + const firstLegacySeasonNumber = legacyBootstrap?.pagination?.data?.[0]?.number; + seasonPageResult = await fetchSeasonPageForCount(titleId, [firstLegacySeasonNumber]); + } catch (error) { + const status = error.response?.status; + if (status !== 404 && status !== 422) { + console.warn(`[DARKIWORLD][SEASONS] fallback legacy indisponible pour titleId=${titleId}: ${error.message}`); + } + } + } + + if (!seasonPageResult) { + return null; + } + + return buildSyntheticSeasonsResponse(titleId, page, perPage, seasonPageResult.data); +} + +// --------------------------------------------------------------------------- +// findAllEntriesForEpisode -- paginate DarkiWorld API to find all entries +// --------------------------------------------------------------------------- +async function findAllEntriesForEpisode({ titleId, seasonId, episodeId, perPage = 100, maxPages = 10 }) { + // Rafraîchir les cookies avant de commencer la pagination + try { + await refreshDarkinoSessionIfNeeded(); + } catch (e) { + console.warn('Erreur lors du rafraîchissement des cookies Darkino:', e.message); + } + + let page = 1; + let foundEntries = []; + let shouldContinue = true; + + while (shouldContinue && page <= maxPages) { + const url = `/api/v1/liens?perPage=${perPage}&page=${page}&title_id=${titleId}&loader=linksdl&season=${seasonId}&filters=&paginate=preferLengthAware`; + try { + const resp = await axiosDarkinoRequest({ + method: 'get', + url: url, + headers: darkiHeaders + }); + + const data = resp.data?.pagination?.data || []; + + // Chercher toutes les entrées correspondant à l'épisode ET les liens de saison complète + const matching = data.filter(entry => + entry.host && + ( + // Liens d'épisode spécifique + (entry.episode_id == episodeId || entry.episode == episodeId || entry.episode_number == episodeId) || + // Liens de saison complète (full_saison = 1) + entry.full_saison == 1 + ) + ); + + if (matching.length > 0) { + foundEntries = [...foundEntries, ...matching]; + } + + // Pagination intelligente + const nextPage = resp.data?.pagination?.next_page; + if (!nextPage) { + shouldContinue = false; + } else { + page = nextPage; + } + } catch (error) { + const status = error.response?.status; + if (status !== 404 && status !== 422) { + console.error(`[ENHANCEMENT] Erreur lors de la recherche des liens (page ${page}, url: ${url}):`, error.message); + } + shouldContinue = false; + } + } + + return foundEntries; +} + +// --------------------------------------------------------------------------- +// GET /download/:type/:id +// Récupérer tous les liens d'amélioration DarkiWorld pour un film ou un épisode +// Params: type (movie/tv), id (TMDB ID) +// Query: season (optionnel pour les séries), episode (optionnel pour les séries) +// --------------------------------------------------------------------------- +router.get('/download/:type/:id', async (req, res) => { + try { + const { type, id } = req.params; + const { season, episode } = req.query; + + // Validation + if (!['movie', 'tv'].includes(type)) { + return res.status(400).json({ + success: false, + error: 'Type invalide. Utilisez "movie" ou "tv"' + }); + } + + if (type === 'tv' && (!season || !episode)) { + return res.status(400).json({ + success: false, + error: 'Pour les séries, les paramètres season et episode sont requis' + }); + } + + // Generate cache key + const cacheKey = generateCacheKey(`darkiworld_download_${type}_${id}${type === 'tv' ? `_${season}_${episode}` : ''}`); + + // Check if results are in cache without expiration (stale-while-revalidate) + const cachedData = await getFromCacheNoExpiration(DOWNLOAD_CACHE_DIR, cacheKey); + let dataReturned = false; + + if (cachedData) { + // console.log(`Résultats de téléchargement pour ${type}/${id} récupérés du cache`); + res.status(200).json(cachedData); // Return cached data immediately + dataReturned = true; + } + + // Vérifier si l'utilisateur a accès premium (optionnel) + const auth = await getAuthIfValid(req); + const darkiworld_premium = auth && auth.userType === 'premium'; + + let allEnhancementLinks = []; + + if (type === 'movie') { + // Pour les films + try { + // 1. Récupérer tous les liens pour le film (pas seulement darkibox) + const liensResp = await axiosDarkinoRequest({ + method: 'get', + url: `/api/v1/liens?perPage=100&title_id=${id}&loader=linksdl&season=1&filters=&paginate=preferLengthAware` + }); + + const allEntries = liensResp.data?.pagination?.data || []; + + // Traiter directement les entrées sans faire de requête de décodage + const enhancementSources = allEntries.map(entry => { + if (!entry) return null; + + const hostInfo = entry.host; + let embedUrl = null; + let provider = hostInfo?.name || 'unknown'; + + // Traitement spécial pour darkibox + if (provider === 'darkibox') { + // Pour darkibox, construire l'URL d'embed avec l'ID + embedUrl = `https://darkibox.com/embed-${entry.id}.html`; + } else { + // Pour les autres providers, utiliser le lien direct s'il existe + embedUrl = entry.lien || `https://darkibox.com/embed-${entry.id}.html`; + } + + return { + id: entry.id, + language: (entry?.langues_compact && entry.langues_compact.length > 0) + ? entry.langues_compact.map(l => l.name).join(', ') + : undefined, + quality: entry?.qual?.qual, + sub: (entry?.subs_compact && entry.subs_compact.length > 0) + ? entry.subs_compact.map(s => s.name).join(', ') + : undefined, + provider: provider, + host_id: hostInfo?.id_host, + host_name: hostInfo?.name, + size: entry?.taille, + upload_date: entry?.created_at, + host_icon: hostInfo?.icon, + view: entry?.view + }; + }); + + allEnhancementLinks = enhancementSources.filter(Boolean); + } catch (err) { + const status = err.response?.status; + if (status !== 404 && status !== 422) { + console.error(`[ENHANCEMENT] Erreur lors de la récupération des liens pour le film (id: ${id}, url: /api/v1/liens?perPage=100&title_id=${id}&loader=linksdl&season=1):`, err.message); + } + } + + } else { + // Pour les séries (épisodes) + try { + // 1. Paginer intelligemment pour trouver l'épisode + const allEntries = await findAllEntriesForEpisode({ + titleId: id, + seasonId: parseInt(season), + episodeId: parseInt(episode), + perPage: 100, + maxPages: 10 + }); + + // Traiter directement les entrées sans faire de requête de décodage + const enhancementSources = allEntries.map(entry => { + if (!entry) return null; + + const hostInfo = entry.host; + let embedUrl = null; + let provider = hostInfo?.name || 'unknown'; + + // Traitement spécial pour darkibox + if (provider === 'darkibox') { + // Pour darkibox, construire l'URL d'embed avec l'ID + embedUrl = `https://darkibox.com/embed-${entry.id}.html`; + } else { + // Pour les autres providers, utiliser le lien direct s'il existe + embedUrl = entry.lien || `https://darkibox.com/embed-${entry.id}.html`; + } + + return { + id: entry.id, + language: (entry?.langues_compact && entry.langues_compact.length > 0) + ? entry.langues_compact.map(l => l.name).join(', ') + : undefined, + quality: entry?.qual?.qual, + sub: (entry?.subs_compact && entry.subs_compact.length > 0) + ? entry.subs_compact.map(s => s.name).join(', ') + : undefined, + provider: provider, + host_id: hostInfo?.id_host, + host_name: hostInfo?.name, + size: entry?.taille, + upload_date: entry?.created_at, + episode_id: entry?.episode_id, + episode_number: entry?.episode_number, + host_icon: hostInfo?.icon, + view: entry?.view, + saison: entry?.saison, + episode: entry?.episode, + full_saison: entry?.full_saison + }; + }); + + allEnhancementLinks = enhancementSources.filter(Boolean); + } catch (err) { + const status = err.response?.status; + if (status !== 404 && status !== 422) { + console.error(`[ENHANCEMENT] Erreur lors de la récupération des liens pour l'épisode (id: ${id}, season: ${season}, episode: ${episode}):`, err.message); + } + } + } + + const responseData = { + success: true, + all: allEnhancementLinks + }; + + // Si on n'a pas encore retourné de données, retourner maintenant + if (!dataReturned) { + res.json(responseData); + } + + // Background update du cache + (async () => { + try { + // Vérifier si le cache doit être mis à jour + const shouldUpdate = await shouldUpdateCache(DOWNLOAD_CACHE_DIR, cacheKey); + if (!shouldUpdate) { + return; // Ne pas mettre à jour le cache + } + + // Si on a des données, sauvegarder dans le cache + if (allEnhancementLinks && allEnhancementLinks.length > 0) { + await saveToCache(DOWNLOAD_CACHE_DIR, cacheKey, responseData); + } + } catch (cacheError) { + // Silent fail on cache save + } + })(); + + } catch (error) { + console.error('❌ Error fetching DarkiWorld enhancement links:', error); + + // Si Darkino retourne 500, ne pas créer/mettre à jour le cache et renvoyer le cache existant si présent + if (error.response && error.response.status >= 500) { + try { + const fallbackCache = await getFromCacheNoExpiration(DOWNLOAD_CACHE_DIR, cacheKey); + if (fallbackCache) { + return res.status(200).json(fallbackCache); + } + } catch (_) { } + } + + if (!res.headersSent) { + res.status(500).json({ + success: false, + error: 'Erreur lors de la récupération des liens d\'amélioration DarkiWorld', + message: error.message + }); + } + } +}); + +// --------------------------------------------------------------------------- +// GET /decode/:id +// Extraire le lien décodé (m3u8) pour un ID de lien DarkiWorld +// Params: id (ID du lien DarkiWorld) +// --------------------------------------------------------------------------- +router.get('/decode/:id', async (req, res) => { + try { + const { id } = req.params; + + if (!id) { + return res.status(400).json({ + success: false, + error: 'ID du lien requis' + }); + } + + // Generate cache key + const cacheKey = generateCacheKey(`darkiworld_decode_${id}`); + + // Check if results are in cache without expiration (stale-while-revalidate) + const cachedData = await getFromCacheNoExpiration(DOWNLOAD_CACHE_DIR, cacheKey); + let dataReturned = false; + let shouldDoBackgroundUpdate = false; + + if (cachedData) { + // Vérifier si le lien en cache est un lien d'embed invalide + const embedUrl = cachedData.embed_url || ''; + const isInvalidEmbedLink = /\/embed-\d+\.html$/i.test(embedUrl); + + if (isInvalidEmbedLink) { + // Le cache contient un lien d'embed invalide, réessayer d'obtenir le bon lien + console.warn(`[DECODE] Cache contient un lien d'embed invalide pour ${id}: ${embedUrl}`); + // Ne pas retourner le cache, continuer pour refetch + } else { + // Cache valide, le retourner immédiatement + res.status(200).json(cachedData); + dataReturned = true; + + // Vérifier si on doit faire un background update (fichier modifié il y a plus de 24h) + shouldDoBackgroundUpdate = await shouldUpdateCache24h(DOWNLOAD_CACHE_DIR, cacheKey); + + // Si pas besoin de background update, on s'arrête là + if (!shouldDoBackgroundUpdate) { + return; + } + // Sinon on continue pour faire le fetch en arrière-plan + } + } + + + + // Si pas de cache valide + // Si en maintenance + if (DARKINO_MAINTENANCE) { + if (!dataReturned) { + return res.status(200).json({ error: 'Service Darkino temporairement indisponible (maintenance)' }); + } + return; // Si on a déjà retourné des données, on arrête juste le traitement (pas de background update) + } + + // Fonction pour récupérer les données fraîches + const fetchFreshData = async () => { + let linkInfo = null; + let embedUrl = null; + let provider = 'unknown'; + let retryCount = 0; + const maxRetries = 2; + + while (retryCount < maxRetries) { + try { + const linkResp = await axiosDarkinoRequest({ + method: 'post', + url: `/api/v1/liens/${id}/download`, + data: { token: '' } + }); + + linkInfo = linkResp.data; + provider = linkInfo?.host?.name || 'unknown'; + + if (provider === 'darkibox') { + const rawDarkiboxLink = typeof linkInfo?.lien === 'string' ? linkInfo.lien : ''; + const darkiboxCodeMatch = rawDarkiboxLink.match(/darkibox\.com\/(?:embed-)?([a-z0-9]{12,})(?:\.html)?/i); + const darkiboxCode = darkiboxCodeMatch ? darkiboxCodeMatch[1] : null; + embedUrl = darkiboxCode + ? `https://darkibox.com/embed-${darkiboxCode}.html` + : (rawDarkiboxLink || `https://darkibox.com/embed-${id}.html`); + } else { + embedUrl = linkInfo?.lien || `https://darkibox.com/embed-${id}.html`; + } + + const isInvalidEmbedLink = /\/embed-\d+\.html$/i.test(embedUrl); + + if (isInvalidEmbedLink && retryCount < maxRetries - 1) { + retryCount++; + await new Promise(resolve => setTimeout(resolve, 1000)); + continue; + } else if (isInvalidEmbedLink) { + throw new Error('Lien d\'embed invalide'); + } + + break; + } catch (err) { + console.error(`[DARKIWORLD DECODE] Attempt ${retryCount + 1} failed for id=${id}:`, err.message); + if (retryCount < maxRetries - 1) { + retryCount++; + await new Promise(resolve => setTimeout(resolve, 1000)); + continue; + } + throw err; + } + } + + return { + success: true, + id: id, + provider: provider, + embed_url: embedUrl, + metadata: linkInfo ? { + language: (linkInfo?.langues_compact && linkInfo.langues_compact.length > 0) + ? linkInfo.langues_compact.map(l => l.name).join(', ') + : undefined, + quality: linkInfo?.qual?.qual, + sub: (linkInfo?.subs_compact && linkInfo.subs_compact.length > 0) + ? linkInfo.subs_compact.map(s => s.name).join(', ') + : undefined, + size: linkInfo?.size, + upload_date: linkInfo?.created_at + } : null + }; + }; + + // Si on fait un background update (données déjà retournées au client) + if (dataReturned && shouldDoBackgroundUpdate) { + // Background update du cache + (async () => { + try { + const freshData = await fetchFreshData(); + if (freshData && freshData.embed_url) { + await saveToCache(DOWNLOAD_CACHE_DIR, cacheKey, freshData); + } + } catch (bgError) { + // Silent fail on background update + } + })(); + return; + } + + // Si on n'a pas encore retourné de données, faire le fetch normal + try { + const responseData = await fetchFreshData(); + + // Retourner les données + res.json(responseData); + + // Mise à jour du cache + if (responseData.embed_url) { + try { + await saveToCache(DOWNLOAD_CACHE_DIR, cacheKey, responseData); + } catch (cacheError) { + // Silent fail on cache save + } + } + } catch (fetchError) { + console.error(`[DARKIWORLD DECODE] Erreur fetch pour id=${id}:`, fetchError.message); + return res.status(404).json({ + success: false, + error: 'Lien non trouvé ou inaccessible', + id: id, + debug: fetchError.message + }); + } + + } catch (error) { + if (res.headersSent) { + console.error('❌ Error decoding DarkiWorld link (headers already sent):', error.message); + return; + } + console.error('❌ Error decoding DarkiWorld link:', error); + + // Si Darkino retourne 500, ne pas créer/mettre à jour le cache et renvoyer le cache existant si présent + if (error.response && error.response.status >= 500) { + try { + const fallbackCache = await getFromCacheNoExpiration(DOWNLOAD_CACHE_DIR, cacheKey); + if (fallbackCache) { + return res.status(200).json(fallbackCache); + } + } catch (_) { } + } + + if (!res.headersSent) { + res.status(500).json({ + success: false, + error: 'Erreur lors du décodage du lien DarkiWorld', + message: error.message + }); + } + } +}); + +// --------------------------------------------------------------------------- +// GET /seasons/:titleId +// Récupérer les saisons d'une série depuis DarkiWorld +// Params: titleId (ID DarkiWorld de la série) +// Query: page (optionnel, défaut: 1), perPage (optionnel, défaut: 8) +// --------------------------------------------------------------------------- +router.get('/seasons/:titleId', async (req, res) => { + let cacheKey; + let dataReturned = false; + try { + const { titleId } = req.params; + const { page = 1, perPage = 8, mode = 'auto' } = req.query; + + if (!titleId) { + return res.status(400).json({ + success: false, + error: 'ID de la série requis' + }); + } + + const currentPage = parsePositiveInt(page, 1); + const itemsPerPage = parsePositiveInt(perPage, 8); + const normalizedMode = mode === 'legacy' ? 'legacy' : mode === 'seasonPage' ? 'seasonPage' : 'auto'; + + // Nouvelle clé de cache pour éviter de ressortir l'ancien format paginé. + cacheKey = generateCacheKey(`darkiworld_seasons_v2_${normalizedMode}_${titleId}_${currentPage}_${itemsPerPage}`); + + // Check if results are in cache without expiration (stale-while-revalidate) + const cachedData = await getFromCacheNoExpiration(DOWNLOAD_CACHE_DIR, cacheKey); + + if (cachedData) { + // console.log(`Saisons pour ${titleId} récupérées du cache`); + res.status(200).json(cachedData); // Return cached data immediately + dataReturned = true; + } + + // Récupérer les saisons depuis DarkiWorld + let responseData = null; + + if (normalizedMode !== 'legacy') { + responseData = await fetchSeasonsCountResponse(titleId, currentPage, itemsPerPage); + } + + if (!responseData) { + responseData = await fetchLegacySeasonsPage(titleId, currentPage, itemsPerPage); + } + + // Si on n'a pas encore retourné de données, retourner maintenant + if (!dataReturned) { + res.json(responseData); + } + + // Background update du cache + (async () => { + try { + // Vérifier si le cache doit être mis à jour + const shouldUpdate = await shouldUpdateCache(DOWNLOAD_CACHE_DIR, cacheKey); + if (!shouldUpdate) { + return; // Ne pas mettre à jour le cache + } + + // Si on a des données, sauvegarder dans le cache + if (responseData && responseData.pagination) { + await saveToCache(DOWNLOAD_CACHE_DIR, cacheKey, responseData); + } + } catch (cacheError) { + // Silent fail on cache save + } + })(); + + } catch (error) { + + // Si Darkino retourne 500, ne pas créer/mettre à jour le cache et renvoyer le cache existant si présent + if (error.response && error.response.status >= 500) { + // Si on a déjà retourné des données (cache), on ne fait RIEN + if (dataReturned) return; + + try { + const fallbackCache = await getFromCacheNoExpiration(DOWNLOAD_CACHE_DIR, cacheKey); + if (fallbackCache) { + return res.status(200).json(fallbackCache); + } + } catch (_) { } + } + + if (!res.headersSent) { + res.status(500).json({ + success: false, + error: 'Erreur lors de la récupération des saisons DarkiWorld', + message: error.message + }); + } + } +}); + +// --------------------------------------------------------------------------- +// GET /episodes/:titleId/:seasonNumber +// Récupérer les épisodes d'une saison depuis DarkiWorld +// Params: titleId (ID DarkiWorld de la série), seasonNumber (numéro de la saison: 0, 1, 2, etc.) +// Query: page (optionnel, défaut: 1), perPage (optionnel, défaut: 30) +// --------------------------------------------------------------------------- +router.get('/episodes/:titleId/:seasonNumber', async (req, res) => { + let dataReturned = false; + try { + const { titleId, seasonNumber } = req.params; + const { page = 1, perPage = 30 } = req.query; + + if (!titleId || seasonNumber === undefined) { + return res.status(400).json({ + success: false, + error: 'ID de la série et numéro de saison requis' + }); + } + + // Generate cache key + const cacheKey = generateCacheKey(`darkiworld_episodes_${titleId}_${seasonNumber}_${page}_${perPage}`); + + // Check if results are in cache without expiration (stale-while-revalidate) + const cachedData = await getFromCacheNoExpiration(DOWNLOAD_CACHE_DIR, cacheKey); + + if (cachedData) { + // console.log(`Épisodes pour ${titleId}/${seasonNumber} récupérés du cache`); + res.status(200).json(cachedData); // Return cached data immediately + dataReturned = true; + } + + // Récupérer les épisodes depuis DarkiWorld + const episodesResponse = await axiosDarkinoRequest({ + method: 'get', + url: `/api/v1/titles/${titleId}/seasons/${seasonNumber}/episodes?perPage=${perPage}&excludeDescription=true&query=&orderBy=episode_number&orderDir=asc&page=${page}` + }); + + const responseData = { + success: true, + ...episodesResponse.data + }; + + // Si on n'a pas encore retourné de données, retourner maintenant + if (!dataReturned) { + res.json(responseData); + } + + // Background update du cache + (async () => { + try { + // Vérifier si le cache doit être mis à jour + const shouldUpdate = await shouldUpdateCache(DOWNLOAD_CACHE_DIR, cacheKey); + if (!shouldUpdate) { + return; // Ne pas mettre à jour le cache + } + + // Si on a des données, sauvegarder dans le cache + if (episodesResponse.data && episodesResponse.data.pagination) { + await saveToCache(DOWNLOAD_CACHE_DIR, cacheKey, responseData); + } + } catch (cacheError) { + // Silent fail on cache save + } + })(); + + } catch (error) { + + // Si Darkino retourne 500, ne pas créer/mettre à jour le cache et renvoyer le cache existant si présent + if (error.response && error.response.status >= 500) { + // Si on a déjà retourné des données (cache), on ne fait RIEN + if (dataReturned) return; + + try { + const fallbackCache = await getFromCacheNoExpiration(DOWNLOAD_CACHE_DIR, cacheKey); + if (fallbackCache) { + return res.status(200).json(fallbackCache); + } + } catch (_) { } + } + + if (!res.headersSent) { + res.status(500).json({ + success: false, + error: 'Erreur lors de la récupération des épisodes DarkiWorld', + message: error.message + }); + } + } +}); + +module.exports = router; +module.exports.configure = configure; +module.exports.findAllEntriesForEpisode = findAllEntriesForEpisode; diff --git a/API/Mainapi/routes/debrid.js b/API/Mainapi/routes/debrid.js new file mode 100644 index 0000000..ef2a0d8 --- /dev/null +++ b/API/Mainapi/routes/debrid.js @@ -0,0 +1,26 @@ +const express = require('express'); + +const { requireVip } = require('../checkVip'); + +const router = express.Router(); + +router.get('/debrid/bestdebrid-key', requireVip, (req, res) => { + const apiKey = (process.env.BESTDEBRID_API_KEY || '').trim(); + + res.setHeader('Cache-Control', 'no-store, private, max-age=0'); + res.setHeader('Pragma', 'no-cache'); + + if (!apiKey) { + return res.status(503).json({ + success: false, + error: 'Cle API BestDebrid non configuree sur le backend' + }); + } + + return res.json({ + success: true, + apiKey + }); +}); + +module.exports = router; diff --git a/API/Mainapi/routes/download.js b/API/Mainapi/routes/download.js new file mode 100644 index 0000000..b2c3eb3 --- /dev/null +++ b/API/Mainapi/routes/download.js @@ -0,0 +1,1027 @@ +/** + * Download routes module. + * Extracted from server.js -- handles film/series download link retrieval, + * m3u8 extraction, Darkibox premium, cache deletion, and anime cache. + * + * Mounted at /api (paths below are relative to that prefix). + */ + +const express = require('express'); +const router = express.Router(); +const path = require('path'); +const fsp = require('fs').promises; +const axios = require('axios'); +const { generateCacheKey, ANIME_SAMA_CACHE_DIR, getCacheRefreshInfo } = require('../utils/cacheManager'); + +// --------------------------------------------------------------------------- +// Dependencies injected via configure() +// --------------------------------------------------------------------------- +let DARKINO_MAINTENANCE; +let DARKINOS_CACHE_DIR; +let darkiworld_premium = false; +let darkiHeaders; +let axiosDarkinoRequest; +let getFromCacheNoExpiration; +let saveToCache; +let shouldUpdateCache; +let refreshDarkinoSessionIfNeeded; + +/** + * Inject runtime dependencies that still live in app.js. + */ +function configure(deps) { + if (deps.DARKINO_MAINTENANCE !== undefined) DARKINO_MAINTENANCE = deps.DARKINO_MAINTENANCE; + if (deps.DARKINOS_CACHE_DIR) DARKINOS_CACHE_DIR = deps.DARKINOS_CACHE_DIR; + if (deps.darkiworld_premium !== undefined) darkiworld_premium = deps.darkiworld_premium; + if (deps.darkiHeaders) darkiHeaders = deps.darkiHeaders; + if (deps.axiosDarkinoRequest) axiosDarkinoRequest = deps.axiosDarkinoRequest; + if (deps.getFromCacheNoExpiration) getFromCacheNoExpiration = deps.getFromCacheNoExpiration; + if (deps.saveToCache) saveToCache = deps.saveToCache; + if (deps.shouldUpdateCache) shouldUpdateCache = deps.shouldUpdateCache; + if (deps.refreshDarkinoSessionIfNeeded) refreshDarkinoSessionIfNeeded = deps.refreshDarkinoSessionIfNeeded; +} + +// --------------------------------------------------------------------------- +// Utility functions (were inline in server.js) +// --------------------------------------------------------------------------- + +const truncateForLog = (value, maxLength = 240) => { + if (typeof value !== 'string') return value; + return value.length > maxLength ? `${value.slice(0, maxLength)}...` : value; +}; + +const buildLogContext = (context = {}) => { + const parts = Object.entries(context) + .filter(([, value]) => value !== undefined && value !== null && value !== '') + .map(([key, value]) => `${key}=${value}`); + return parts.length > 0 ? parts.join(' ') : 'no-context'; +}; + +const summarizeErrorForLog = (error) => { + const responseBody = error?.response?.data; + return { + message: error?.message, + code: error?.code, + status: error?.response?.status, + statusText: error?.response?.statusText, + responseSnippet: typeof responseBody === 'string' + ? truncateForLog(responseBody, 500) + : responseBody && typeof responseBody === 'object' + ? truncateForLog(JSON.stringify(responseBody), 500) + : undefined + }; +}; + +const summarizeSourceForLog = (source) => { + if (!source) return null; + return { + src: truncateForLog(source.src), + language: source.language, + quality: source.quality, + sub: source.sub, + hasM3u8: !!source.m3u8 + }; +}; + +const summarizeSourcesForLog = (sources = [], limit = 5) => + sources.slice(0, limit).map(summarizeSourceForLog); + +const validateM3u8Url = async (m3u8Url, _useProxy = false, logContext = {}) => { + if (!m3u8Url) return { isValid: false, quality: null }; + try { + const response = await axios.get(m3u8Url, { + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:134.0) Gecko/20100101 Firefox/134.0', + 'Accept': '*/*', + 'Accept-Language': 'en-US,en;q=0.5', + 'Sec-Fetch-Dest': 'empty', + 'Sec-Fetch-Mode': 'cors', + 'Sec-Fetch-Site': 'cross-site' + }, + timeout: 2000, + validateStatus: (status) => status === 200, + decompress: true + }); + const contentType = response.headers['content-type']; + const isValidContent = contentType && ( + contentType.includes('application/vnd.apple.mpegurl') || + contentType.includes('application/x-mpegurl') || + contentType.includes('audio/mpegurl') || + contentType.includes('text/plain') + ); + const isValidM3u8 = response.data && typeof response.data === 'string' && + (response.data.includes('#EXTM3U') || response.data.includes('#EXT-X-VERSION')); + const isValid = isValidContent || isValidM3u8; + let quality = null; + if (isValid && response.data && typeof response.data === 'string') { + const content = response.data; + const resolutionMatch = content.match(/RESOLUTION=(\d+x\d+)/i); + if (resolutionMatch) { + const [width, height] = resolutionMatch[1].split('x').map(Number); + if (width >= 3840 || height >= 2160) quality = '4K'; + else if (width >= 1920 || height >= 1080) quality = '1080p'; + else if (width >= 1280 || height >= 720) quality = '720p'; + else if (width >= 854 || height >= 480) quality = '480p'; + else if (width >= 640 || height >= 360) quality = '360p'; + else quality = `${height}p`; + } else { + const qualityMatch = content.match(/(\d+p|4k|hd|sd)/gi); + if (qualityMatch) { + const qs = qualityMatch[0].toLowerCase(); + if (qs.includes('4k')) quality = '4K'; + else if (qs.includes('1080p') || qs.includes('hd')) quality = '1080p'; + else if (qs.includes('720p')) quality = '720p'; + else if (qs.includes('480p')) quality = '480p'; + else if (qs.includes('360p')) quality = '360p'; + else quality = qs.toUpperCase(); + } + } + } + return { isValid, quality }; + } catch (_error) { + return { isValid: false, quality: null }; + } +}; + +const extractM3u8Url = async (darkiboxUrl, logContext = {}) => { + let timeoutId; + try { + const axiosPromise = axios.get(darkiboxUrl); + const timeoutPromise = new Promise((_, reject) => + { timeoutId = setTimeout(() => reject(new Error('Request timed out (manual)')), 4500); } + ); + const response = await Promise.race([axiosPromise, timeoutPromise]); + const htmlContent = response.data; + const playerConfigMatch = htmlContent.match(/sources:\s*\[\s*{\s*src:\s*"([^"]+)"/); + if (playerConfigMatch && playerConfigMatch[1]) { + const m3u8Url = playerConfigMatch[1]; + const validation = await validateM3u8Url(m3u8Url, false, { + ...logContext, + sourceUrl: truncateForLog(darkiboxUrl, 160) + }); + if (validation.isValid) { + return { url: m3u8Url, quality: validation.quality }; + } + return null; + } + return null; + } catch (_error) { + return null; + } finally { + if (timeoutId) clearTimeout(timeoutId); + } +}; + +const deduplicateSourcesWithPreference = (sources = []) => { + const normalizeLang = (value) => (typeof value === 'string' ? value.trim().toLowerCase() : ''); + const mergeMissingFields = (main, other) => { + const merged = { ...main }; + for (const field of ['language', 'quality', 'sub', 'provider', 'm3u8', 'src']) { + if ((merged[field] === undefined || merged[field] === null || merged[field] === '') && other[field]) { + merged[field] = other[field]; + } + } + return merged; + }; + const choosePreferred = (current, candidate) => { + if (!current) return { ...candidate }; + if (!candidate) return { ...current }; + const currentLang = normalizeLang(current.language); + const candidateLang = normalizeLang(candidate.language); + let winner = current, loser = candidate; + if (!current.m3u8 && candidate.m3u8) { winner = candidate; loser = current; } + else if (current.m3u8 && !candidate.m3u8) { winner = current; loser = candidate; } + else if (candidateLang === 'multi' && currentLang !== 'multi') { winner = candidate; loser = current; } + else if (currentLang === 'multi' && candidateLang !== 'multi') { winner = current; loser = candidate; } + else if (!current.language && candidate.language) { winner = candidate; loser = current; } + return mergeMissingFields(winner, loser); + }; + const byKey = new Map(); + for (const source of sources) { + if (!source) continue; + const key = source.m3u8 || source.src; + if (!key) continue; + byKey.set(key, choosePreferred(byKey.get(key), source)); + } + return [...byKey.values()]; +}; + +// --------------------------------------------------------------------------- +// findDarkiboxEntriesForEpisode -- paginate Darkibox API to find entries +// --------------------------------------------------------------------------- +async function findDarkiboxEntriesForEpisode({ titleId, seasonId, episodeId, perPage = 100, maxPages = 10 }) { + // Rafraichir les cookies avant de commencer la pagination + try { + await refreshDarkinoSessionIfNeeded(); + } catch (e) { + console.warn('Erreur lors du rafraichissement des cookies Darkino:', e.message); + } + let page = 1; + let foundEntries = []; + let shouldContinue = true; + while (shouldContinue && page <= maxPages) { + const url = `/api/v1/liens?perPage=${perPage}&page=${page}&title_id=${titleId}&loader=linksdl&season=${seasonId}&filters=&paginate=preferLengthAware`; + try { + const resp = await axiosDarkinoRequest({ + method: 'get', + url: url, + headers: darkiHeaders + }); + const data = resp.data?.pagination?.data || []; + // Cherche les entrees correspondant a l'episode + const matching = data.filter(entry => + entry.host && entry.host.id_host === 2 && entry.host.name === 'darkibox' && + (entry.episode_id == episodeId || entry.episode == episodeId || entry.episode_number == episodeId) + ); + if (matching.length > 0) { + foundEntries = matching; + break; + } + // Pagination intelligente + const nextPage = resp.data?.pagination?.next_page; + if (!nextPage) { + shouldContinue = false; + } else { + page = nextPage; + } + } catch (error) { + console.error(`[DARKIBOX] Erreur lors de la recherche des liens (page ${page}) ${buildLogContext({ titleId, seasonId, episodeId })}`, summarizeErrorForLog(error)); + shouldContinue = false; + } + } + return foundEntries; +} + +// =========================================================================== +// ROUTES (mounted at /api, so paths are relative) +// =========================================================================== + +// --------------------------------------------------------------------------- +// GET /films/download/:id -- retrieve download links for a film +// --------------------------------------------------------------------------- +router.get('/films/download/:id', async (req, res) => { + if (DARKINO_MAINTENANCE) { + return res.status(200).json({ error: 'Service Darkino temporairement indisponible (maintenance)' }); + } + try { + const { id } = req.params; + const cacheKey = generateCacheKey(`films_download_${id}`); + const cachedData = await getFromCacheNoExpiration(DARKINOS_CACHE_DIR, cacheKey); + const M3U8_CACHE_EXPIRY = 8 * 60 * 60 * 1000; // 8 hours in milliseconds + + let dataReturned = false; + if (cachedData && cachedData.sources !== undefined) { + const now = Date.now(); + const needM3u8Refresh = !cachedData.m3u8Timestamp || (now - cachedData.m3u8Timestamp > M3U8_CACHE_EXPIRY); + let sourcesWithM3u8; + if (!needM3u8Refresh && cachedData.sourcesWithM3u8) { + sourcesWithM3u8 = cachedData.sourcesWithM3u8; + const validSources = sourcesWithM3u8.filter(source => source.m3u8); + if (validSources.length === 0) { + // Aucun m3u8 valide dans le cache, on force la re-extraction + sourcesWithM3u8 = await Promise.all( + cachedData.sources.map(async (source, idx) => { + const m3u8Result = await extractM3u8Url(source.src); + if (m3u8Result) { + return { + ...source, + m3u8: m3u8Result.url, + quality: m3u8Result.quality || source.quality + }; + } + return { ...source, m3u8: null }; + }) + ); + const newCacheData = { + ...cachedData, + sourcesWithM3u8: sourcesWithM3u8, + m3u8Timestamp: Date.now() + }; + await saveToCache(DARKINOS_CACHE_DIR, cacheKey, newCacheData); + } + } else { + sourcesWithM3u8 = await Promise.all( + cachedData.sources.map(async (source, idx) => { + const m3u8Result = await extractM3u8Url(source.src); + if (m3u8Result) { + return { + ...source, + m3u8: m3u8Result.url, + quality: m3u8Result.quality || source.quality + }; + } + return { ...source, m3u8: null }; + }) + ); + const newCacheData = { + ...cachedData, + sourcesWithM3u8: sourcesWithM3u8, + m3u8Timestamp: Date.now() + }; + await saveToCache(DARKINOS_CACHE_DIR, cacheKey, newCacheData); + } + const dedupedSources = deduplicateSourcesWithPreference(sourcesWithM3u8); + // Filtrer les sources avec m3u8: null avant de retourner + const filteredSources = dedupedSources.filter(source => source.m3u8); + // Retourner les sources dedupliquees et filtrees + res.status(200).json({ sources: filteredSources }); + dataReturned = true; + (async () => { + try { + const shouldUpdate_ = await shouldUpdateCache(DARKINOS_CACHE_DIR, cacheKey); + if (!shouldUpdate_) { + return; + } + + await refreshDarkinoSessionIfNeeded(); + const response = await axiosDarkinoRequest({ method: 'get', url: `/api/v1/titles/${id}/download` }); + let freshSources = response.data.alternative_videos || []; + if (response.data.video) { + freshSources.unshift(response.data.video); + } + if (freshSources.length > 0) { + const basicSources = freshSources.map(source => ({ + src: source.src, + language: source.language, + quality: source.quality, + sub: source.sub + })); + const currentCacheData = await getFromCacheNoExpiration(DARKINOS_CACHE_DIR, cacheKey) || {}; + if (JSON.stringify(basicSources) !== JSON.stringify(currentCacheData.sources)) { + await saveToCache(DARKINOS_CACHE_DIR, cacheKey, { sources: basicSources }); + } + } + } catch (refreshError) { + } + })(); + return; + } + // Si pas de cache valide, comportement normal (requete Darkino) + const maxRetries = 3; + let retryCount = 0; + let response; + let success = false; + await refreshDarkinoSessionIfNeeded(); + while (!success && retryCount < maxRetries) { + try { + response = await axiosDarkinoRequest({ method: 'get', url: `/api/v1/titles/${id}/download` }); + success = true; + } catch (error) { + if (error.response?.data?.message === "Il y a eu un probleme. Veuillez reessayer plus tard.") { + throw error; + } + + // Arreter immediatement sur les erreurs 500/403 + if (error.response && (error.response.status === 500 || error.response.status === 403)) { + throw error; + } + + retryCount++; + if (retryCount >= maxRetries) { + throw error; + } + if (!error.response) { + const delay = Math.min(2000 * Math.pow(1.5, retryCount), 5000) + (Math.random() * 500); + await new Promise(resolve => setTimeout(resolve, delay)); + } else { + throw error; + } + } + } + let sources = response.data.alternative_videos || []; + if (response.data.video) { + sources.unshift(response.data.video); + } + const basicSources = sources.map(source => ({ + src: source.src, + language: source.language, + quality: source.quality, + sub: source.sub + })); + + // --- DARKIBOX ENHANCEMENT START --- + if (darkiworld_premium) { + try { + // 1. Fetch all links for the film + const darkiboxLiensResp = await axiosDarkinoRequest({ method: 'get', url: `/api/v1/liens?perPage=100&title_id=${id}&loader=linksdl&season=1&filters=&paginate=preferLengthAware` }); + const darkiboxEntries = (darkiboxLiensResp.data?.pagination?.data || []).filter( + entry => entry.host && entry.host.id_host === 2 && entry.host.name === 'darkibox' + ); + const darkiboxIds = darkiboxEntries.map(entry => entry.id); + if (darkiboxIds.length > 0) { + // 2. POST to download-premium with all darkibox IDs + const darkiboxDownloadResp = await axiosDarkinoRequest({ method: 'post', url: `/api/v1/download-premium/${darkiboxIds.join(',')}` }); + const darkiboxLinks = (darkiboxDownloadResp.data?.liens || []).filter(l => l.lien && l.lien.includes('darkibox.com')); + // 3. For each link, extract m3u8 + const darkiboxSources = await Promise.all(darkiboxLinks.map(async (lienObj) => { + let idMatch = lienObj.lien.match(/(?:\/d\/|\/)([a-z0-9]{12,})/i); + let darkiboxId = idMatch ? idMatch[1] : null; + let m3u8Url = null; + let embedUrl = null; + if (darkiboxId) { + embedUrl = `https://darkibox.com/embed-${darkiboxId}.html`; + const m3u8Result = await extractM3u8Url(embedUrl); + m3u8Url = m3u8Result?.url || null; + } + const meta = darkiboxEntries.find(e => e.id === lienObj.id); + return m3u8Url ? { + src: embedUrl, + m3u8: m3u8Url, + language: (meta?.langues_compact && meta.langues_compact.length > 0) ? meta.langues_compact.map(l => l.name).join(', ') : undefined, + quality: meta?.qual?.qual, + sub: (meta?.subs_compact && meta.subs_compact.length > 0) ? meta.subs_compact.map(s => s.name).join(', ') : undefined, + provider: 'darkibox' + } : null; + })); + const validDarkiboxSources = darkiboxSources.filter(Boolean); + for (const src of validDarkiboxSources) { + if (!basicSources.some(s => s.src === src.src)) { + basicSources.push(src); + } + } + } + } catch (err) { + console.error('[DARKIBOX] Error enhancing darkibox links:', err.message); + } + } + // --- DARKIBOX ENHANCEMENT END --- + + // Extract and cache m3u8 URLs + let sourcesWithM3u8 = await Promise.all( + basicSources.map(async (source, idx) => { + if (source.m3u8) { + const validation = await validateM3u8Url(source.m3u8, false); + if (validation.isValid) { + return { + ...source, + m3u8: source.m3u8, + quality: validation.quality || source.quality + }; + } else { + return { ...source, m3u8: null }; + } + } else { + const m3u8Result = await extractM3u8Url(source.src); + if (m3u8Result) { + return { + ...source, + m3u8: m3u8Result.url, + quality: m3u8Result.quality || source.quality + }; + } + return { ...source, m3u8: null }; + } + }) + ); + // Retry extraction if no valid sources (up to 2 more times) + let validSources = sourcesWithM3u8.filter(source => source.m3u8); + let m3u8RetryCount = 0; + while (validSources.length === 0 && m3u8RetryCount < 2) { + m3u8RetryCount++; + await new Promise(r => setTimeout(r, 500)); + sourcesWithM3u8 = await Promise.all( + basicSources.map(async (source, idx) => { + if (source.m3u8) { + const validation = await validateM3u8Url(source.m3u8, false); + if (validation.isValid) { + return { + ...source, + m3u8: source.m3u8, + quality: validation.quality || source.quality + }; + } else { + return { ...source, m3u8: null }; + } + } else { + const m3u8Result = await extractM3u8Url(source.src); + if (m3u8Result) { + return { + ...source, + m3u8: m3u8Result.url, + quality: m3u8Result.quality || source.quality + }; + } + return { ...source, m3u8: null }; + } + }) + ); + validSources = sourcesWithM3u8.filter(source => source.m3u8); + } + const dedupedSources = deduplicateSourcesWithPreference(sourcesWithM3u8); + // Save both the basic sources and the sources with m3u8 + await saveToCache(DARKINOS_CACHE_DIR, cacheKey, { + sources: basicSources, + sourcesWithM3u8: sourcesWithM3u8, + m3u8Timestamp: Date.now() + }); + // Filtrer les sources avec m3u8: null avant de retourner + const filteredSources = dedupedSources.filter(source => source.m3u8); + res.status(200).json({ sources: filteredSources }); + } catch (error) { + res.status(500).json({ error: 'Erreur lors de la recuperation des liens de telechargement' }); + } +}); + +// --------------------------------------------------------------------------- +// GET /series/download/:titleId/season/:seasonId/episode/:episodeId +// --------------------------------------------------------------------------- +router.get('/series/download/:titleId/season/:seasonId/episode/:episodeId', async (req, res) => { + if (DARKINO_MAINTENANCE) { + return res.status(200).json({ error: 'Service Darkino temporairement indisponible (maintenance)' }); + } + const { titleId, seasonId, episodeId } = req.params; + const cacheKey = generateCacheKey(`series_download_${titleId}_${seasonId}_${episodeId}`); + const requestContext = { + route: 'series_download', + titleId, + seasonId, + episodeId, + cacheKey + }; + try { + const cachedData = await getFromCacheNoExpiration(DARKINOS_CACHE_DIR, cacheKey); + const M3U8_CACHE_EXPIRY = 8 * 60 * 60 * 1000; + + let dataReturned = false; + if (cachedData && cachedData.sources !== undefined) { + const now = Date.now(); + const needM3u8Refresh = !cachedData.m3u8Timestamp || + (now - cachedData.m3u8Timestamp > M3U8_CACHE_EXPIRY); + + let sourcesWithM3u8; + let validSources = []; + + if (!needM3u8Refresh && cachedData.sourcesWithM3u8) { + sourcesWithM3u8 = cachedData.sourcesWithM3u8; + validSources = sourcesWithM3u8.filter(source => source.m3u8); + } + + if (needM3u8Refresh || validSources.length === 0) { + sourcesWithM3u8 = await Promise.all( + cachedData.sources.map(async (source, sourceIndex) => { + const m3u8Result = await extractM3u8Url(source.src, { + ...requestContext, + phase: 'cache_reextract', + sourceIndex + }); + if (m3u8Result) { + return { + ...source, + m3u8: m3u8Result.url, + quality: m3u8Result.quality || source.quality + }; + } + return { ...source, m3u8: null }; + }) + ); + + const newCacheData = { + ...cachedData, + sourcesWithM3u8: sourcesWithM3u8, + m3u8Timestamp: Date.now() + }; + await saveToCache(DARKINOS_CACHE_DIR, cacheKey, newCacheData); + validSources = sourcesWithM3u8.filter(source => source.m3u8); + } + + const dedupedSources = deduplicateSourcesWithPreference(validSources); + const filteredSources = dedupedSources.filter(source => source.m3u8); + const cachedSourceCount = Array.isArray(cachedData.sources) ? cachedData.sources.length : 0; + const cachedSourcesWithM3u8Count = Array.isArray(cachedData.sourcesWithM3u8) ? cachedData.sourcesWithM3u8.length : 0; + const cacheRefreshInfo = await getCacheRefreshInfo(DARKINOS_CACHE_DIR, cacheKey); + const shouldRefreshCacheNow = cacheRefreshInfo.shouldRefreshNow; + const refreshSummary = shouldRefreshCacheNow + ? 'refresh possible immediatement' + : `refresh possible dans ${cacheRefreshInfo.refreshInMinutes} min (${cacheRefreshInfo.refreshAvailableAt})`; + const shouldForceLiveRefetch = filteredSources.length === 0; + if (!shouldForceLiveRefetch) { + res.status(200).json({ sources: filteredSources }); + dataReturned = true; + + (async () => { + try { + if (!shouldRefreshCacheNow) { + return; + } + + await refreshDarkinoSessionIfNeeded(); + const response = await axiosDarkinoRequest({ method: 'get', url: `/api/v1/titles/${titleId}/season/${seasonId}/episode/${episodeId}/download`, headers: darkiHeaders }); + let freshSources = response.data.alternative_videos || []; + if (response.data.video) { + freshSources.unshift(response.data.video); + } + // Filtrer les sources pour l'episode demande + freshSources = freshSources.filter(source => { + return !source.episode || source.episode.toString() === episodeId.toString(); + }); + if (freshSources.length > 0) { + const basicSources = freshSources.map(source => ({ + src: source.src, + language: source.language, + quality: source.quality, + sub: source.sub + })); + + const currentCacheData = await getFromCacheNoExpiration(DARKINOS_CACHE_DIR, cacheKey) || {}; + if (JSON.stringify(basicSources) !== JSON.stringify(currentCacheData.sources)) { + await saveToCache(DARKINOS_CACHE_DIR, cacheKey, { sources: basicSources }); + } + } + } catch (_refreshError) { + } + })(); + return; + } + } + // Si pas de cache valide, comportement normal (requete Darkino) + const maxRetries = 3; + let retryCount = 0; + let response; + let success = false; + await refreshDarkinoSessionIfNeeded(); + while (!success && retryCount < maxRetries) { + try { + response = await axiosDarkinoRequest({ method: 'get', url: `/api/v1/titles/${titleId}/season/${seasonId}/episode/${episodeId}/download`, headers: darkiHeaders }); + success = true; + } catch (error) { + if (error.response?.data?.message === "Il y a eu un probleme. Veuillez reessayer plus tard.") { + throw error; + } + + // Arreter immediatement sur les erreurs 500/403 + if (error.response && (error.response.status === 500 || error.response.status === 403)) { + throw error; + } + + retryCount++; + if (retryCount >= maxRetries) { + throw error; + } + const delay = Math.min(2000 * Math.pow(2, retryCount), 30000) + (Math.random() * 1000); + await new Promise(resolve => setTimeout(resolve, delay)); + } + } + let sources = response.data.alternative_videos || []; + if (response.data.video) { + sources.unshift(response.data.video); + } + // Filtrer les sources pour l'episode demande + sources = sources.filter(source => { + return !source.episode || source.episode.toString() === episodeId.toString(); + }); + const basicSources = sources.map(source => ({ + src: source.src, + language: source.language, + quality: source.quality, + sub: source.sub + })); + // --- DARKIBOX ENHANCEMENT START --- + if (darkiworld_premium) { + try { + const darkiboxEntries = await findDarkiboxEntriesForEpisode({ titleId, seasonId, episodeId, perPage: 100, maxPages: 10 }); + const darkiboxIds = darkiboxEntries.map(entry => entry.id); + if (darkiboxIds.length > 0) { + const darkiboxDownloadResp = await axiosDarkinoRequest({ method: 'post', url: `/api/v1/download-premium/${darkiboxIds.join(',')}` }); + const darkiboxLinks = (darkiboxDownloadResp.data?.liens || []).filter(l => l.lien && l.lien.includes('darkibox.com')); + const darkiboxSources = await Promise.all(darkiboxLinks.map(async (lienObj) => { + let idMatch = lienObj.lien.match(/(?:\/d\/|\/)([a-z0-9]{12,})/i); + let darkiboxId = idMatch ? idMatch[1] : null; + let m3u8Url = null; + let embedUrl = null; + if (darkiboxId) { + embedUrl = `https://darkibox.com/embed-${darkiboxId}.html`; + const m3u8Result = await extractM3u8Url(embedUrl); + m3u8Url = m3u8Result?.url || null; + } + const meta = darkiboxEntries.find(e => e.id === lienObj.id); + return m3u8Url ? { + src: embedUrl, + m3u8: m3u8Url, + language: (meta?.langues_compact && meta.langues_compact.length > 0) ? meta.langues_compact.map(l => l.name).join(', ') : undefined, + quality: meta?.qual?.qual, + sub: (meta?.subs_compact && meta.subs_compact.length > 0) ? meta.subs_compact.map(s => s.name).join(', ') : undefined, + provider: 'darkibox' + } : null; + })); + const validDarkiboxSources = darkiboxSources.filter(Boolean); + for (const src of validDarkiboxSources) { + if (!basicSources.some(s => s.src === src.src)) { + basicSources.push(src); + } + } + } + } catch (err) { + console.error('[DARKIBOX] Error enhancing darkibox links (series):', err.message); + } + } + // --- DARKIBOX ENHANCEMENT END --- + + // Extract and cache m3u8 URLs + let sourcesWithM3u8 = await Promise.all( + basicSources.map(async (source, sourceIndex) => { + if (source.m3u8) { + const validation = await validateM3u8Url(source.m3u8, false, { + ...requestContext, + phase: 'initial_validation', + sourceIndex + }); + if (validation.isValid) { + return { + ...source, + m3u8: source.m3u8, + quality: validation.quality || source.quality + }; + } else { + return { ...source, m3u8: null }; + } + } else { + const m3u8Result = await extractM3u8Url(source.src, { + ...requestContext, + phase: 'initial_extract', + sourceIndex + }); + if (m3u8Result) { + return { + ...source, + m3u8: m3u8Result.url, + quality: m3u8Result.quality || source.quality + }; + } + return { ...source, m3u8: null }; + } + }) + ); + // Retry extraction if no valid sources (up to 2 more times) + let validSources = sourcesWithM3u8.filter(source => source.m3u8); + let m3u8RetryCount = 0; + while (validSources.length === 0 && m3u8RetryCount < 2) { + m3u8RetryCount++; + await new Promise(r => setTimeout(r, 500)); + sourcesWithM3u8 = await Promise.all( + basicSources.map(async (source, sourceIndex) => { + if (source.m3u8) { + const validation = await validateM3u8Url(source.m3u8, false, { + ...requestContext, + phase: `retry_validation_${m3u8RetryCount}`, + sourceIndex + }); + if (validation.isValid) { + return { + ...source, + m3u8: source.m3u8, + quality: validation.quality || source.quality + }; + } else { + return { ...source, m3u8: null }; + } + } else { + const m3u8Result = await extractM3u8Url(source.src, { + ...requestContext, + phase: `retry_extract_${m3u8RetryCount}`, + sourceIndex + }); + if (m3u8Result) { + return { + ...source, + m3u8: m3u8Result.url, + quality: m3u8Result.quality || source.quality + }; + } + return { ...source, m3u8: null }; + } + }) + ); + validSources = sourcesWithM3u8.filter(source => source.m3u8); + } + // Deduplication des sources par m3u8 (prioritaire) puis src + const seenM3u8 = new Set(); + const seenSrc = new Set(); + const dedupedSources = []; + for (const source of sourcesWithM3u8) { + const key = source.m3u8 || source.src; + if (!key) continue; + if (!seenM3u8.has(key)) { + seenM3u8.add(key); + dedupedSources.push(source); + } + } + // Deduplication supplementaire sur src + const finalSources = []; + for (const source of dedupedSources) { + if (!seenSrc.has(source.src)) { + seenSrc.add(source.src); + finalSources.push(source); + } + } + // Save both the basic sources and the sources with m3u8 + await saveToCache(DARKINOS_CACHE_DIR, cacheKey, { + sources: basicSources, + sourcesWithM3u8: sourcesWithM3u8, + m3u8Timestamp: Date.now() + }); + // Filtrer les sources avec m3u8: null avant de retourner + const filteredSources = finalSources.filter(source => source.m3u8 !== null); + res.status(200).json({ sources: filteredSources }); + } catch (error) { + res.status(500).json({ error: 'Erreur lors de la recuperation des liens de telechargement' }); + } +}); + +// --------------------------------------------------------------------------- +// GET /darkino/download-premium/:id +// --------------------------------------------------------------------------- +router.get('/darkino/download-premium/:id', async (req, res) => { + try { + const { id } = req.params; + const response = await axiosDarkinoRequest({ method: 'post', url: `/api/v1/download-premium/${id}` }); + res.status(response.status).json(response.data); + } catch (error) { + console.error('Erreur lors de la requete download-premium:', error.response?.status || error.message); + if (error.response) { + res.status(error.response.status).json({ error: error.response.data || 'Erreur lors de la requete download-premium' }); + } else { + res.status(500).json({ error: 'Erreur lors de la requete download-premium' }); + } + } +}); + +// --------------------------------------------------------------------------- +// GET /titles/:id/download -- download links via title ID +// --------------------------------------------------------------------------- +router.get('/titles/:id/download', async (req, res) => { + if (DARKINO_MAINTENANCE) { + return res.status(200).json({ error: 'Service Darkino temporairement indisponible (maintenance)' }); + } + try { + const { id } = req.params; + + // Generate cache key + const cacheKey = generateCacheKey(`titles_download_${id}`); + + // Check if results are in cache + const cachedData = await getFromCacheNoExpiration(DARKINOS_CACHE_DIR, cacheKey); + const M3U8_CACHE_EXPIRY = 8 * 60 * 60 * 1000; + + let dataReturned = false; + if (cachedData && cachedData.sources !== undefined) { + const now = Date.now(); + const needM3u8Refresh = !cachedData.m3u8Timestamp || (now - cachedData.m3u8Timestamp > M3U8_CACHE_EXPIRY); + let sourcesWithM3u8 = cachedData.sourcesWithM3u8 || []; + + if (needM3u8Refresh) { + sourcesWithM3u8 = await Promise.all( + cachedData.sources.map(async (source) => { + const m3u8Result = await extractM3u8Url(source.src); + if (m3u8Result) { + return { + ...source, + m3u8: m3u8Result.url, + quality: m3u8Result.quality || source.quality + }; + } + return { ...source, m3u8: null }; + }) + ); + // Mise a jour du cache avec les URLs m3u8 rafraichies + await saveToCache(DARKINOS_CACHE_DIR, cacheKey, { + sources: cachedData.sources, + sourcesWithM3u8: sourcesWithM3u8, + m3u8Timestamp: now + }); + } + + // Deduplication des sources par m3u8 + const seenM3u8 = new Set(); + const seenSrc = new Set(); + const dedupedSources = []; + for (const source of sourcesWithM3u8) { + const key = source.m3u8 || source.src; + if (!key) continue; + if (!seenM3u8.has(key)) { + seenM3u8.add(key); + dedupedSources.push(source); + } + } + const finalSources = []; + for (const source of dedupedSources) { + if (!seenSrc.has(source.src)) { + seenSrc.add(source.src); + finalSources.push(source); + } + } + const filteredSources = finalSources.filter(source => source.m3u8 !== null); + res.status(200).json({ sources: filteredSources }); + dataReturned = true; + (async () => { + try { + const shouldUpdate_ = await shouldUpdateCache(DARKINOS_CACHE_DIR, cacheKey); + if (!shouldUpdate_) { + return; + } + + await refreshDarkinoSessionIfNeeded(); + const response = await axiosDarkinoRequest({ method: 'get', url: `/api/v1/titles/${id}/download` }); + let freshSources = response.data.alternative_videos || []; + if (response.data.video) { + freshSources.unshift(response.data.video); + } + if (freshSources.length > 0) { + const basicSources = freshSources.map(source => ({ + src: source.src, + language: source.language, + quality: source.quality, + sub: source.sub + })); + const currentCacheData = await getFromCacheNoExpiration(DARKINOS_CACHE_DIR, cacheKey) || {}; + if (JSON.stringify(basicSources) !== JSON.stringify(currentCacheData.sources)) { + await saveToCache(DARKINOS_CACHE_DIR, cacheKey, { sources: basicSources }); + } + } + } catch (refreshError) { + } + })(); + return; + } + // Si pas de cache valide, comportement normal (requete Darkino) + const maxRetries = 3; + let retryCount = 0; + let response; + let success = false; + await refreshDarkinoSessionIfNeeded(); + while (!success && retryCount < maxRetries) { + try { + response = await axiosDarkinoRequest({ method: 'get', url: `/api/v1/titles/${id}/download` }); + success = true; + } catch (error) { + if (error.response?.data?.message === "Il y a eu un probleme. Veuillez reessayer plus tard.") { + throw error; + } + + if (error.response && (error.response.status === 500 || error.response.status === 403)) { + throw error; + } + + retryCount++; + if (retryCount >= maxRetries) { + throw error; + } + if (!error.response) { + const delay = Math.min(2000 * Math.pow(1.5, retryCount), 5000) + (Math.random() * 500); + await new Promise(resolve => setTimeout(resolve, delay)); + } else { + throw error; + } + } + } + // ... existing code (process response.data) ... + + } catch (error) { + console.error(`Erreur lors de la recuperation des liens de telechargement:`, error); + res.status(500).json({ error: 'Erreur lors de la recuperation des liens de telechargement' }); + } +}); + +// --------------------------------------------------------------------------- +// DELETE /films/download/:id/cache -- delete film download cache +// --------------------------------------------------------------------------- +router.delete('/films/download/:id/cache', async (req, res) => { + try { + const { id } = req.params; + const cacheKey = generateCacheKey(`films_download_${id}`); + const cacheFile = path.join(DARKINOS_CACHE_DIR, `${cacheKey}.json`); + await fsp.unlink(cacheFile); + return res.status(200).json({ success: true, message: `Cache film ${id} supprime.` }); + } catch (err) { + if (err.code === 'ENOENT') { + return res.status(404).json({ success: false, error: 'Cache introuvable.' }); + } + console.error('Erreur suppression cache film :', err); + return res.status(500).json({ success: false, error: 'Erreur serveur.' }); + } +}); + +// --------------------------------------------------------------------------- +// DELETE /series/download/:titleId/season/:seasonId/episode/:episodeId/cache +// --------------------------------------------------------------------------- +router.delete('/series/download/:titleId/season/:seasonId/episode/:episodeId/cache', async (req, res) => { + try { + const { titleId, seasonId, episodeId } = req.params; + const cacheKey = generateCacheKey(`series_download_${titleId}_${seasonId}_${episodeId}`); + const cacheFile = path.join(DARKINOS_CACHE_DIR, `${cacheKey}.json`); + await fsp.unlink(cacheFile); + return res.status(200).json({ success: true, message: `Cache episode ${titleId}/${seasonId}/${episodeId} supprime.` }); + } catch (err) { + if (err.code === 'ENOENT') { + return res.status(404).json({ success: false, error: 'Cache introuvable.' }); + } + console.error('Erreur suppression cache episode :', err); + return res.status(500).json({ success: false, error: 'Erreur serveur.' }); + } +}); + +// --------------------------------------------------------------------------- +// Exports +// --------------------------------------------------------------------------- +module.exports = router; +module.exports.configure = configure; +module.exports.findDarkiboxEntriesForEpisode = findDarkiboxEntriesForEpisode; diff --git a/API/Mainapi/routes/dragiv.js b/API/Mainapi/routes/dragiv.js new file mode 100644 index 0000000..73daefa --- /dev/null +++ b/API/Mainapi/routes/dragiv.js @@ -0,0 +1,518 @@ +/** + * Dragiv routes module. + * Extracted from server.js -- handles Dragiv movie source search and retrieval + * (films only). + * + * Mounted at /api/dragiv (paths below are relative to that prefix). + */ + +const express = require('express'); +const router = express.Router(); +const path = require('path'); +const fsp = require('fs').promises; +const axios = require('axios'); +const { CACHE_DIR, generateCacheKey } = require('../utils/cacheManager'); +const { redis } = require('../config/redis'); +const { fetchTmdbDetails } = require('../utils/tmdbCache'); + +// === DRAGIV CONFIGURATION === +const DRAGIV_BASE = 'https://kimpav.com'; +const DRAGIV_KEY = 'ph4p9rv4jpx7mg'; + +// Deduplication des requêtes Dragiv en cours +const ongoingDragivRequests = new Map(); +const DRAGIV_REQUEST_TIMEOUT = 30000; // 30s timeout par requête +const DRAGIV_STALE_CLEANUP_MS = 10 * 60 * 1000; // 10 min max pour une entrée + +const getOrCreateDragivRequest = async (cacheKey, requestFunction) => { + if (ongoingDragivRequests.has(cacheKey)) { + const existing = ongoingDragivRequests.get(cacheKey); + let dedupTimer; + return Promise.race([ + existing.promise.finally(() => clearTimeout(dedupTimer)), + new Promise((_, reject) => { dedupTimer = setTimeout(() => reject(new Error('Dragiv dedup timeout')), DRAGIV_REQUEST_TIMEOUT); }) + ]); + } + + const requestPromise = (async () => { + let timeoutTimer; + try { + return await Promise.race([ + requestFunction().finally(() => clearTimeout(timeoutTimer)), + new Promise((_, reject) => { timeoutTimer = setTimeout(() => reject(new Error('Dragiv request timeout')), DRAGIV_REQUEST_TIMEOUT); }) + ]); + } finally { + clearTimeout(timeoutTimer); + ongoingDragivRequests.delete(cacheKey); + } + })(); + + ongoingDragivRequests.set(cacheKey, { promise: requestPromise, createdAt: Date.now() }); + return requestPromise; +}; + +// Nettoyage périodique des requêtes Dragiv bloquées +setInterval(() => { + const now = Date.now(); + let cleaned = 0; + for (const [key, entry] of ongoingDragivRequests) { + if (now - entry.createdAt > DRAGIV_STALE_CLEANUP_MS) { + ongoingDragivRequests.delete(key); + cleaned++; + } + } + if (cleaned > 0) console.log(`[DRAGIV DEDUP] Nettoyage: ${cleaned} requêtes expirées supprimées`); +}, 5 * 60 * 1000).unref(); + +// --------------------------------------------------------------------------- +// Dependencies injected via configure() +// --------------------------------------------------------------------------- +let getFromCacheNoExpiration; + +/** + * Inject runtime dependencies that still live in server.js. + */ +function configure(deps) { + if (deps.getFromCacheNoExpiration) getFromCacheNoExpiration = deps.getFromCacheNoExpiration; +} + +// --------------------------------------------------------------------------- +// parseDragivMovieList -- parse movie entries from Dragiv HTML +// --------------------------------------------------------------------------- +function parseDragivMovieList(html) { + // Le HTML est structuré : \n\n Titre (Année) HD\n + const movieRegex = /href="(\/ph4p9rv4jpx7mg\/b\/kimpav\/(\d+))"[^>]*>\s*([\s\S]*?)<\/a>/g; + const matches = [...html.matchAll(movieRegex)]; + + const movies = []; + const seen = new Set(); + + for (const match of matches) { + const moviePath = match[1]; + const movieId = match[2]; + // Nettoyer le titre : retirer les balises HTML et les espaces superflus + const rawTitle = match[3].replace(/<[^>]+>/g, '').replace(/\s+/g, ' ').trim(); + + if (!seen.has(movieId) && rawTitle.length > 0) { + seen.add(movieId); + movies.push({ + id: movieId, + title: rawTitle, + url: `${DRAGIV_BASE}${moviePath}`, + path: moviePath + }); + } + } + + return movies; +} + +// --------------------------------------------------------------------------- +// searchDragivMovies -- search movies on Dragiv via POST +// --------------------------------------------------------------------------- +async function searchDragivMovies(query) { + const homeUrl = `${DRAGIV_BASE}/${DRAGIV_KEY}/home/kimpav`; + + const response = await axios.post(homeUrl, `searchword=${encodeURIComponent(query)}`, { + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', + 'Referer': homeUrl, + 'Content-Type': 'application/x-www-form-urlencoded', + 'Cookie': 'g=true' + }, + maxRedirects: 5, + timeout: 15000 + }); + + return parseDragivMovieList(response.data); +} + +// --------------------------------------------------------------------------- +// fetchDragivHomeMovies -- retrieve movie list from Dragiv homepage (fallback) +// --------------------------------------------------------------------------- +async function fetchDragivHomeMovies() { + const homeUrl = `${DRAGIV_BASE}/${DRAGIV_KEY}/home/kimpav`; + + const response = await axios.get(homeUrl, { + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', + 'Referer': DRAGIV_BASE, + 'Cookie': 'g=true' + }, + timeout: 15000 + }); + + return parseDragivMovieList(response.data); +} + +// --------------------------------------------------------------------------- +// fetchDragivMovieData -- retrieve sources for a Dragiv movie by internal ID +// --------------------------------------------------------------------------- +async function fetchDragivMovieData(movieId) { + const movieUrl = `${DRAGIV_BASE}/${DRAGIV_KEY}/b/kimpav/${movieId}`; + + const response = await axios.get(movieUrl, { + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', + 'Referer': `${DRAGIV_BASE}/${DRAGIV_KEY}/home/kimpav`, + 'Cookie': 'g=true' + }, + timeout: 15000 + }); + + const html = response.data; + + const titleMatch = html.match(/([^<]+)<\/title>/i); + const title = titleMatch ? titleMatch[1].replace(/^(Dragiv|Kimpav)\s*-\s*/i, '').trim() : 'Unknown'; + + const iframeMatch = html.match(/<iframe[^>]+src="(https:\/\/sharecloudy\.com\/[^"]+)"/i); + if (!iframeMatch) { + return { success: false, error: 'No iframe found', id: movieId, title }; + } + + const iframeUrl = iframeMatch[1]; + + const iframeResponse = await axios.get(iframeUrl, { + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', + 'Referer': movieUrl + }, + timeout: 15000 + }); + + const iframeHtml = iframeResponse.data; + + const m3u8Match = iframeHtml.match(/file:\s*"(https:\/\/[^"]+\.m3u8[^"]*)"/i); + if (!m3u8Match) { + return { success: false, error: 'No m3u8 found in iframe', id: movieId, title, iframeUrl }; + } + + const m3u8Url = m3u8Match[1]; + + // Extraire les qualités disponibles + const qualityRegex = /{\s*file:\s*"([^"]+\.m3u8[^"]*)"\s*,\s*label:\s*"([^"]+)"/g; + const qualityMatches = [...iframeHtml.matchAll(qualityRegex)]; + + const qualities = qualityMatches.length > 0 + ? qualityMatches.map(m => ({ url: m[1], quality: m[2] })) + : [{ url: m3u8Url, quality: 'HD' }]; + + return { + success: true, + id: movieId, + title, + movieUrl, + iframeUrl, + m3u8: m3u8Url, + qualities, + provider: 'sharecloudy.com', + referer: iframeUrl, + note: 'Le m3u8 nécessite le header Referer pour fonctionner' + }; +} + +// --------------------------------------------------------------------------- +// calculateDragivMatchScore -- compute title match score using Jaccard similarity +// --------------------------------------------------------------------------- +function calculateDragivMatchScore(dragivTitle, searchTitle, tmdbTitle, tmdbOriginalTitle) { + // Retirer les tags de qualité/statut des titres Dragiv (HD, VOSTFR, NEW, etc.) + const cleanTags = (str) => str + .replace(/\b(HD|VOSTFR|VF|NEW|CAM|TS|TC|DVDRIP|BDRIP|WEBRIP|HDTV)\b/gi, '') + .replace(/\+\d+/g, '') + .trim(); + + const normalize = (str) => cleanTags(str).toLowerCase() + .replace(/[:\-–—'"]/g, ' ') + .replace(/[^\w\s\u00C0-\u024F]/g, '') + .replace(/\s+/g, ' ') + .trim(); + + const removeYear = (str) => str.replace(/\(?\d{4}\)?/g, '').replace(/\s+/g, ' ').trim(); + // Ne pas traiter les années (4 chiffres >= 1900) comme des tokens de suite + const isYear = (token) => /^\d{4}$/.test(token) && parseInt(token) >= 1900; + const sequelTokenRegex = /^(\d+|i|ii|iii|iv|v|vi|vii|viii|ix|x)$/i; + const getSequelTokens = (str) => { + if (!str) return new Set(); + return new Set( + str + .split(' ') + .map(token => token.trim().toLowerCase()) + .filter(token => sequelTokenRegex.test(token) && !isYear(token)) + ); + }; + const hasSequelMismatch = (candidateTitleOnly, referenceTitleOnly) => { + const candidateTokens = getSequelTokens(candidateTitleOnly); + const referenceTokens = getSequelTokens(referenceTitleOnly); + + if (candidateTokens.size === 0 && referenceTokens.size === 0) return false; + if (candidateTokens.size === 0 || referenceTokens.size === 0) return true; + + for (const token of candidateTokens) { + if (referenceTokens.has(token)) return false; + } + return true; + }; + + const dragivNorm = normalize(dragivTitle); + const searchNorm = normalize(searchTitle); + const tmdbNorm = normalize(tmdbTitle); + const tmdbOrigNorm = normalize(tmdbOriginalTitle || ''); + + const dragivTitleOnly = removeYear(dragivNorm); + const tmdbTitleOnly = removeYear(tmdbNorm); + const tmdbOrigTitleOnly = removeYear(tmdbOrigNorm); + + // Bloque les faux positifs de suites: ex. "Zootopie" vs "Zootopie 2" + const mismatchWithTmdb = hasSequelMismatch(dragivTitleOnly, tmdbTitleOnly); + const mismatchWithTmdbOriginal = tmdbOrigTitleOnly.length > 0 + ? hasSequelMismatch(dragivTitleOnly, tmdbOrigTitleOnly) + : true; + + if (mismatchWithTmdb && mismatchWithTmdbOriginal) return 0; + + // Match exact (titre complet ou sans année) + if (dragivNorm === searchNorm || dragivNorm === tmdbNorm) return 1.0; + if (tmdbOrigNorm.length > 0 && dragivNorm === tmdbOrigNorm) return 1.0; + if (dragivTitleOnly.length > 0 && tmdbTitleOnly.length > 0 && dragivTitleOnly === tmdbTitleOnly) return 1.0; + if (tmdbOrigTitleOnly.length > 0 && dragivTitleOnly === tmdbOrigTitleOnly) return 1.0; + + // Jaccard similarity sur les mots (plus robuste que substring includes) + const getWords = (str) => { + const words = str.split(' ').filter(w => w.length > 1); + return new Set(words); + }; + + const jaccard = (setA, setB) => { + if (setA.size === 0 || setB.size === 0) return 0; + let intersectionSize = 0; + for (const item of setA) { + if (setB.has(item)) intersectionSize++; + } + const unionSize = new Set([...setA, ...setB]).size; + return intersectionSize / unionSize; + }; + + const dragivWords = getWords(dragivTitleOnly); + const tmdbWords = getWords(tmdbTitleOnly); + const tmdbOrigWords = tmdbOrigTitleOnly.length > 0 ? getWords(tmdbOrigTitleOnly) : new Set(); + + let score = Math.max( + jaccard(dragivWords, tmdbWords), + tmdbOrigWords.size > 0 ? jaccard(dragivWords, tmdbOrigWords) : 0 + ); + + // Bonus année uniquement si le titre a déjà un bon score + if (score >= 0.5) { + const yearMatch = dragivTitle.match(/\((\d{4})\)/); + const searchYearMatch = searchTitle.match(/\((\d{4})\)/); + if (yearMatch && searchYearMatch && yearMatch[1] === searchYearMatch[1]) { + score = Math.min(score + 0.1, 1.0); + } + } + + return score; +} + +// --------------------------------------------------------------------------- +// fetchDragivByTmdbId -- search Dragiv for a movie by TMDB ID +// --------------------------------------------------------------------------- +async function fetchDragivByTmdbId(tmdbId) { + try { + // 1. Récupérer les infos TMDB (cached via Redis) + const tmdbMovie = await fetchTmdbDetails('https://api.themoviedb.org/3', process.env.TMDB_API_KEY, tmdbId, 'movie', 'fr-FR'); + + if (!tmdbMovie || !tmdbMovie.title) { + return { success: false, error: 'TMDB movie not found', tmdb_id: tmdbId }; + } + + const year = tmdbMovie.release_date ? tmdbMovie.release_date.split('-')[0] : null; + const searchTitle = year ? `${tmdbMovie.title} (${year})` : tmdbMovie.title; + + // 2. Rechercher sur Dragiv par nom complet du film (POST search) + let allMovies = await searchDragivMovies(tmdbMovie.title); + + // Fallback: si la recherche ne retourne rien, essayer avec le titre original + if (allMovies.length === 0 && tmdbMovie.original_title && tmdbMovie.original_title !== tmdbMovie.title) { + allMovies = await searchDragivMovies(tmdbMovie.original_title); + } + + // Fallback ultime: homepage + if (allMovies.length === 0) { + allMovies = await fetchDragivHomeMovies(); + } + + // 3. Trouver le meilleur match + let bestMatch = null; + let bestScore = 0; + + for (const movie of allMovies) { + const score = calculateDragivMatchScore(movie.title, searchTitle, tmdbMovie.title, tmdbMovie.original_title); + if (score > bestScore) { + bestScore = score; + bestMatch = movie; + } + } + + // 4. Si trouvé avec un bon score, récupérer les sources (seuil strict pour éviter faux positifs) + if (bestMatch && bestScore >= 0.8) { + const movieData = await fetchDragivMovieData(bestMatch.id); + + // Vérification post-fetch : le titre de la page Dragiv doit aussi correspondre au film TMDB + if (movieData.success && movieData.title) { + const postFetchScore = calculateDragivMatchScore(movieData.title, searchTitle, tmdbMovie.title, tmdbMovie.original_title); + if (postFetchScore < 0.5) { + return { + success: false, + error: 'Movie not found on Dragiv (post-fetch title mismatch)', + tmdb_id: parseInt(tmdbId), + searched_title: searchTitle, + best_match: { title: bestMatch.title, score: bestScore }, + page_title: movieData.title, + page_score: postFetchScore + }; + } + } + + if (movieData.success) { + return { + success: true, + tmdb_id: parseInt(tmdbId), + tmdb: { + id: tmdbMovie.id, + title: tmdbMovie.title, + original_title: tmdbMovie.original_title, + overview: tmdbMovie.overview, + release_date: tmdbMovie.release_date, + vote_average: tmdbMovie.vote_average, + poster_path: tmdbMovie.poster_path ? `https://image.tmdb.org/t/p/w500${tmdbMovie.poster_path}` : null, + backdrop_path: tmdbMovie.backdrop_path ? `https://image.tmdb.org/t/p/original${tmdbMovie.backdrop_path}` : null, + genres: tmdbMovie.genres || [], + runtime: tmdbMovie.runtime + }, + dragiv: { + id: movieData.id, + title: movieData.title, + movieUrl: movieData.movieUrl, + iframeUrl: movieData.iframeUrl, + m3u8: movieData.m3u8, + qualities: movieData.qualities, + provider: movieData.provider, + referer: movieData.referer + }, + match_score: bestScore, + source: 'dragiv' + }; + } + } + + // 5. Pas trouvé + return { + success: false, + error: 'Movie not found on Dragiv', + tmdb_id: parseInt(tmdbId), + searched_title: searchTitle, + best_match: bestMatch ? { title: bestMatch.title, score: bestScore } : null + }; + + } catch (error) { + return { success: false, error: error.message, tmdb_id: tmdbId }; + } +} + +// --------------------------------------------------------------------------- +// updateDragivCache -- background cache update +// --------------------------------------------------------------------------- +async function updateDragivCache(cacheKey, tmdbid) { + try { + const newData = await fetchDragivByTmdbId(tmdbid); + if (newData && newData.success) { + await fsp.writeFile(path.join(CACHE_DIR.DRAGIV, `${cacheKey}.json`), JSON.stringify(newData), 'utf-8'); + // cache updated + } + } catch (error) { + // Ne pas toucher au cache existant en cas d'erreur + } +} + +// --------------------------------------------------------------------------- +// GET /movie/:tmdbid +// Chercher un film Dragiv par TMDB ID +// --------------------------------------------------------------------------- +router.get('/movie/:tmdbid', async (req, res) => { + const { tmdbid } = req.params; + const cacheKey = generateCacheKey(`dragiv_movie_${tmdbid}`); + + try { + // 1. Try cache + const cachedData = await getFromCacheNoExpiration(CACHE_DIR.DRAGIV, cacheKey); + if (cachedData) { + if (cachedData.notFound) { + res.status(404).json({ error: 'Movie not found on Dragiv (Cached)' }); + } else { + res.json(cachedData); + } + + // Background update si ancien (20 min) + const cacheFilePath = path.join(CACHE_DIR.DRAGIV, `${cacheKey}.json`); + try { + const stats = await fsp.stat(cacheFilePath); + const age = Date.now() - stats.mtime.getTime(); + if (age > 20 * 60 * 1000) { + updateDragivCache(cacheKey, tmdbid).catch(() => {}); + } + } catch (e) { /* ignore */ } + return; + } + + // 2. Fetch fresh avec deduplication + const data = await getOrCreateDragivRequest(cacheKey, () => fetchDragivByTmdbId(tmdbid)); + + if (!data || !data.success) { + const notFoundData = { notFound: true, tmdbId: tmdbid, timestamp: Date.now() }; + await fsp.writeFile(path.join(CACHE_DIR.DRAGIV, `${cacheKey}.json`), JSON.stringify(notFoundData), 'utf-8'); + return res.status(404).json({ error: 'Movie not found on Dragiv' }); + } + + await fsp.writeFile(path.join(CACHE_DIR.DRAGIV, `${cacheKey}.json`), JSON.stringify(data), 'utf-8'); + res.json(data); + + } catch (error) { + if (error.message && error.message.includes('not found')) { + return res.status(404).json({ error: error.message }); + } + res.status(500).json({ error: 'Internal Server Error' }); + } +}); + +// --------------------------------------------------------------------------- +// GET /movie/:tmdbid/clear-cache +// Vider le cache Dragiv d'un film +// --------------------------------------------------------------------------- +router.get('/movie/:tmdbid/clear-cache', async (req, res) => { + const { tmdbid } = req.params; + const cacheKey = generateCacheKey(`dragiv_movie_${tmdbid}`); + const cacheFilePath = path.join(CACHE_DIR.DRAGIV, `${cacheKey}.json`); + + try { + // Supprimer le fichier JSON + la clé Redis + const memKey = `${CACHE_DIR.DRAGIV}:${cacheKey}`; + await Promise.allSettled([ + fsp.unlink(cacheFilePath), + redis.del(memKey) + ]); + res.json({ success: true, message: `Cache cleared for movie ${tmdbid}` }); + } catch (error) { + res.status(500).json({ error: 'Internal Server Error' }); + } +}); + +// DRAGIV source loaded (films only) + +module.exports = router; +module.exports.configure = configure; +module.exports.searchDragivMovies = searchDragivMovies; +module.exports.fetchDragivHomeMovies = fetchDragivHomeMovies; +module.exports.fetchDragivMovieData = fetchDragivMovieData; +module.exports.calculateDragivMatchScore = calculateDragivMatchScore; +module.exports.fetchDragivByTmdbId = fetchDragivByTmdbId; +module.exports.updateDragivCache = updateDragivCache; diff --git a/API/Mainapi/routes/francetv.js b/API/Mainapi/routes/francetv.js new file mode 100644 index 0000000..27a2ad7 --- /dev/null +++ b/API/Mainapi/routes/francetv.js @@ -0,0 +1,793 @@ +/** + * France.TV (FTV) routes module. + * Extracted from server.js -- handles France.TV search, episode listing, + * and programme/video info extraction. + * + * Mounted at /api/ftv (paths below are relative to that prefix). + */ + +const express = require('express'); +const router = express.Router(); +const axios = require('axios'); +const cheerio = require('cheerio'); +const { CACHE_DIR, generateCacheKey } = require('../utils/cacheManager'); + +// =========================================================================================== +// ===== FRANCE.TV (FTV) SOURCE — Recherche + épisodes d'une série/collection ===== +// =========================================================================================== + +const FTV_BASE = 'https://www.france.tv'; + +// --- FTV: Cache du next-action hash (TTL 30 min) --- +let ftvNextActionHash = null; +let ftvNextActionExpiry = 0; + +// Headers complets pour simuler un vrai navigateur Chrome sur france.tv +const FTV_BROWSER_HEADERS = { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36', + 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8', + 'Accept-Language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7', + 'Accept-Encoding': 'gzip, deflate, br, zstd', + 'Cache-Control': 'no-cache', + 'Pragma': 'no-cache', + 'Sec-Ch-Ua': '"Chromium";v="131", "Not_A Brand";v="24"', + 'Sec-Ch-Ua-Mobile': '?0', + 'Sec-Ch-Ua-Platform': '"Windows"', + 'Sec-Fetch-Dest': 'document', + 'Sec-Fetch-Mode': 'navigate', + 'Sec-Fetch-Site': 'none', + 'Sec-Fetch-User': '?1', + 'Upgrade-Insecure-Requests': '1', +}; + +// --------------------------------------------------------------------------- +// Dependencies injected via configure() +// --------------------------------------------------------------------------- +let getFromCacheWithExpiration; +let saveToCache; + +/** + * Inject runtime dependencies that still live in server.js. + */ +function configure(deps) { + if (deps.getFromCacheWithExpiration) getFromCacheWithExpiration = deps.getFromCacheWithExpiration; + if (deps.saveToCache) saveToCache = deps.saveToCache; +} + +// --------------------------------------------------------------------------- +// getFtvNextActionHash -- dynamically retrieve the Next.js server action hash +// --------------------------------------------------------------------------- +/** + * Récupère dynamiquement le hash next-action depuis la page /recherche/ + * Ce hash change à chaque redéploiement de france.tv (Next.js Server Actions). + * + * Étapes : + * 1. GET https://www.france.tv/recherche/ + * 2. Trouver le <script src="/_next/static/chunks/app/recherche/page-XXXX.js"> + * 3. GET ce fichier JS + * 4. Extraire le hash de createServerReference("HASH", ...) + * + * Retente jusqu'à 3 fois en cas d'échec (connexion directe, sans proxy). + */ +async function getFtvNextActionHash() { + const now = Date.now(); + if (ftvNextActionHash && now < ftvNextActionExpiry) { + return ftvNextActionHash; + } + + const MAX_RETRIES = 3; + + for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) { + console.log(`[FTV] Fetching next-action hash (attempt ${attempt}/${MAX_RETRIES}, direct) ...`); + + try { + // Étape 1: Charger la page /recherche/ + const pageResponse = await axios.get(`${FTV_BASE}/recherche/`, { + headers: { ...FTV_BROWSER_HEADERS }, + proxy: false, + timeout: 15000, + maxRedirects: 5, + }); + + const html = pageResponse.data; + let hash = null; + + // Étape 2: Trouver le script chunk de la page recherche + // Pattern: <script src="/_next/static/chunks/app/recherche/page-XXXX.js" async=""> + const scriptMatch = html.match(/<script[^>]+src="(\/_next\/static\/chunks\/app\/recherche\/page-[^"]+\.js)"/); + + if (scriptMatch) { + const scriptUrl = `${FTV_BASE}${scriptMatch[1]}`; + console.log(`[FTV] Found recherche chunk: ${scriptUrl}`); + + // Étape 3: Télécharger le fichier JS + try { + const jsResponse = await axios.get(scriptUrl, { + headers: { + 'User-Agent': FTV_BROWSER_HEADERS['User-Agent'], + 'Accept': '*/*', + 'Accept-Language': 'fr-FR,fr;q=0.9', + 'Accept-Encoding': 'gzip, deflate, br, zstd', + 'Referer': `${FTV_BASE}/recherche/`, + 'Sec-Ch-Ua': FTV_BROWSER_HEADERS['Sec-Ch-Ua'], + 'Sec-Ch-Ua-Mobile': '?0', + 'Sec-Ch-Ua-Platform': '"Windows"', + 'Sec-Fetch-Dest': 'script', + 'Sec-Fetch-Mode': 'no-cors', + 'Sec-Fetch-Site': 'same-origin', + }, + proxy: false, + timeout: 15000, + }); + + const jsCode = jsResponse.data; + + // Étape 4: Extraire le hash de createServerReference("HASH", ...) + const serverRefMatch = jsCode.match(/createServerReference\)\s*\(\s*"([a-f0-9]{40,})"/); + if (serverRefMatch) { + hash = serverRefMatch[1]; + console.log(`[FTV] Found next-action hash via createServerReference: ${hash}`); + } + + // Fallback: chercher aussi le pattern searchAction + if (!hash) { + const searchActionMatch = jsCode.match(/"([a-f0-9]{40,})"[^]*?"searchAction"/); + if (searchActionMatch) { + hash = searchActionMatch[1]; + console.log(`[FTV] Found next-action hash via searchAction: ${hash}`); + } + } + } catch (jsErr) { + console.error(`[FTV] Error fetching JS chunk: ${jsErr.message}`); + } + } else { + console.warn('[FTV] Could not find recherche page chunk script tag'); + } + + // Fallback: chercher directement dans le HTML + if (!hash) { + const actionIdMatch = html.match(/\$ACTION_ID_([a-f0-9]{40,})/); + if (actionIdMatch) { + hash = actionIdMatch[1]; + console.log(`[FTV] Found next-action hash via $ACTION_ID_ fallback: ${hash}`); + } + } + + if (hash) { + ftvNextActionHash = hash; + ftvNextActionExpiry = now + 30 * 60 * 1000; // Cache 30 min + return hash; + } + + console.warn(`[FTV] Attempt ${attempt}: could not extract hash from page content`); + } catch (err) { + console.error(`[FTV] Attempt ${attempt} failed (direct): ${err.response?.status || err.message}`); + if (attempt < MAX_RETRIES) { + // Petit délai avant de retry avec un autre proxy + await new Promise(r => setTimeout(r, 500)); + } + } + } + + console.warn('[FTV] Could not extract next-action hash after all retries'); + return null; +} + +// --------------------------------------------------------------------------- +// POST /search +// Body: { "query": "ninjago" } +// Recherche sur france.tv et renvoie les programmes (séries/collections) et vidéos individuelles. +// --------------------------------------------------------------------------- +router.post('/search', async (req, res) => { + try { + const { query } = req.body; + if (!query || typeof query !== 'string' || !query.trim()) { + return res.status(400).json({ success: false, error: 'Le paramètre "query" est requis' }); + } + + const searchTerm = query.trim(); + + // Check cache (1h expiration for search) + const cacheKey = generateCacheKey(`ftv_search_${searchTerm.toLowerCase()}`); + const cached = await getFromCacheWithExpiration(CACHE_DIR.FTV, cacheKey, 1); + if (cached) { + console.log(`[FTV] Search cache hit for "${searchTerm}"`); + return res.json(cached); + } + + // Récupérer dynamiquement le hash next-action (change à chaque déploiement de france.tv) + const nextActionHash = await getFtvNextActionHash(); + if (!nextActionHash) { + return res.status(502).json({ success: false, error: 'Impossible de récupérer le hash de recherche France.tv. Le site a peut-être changé.' }); + } + + console.log(`[FTV] Using next-action hash: ${nextActionHash}`); + + const response = await axios.post(`${FTV_BASE}/recherche/`, [searchTerm], { + headers: { + 'accept': 'text/x-component', + 'accept-encoding': 'gzip, deflate, br, zstd', + 'accept-language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7', + 'cache-control': 'no-cache', + 'content-type': 'text/plain;charset=UTF-8', + 'next-action': nextActionHash, + 'next-router-state-tree': '%5B%22%22%2C%7B%22children%22%3A%5B%22recherche%22%2C%7B%22children%22%3A%5B%22__PAGE__%22%2C%7B%7D%2Cnull%2Cnull%5D%7D%2Cnull%2Cnull%5D%7D%2Cnull%2Cnull%2Ctrue%5D', + 'origin': FTV_BASE, + 'pragma': 'no-cache', + 'priority': 'u=1, i', + 'referer': `${FTV_BASE}/recherche/`, + 'sec-ch-ua': '"Chromium";v="131", "Not_A Brand";v="24"', + 'sec-ch-ua-mobile': '?0', + 'sec-ch-ua-platform': '"Windows"', + 'sec-fetch-dest': 'empty', + 'sec-fetch-mode': 'cors', + 'sec-fetch-site': 'same-origin', + 'user-agent': FTV_BROWSER_HEADERS['User-Agent'], + }, + proxy: false, + timeout: 15000, + validateStatus: () => true, + }); + + console.log(`[FTV] Search response status: ${response.status}`); + const text = typeof response.data === 'string' ? response.data : JSON.stringify(response.data); + console.log(`[FTV] Response text length: ${text.length}`); + + // Si 404, le hash a expiré entre-temps, forcer un refresh + if (response.status === 404) { + console.warn('[FTV] Got 404 — next-action hash is stale, invalidating cache...'); + ftvNextActionHash = null; + ftvNextActionExpiry = 0; + return res.json({ success: true, programs: [], videos: [], error_hint: 'Hash expiré, réessayez' }); + } + + // Parse RSC streaming format: lines like "1:{...json...}" + const lines = text.split('\n'); + let searchData = null; + for (const line of lines) { + if (line.trim()) console.log(`[FTV] RSC Line prefix: ${line.substring(0, 10)}...`); + // Chercher la ligne de données — peut commencer par 1:, 2:, etc. + const dataMatch = line.match(/^(\d+):\s*(\{.+)/); + if (dataMatch) { + console.log(`[FTV] Found data line starting with ${dataMatch[1]}: (length ${line.length})`); + try { + const parsed = JSON.parse(dataMatch[2]); + // Le résultat de recherche contient taxonomy et/ou video + if (parsed.taxonomy || parsed.video) { + searchData = parsed; + console.log(`[FTV] Parsed success. Taxonomy items: ${parsed.taxonomy ? parsed.taxonomy.length : 0}, Videos: ${parsed.video ? parsed.video.length : 0}`); + break; + } + } catch (e) { + console.error(`[FTV] JSON Parse error on line ${dataMatch[1]}:: ${e.message}`); + } + } + } + + if (!searchData) { + console.log('[FTV] No searchData found in RSC response lines.'); + // Log premiers 500 chars pour debug + console.log(`[FTV] Response preview: ${text.substring(0, 500)}`); + return res.json({ success: true, programs: [], videos: [] }); + } + + // Extract programs from taxonomy array + const programs = (searchData.taxonomy || []) + .filter(item => item.content && item.content.url) + .map(item => ({ + title: item.content.title || '', + description: item.content.description || '', + url: `${FTV_BASE}${item.content.url}`, + thumbnail: item.content.thumbnail?.x2 || item.content.thumbnail?.x1 || null, + type: item.content.type || 'program', // "program" or "collection" + channel: item.content.channel || null, + category: item.content.category?.label || null, + program_id: item.tracking?.program_id || null, + })); + + // Extract videos (individual episodes / films) + const videos = (searchData.video || []) + .filter(item => item.content && item.content.url) + .map(item => ({ + title: item.content.title || '', + titleLeading: item.content.titleLeading || '', + description: item.content.description || '', + url: `${FTV_BASE}${item.content.url}`, + thumbnail: item.content.thumbnail?.x2 || item.content.thumbnail?.x1 || null, + type: item.content.type || 'video', + channel: item.content.channel || null, + category: item.content.category?.label || null, + id: item.content.id || null, + season: item.content.title?.match(/^S(\d+)/)?.[1] || null, + episode: item.content.title?.match(/E(\d+)/)?.[1] || null, + csa: item.content.csa || null, + caption: item.content.caption || null, + })); + + console.log(`[FTV] Search results - Programs: ${programs.length}, Videos: ${videos.length}`); + const searchResult = { success: true, programs, videos }; + await saveToCache(CACHE_DIR.FTV, cacheKey, searchResult); + return res.json(searchResult); + + } catch (error) { + console.error('[FTV] Search error:', error.message); + return res.status(500).json({ success: false, error: error.message }); + } +}); + +// --------------------------------------------------------------------------- +// GET /episodes?url=https://www.france.tv/france-3/lego-ninjago +// Récupère la page d'un programme et extrait tous les épisodes disponibles. +// Retourne la liste des épisodes avec leur URL d'extraction. +// --------------------------------------------------------------------------- +router.get('/episodes', async (req, res) => { + try { + const { url } = req.query; + if (!url || !url.includes('france.tv')) { + return res.status(400).json({ success: false, error: 'URL france.tv requise' }); + } + + // Check cache (4h expiration for episodes) + const epCacheKey = generateCacheKey(`ftv_episodes_${url}`); + const epCached = await getFromCacheWithExpiration(CACHE_DIR.FTV, epCacheKey, 4); + if (epCached) { + console.log(`[FTV] Episodes cache hit for ${url}`); + return res.json(epCached); + } + + const response = await axios.get(url, { + headers: { ...FTV_BROWSER_HEADERS }, + proxy: false, + timeout: 15000, + }); + + const html = response.data; + const episodes = []; + const seen = new Set(); + + // Extract JSON data from self.__next_f.push() calls in the HTML + const scriptRegex = /self\.__next_f\.push\(\[1,"(.*?)"\]\)/gs; + let scriptMatch; + let fullJsonText = ''; + + while ((scriptMatch = scriptRegex.exec(html)) !== null) { + // Unescape the string content + let chunk = scriptMatch[1]; + try { + // The content is JSON-escaped (\\", \\n, \\u00xx, etc.) + chunk = JSON.parse(`"${chunk}"`); + } catch { /* use as-is */ } + fullJsonText += chunk; + } + + // Most reliable: extract via Cheerio + script parsing + const $ = cheerio.load(html); + + // Gather ALL text from __next_f scripts + let allScriptData = ''; + $('script').each((_, el) => { + const raw = $(el).html() || ''; + if (raw.includes('__next_f')) { + const pushMatch = raw.match(/self\.__next_f\.push\(\[1,"(.*)"\]\)/s); + if (pushMatch) { + try { + allScriptData += JSON.parse(`"${pushMatch[1]}"`); + } catch { + allScriptData += pushMatch[1]; + } + } + } + }); + + // Now parse the concatenated text to find video objects + // Split by "variant" which marks the end of each card object + const cardChunks = allScriptData.split('"variant"'); + + for (const chunk of cardChunks) { + // Check if this chunk has a video-type content with a .html URL + if (!chunk.includes('"type":"video"') && !chunk.includes('"type": "video"')) continue; + + const urlMatch = chunk.match(/"url"\s*:\s*"(\/[^"]+\.html)"/); + if (!urlMatch) continue; + + const epUrl = urlMatch[1]; + if (seen.has(epUrl)) continue; + seen.add(epUrl); + + // Extract fields from this chunk + const titleMatch = chunk.match(/"title"\s*:\s*"([^"]+)"/); + const leadMatch = chunk.match(/"titleLeading"\s*:\s*"([^"]+)"/); + const descMatch = chunk.match(/"description"\s*:\s*"([^"]*(?:\\.[^"]*)*)"/); + const thumbMatch = chunk.match(/"x2"\s*:\s*"(https:\/\/medias\.france\.tv\/[^"]+)"/); + const idMatch = chunk.match(/"id"\s*:\s*(\d{4,})/); + const csaMatch = chunk.match(/"csa"\s*:\s*"([^"]+)"/); + + const title = titleMatch ? titleMatch[1] : ''; + const seasonMatch = title.match(/^S(\d+)/); + const episodeMatch = title.match(/E(\d+)/); + + let desc = descMatch ? descMatch[1] : ''; + try { desc = JSON.parse(`"${desc}"`); } catch { /* use as-is */ } + + episodes.push({ + title: title, + program: leadMatch ? leadMatch[1] : '', + description: desc, + url: `${FTV_BASE}${epUrl}`, + thumbnail: thumbMatch ? thumbMatch[1] : null, + id: idMatch ? parseInt(idMatch[1]) : null, + season: seasonMatch ? parseInt(seasonMatch[1]) : null, + episode: episodeMatch ? parseInt(episodeMatch[1]) : null, + csa: csaMatch ? csaMatch[1] : null, + }); + } + + // Sort by season then episode + episodes.sort((a, b) => { + if (a.season !== b.season) return (a.season || 0) - (b.season || 0); + return (a.episode || 0) - (b.episode || 0); + }); + + const episodesResult = { + success: true, + program_url: url, + total: episodes.length, + episodes, + }; + await saveToCache(CACHE_DIR.FTV, epCacheKey, episodesResult); + return res.json(episodesResult); + + } catch (error) { + console.error('[FTV] Episodes error:', error.message); + return res.status(500).json({ success: false, error: error.message }); + } +}); + +// --------------------------------------------------------------------------- +// GET /info?url=https://www.france.tv/france-5/le-monde-de-jamy/... +// Récupère les informations d'une page film (player) ou série (programme). +// Détecte automatiquement le type de page et retourne les données structurées. +// --------------------------------------------------------------------------- +router.get('/info', async (req, res) => { + try { + const { url } = req.query; + if (!url || !url.includes('france.tv')) { + return res.status(400).json({ success: false, error: 'URL france.tv requise' }); + } + + // Check cache (4h expiration for info) + const infoCacheKey = generateCacheKey(`ftv_info_${url}`); + const infoCached = await getFromCacheWithExpiration(CACHE_DIR.FTV, infoCacheKey, 4); + if (infoCached) { + console.log(`[FTV] Info cache hit for ${url}`); + return res.json(infoCached); + } + + const response = await axios.get(url, { + headers: { ...FTV_BROWSER_HEADERS }, + proxy: false, + timeout: 15000, + }); + + const html = response.data; + + // ---- Extract all RSC data from self.__next_f.push() calls ---- + const pushRegex = /self\.__next_f\.push\(\[1,\s*"((?:[^"\\]|\\.)*)"\]\)/g; + let allRscText = ''; + let pushMatch; + while ((pushMatch = pushRegex.exec(html)) !== null) { + let chunk = pushMatch[1]; + try { chunk = JSON.parse(`"${chunk}"`); } catch { /* use as-is */ } + allRscText += chunk; + } + + // ---- Detect page type ---- + const isPlayer = /"pageType"\s*:\s*"player"/.test(allRscText) || /data-template-id="player-replay"/.test(html); + const isProgramme = /"pageType"\s*:\s*"programme"/.test(allRscText) || /data-template-id="programme"/.test(html); + + if (isPlayer) { + // ===== FILM / VIDEO PAGE ===== + const result = { success: true, type: 'video' }; + + // Extract title - try JSON-LD VideoObject first + const ldJsonRegex = /<script[^>]*type="application\/ld\+json"[^>]*>([\s\S]*?)<\/script>/g; + let ldMatch; + while ((ldMatch = ldJsonRegex.exec(html)) !== null) { + try { + const ld = JSON.parse(ldMatch[1]); + if (ld['@type'] === 'VideoObject') { + result.title = ld.name || ''; + result.description = ld.description || ''; + result.thumbnail = (ld.thumbnailUrl && ld.thumbnailUrl[0]) || ''; + result.duration = ld.duration || ''; + result.director = ld.director ? (ld.director.name || ld.director) : ''; + result.uploadDate = ld.uploadDate || ''; + result.expires = ld.expires || ''; + break; + } + } catch { /* skip invalid JSON-LD */ } + } + + // Extract additional fields from RSC data + const csaMatch = allRscText.match(/"csaCode"\s*:\s*"([^"]+)"/); + result.csa = csaMatch ? csaMatch[1] : null; + + const channelMatch = allRscText.match(/"broadcastChannel"\s*:\s*"([^"]+)"/); + result.channel = channelMatch ? channelMatch[1] : null; + if (!result.channel) { + const ch2 = allRscText.match(/"channel"\s*:\s*"([^"]+)"/); + result.channel = ch2 ? ch2[1] : null; + } + + // Extract title from RSC if not from JSON-LD + if (!result.title) { + const titleMatch = allRscText.match(/"pageName"\s*:\s*"([^"]+)"/); + result.title = titleMatch ? titleMatch[1].replace(/_/g, ' ') : ''; + } + + // Extract description from RSC if not from JSON-LD + if (!result.description) { + const descMatch = allRscText.match(/"description"\s*:\s*"((?:[^"\\]|\\.)*)"/); + if (descMatch) { + try { result.description = JSON.parse(`"${descMatch[1]}"`); } + catch { result.description = descMatch[1]; } + } + } + + // Extract thumbnail from RSC if not from JSON-LD + if (!result.thumbnail) { + const thumbMatch = allRscText.match(/"vignette_16x9"[^}]*?"1800"\s*:\s*"([^"]+)"/); + result.thumbnail = thumbMatch ? thumbMatch[1] : null; + if (!result.thumbnail) { + const thumbAlt = allRscText.match(/https:\/\/medias\.france\.tv\/[^"]+\.jpg/); + result.thumbnail = thumbAlt ? thumbAlt[0] : null; + } + } + + // Extract duration in seconds from RSC if available + const durationSecMatch = allRscText.match(/"duration"\s*:\s*(\d{2,})/); + result.durationSeconds = durationSecMatch ? parseInt(durationSecMatch[1]) : null; + + // Extract program name + const progMatch = allRscText.match(/"programName"\s*:\s*"([^"]+)"/); + result.program = progMatch ? progMatch[1].replace(/_/g, ' ') : null; + + // Extract categories + const catMatch = allRscText.match(/"categories"\s*:\s*\["([^"]+)"\]/); + result.category = catMatch ? catMatch[1] : null; + + await saveToCache(CACHE_DIR.FTV, infoCacheKey, result); + return res.json(result); + } else if (isProgramme) { + // ===== SÉRIE / PROGRAMME PAGE ===== + const result = { success: true, type: 'programme' }; + + // Extract programme title from <title> tag or RSC + const titleTagMatch = html.match(/<title[^>]*>([^<]+)<\/title>/); + result.title = titleTagMatch ? titleTagMatch[1].replace(/ - (Regarder|France \d|France\.tv).*$/i, '').trim() : ''; + + // Extract description + const metaDescMatch = html.match(/<meta\s+name="description"\s+content="([^"]+)"/); + result.description = metaDescMatch ? metaDescMatch[1] : ''; + + // Try to get full description from RSC if meta one is truncated + if (result.description.endsWith('...') || result.description.endsWith('\u2026') || result.description.length < 150) { + const rscDescMatch = allRscText.match(/"description"\s*:\s*"((?:[^"\\]|\\.)*)"/); + if (rscDescMatch) { + try { + const parsedDesc = JSON.parse(`"${rscDescMatch[1]}"`); + if (parsedDesc.length > result.description.length) { + result.description = parsedDesc; + } + } catch { + if (rscDescMatch[1].length > result.description.length) { + result.description = rscDescMatch[1]; + } + } + } + } + + // Extract thumbnail from og:image + const ogImageMatch = html.match(/<meta\s+property="og:image"\s+content="([^"]+)"/); + result.thumbnail = ogImageMatch ? ogImageMatch[1] : null; + + // Extract channel + const channelMatch = allRscText.match(/"channel"\s*:\s*"([^"]+)"/); + result.channel = channelMatch ? channelMatch[1] : null; + + // Extract program_id + const progIdMatch = allRscText.match(/"program_id"\s*:\s*"(\d+)"/); + result.programId = progIdMatch ? progIdMatch[1] : null; + + // Extract category + const catMatch = allRscText.match(/"category"\s*:\s*"([^"]+)"/); + result.category = catMatch ? catMatch[1] : null; + + // ---- Extract cast/crew from RSC text ---- + const directorMatch = allRscText.match(/R\u00e9alis\u00e9 par\s*:\s*([^"\\]+)/); + result.director = directorMatch ? directorMatch[1].trim() : null; + + const castMatch = allRscText.match(/Avec\s*:\s*([^"\\]+)/); + result.cast = castMatch ? castMatch[1].trim() : null; + + // ---- Extract seasons and episodes ---- + const seasons = []; + const $ = cheerio.load(html); + + // Gather ALL text from __next_f scripts + let allScriptData = ''; + $('script').each((_, el) => { + const raw = $(el).html() || ''; + if (raw.includes('__next_f')) { + const pm = raw.match(/self\.__next_f\.push\(\[1,"(.*)"\]\)/s); + if (pm) { + try { allScriptData += JSON.parse(`"${pm[1]}"`); } + catch { allScriptData += pm[1]; } + } + } + }); + + // More robust approach: split by "Saison" markers and extract episode blocks + const seasonSplits = allScriptData.split(/(?=\["Saison\s+\d+")/); + + for (const block of seasonSplits) { + const nameMatch = block.match(/^\["(Saison\s+\d+)"/); + if (!nameMatch) continue; + + const seasonName = nameMatch[1]; + const seasonNum = parseInt(seasonName.match(/\d+/)[0]); + const blockEpisodes = []; + const blockSeen = new Set(); + + // Split by "variant" to find individual episode cards + const cardChunks = block.split('"variant"'); + + for (const chunk of cardChunks) { + if (!chunk.includes('"type":"video"')) continue; + + const urlMatch = chunk.match(/"url"\s*:\s*"(\/[^"]+\.html)"/); + if (!urlMatch) continue; + + const epUrl = urlMatch[1]; + if (blockSeen.has(epUrl)) continue; + blockSeen.add(epUrl); + + const titleMatch = chunk.match(/"title"\s*:\s*"([^"]+)"/); + const leadMatch = chunk.match(/"titleLeading"\s*:\s*"([^"]+)"/); + const descMatch = chunk.match(/"description"\s*:\s*"((?:[^"\\]|\\.)*)"/); + const thumbMatch = chunk.match(/"x2"\s*:\s*"(https:\/\/[^"]+)"/); + const idMatch = chunk.match(/"content_id"\s*:\s*(\d+)/); + let idMatch2; + if (!idMatch) { + idMatch2 = chunk.match(/"id"\s*:\s*(\d{4,})/); + } + const csaMatch = chunk.match(/"csa"\s*:\s*"([^"]+)"/); + const durationMatch = chunk.match(/"duration"\s*:\s*"([^"]+)"/); + const vfIdMatch = chunk.match(/"video_factory_id"\s*:\s*"([0-9a-f-]{36})"/); + + const title = titleMatch ? titleMatch[1] : ''; + const epNumMatch = title.match(/E(\d+)/); + + let desc = descMatch ? descMatch[1] : ''; + try { desc = JSON.parse(`"${desc}"`); } catch { /* use as-is */ } + + blockEpisodes.push({ + title, + program: leadMatch ? leadMatch[1] : '', + description: desc, + url: `${FTV_BASE}${epUrl}`, + thumbnail: thumbMatch ? thumbMatch[1] : null, + contentId: (idMatch ? parseInt(idMatch[1]) : (idMatch2 ? parseInt(idMatch2[1]) : null)), + videoId: vfIdMatch ? vfIdMatch[1] : null, + season: seasonNum, + episode: epNumMatch ? parseInt(epNumMatch[1]) : null, + csa: csaMatch ? csaMatch[1] : null, + duration: durationMatch ? durationMatch[1] : null, + }); + } + + // Sort episodes by episode number + blockEpisodes.sort((a, b) => (a.episode || 0) - (b.episode || 0)); + + if (blockEpisodes.length > 0) { + seasons.push({ + name: seasonName, + number: seasonNum, + episodeCount: blockEpisodes.length, + episodes: blockEpisodes, + }); + } + } + + // If no seasons found with the split approach, try the card-based approach from /episodes + if (seasons.length === 0) { + const fallbackEpisodes = []; + const fallbackSeen = new Set(); + const cardChunks = allScriptData.split('"variant"'); + + for (const chunk of cardChunks) { + if (!chunk.includes('"type":"video"')) continue; + const urlMatch = chunk.match(/"url"\s*:\s*"(\/[^"]+\.html)"/); + if (!urlMatch) continue; + const epUrl = urlMatch[1]; + if (fallbackSeen.has(epUrl)) continue; + fallbackSeen.add(epUrl); + + const titleMatch = chunk.match(/"title"\s*:\s*"([^"]+)"/); + const leadMatch = chunk.match(/"titleLeading"\s*:\s*"([^"]+)"/); + const descMatch = chunk.match(/"description"\s*:\s*"((?:[^"\\]|\\.)*)"/); + const thumbMatch = chunk.match(/"x2"\s*:\s*"(https:\/\/[^"]+)"/); + const idMatch = chunk.match(/"content_id"\s*:\s*(\d+)/) || chunk.match(/"id"\s*:\s*(\d{4,})/); + const vfIdMatch = chunk.match(/"video_factory_id"\s*:\s*"([0-9a-f-]{36})"/); + const durationMatch = chunk.match(/"duration"\s*:\s*"([^"]+)"/); + const csaMatch = chunk.match(/"csa"\s*:\s*"([^"]+)"/); + const title = titleMatch ? titleMatch[1] : ''; + + let desc = descMatch ? descMatch[1] : ''; + try { desc = JSON.parse(`"${desc}"`); } catch {} + + const seasonMatch = title.match(/S(\d+)/); + const epMatch = title.match(/E(\d+)/); + + fallbackEpisodes.push({ + title, + program: leadMatch ? leadMatch[1] : '', + description: desc, + url: `${FTV_BASE}${epUrl}`, + thumbnail: thumbMatch ? thumbMatch[1] : null, + contentId: idMatch ? parseInt(idMatch[1]) : null, + videoId: vfIdMatch ? vfIdMatch[1] : null, + season: seasonMatch ? parseInt(seasonMatch[1]) : null, + episode: epMatch ? parseInt(epMatch[1]) : null, + csa: csaMatch ? csaMatch[1] : null, + duration: durationMatch ? durationMatch[1] : null, + }); + } + + if (fallbackEpisodes.length > 0) { + // Group by season + const seasonMap = {}; + for (const ep of fallbackEpisodes) { + const sNum = ep.season || 1; + if (!seasonMap[sNum]) seasonMap[sNum] = []; + seasonMap[sNum].push(ep); + } + for (const [sNum, eps] of Object.entries(seasonMap)) { + eps.sort((a, b) => (a.episode || 0) - (b.episode || 0)); + seasons.push({ + name: `Saison ${sNum}`, + number: parseInt(sNum), + episodeCount: eps.length, + episodes: eps, + }); + } + seasons.sort((a, b) => a.number - b.number); + } + } + + result.seasons = seasons; + result.totalEpisodes = seasons.reduce((sum, s) => sum + s.episodeCount, 0); + + await saveToCache(CACHE_DIR.FTV, infoCacheKey, result); + return res.json(result); + + } else { + // Unknown page type + return res.json({ + success: false, + error: 'Type de page non reconnu (ni player ni programme)', + hint: 'Vérifiez que l\'URL pointe vers un film/vidéo ou une série sur france.tv', + }); + } + + } catch (error) { + console.error('[FTV] Info error:', error.message); + return res.status(500).json({ success: false, error: error.message }); + } +}); + +console.log('FTV (france.tv) source loaded'); + +module.exports = router; +module.exports.configure = configure; +module.exports.getFtvNextActionHash = getFtvNextActionHash; diff --git a/API/Mainapi/routes/frenchstream.js b/API/Mainapi/routes/frenchstream.js new file mode 100644 index 0000000..ec3a500 --- /dev/null +++ b/API/Mainapi/routes/frenchstream.js @@ -0,0 +1,666 @@ +/** + * FrenchStream helper module. + * Extracted from server.js -- provides scraping functions for FrenchStream. + * This is NOT an Express router; it exports plain functions used by tmdb.js. + */ + +const cheerio = require('cheerio'); +const axios = require('axios'); + +const FRENCHSTREAM_BASE_URL = 'https://frenchstream.food'; + +// --------------------------------------------------------------------------- +// Dependencies injected via configure() +// --------------------------------------------------------------------------- +let makeRequestWithCorsFallback; +let axiosFrenchStreamRequest; +let findTvSeriesOnTMDB; + +/** + * Inject runtime dependencies that still live in server.js. + */ +function configure(deps) { + if (deps.makeRequestWithCorsFallback) makeRequestWithCorsFallback = deps.makeRequestWithCorsFallback; + if (deps.axiosFrenchStreamRequest) axiosFrenchStreamRequest = deps.axiosFrenchStreamRequest; + if (deps.findTvSeriesOnTMDB) findTvSeriesOnTMDB = deps.findTvSeriesOnTMDB; +} + +// --------------------------------------------------------------------------- +// getFrenchStreamMovie +// --------------------------------------------------------------------------- +async function getFrenchStreamMovie(imdbId) { + try { + const searchUrl = `${FRENCHSTREAM_BASE_URL}/xfsearch/${imdbId}`; + + const searchResponse = await makeRequestWithCorsFallback(searchUrl, { timeout: 5000, decompress: true }); + const $search = cheerio.load(searchResponse.data); + + // Find the movie link in search results + let movieLink = null; + $search('.short').each((index, element) => { + const $element = $search(element); + const link = $element.find('.short-poster').attr('href'); + if (link && !movieLink) { + movieLink = link; + } + }); + + if (!movieLink) { + return { error: 'Movie not found on FrenchStream' }; + } + + const movieResponse = await makeRequestWithCorsFallback(movieLink, { timeout: 5000, decompress: true }); + const $movie = cheerio.load(movieResponse.data); + + // Extract iframe src using the specified XPath logic + let iframeSrc = $movie('body > div:nth-child(2) > div:nth-child(1) > div > article > div:nth-child(1) > div > div > div:nth-child(1) > div > div > div > iframe').attr('src'); + + if (!iframeSrc) { + // Fallback selectors + iframeSrc = $movie('iframe[src*="frenchcloud.cam"]').attr('src'); + } + + if (!iframeSrc) { + // Try finding it in the tabs content if the structure is slightly different + iframeSrc = $movie('.tabs-content iframe').attr('src'); + } + + if (!iframeSrc) { + return { error: 'Iframe not found on movie page' }; + } + + // Fetch the iframe content (FrenchCloud page) + const iframeResponse = await axios.get(iframeSrc, { + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', + 'Referer': `${FRENCHSTREAM_BASE_URL}/` + }, + timeout: 15000, + decompress: true + }); + + const $iframe = cheerio.load(iframeResponse.data); + const playerLinks = []; + + $iframe('._player-mirrors li').each((index, element) => { + const $element = $iframe(element); + const dataLink = $element.attr('data-link'); + const playerName = $element.text().trim(); + const isHD = $element.hasClass('fullhd'); + + // Skip links that contain frenchcloud.cam (often the embed itself) + if (!dataLink || dataLink.includes('frenchcloud.cam')) { + return; + } + + // Add protocol to links that start with // + let formattedLink = dataLink; + if (dataLink.startsWith('//')) { + formattedLink = 'https:' + dataLink; + } + + playerLinks.push({ + player: playerName, + link: formattedLink, + is_hd: isHD + }); + }); + + return { + iframe_src: iframeSrc, + player_links: playerLinks + }; + + } catch (error) { + return { error: `Failed to fetch movie data: ${error.message}` }; + } +} + +// --------------------------------------------------------------------------- +// getFrenchStreamSeries +// --------------------------------------------------------------------------- +async function getFrenchStreamSeries(id) { + try { + const targetUrl = `${FRENCHSTREAM_BASE_URL}/xfsearch/${id}`; + + const response = await makeRequestWithCorsFallback(targetUrl, { + timeout: 5000, + decompress: true + }); + + const $ = cheerio.load(response.data); + + // Find all series in the search results + const seriesList = []; + $('.short').each(async (index, element) => { + try { + const $element = $(element); + const link = $element.find('.short-poster').attr('href'); + const title = $element.find('.short-title').text().trim(); + + // Skip items that don't have "saison" in their title + if (!title.toLowerCase().includes('saison')) { + return; + } + + const posterImg = $element.find('.short-poster img').attr('src'); + const poster = posterImg ? (posterImg.startsWith('/') ? `${FRENCHSTREAM_BASE_URL}${posterImg}` : posterImg) : null; + const audioType = $element.find('.film-verz a').text().trim(); + + // Extract episode count if available + let episodeCount = null; + const episodeElement = $element.find('.mli-eps i'); + if (episodeElement.length > 0) { + episodeCount = parseInt(episodeElement.text().trim()); + } + + seriesList.push({ + title, + link, + poster, + audio_type: audioType, + episode_count: episodeCount, + seasons: [] // Will be populated later for each series + }); + } catch (error) { + console.error(`Error parsing series element:`, error); + } + }); + + return seriesList; + } catch (error) { + return { error: `Erreur lors de la recuperation des series: ${error.message}` }; + } +} + +// --------------------------------------------------------------------------- +// getFrenchStreamSeriesDetails +// --------------------------------------------------------------------------- +async function getFrenchStreamSeriesDetails(seriesUrl, originalTitle) { + try { + // Convertir les anciens domaines FrenchStream vers le domaine actif. + const targetUrl = seriesUrl + .replace('fr.french-stream.sbs', 'frenchstream.food') + .replace('french-stream.gratis', 'frenchstream.food') + .replace('french-stream.legal', 'frenchstream.food') + .replace('french-stream.one', 'frenchstream.food'); + + const response = await makeRequestWithCorsFallback(targetUrl, { + timeout: 5000, + decompress: true + }); + + const $ = cheerio.load(response.data); + + const seriesTitle = originalTitle; + + // Extract release date from <span class="release"> 2023 - </span> + let releaseDate = null; + + // Essayer plusieurs selecteurs possibles pour la date de sortie + const releaseSelectors = [ + 'article div.fmain div.fleft div.poster span.release', + 'span.release', + 'article div.container div div span.release', + 'div.poster span.release', + '.release' + ]; + + // Essayer chaque selecteur jusqu'a ce qu'on trouve la date + for (const selector of releaseSelectors) { + const releaseElement = $(selector); + if (releaseElement.length > 0) { + const releaseDateText = releaseElement.text().trim(); + // Extract year from text like "2023 - " + const yearMatch = releaseDateText.match(/(\d{4})/); + if (yearMatch) { + releaseDate = yearMatch[1]; + break; + } + } + } + + // Si toujours pas trouve, chercher dans toute la page + if (!releaseDate) { + // Chercher tout texte contenant 4 chiffres qui pourrait etre une annee + const allText = $('body').text(); + const yearMatches = allText.match(/\b(19\d{2}|20\d{2})\b/g); + if (yearMatches && yearMatches.length > 0) { + // Prendre la premiere annee trouvee dans la page + releaseDate = yearMatches[0]; + } + } + + // Extract summary from <p> inside #s-desc element + let summary = null; + + // Essayer differentes approches pour trouver le resume + const summarySelectorApproaches = [ + // Approche 1: XPath complet converti en selecteur CSS + () => { + const summaryElement = $('body > div:nth-child(2) > div > div > article > div:nth-child(3) > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > p:nth-child(2)'); + return summaryElement.length > 0 ? summaryElement.text().trim() : null; + }, + + // Approche 2: Recherche dans la zone principale du contenu + () => { + const mainContent = $('.finfo, .fcontent, .fdesc, #s-desc'); + if (mainContent.length > 0) { + const paragraphs = mainContent.find('p'); + // Recuperer le paragraphe le plus long (probablement le resume) + let longestText = ""; + paragraphs.each((i, el) => { + const text = $(el).text().trim(); + if (text.length > longestText.length && + !text.includes("Resume du film") && + !text.includes("streaming complet")) { + longestText = text; + } + }); + return longestText.length > 100 ? longestText : null; + } + return null; + }, + + // Approche 3: Recherche par mots-cles + () => { + // Mots-cles qui indiquent probablement un resume + const summaryKeywords = ["histoire", "serie", "saison", "episode", "personnage", "aventure"]; + const paragraphs = $('p'); + let bestMatch = null; + let bestScore = 0; + + paragraphs.each((i, el) => { + const text = $(el).text().trim(); + if (text.length < 100) return; // Trop court pour etre un resume + + // Calculer un score base sur les mots-cles presents + let score = 0; + const lowerText = text.toLowerCase(); + summaryKeywords.forEach(keyword => { + if (lowerText.includes(keyword)) score++; + }); + + // Bonus pour la longueur (resumes typiquement plus longs) + score += Math.min(text.length / 200, 3); + + // Malus pour les textes generiques + if (text.includes("streaming") || text.includes("vostfr") || + text.includes("gratuit") || text.includes("Resume du film")) { + score -= 5; + } + + if (score > bestScore) { + bestScore = score; + bestMatch = text; + } + }); + + return bestScore > 2 ? bestMatch : null; + }, + + // Approche 4: Recherche directe du texte apres les divs de metadonnees + () => { + // Trouver une div qui contient la date de sortie, puis chercher un paragraphe apres + const releaseDiv = $('span.release').closest('div'); + if (releaseDiv.length > 0) { + // Chercher le premier paragraphe substantiel apres cette div + let currentElement = releaseDiv; + let found = false; + + // Parcourir jusqu'a 10 elements suivants + for (let i = 0; i < 10 && !found; i++) { + currentElement = currentElement.next(); + if (currentElement.length === 0) break; + + // Si c'est un paragraphe, verifier son contenu + if (currentElement.is('p')) { + const text = currentElement.text().trim(); + if (text.length > 100 && + !text.includes("Resume du film") && + !text.includes("streaming complet")) { + found = true; + return text; + } + } + + // Si c'est une div, chercher des paragraphes a l'interieur + const innerP = currentElement.find('p'); + if (innerP.length > 0) { + const text = innerP.first().text().trim(); + if (text.length > 100 && + !text.includes("Resume du film") && + !text.includes("streaming complet")) { + found = true; + return text; + } + } + } + } + return null; + } + ]; + + // Essayer chaque approche jusqu'a trouver un resume + for (const approach of summarySelectorApproaches) { + try { + const result = approach(); + if (result) { + summary = result; + break; + } + } catch (error) { + console.error(`Erreur lors de l'extraction du resume: ${error.message}`); + } + } + + // Derniere tentative: analyse du HTML brut + if (!summary) { + try { + const htmlContent = response.data; + + // Chercher le texte qui pourrait etre un resume apres des marqueurs communs + const resumeMarkers = [ + '<div class="fdesc">', + '<div id="s-desc">', + '<h2>Synopsis</h2>', + '<h3>Synopsis</h3>', + 'Synopsis :' + ]; + + for (const marker of resumeMarkers) { + const markerIndex = htmlContent.indexOf(marker); + if (markerIndex !== -1) { + // Chercher le premier paragraphe substantiel apres ce marqueur + const afterMarker = htmlContent.substring(markerIndex + marker.length); + const paragraphMatch = afterMarker.match(/<p[^>]*>([^<]{100,})<\/p>/); + + if (paragraphMatch && paragraphMatch[1]) { + summary = paragraphMatch[1].trim(); + break; + } + } + } + } catch (error) { + console.error(`Erreur lors de l'analyse du HTML brut: ${error.message}`); + } + } + + // Valider que le resume n'est pas un texte par defaut + if (summary && ( + summary.includes("Resume du film") || + summary.includes("streaming complet") || + summary.includes("vf et vostfr") || + summary.includes("vod gratuit sans limite") + )) { + summary = null; + } + + // Find series on TMDB using the extracted info + let tmdbData = null; + if (seriesTitle) { + // Pass the original title from FrenchStream; findTvSeriesOnTMDB will clean it + tmdbData = await findTvSeriesOnTMDB(seriesTitle, releaseDate, summary); + } + + // Find all seasons using the new structure + const seasons = []; + const seasonsContainer = $('.tab-content > .tab-pane'); // Updated selector + + seasonsContainer.each((seasonIndex, seasonElement) => { + try { + const $seasonElement = $(seasonElement); + const seasonId = $seasonElement.attr('id'); // e.g., season-1 + const seasonNumberMatch = seasonId ? seasonId.match(/\d+$/) : null; + const seasonNumber = seasonNumberMatch ? parseInt(seasonNumberMatch[0]) : seasonIndex + 1; + const seasonTitle = `Saison ${seasonNumber}`; + + const episodesMap = new Map(); // Use a map to group by episode number + + // Find all episodes in this season + const episodeElements = $seasonElement.find('ul li'); + + episodeElements.each((episodeIndex, episodeElement) => { + try { + const $episodeElement = $(episodeElement); + const episodeLink = $episodeElement.find('a').first(); + + // Extract episode info + const episodeNumStr = episodeLink.text().trim(); + const episodeNumMatch = episodeNumStr.match(/^\d+/); + const episodeNum = episodeNumMatch ? episodeNumMatch[0] : episodeNumStr; + + const episodeTitle = episodeLink.attr('data-title') || `Episode ${episodeNumStr}`; + const isVOSTFR = episodeTitle.includes('VOSTFR'); + const langKey = isVOSTFR ? 'vostfr' : 'vf'; + + // Get player links + const players = []; + $episodeElement.find('.mirrors a').each((playerIndex, playerElement) => { + const $playerElement = $(playerElement); + const playerName = $playerElement.text().trim(); + const playerLink = $playerElement.attr('data-link'); + + if (playerLink) { + players.push({ + name: playerName, + link: playerLink + }); + } + }); + + // Get or create the entry for this episode number + if (!episodesMap.has(episodeNum)) { + episodesMap.set(episodeNum, { + number: episodeNum, + versions: {} + }); + } + + // Add the current language version + episodesMap.get(episodeNum).versions[langKey] = { + title: episodeTitle, + players: players + }; + + } catch (error) { + console.error(`Error parsing episode element (Index ${episodeIndex}) in ${seriesUrl}:`, error.message); + } + }); + + // Convert map values to array and sort numerically by episode number + const episodes = Array.from(episodesMap.values()).sort((a, b) => { + const numA = parseInt(a.number); + const numB = parseInt(b.number); + if (isNaN(numA) || isNaN(numB)) return a.number.localeCompare(b.number); + return numA - numB; + }); + + seasons.push({ + number: seasonNumber, + title: seasonTitle, + episodes: episodes + }); + } catch (error) { + console.error(`Error parsing season element (ID ${seasonId || 'unknown'}) in ${seriesUrl}:`, error.message); + } + }); + + return { + title: seriesTitle, + release_date: releaseDate, + summary: summary, + tmdb_data: tmdbData, + seasons: seasons + }; + } catch (error) { + return { error: `Failed to fetch series details: ${error.message}` }; + } +} + +// --------------------------------------------------------------------------- +// extractSeriesInfo -- helper to extract base name and part number +// --------------------------------------------------------------------------- +const extractSeriesInfo = (title) => { + let baseName = title; + let partNumber = 1; // Default to part 1 + let seasonInfo = {}; // Store season range if present + + // Match "Part X (Saison Y - Z)" + const partMatch = title.match(/\s*Part\s+(\d+)\s*\(Saison\s+(\d+)\s*-\s*(\d+)\)/i); + if (partMatch) { + partNumber = parseInt(partMatch[1]); + seasonInfo = { + part: partNumber, + start: parseInt(partMatch[2]), + end: parseInt(partMatch[3]) + }; + // Remove the Part info from the base name + baseName = baseName.replace(/\s*Part\s+\d+\s*\(Saison\s+\d+\s*-\s*\d+\)/i, ''); + } + + // Remove trailing "- Saison X" + baseName = baseName.replace(/\s*-\s*Saison\s+\d+$/i, ''); + + // Remove potential year in parenthesis if not already removed by part info + baseName = baseName.replace(/\s*\(\d{4}\)/, ''); + + return { baseName: baseName.trim(), partNumber, seasonInfo }; +}; + +// --------------------------------------------------------------------------- +// mergeSeriesParts -- merge multiple parts of a series +// --------------------------------------------------------------------------- +const mergeSeriesParts = (parts) => { + if (!parts || parts.length === 0) { + return null; + } + if (parts.length === 1) { + return parts[0]; // Nothing to merge + } + + // Sort parts by partNumber (extracted during grouping) + parts.sort((a, b) => a.partNumber - b.partNumber); + + const mainPart = parts[0]; + const mergedSeasons = [...(mainPart.seasons || [])]; // Start with seasons from part 1 + + // Track the maximum season number added so far + let maxSeasonNumberSoFar = 0; + if (mergedSeasons.length > 0) { + maxSeasonNumberSoFar = Math.max(...mergedSeasons.map(s => s.number)); + } + + for (let i = 1; i < parts.length; i++) { + const currentPart = parts[i]; + + // Calculate the adjustment based on the max season number from the *previous* merged parts + const adjustment = maxSeasonNumberSoFar; + + if (!currentPart.seasons || currentPart.seasons.length === 0) { + console.log(` Part ${currentPart.partNumber} has no seasons to merge.`); + continue; + } + + console.log(` Adjusting ${currentPart.seasons.length} season(s) for Part ${currentPart.partNumber}.`); + + let partMaxSeason = 0; // Track max season added *in this part* + currentPart.seasons.forEach(season => { + const originalSeasonNumber = season.number; + // The adjusted season number is the previous max + the original number from this part + const adjustedSeasonNumber = adjustment + originalSeasonNumber; + console.log(` Merging Season ${originalSeasonNumber} -> ${adjustedSeasonNumber}`); + + // Create a new season object to avoid modifying the original + const adjustedSeason = { + ...season, + number: adjustedSeasonNumber, + // Adjust title like "Saison X" + title: `Saison ${adjustedSeasonNumber}` + }; + mergedSeasons.push(adjustedSeason); + if (adjustedSeasonNumber > partMaxSeason) { + partMaxSeason = adjustedSeasonNumber; + } + }); + // Update the overall max season number + maxSeasonNumberSoFar = partMaxSeason; + } + + // Return the main part with merged seasons + // Ensure seasons are sorted correctly after merging + mergedSeasons.sort((a, b) => a.number - b.number); + + return { + ...mainPart, // Use metadata from the main part + seasons: mergedSeasons + }; +}; + +// --------------------------------------------------------------------------- +// cleanTvCacheData -- helper to clean TV cache data before sending +// --------------------------------------------------------------------------- +const cleanTvCacheData = (cachedData) => { + if (!cachedData || !cachedData.series) { + return cachedData; // Return as is if structure is unexpected + } + return { + type: cachedData.type || 'tv', // ensure type is present + series: (cachedData.series || []).map(s => ({ + title: s.title || s.baseName, // Use baseName if available + audio_type: s.audio_type, + episode_count: s.episode_count, + release_date: s.release_date, + summary: s.summary, + tmdb_data: s.tmdb_data ? { + id: s.tmdb_data.id, + name: s.tmdb_data.name, + overview: s.tmdb_data.overview, + first_air_date: s.tmdb_data.first_air_date, + poster_path: s.tmdb_data.poster_path, + backdrop_path: s.tmdb_data.backdrop_path, + vote_average: s.tmdb_data.vote_average, + match_score: s.tmdb_data.match_score, + is_season_part: s.tmdb_data.is_season_part, // Include season part info + season_offset: s.tmdb_data.season_offset + } : null, + seasons: s.seasons || [] + })) + }; +}; + +// --------------------------------------------------------------------------- +// checkFrenchStreamVersion +// --------------------------------------------------------------------------- +async function checkFrenchStreamVersion(imdbId) { + try { + const url = `${FRENCHSTREAM_BASE_URL}/xfsearch/${imdbId}`; + const response = await axiosFrenchStreamRequest({ method: 'get', url }); + const $ = cheerio.load(response.data); + + // Recherche de la version du film avec le XPath fourni + const versionElement = $('*[id="dle-content"] div div span:nth-child(2) a'); + const version = versionElement.text().trim(); + + return { + version: version || 'Unknown', + url: versionElement.attr('href') || null + }; + } catch (error) { + return { version: 'Unknown', url: null }; + } +} + +// --------------------------------------------------------------------------- +// Exports +// --------------------------------------------------------------------------- +module.exports = { + configure, + getFrenchStreamMovie, + getFrenchStreamSeries, + getFrenchStreamSeriesDetails, + extractSeriesInfo, + mergeSeriesParts, + cleanTvCacheData, + checkFrenchStreamVersion +}; diff --git a/API/Mainapi/routes/fstream.js b/API/Mainapi/routes/fstream.js new file mode 100644 index 0000000..f8224de --- /dev/null +++ b/API/Mainapi/routes/fstream.js @@ -0,0 +1,1881 @@ +/** + * FStream routes. + * Extracted from server.js -- FStream authentication, search, scraping, player extraction, and routes. + * Mount point: app.use('/api/fstream', router) + */ + +const express = require('express'); +const router = express.Router(); +const axios = require('axios'); +const cheerio = require('cheerio'); +const path = require('path'); +const fsp = require('fs').promises; + +const { getRedis } = require('../config/redis'); +const { fetchTmdbDetails } = require('../utils/tmdbCache'); +const { + CACHE_DIR, + generateFStreamCacheKey, + getFStreamFromCache, + saveFStreamToCache, + ongoingFStreamRequests, + getOrCreateFStreamRequest +} = require('../utils/cacheManager'); +const axiosHelpers = require('../utils/axiosHelpers'); +const { axiosFStreamRequest } = axiosHelpers; +const { PROXIES, DARKINO_PROXIES, getProxyAgent, getDarkinoHttpProxyAgent } = require('../utils/proxyManager'); + +// === FStream Configuration === +const TMDB_API_KEY = process.env.TMDB_API_KEY || ''; +const TMDB_API_URL = 'https://api.themoviedb.org/3'; +const FSTREAM_BASE_URL = 'https://french-stream.one/'; +const FSTREAM_SEARCH_URL = `${FSTREAM_BASE_URL}/engine/ajax/search.php`; + +// === FStream Authentication === +const FSTREAM_LOGIN_NAME = process.env.FSTREAM_LOGIN_NAME || ''; +const FSTREAM_LOGIN_PASSWORD = process.env.FSTREAM_LOGIN_PASSWORD || ''; + +let fstreamLoginPromise = null; + +// Configuration des cookies FStream +const fstreamCookies = { + 'PHPSESSID': '', + 'dle_user_id': '', + 'dle_password': '', + 'dle_skin': 'VFV25', + 'dle_newpm': '0', + '__cf_logged_in': '1', + 'CF_VERIFIED_DEVICE_ae9bb95a6761c08a92f916b7ed7d2c4a985eb220591d1410240412c516f37b0c': '1756239054' +}; + +let fstreamRequestCounter = 0; +const MAX_REQUESTS_PER_SESSION = 5; + +function extractCookieValue(cookies, name) { + if (!cookies || !Array.isArray(cookies)) return null; + const target = cookies.find(c => typeof c === 'string' && c.startsWith(`${name}=`)); + if (!target) return null; + const semi = target.indexOf(';'); + const pair = semi !== -1 ? target.slice(0, semi) : target; + const idx = pair.indexOf('='); + return idx !== -1 ? pair.slice(idx + 1) : null; +} + +async function loginToFStream() { + if (fstreamLoginPromise) return fstreamLoginPromise; + fstreamLoginPromise = (async () => { + try { + // We need the raw axiosFStream instance for login (no proxy) + // Use axios directly for the login request + const formData = new URLSearchParams(); + formData.append('login_name', FSTREAM_LOGIN_NAME); + formData.append('login_password', FSTREAM_LOGIN_PASSWORD); + formData.append('login', 'submit'); + + const response = await axios({ + method: 'post', + url: FSTREAM_BASE_URL, + data: formData, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Origin': FSTREAM_BASE_URL, + 'Referer': FSTREAM_BASE_URL, + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' + }, + timeout: 15000, + maxRedirects: 5, + validateStatus: () => true + }); + + const setCookie = response.headers && (response.headers['set-cookie'] || response.headers['Set-Cookie']); + const phpsessid = extractCookieValue(setCookie, 'PHPSESSID'); + const dleUserId = extractCookieValue(setCookie, 'dle_user_id'); + const dlePassword = extractCookieValue(setCookie, 'dle_password'); + const dleNewpm = extractCookieValue(setCookie, 'dle_newpm'); + + if (phpsessid) { + fstreamCookies['PHPSESSID'] = phpsessid; + } else { + throw new Error('PHPSESSID non present dans set-cookie'); + } + if (dleUserId) fstreamCookies['dle_user_id'] = dleUserId; + if (dlePassword) fstreamCookies['dle_password'] = dlePassword; + if (dleNewpm) fstreamCookies['dle_newpm'] = dleNewpm; + // Connexion reussie, cookies recuperes + + // Changer le skin vers VFV25 via POST + try { + const skinCookieHeader = Object.entries(fstreamCookies) + .filter(([, v]) => v !== '' && v != null) + .map(([k, v]) => `${k}=${v}`) + .join('; '); + + const skinFormData = new URLSearchParams(); + skinFormData.append('skin_name', 'VFV25'); + skinFormData.append('action_skin_change', 'yes'); + + await axios({ + method: 'post', + url: FSTREAM_BASE_URL, + data: skinFormData, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Origin': FSTREAM_BASE_URL, + 'Referer': FSTREAM_BASE_URL + '/', + 'Cookie': skinCookieHeader, + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' + }, + timeout: 15000, + maxRedirects: 5, + validateStatus: () => true + }); + + fstreamCookies['dle_skin'] = 'VFV25'; + // Skin change vers VFV25 + } catch (skinError) { + console.warn('[FSTREAM LOGIN] Erreur changement de skin:', skinError.message); + } + + return true; + } finally { + fstreamLoginPromise = null; + } + })(); + return fstreamLoginPromise; +} + +async function ensureFStreamSession() { + if (!fstreamCookies['PHPSESSID'] || fstreamRequestCounter >= MAX_REQUESTS_PER_SESSION) { + await loginToFStream(); + fstreamRequestCounter = 0; + } +} + +// Inject fstream session management into axiosHelpers so axiosFStreamRequest works +axiosHelpers.configure({ + ensureFStreamSession, + fstreamCookies, + getFstreamRequestCounter: () => fstreamRequestCounter, + incrementFstreamRequestCounter: () => { fstreamRequestCounter++; } +}); + +// === TMDB Helper (cached via Redis) === +async function getFStreamTMDBDetails(id, type) { + try { + const [frData, enData] = await Promise.all([ + fetchTmdbDetails(TMDB_API_URL, TMDB_API_KEY, id, type, 'fr-FR'), + fetchTmdbDetails(TMDB_API_URL, TMDB_API_KEY, id, type, 'en-US') + ]); + + if (!frData) return null; + + return { + id: frData.id, + title: type === 'movie' ? frData.title : frData.name, + original_title: type === 'movie' ? frData.original_title : frData.original_name, + name_no_lang: enData ? (type === 'movie' ? enData.title : enData.name) : null, + release_date: type === 'movie' ? frData.release_date : frData.first_air_date, + overview: frData.overview + }; + } catch (error) { + console.error(`Erreur lors de la recuperation des details TMDB pour ${id} (${type}):`, error); + return null; + } +} + +// === Title Similarity (local copy for FStream matching) === +function calculateTitleSimilarity(title1, title2) { + if (!title1 || !title2) return 0; + const t1 = title1.toLowerCase(); + const t2 = title2.toLowerCase(); + const normalize = (str) => str + .normalize("NFD") + .replace(/[\u0300-\u036f]/g, "") + .replace(/[^\w\s]/g, " ") + .replace(/\s+/g, " ") + .trim(); + const norm1 = normalize(t1); + const norm2 = normalize(t2); + if (norm1 === norm2) return 1.0; + + // Token overlap approach + const tokens1 = new Set(norm1.split(' ').filter(Boolean)); + const tokens2 = new Set(norm2.split(' ').filter(Boolean)); + let intersection = 0; + for (const t of tokens1) { if (tokens2.has(t)) intersection++; } + const union = new Set([...tokens1, ...tokens2]).size; + return union === 0 ? 0 : intersection / union; +} + +// === Search Functions === +async function searchFStream(query, page = 1) { + try { + const formData = new URLSearchParams(); + formData.append('query', query); + formData.append('page', page.toString()); + + const response = await axiosFStreamRequest({ + method: 'post', + url: FSTREAM_SEARCH_URL, + data: formData, + headers: { 'Content-Type': 'application/x-www-form-urlencoded' } + }); + + if (response.status !== 200) throw new Error(`Erreur HTTP: ${response.status}`); + return response.data; + } catch (error) { + if (error.response) { + const status = error.response.status; + if (status === 429 || status === 403 || status === 503 || status === 502) throw error; + } + console.error(`Erreur lors de la recherche FStream: ${error.message}`); + throw error; + } +} + +async function searchFStreamDirect(query, page = 1) { + try { + const formData = new URLSearchParams(); + formData.append('query', query); + formData.append('page', page.toString()); + + const response = await axiosFStreamRequest({ + method: 'post', + url: FSTREAM_SEARCH_URL, + data: formData, + headers: { 'Content-Type': 'application/x-www-form-urlencoded' } + }); + + if (response.status !== 200) throw new Error(`Erreur HTTP: ${response.status}`); + return response.data; + } catch (error) { + if (error.response) { + const status = error.response.status; + if (status === 429 || status === 403 || status === 503 || status === 502) throw error; + } + throw error; + } +} + +async function fetchFStreamSeasonSearchResults(tmdbId, serieTitle) { + try { + const formData = new URLSearchParams(); + formData.append('serie_tag', `s-${tmdbId}`); + + const response = await axiosFStreamRequest({ + method: 'post', + url: `${FSTREAM_BASE_URL}/engine/ajax/get_seasons.php`, + data: formData, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', + 'X-Requested-With': 'XMLHttpRequest' + }, + timeout: 6000 + }); + + let seasonsData = response.data; + if (typeof seasonsData === 'string') { + const trimmed = seasonsData.trim(); + if (!trimmed) return []; + try { seasonsData = JSON.parse(trimmed); } + catch (parseError) { + console.error(`[FSTREAM TV] Impossible de parser les saisons pour ${tmdbId}: ${parseError.message}`); + return []; + } + } + + if (!Array.isArray(seasonsData)) return []; + + const normalizedSerieTitle = serieTitle || ''; + + return seasonsData + .map((season) => { + if (!season) return null; + const rawTitle = season.title || ''; + const altName = season.alt_name || ''; + const seasonMatch = rawTitle.match(/Saison\s+(\d+)/i) || altName.match(/saison-(\d+)/i); + if (!seasonMatch) return null; + + const seasonNumber = parseInt(seasonMatch[1], 10); + if (Number.isNaN(seasonNumber)) return null; + + const rawYear = season.serie_anne; + const year = rawYear && /^\d{4}$/.test(String(rawYear)) ? parseInt(rawYear, 10) : null; + + const fullUrl = (season.full_url || '').replace(/\\/g, '/'); + if (!fullUrl) return null; + const normalizedLink = fullUrl.startsWith('http') + ? fullUrl + : `${FSTREAM_BASE_URL}${fullUrl.startsWith('/') ? '' : '/'}${fullUrl}`; + + const baseTitle = rawTitle || `Saison ${seasonNumber}`; + const combinedTitle = normalizedSerieTitle ? `${normalizedSerieTitle} - ${baseTitle}` : baseTitle; + + return { + title: combinedTitle, + originalTitle: rawTitle || combinedTitle, + link: normalizedLink, + seasonNumber, + year + }; + }) + .filter(Boolean); + } catch (error) { + console.error(`[FSTREAM TV] Erreur lors de la recuperation des saisons pour ${tmdbId}: ${error.message}`); + return []; + } +} + +// === Scraping Functions === +async function scrapeFStreamRecentMovies() { + try { + const response = await axiosFStreamRequest({ + method: 'get', + url: `${FSTREAM_BASE_URL}/films/`, + timeout: 10000 + }); + + if (response.status !== 200) throw new Error(`Erreur HTTP: ${response.status}`); + if (!response.data || typeof response.data !== 'string') throw new Error('La reponse n\'est pas du HTML valide'); + + const $ = cheerio.load(response.data); + const movies = []; + + const dleContent = $('#dle-content'); + let filmElements; + + if (dleContent.length > 0) { + filmElements = dleContent.find('.short.film'); + if (filmElements.length === 0) filmElements = dleContent.find('div.short.film'); + if (filmElements.length === 0) filmElements = dleContent.find('div[class*="short"][class*="film"]'); + if (filmElements.length === 0) { + const shortInDle = dleContent.find('.short'); + if (shortInDle.length > 0) filmElements = shortInDle; + } + } else { + filmElements = $('.short.film'); + if (filmElements.length === 0) filmElements = $('div.short.film'); + if (filmElements.length === 0) filmElements = $('div[class*="short"][class*="film"]'); + if (filmElements.length === 0) { + const allShorts = $('.short'); + if (allShorts.length > 0) filmElements = allShorts; + } + } + + filmElements.each((index, element) => { + try { + const $el = $(element); + const titleElement = $el.find('.short-title'); + if (titleElement.length === 0) return; + const title = titleElement.text().trim(); + if (!title) return; + + const linkElement = $el.find('a.short-poster'); + if (linkElement.length === 0) return; + const href = linkElement.attr('href'); + if (!href) return; + + const fullLink = href.startsWith('http') ? href + : href.startsWith('/') ? `${FSTREAM_BASE_URL}${href}` + : `${FSTREAM_BASE_URL}/${href}`; + + let movieId = null; + const idMatch = href.match(/(\d+)/); + if (idMatch) movieId = idMatch[1]; + + let trailerId = null; + if (movieId) { + let trailerElement = $el.find(`span#trailer-${movieId}`); + if (trailerElement.length === 0) trailerElement = $(`span#trailer-${movieId}`); + if (trailerElement.length > 0) trailerId = trailerElement.text().trim(); + } + + let description = null; + if (movieId) { + let descElement = $el.find(`span#desc-${movieId}`); + if (descElement.length === 0) descElement = $(`span#desc-${movieId}`); + if (descElement.length > 0) description = descElement.text().trim(); + } + + const quality = $el.find('.film-quality a').text().trim() || null; + const version = $el.find('.film-version a').text().trim() || null; + + const imgElement = $el.find('img'); + let posterUrl = null; + if (imgElement.length > 0) { + posterUrl = imgElement.attr('src'); + if (posterUrl && !posterUrl.startsWith('http')) { + posterUrl = posterUrl.startsWith('/') + ? `${FSTREAM_BASE_URL}${posterUrl}` + : `${FSTREAM_BASE_URL}/${posterUrl}`; + } + } + + const ratingElement = $el.find('.vote-score'); + let rating = null; + if (ratingElement.length > 0) { + const ratingText = ratingElement.text().trim(); + const ratingMatch = ratingText.match(/(\d+\.?\d*)/); + if (ratingMatch) rating = parseFloat(ratingMatch[1]); + } + + movies.push({ + title, link: fullLink, id: movieId, trailerId, description, + quality, version, posterUrl, rating, source: 'fstream_recent' + }); + } catch (error) { + console.error(`[FSTREAM RECENT] Erreur lors du parsing d'un film: ${error.message}`); + } + }); + + return movies; + } catch (error) { + console.error(`[FSTREAM RECENT] Erreur lors du scraping: ${error.message}`); + return []; + } +} + +async function scrapeFStreamRecentSeries() { + try { + const response = await axiosFStreamRequest({ + method: 'get', + url: `${FSTREAM_BASE_URL}/s-tv/`, + timeout: 10000 + }); + + if (response.status !== 200) throw new Error(`Erreur HTTP: ${response.status}`); + + const $ = cheerio.load(response.data); + const series = []; + const seriesElements = $('#dle-content .short.serie'); + + seriesElements.each((index, element) => { + try { + const $el = $(element); + const titleElement = $el.find('.short-title'); + if (titleElement.length === 0) return; + const title = titleElement.text().trim(); + if (!title) return; + + const linkElement = $el.find('a.short-poster'); + if (linkElement.length === 0) return; + const href = linkElement.attr('href'); + if (!href) return; + + const fullLink = href.startsWith('http') ? href : `${FSTREAM_BASE_URL}${href}`; + + let seriesId = null; + const idMatch = href.match(/(\d+)/); + if (idMatch) seriesId = idMatch[1]; + + series.push({ + title, link: fullLink, id: seriesId, tmdbId: null, source: 'fstream_recent_series' + }); + } catch (error) { + console.error(`[FSTREAM RECENT SERIES] Erreur lors du parsing d'une serie: ${error.message}`); + } + }); + + return series; + } catch (error) { + console.error(`[FSTREAM RECENT SERIES] Erreur lors du scraping: ${error.message}`); + return []; + } +} + +// === Finding Functions === +async function findMovieInRecentFStream(tmdbTitle, tmdbYear) { + try { + const recentMovies = await scrapeFStreamRecentMovies(); + if (recentMovies.length === 0) return null; + + const extractYear = (title) => { + const yearMatch = title.match(/\((\d{4})\)/); + return yearMatch ? yearMatch[1] : null; + }; + + const removeYear = (title) => title.replace(/\s*\((\d{4})\)\s*$/, '').trim(); + + const normalizeTitle = (str) => { + if (!str) return ''; + let cleaned = removeYear(str); + return cleaned.toLowerCase().normalize('NFD') + .replace(/[\u0300-\u036f]/g, '') + .replace(/[^\w\s]/g, '') + .replace(/\s+/g, ' ') + .trim(); + }; + + let yearToMatch = tmdbYear; + if (!yearToMatch) yearToMatch = extractYear(tmdbTitle); + + const tmdbTitleWithoutYear = removeYear(tmdbTitle); + const normalizedTmdbTitle = normalizeTitle(tmdbTitleWithoutYear); + + let bestMatch = null; + let bestSimilarity = 0; + + for (const movie of recentMovies) { + const normalizedMovieTitle = normalizeTitle(movie.title); + if (normalizedMovieTitle === normalizedTmdbTitle) return movie; + + const similarity = calculateTitleSimilarity(normalizedTmdbTitle, normalizedMovieTitle); + if (similarity > bestSimilarity) { + bestSimilarity = similarity; + bestMatch = movie; + } + } + + if (bestMatch && bestSimilarity >= 0.7) return bestMatch; + + if (bestMatch && bestSimilarity >= 0.6 && normalizedTmdbTitle.length > 3) { + const tmdbWords = normalizedTmdbTitle.split(/\s+/).filter(w => w.length > 2); + const movieWords = normalizeTitle(bestMatch.title).split(/\s+/).filter(w => w.length > 2); + const allWordsMatch = tmdbWords.length > 0 && ( + tmdbWords.every(word => movieWords.some(mw => mw.includes(word) || word.includes(mw))) || + movieWords.every(word => tmdbWords.some(tw => tw.includes(word) || word.includes(tw))) + ); + if (allWordsMatch) { + // Verifier que les tokens bruts (sans filtre de longueur) ont un recouvrement suffisant + const rawTmdbTokens = normalizedTmdbTitle.split(/\s+/).filter(Boolean); + const rawMovieTokens = new Set(normalizeTitle(bestMatch.title).split(/\s+/).filter(Boolean)); + const rawCoverage = rawTmdbTokens.length > 0 ? rawTmdbTokens.filter(t => rawMovieTokens.has(t)).length / rawTmdbTokens.length : 0; + if (rawCoverage >= 0.75) return bestMatch; + } + } + + return null; + } catch (error) { + console.error(`[FSTREAM RECENT] Erreur lors de la recherche: ${error.message}`); + return null; + } +} + +async function findSeriesInRecentFStream(tmdbTitle, tmdbYear) { + try { + const recentSeries = await scrapeFStreamRecentSeries(); + if (recentSeries.length === 0) return null; + + const normalizeTitle = (str) => (str || '') + .toLowerCase().normalize('NFD') + .replace(/[\u0300-\u036f]/g, '') + .replace(/[^\w\s]/g, '') + .replace(/\s+/g, ' ') + .trim(); + + const normalizedTmdbTitle = normalizeTitle(tmdbTitle); + + for (const series of recentSeries) { + const normalizedSeriesTitle = normalizeTitle(series.title); + if (normalizedSeriesTitle === normalizedTmdbTitle) return series; + const similarity = calculateTitleSimilarity(normalizedTmdbTitle, normalizedSeriesTitle); + if (similarity > 0.8) return series; + } + + return null; + } catch (error) { + console.error(`[FSTREAM RECENT SERIES] Erreur lors de la recherche: ${error.message}`); + return null; + } +} + +// === API-based extraction helpers === +function extractPageIdFromUrl(url) { + if (!url) return null; + const match = url.match(/\/(\d+)-[^/]+\.html/); + return match ? match[1] : null; +} + +function extractBaseUrlFromLink(url) { + try { + const parsed = new URL(url); + return `${parsed.protocol}//${parsed.host}`; + } catch { + return FSTREAM_BASE_URL; + } +} + +// Construit une liste melangee de proxies SOCKS5 + Darkino HTTP +function getShuffledAllProxies() { + const all = []; + // Ajouter les SOCKS5 + if (PROXIES && PROXIES.length > 0) { + PROXIES.forEach(p => all.push({ proxy: p, type: 'socks5' })); + } + // Ajouter les Darkino HTTP + if (DARKINO_PROXIES && DARKINO_PROXIES.length > 0) { + DARKINO_PROXIES.forEach(p => all.push({ proxy: p, type: 'darkino' })); + } + // Melanger + for (let i = all.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [all[i], all[j]] = [all[j], all[i]]; + } + return all; +} + +function getAgentForProxy(entry) { + if (entry.type === 'socks5') { + const agent = getProxyAgent(entry.proxy); + return { httpAgent: agent, httpsAgent: agent }; + } + // darkino HTTP proxy + return getDarkinoHttpProxyAgent(entry.proxy); +} + +async function fetchEpisodesFromApi(pageUrl) { + const pageId = extractPageIdFromUrl(pageUrl); + if (!pageId) return null; + + const baseUrl = extractBaseUrlFromLink(pageUrl); + const apiUrl = `${baseUrl}/engine/ajax/episodes_p.php?id=${pageId}`; + + const proxies = getShuffledAllProxies(); + const maxAttempts = Math.min(proxies.length, 3); + let lastError = null; + + for (let i = 0; i < maxAttempts; i++) { + const entry = proxies[i]; + const agents = getAgentForProxy(entry); + + try { + const response = await axios({ + method: 'get', + url: apiUrl, + timeout: 10000, + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36', + 'Referer': pageUrl, + 'Accept': 'application/json, text/plain, */*' + }, + ...(agents ? { httpAgent: agents.httpAgent || agents, httpsAgent: agents.httpsAgent || agents, proxy: false } : {}) + }); + + if (response.status === 429) { + console.log(`[FStream] API episodes_p: 429 avec proxy ${entry.type} #${i}, retry...`); + continue; + } + if (response.status !== 200 || !response.data) return null; + + const data = typeof response.data === 'string' ? JSON.parse(response.data) : response.data; + if (!data || typeof data !== 'object') return null; + + const episodes = {}; + const langMap = { vf: 'VF', vostfr: 'VOSTFR', vo: 'VOENG' }; + + for (const [langKey, langLabel] of Object.entries(langMap)) { + const langData = data[langKey]; + if (!langData || typeof langData !== 'object') continue; + + for (const [epNum, providers] of Object.entries(langData)) { + const epNumber = parseInt(epNum); + if (isNaN(epNumber) || epNumber === 0) continue; + + if (!episodes[epNumber]) { + episodes[epNumber] = { + number: epNumber, + title: `Episode ${epNumber}`, + languages: { VF: [], VOSTFR: [], VOENG: [], Default: [] } + }; + } + + for (const [provider, url] of Object.entries(providers)) { + if (!url || typeof url !== 'string' || !url.startsWith('http')) continue; + let displayName = provider; + if (provider === 'premium') displayName = 'Premium'; + else if (provider === 'vidzy') displayName = 'Vidzy'; + else if (provider === 'uqload') displayName = 'Uqload'; + else if (provider === 'netu') displayName = 'Netu'; + else if (provider === 'voe') displayName = 'Voe'; + else displayName = provider.charAt(0).toUpperCase() + provider.slice(1); + + const exists = episodes[epNumber].languages[langLabel].some(p => p.url === url); + if (!exists) { + episodes[epNumber].languages[langLabel].push({ url, type: 'embed', quality: 'HD', player: displayName }); + } + } + } + } + + // Enrichir avec les infos (titres, synopsis) si disponibles + if (data.info && typeof data.info === 'object') { + for (const [epNum, info] of Object.entries(data.info)) { + const epNumber = parseInt(epNum); + if (episodes[epNumber] && info.title) { + episodes[epNumber].title = info.title; + } + } + } + + if (Object.keys(episodes).length > 0) { + return episodes; + } + return null; + } catch (error) { + lastError = error; + if (error.response?.status === 429) { + console.log(`[FStream] API episodes_p: 429 avec proxy ${entry.type} #${i}, retry...`); + continue; + } + console.error(`[FStream] Erreur API episodes_p (proxy ${entry.type} #${i}): ${error.message}`); + continue; + } + } + + if (lastError) console.error(`[FStream] API episodes_p: tous les proxies ont echoue. Derniere erreur: ${lastError.message}`); + return null; +} + +async function fetchMoviePlayersFromApi(pageUrl) { + const pageId = extractPageIdFromUrl(pageUrl); + if (!pageId) return null; + + const baseUrl = extractBaseUrlFromLink(pageUrl); + const apiUrl = `${baseUrl}/engine/ajax/film_api.php?id=${pageId}`; + + const proxies = getShuffledAllProxies(); + const maxAttempts = Math.min(proxies.length, 3); + let lastError = null; + + for (let i = 0; i < maxAttempts; i++) { + const entry = proxies[i]; + const agents = getAgentForProxy(entry); + + try { + const response = await axios({ + method: 'get', + url: apiUrl, + timeout: 10000, + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36', + 'Referer': pageUrl, + 'Accept': 'application/json, text/plain, */*' + }, + ...(agents ? { httpAgent: agents.httpAgent || agents, httpsAgent: agents.httpsAgent || agents, proxy: false } : {}) + }); + + if (response.status === 429) { + console.log(`[FStream] API film_api: 429 avec proxy ${entry.type} #${i}, retry...`); + continue; + } + if (response.status !== 200 || !response.data) return null; + + const data = typeof response.data === 'string' ? JSON.parse(response.data) : response.data; + if (!data || !data.players || typeof data.players !== 'object') return null; + + const players = []; + const versionMap = { 'default': 'Default', 'vf': 'VF', 'vfq': 'VFQ', 'vff': 'VFF', 'vostfr': 'VOSTFR' }; + + for (const [provider, versions] of Object.entries(data.players)) { + if (!versions || typeof versions !== 'object') continue; + + for (const [versionKey, url] of Object.entries(versions)) { + if (!url || typeof url !== 'string') continue; + let finalUrl = url; + if (provider === 'netu' && !url.startsWith('http')) { + finalUrl = `https://www.fembed.com/v/${url}`; + } + if (!finalUrl.startsWith('http')) continue; + + let displayName = provider; + if (provider === 'premium') displayName = 'Premium'; + else if (provider === 'vidzy') displayName = 'Vidzy'; + else if (provider === 'uqload') displayName = 'Uqload'; + else if (provider === 'netu') displayName = 'Netu'; + else if (provider === 'voe') displayName = 'Voe'; + else if (provider === 'dood') displayName = 'Dood'; + else if (provider === 'filmoon') displayName = 'Filmoon'; + else displayName = provider.charAt(0).toUpperCase() + provider.slice(1); + + const version = versionMap[versionKey] || versionKey.toUpperCase(); + players.push({ url: finalUrl, type: 'embed', quality: 'HD', player: displayName, version }); + } + } + + if (players.length > 0) { + return players; + } + return null; + } catch (error) { + lastError = error; + if (error.response?.status === 429) { + console.log(`[FStream] API film_api: 429 avec proxy ${entry.type} #${i}, retry...`); + continue; + } + console.error(`[FStream] Erreur API film_api (proxy ${entry.type} #${i}): ${error.message}`); + continue; + } + } + + if (lastError) console.error(`[FStream] API film_api: tous les proxies ont echoue. Derniere erreur: ${lastError.message}`); + return null; +} + +// === High-level wrappers: API-first, HTML fallback === +// Bypass le fetch HTML (souvent 429) en appelant l'API directe d'abord +async function getSeriesPlayersForUrl(pageUrl) { + // 1. API directe (pas de login, pool proxy combine) + const apiEpisodes = await fetchEpisodesFromApi(pageUrl); + if (apiEpisodes && Object.keys(apiEpisodes).length > 0) { + const organizedPlayers = { VF: [], VOSTFR: [], VOENG: [], Default: [] }; + let totalPlayers = 0; + Object.values(apiEpisodes).forEach(episode => { + Object.entries(episode.languages).forEach(([lang, players]) => { + if (players.length > 0) { + if (organizedPlayers[lang]) organizedPlayers[lang].push(...players); + totalPlayers += players.length; + } + }); + }); + return { organized: organizedPlayers, episodes: apiEpisodes, total: totalPlayers, fstreamReleaseDate: null, fromApi: true }; + } + + // 2. Fallback: fetch HTML + console.log(`[FStream] getSeriesPlayersForUrl: API echouee, fallback HTML pour ${pageUrl}`); + const contentResponse = await axiosFStreamRequest({ method: 'get', url: pageUrl }); + if (contentResponse.status !== 200) return { organized: { VF: [], VOSTFR: [], VOENG: [], Default: [] }, episodes: {}, total: 0, fstreamReleaseDate: null }; + return await extractFStreamPlayers(contentResponse.data, true, pageUrl); +} + +async function getMoviePlayersForUrl(pageUrl) { + // 1. API directe + const apiPlayers = await fetchMoviePlayersFromApi(pageUrl); + if (apiPlayers && apiPlayers.length > 0) { + const uniquePlayers = []; + const seenUrls = new Set(); + apiPlayers.forEach(player => { + if (!seenUrls.has(player.url)) { seenUrls.add(player.url); uniquePlayers.push(player); } + }); + const organized = { VFQ: [], VFF: [], VOSTFR: [], Default: [] }; + uniquePlayers.forEach(player => { + const version = (player.version && organized[player.version]) ? player.version : 'Default'; + organized[version].push({ url: player.url, type: player.type, quality: player.quality, player: player.player || 'Lecteur' }); + }); + return { organized, total: uniquePlayers.length, fromApi: true }; + } + + // 2. Fallback: fetch HTML + console.log(`[FStream] getMoviePlayersForUrl: API echouee, fallback HTML pour ${pageUrl}`); + const contentResponse = await axiosFStreamRequest({ method: 'get', url: pageUrl }); + if (contentResponse.status !== 200) return { organized: { VFQ: [], VFF: [], VOSTFR: [], Default: [] }, total: 0 }; + return await extractFStreamPlayers(contentResponse.data, false, pageUrl); +} + +// === Player Extraction === +async function extractFStreamPlayers(htmlContent, isSeries = false, pageUrl = null) { + try { + const $ = cheerio.load(htmlContent); + let players = []; + + if (isSeries) { + return await extractFStreamSeriesPlayers(htmlContent, pageUrl); + } else { + // Methode API (la plus fiable) + if (pageUrl) { + const apiPlayers = await fetchMoviePlayersFromApi(pageUrl); + if (apiPlayers && apiPlayers.length > 0) { + players = apiPlayers; + } + } + + // Pour les films - extraction via #film-data + const filmData = $('#film-data'); + if (players.length === 0 && filmData.length > 0) { + const providers = ['premium', 'vidzy', 'uqload', 'dood', 'voe', 'filmoon', 'netu']; + providers.forEach(provider => { + const versions = { 'vostfr': 'VOSTFR', 'vff': 'VFF', 'vfq': 'VFQ', '': 'Default' }; + Object.entries(versions).forEach(([suffix, label]) => { + const attr = `data-${provider}${suffix}`; + const value = filmData.attr(attr); + if (value && value.trim() !== '') { + let url = value; + if (provider === 'netu' && !value.startsWith('http')) { + url = `https://www.fembed.com/v/${value}`; + } + if (url.startsWith('http')) { + players.push({ url, type: 'embed', quality: 'HD', player: provider, version: label }); + } + } + }); + }); + } + + // Fallback: script parsing + if (players.length === 0) { + const scriptContent = $('script').text(); + const playerUrlsMatch = scriptContent.match(/var\s+playerUrls\s*=\s*({[\s\S]*?});/); + if (playerUrlsMatch && playerUrlsMatch[1]) { + try { + const playerUrlsStr = playerUrlsMatch[1]; + const playerPattern = /"([^"]+)":\s*{([^}]+)}/g; + let playerMatch; + while ((playerMatch = playerPattern.exec(playerUrlsStr)) !== null) { + const playerName = playerMatch[1]; + const versionsStr = playerMatch[2]; + const versionPattern = /"([^"]+)":\s*"([^"]*)"/g; + let versionMatch; + while ((versionMatch = versionPattern.exec(versionsStr)) !== null) { + const version = versionMatch[1]; + const url = versionMatch[2]; + if (url && url.trim() !== '') { + players.push({ url, type: 'embed', quality: 'HD', player: playerName, version }); + } + } + } + if (players.length === 0) { + const urlPattern = /"([^"]+)":\s*"([^"]+)"/g; + let match; + while ((match = urlPattern.exec(playerUrlsStr)) !== null) { + const key = match[1]; + const url = match[2]; + if (url && url.includes('http') && !key.includes('Default') && !key.includes('VFQ') && !key.includes('VFF') && !key.includes('VOSTFR')) { + players.push({ url, type: 'embed', quality: 'HD', player: key }); + } + } + } + } catch (parseError) { + console.error('Erreur lors du parsing de playerUrls:', parseError.message); + } + } + + if (players.length === 0) { + const urlPattern = /https?:\/\/[^\s"']+/g; + const urls = scriptContent.match(urlPattern); + if (urls) { + urls.forEach(url => { + if (url.includes('embed') || url.includes('player')) { + players.push({ url, type: 'embed', quality: 'HD' }); + } + }); + } + } + } + + // Fallback: iframes + if (players.length === 0) { + $('iframe[src], a[href*="embed"], a[href*="player"]').each((_, element) => { + const $el = $(element); + const src = $el.attr('src') || $el.attr('href'); + if (src && !src.includes('episodes-suivant')) { + players.push({ + url: src.startsWith('http') ? src : `${FSTREAM_BASE_URL}${src}`, + type: 'embed', quality: 'HD' + }); + } + }); + } + } + + // Deduplicate and organize + const uniquePlayers = []; + const seenUrls = new Set(); + players.forEach(player => { + if (!seenUrls.has(player.url)) { + seenUrls.add(player.url); + uniquePlayers.push(player); + } + }); + + const organizedPlayers = { VFQ: [], VFF: [], VOSTFR: [], Default: [] }; + uniquePlayers.forEach(player => { + const version = (player.version && organizedPlayers[player.version]) ? player.version : 'Default'; + organizedPlayers[version].push({ + url: player.url, type: player.type, quality: player.quality, player: player.player || 'Lecteur' + }); + }); + + return { organized: organizedPlayers, total: uniquePlayers.length }; + } catch (error) { + console.error(`Erreur lors de l'extraction des lecteurs FStream: ${error.message}`); + return { organized: { VFQ: [], VFF: [], VOSTFR: [], Default: [] }, total: 0 }; + } +} + +async function extractFStreamSeriesPlayers(htmlContent, pageUrl = null) { + try { + const $ = cheerio.load(htmlContent); + let episodes = {}; + + // Extract release date (toujours depuis le HTML) + let fstreamReleaseDate = null; + const selectors = [ + 'html body div:nth-child(2) div div:nth-child(2) article div:nth-child(2) div:nth-child(1) div:nth-child(1) div:nth-child(1) span:nth-child(2)', + 'span.release', 'div[class*="release"] span', 'article div span[class*="release"]', + 'div[class*="info"] span[class*="release"]', 'div[class*="meta"] span[class*="release"]' + ]; + for (const selector of selectors) { + const releaseSpan = $(selector); + if (releaseSpan.length > 0) { + const releaseText = releaseSpan.text().trim(); + const yearMatch = releaseText.match(/(\d{4})/); + if (yearMatch) { fstreamReleaseDate = yearMatch[1]; break; } + } + } + if (!fstreamReleaseDate) { + const allText = $.text(); + const yearMatches = allText.match(/(\d{4})\s*-\s*/g); + if (yearMatches && yearMatches.length > 0) { + const firstYear = yearMatches[0].match(/(\d{4})/)[1]; + if (parseInt(firstYear) >= 1900 && parseInt(firstYear) <= new Date().getFullYear() + 2) { + fstreamReleaseDate = firstYear; + } + } + } + + // Methode API (la plus fiable) + let foundEpisodesData = false; + if (pageUrl) { + const apiEpisodes = await fetchEpisodesFromApi(pageUrl); + if (apiEpisodes) { + Object.assign(episodes, apiEpisodes); + foundEpisodesData = true; + } + } + + // New method: HTML IDs + if (!foundEpisodesData) try { + const versionMap = { + '#episodes-vf-data': 'VF', + '#episodes-vostfr-data': 'VOSTFR', + '#episodes-vo-data': 'VOENG' + }; + for (const [selector, langKey] of Object.entries(versionMap)) { + const container = $(selector); + if (container.length > 0) { + container.children('div').each((_, element) => { + const $el = $(element); + const epNumStr = $el.attr('data-ep'); + if (!epNumStr) return; + const epNum = parseInt(epNumStr); + if (isNaN(epNum) || epNum === 0) return; + + const attributes = { + 'data-premium': 'FSvid', 'data-vidzy': 'Vidzy', + 'data-uqload': 'Uqload', 'data-netu': 'Netu', 'data-voe': 'Voe' + }; + const playersToAdd = []; + Object.entries(attributes).forEach(([attr, playerName]) => { + const url = $el.attr(attr); + if (url && url.startsWith('http')) { + playersToAdd.push({ url, type: 'embed', quality: 'HD', player: playerName }); + } + }); + + if (playersToAdd.length > 0) { + if (!episodes[epNum]) { + episodes[epNum] = { number: epNum, title: `Episode ${epNum}`, languages: { VF: [], VOSTFR: [], VOENG: [], Default: [] } }; + } + playersToAdd.forEach(player => { + const exists = episodes[epNum].languages[langKey].some(p => p.url === player.url); + if (!exists) episodes[epNum].languages[langKey].push(player); + }); + } + }); + if (Object.keys(episodes).length > 0) foundEpisodesData = true; + } + } + if (foundEpisodesData) { + // Donnees trouvees via les IDs HTML + } + } catch (newMethodError) { + console.error(`[FStream] Erreur nouvelle methode extraction: ${newMethodError.message}`); + } + + // Legacy: episodesData from script + if (!foundEpisodesData) $('script').each((_, scriptEl) => { + const scriptContent = $(scriptEl).html() || ''; + const episodesDataMatch = scriptContent.match(/var\s+episodesData\s*=\s*(\{[\s\S]*?\});(?:\s*var|\s*\n\s*var|\s*\n\s*\n)/); + if (episodesDataMatch && episodesDataMatch[1]) { + try { + let jsonStr = episodesDataMatch[1]; + const vfMatch = jsonStr.match(/vf:\s*\{([\s\S]*?)\},\s*(?:vostfr|vo):/); + const vostfrMatch = jsonStr.match(/vostfr:\s*\{([\s\S]*?)\},\s*vo:/); + const voMatch = jsonStr.match(/vo:\s*\{([\s\S]*?)\}\s*\}/); + + const parseLanguageEpisodes = (langContent, langKey) => { + if (!langContent) return; + const episodePattern = /(\d+):\s*\{([^}]+)\}/g; + let epMatch; + while ((epMatch = episodePattern.exec(langContent)) !== null) { + const epNum = parseInt(epMatch[1]); + const playersContent = epMatch[2]; + if (!episodes[epNum]) { + episodes[epNum] = { number: epNum, title: `Episode ${epNum}`, languages: { VF: [], VOSTFR: [], VOENG: [], Default: [] } }; + } + const playerPattern = /(\w+):"([^"]+)"/g; + let playerMatch; + while ((playerMatch = playerPattern.exec(playersContent)) !== null) { + const playerName = playerMatch[1]; + const playerUrl = playerMatch[2]; + if (!playerUrl || playerUrl.includes('[') || playerUrl.includes('xfvalue_')) continue; + let displayName = playerName.toUpperCase(); + if (playerName === 'vidzy') displayName = 'Vidzy'; + else if (playerName === 'uqload') displayName = 'Uqload'; + else if (playerName === 'netu') displayName = 'Netu'; + else if (playerName === 'voe') displayName = 'Voe'; + else if (playerName === 'premium') displayName = 'Premium'; + const player = { url: playerUrl, type: 'embed', quality: 'HD', player: displayName }; + const targetLang = langKey === 'vo' ? 'VOENG' : (langKey === 'vostfr' ? 'VOSTFR' : 'VF'); + const exists = episodes[epNum].languages[targetLang].some(p => p.url === playerUrl); + if (!exists) episodes[epNum].languages[targetLang].push(player); + } + } + }; + + if (vfMatch && vfMatch[1]) parseLanguageEpisodes(vfMatch[1], 'vf'); + if (vostfrMatch && vostfrMatch[1]) parseLanguageEpisodes(vostfrMatch[1], 'vostfr'); + if (voMatch && voMatch[1]) parseLanguageEpisodes(voMatch[1], 'vo'); + + foundEpisodesData = Object.keys(episodes).length > 0; + if (foundEpisodesData) { + console.log(`[FStream] Parsed episodesData: ${Object.keys(episodes).length} episodes found`); + } + } catch (parseError) { + console.error('[FStream] Erreur parsing episodesData:', parseError.message); + } + } + }); + + // Legacy HTML method + if (!foundEpisodesData) { + console.log('[FStream] episodesData non trouve, utilisation de la methode legacy...'); + $('div.fullsfeature').each((_, element) => { + const $episode = $(element); + const titleSpan = $episode.find('.selink span').first(); + const episodeTitle = titleSpan.text().trim(); + if (!episodeTitle || episodeTitle.trim() === '') return; + + let language = 'Default'; + if (episodeTitle.toLowerCase().includes('vostfr')) language = 'VOSTFR'; + else if (episodeTitle.toLowerCase().includes('vf')) language = 'VFF'; + + const episodeMatch = episodeTitle.match(/episode\s+(\d+)/i); + const episodeNumber = episodeMatch ? parseInt(episodeMatch[1]) : 1; + const episodePlayers = []; + $episode.find('ul.btnss a.fsctab').each((_, linkElement) => { + const $link = $(linkElement); + const href = $link.attr('href'); + const playerName = $link.text().trim(); + if (href && href.startsWith('http') && !href.includes('episodes-suivant')) { + episodePlayers.push({ url: href, type: 'embed', quality: 'HD', player: playerName }); + } + }); + + if (episodePlayers.length > 0) { + if (!episodes[episodeNumber]) { + episodes[episodeNumber] = { number: episodeNumber, title: episodeTitle, languages: { VF: [], VOSTFR: [], VOENG: [], Default: [] } }; + } + const langKey = language === 'VOSTFR' ? 'VOSTFR' : 'VF'; + episodes[episodeNumber].languages[langKey] = episodePlayers; + } + }); + + $('div.elink a.fstab').each((_, linkElement) => { + const $link = $(linkElement); + const href = $link.attr('href'); + const linkText = $link.text().trim(); + if (!href || !href.startsWith('http') || linkText.trim() === '') return; + + const episodeMatch = linkText.match(/episode\s+(\d+)/i); + if (!episodeMatch) return; + const episodeNumber = parseInt(episodeMatch[1]); + + let language = 'Default'; + const lowerText = linkText.toLowerCase(); + if (lowerText.includes('vosteng') || lowerText.includes('voeng')) language = 'VOENG'; + else if (lowerText.includes('vostfr')) language = 'VOSTFR'; + else if (lowerText.includes('vf')) language = 'VFF'; + + let playerName = 'Unknown'; + if (href.includes('fsvid.lol')) playerName = 'FSvid'; + else if (href.includes('vidzy.org')) playerName = 'Vidzy'; + else if (href.includes('uqload')) playerName = 'Uqload'; + else if (href.includes('voe.sx')) playerName = 'Voe'; + + const player = { url: href, type: 'embed', quality: 'HD', player: playerName }; + if (!episodes[episodeNumber]) { + episodes[episodeNumber] = { number: episodeNumber, title: linkText, languages: { VF: [], VOSTFR: [], VOENG: [], Default: [] } }; + } + const langKey = language === 'VOENG' ? 'VOENG' : (language === 'VOSTFR' ? 'VOSTFR' : 'VF'); + const existingPlayer = episodes[episodeNumber].languages[langKey].find(p => p.url === href); + if (!existingPlayer) episodes[episodeNumber].languages[langKey].push(player); + }); + } + + // Organize by language + const organizedPlayers = { VF: [], VOSTFR: [], VOENG: [], Default: [] }; + let totalPlayers = 0; + Object.values(episodes).forEach(episode => { + Object.entries(episode.languages).forEach(([lang, players]) => { + if (players.length > 0) { + organizedPlayers[lang].push(...players); + totalPlayers += players.length; + } + }); + }); + + return { organized: organizedPlayers, episodes, total: totalPlayers, fstreamReleaseDate }; + } catch (error) { + console.error(`Erreur lors de l'extraction des lecteurs serie FStream: ${error.message}`); + return { organized: { VF: [], VOSTFR: [], VOENG: [], Default: [] }, episodes: {}, total: 0, fstreamReleaseDate: null }; + } +} + +// === Filtering === +function filterFStreamResults(results, originalTitle, releaseYear) { + try { + const $ = cheerio.load(results); + const filteredResults = []; + + $('div.search-item').each((_, element) => { + const $el = $(element); + const titleElement = $el.find('.search-title'); + const title = titleElement.text().trim(); + const onclickAttr = $el.attr('onclick'); + let link = null; + if (onclickAttr) { + const linkMatch = onclickAttr.match(/location\.href=['"]([^'\"]+)['"]/); + if (linkMatch) link = linkMatch[1]; + } + if (!title || !link) return; + + let cleanTitle = title; + let seasonNumber = null; + let year = null; + + const yearMatch = title.match(/\((\d{4})\)/); + if (yearMatch) { + year = parseInt(yearMatch[1]); + cleanTitle = title.replace(/\s*\(\d{4}\)/, '').trim(); + } + + // Fallback: extraire l'annee de l'URL (ex: magnum-saison-5-1980.html) + if (!year && link) { + const urlYearMatch = link.match(/-(\d{4})\.html/); + if (urlYearMatch) year = parseInt(urlYearMatch[1]); + } + + const seasonMatch = cleanTitle.match(/Saison\s+(\d+)/i); + if (seasonMatch) { + seasonNumber = parseInt(seasonMatch[1]); + cleanTitle = cleanTitle.replace(/\s*-\s*Saison\s+\d+$/i, '').trim(); + } else { + const originalSeasonMatch = title.match(/Saison\s+(\d+)/i); + if (originalSeasonMatch) seasonNumber = parseInt(originalSeasonMatch[1]); + } + + const normalize = (str) => (str || '').toLowerCase().normalize('NFD') + .replace(/[\u0300-\u036f]/g, '').replace(/[''`\u00b4]/g, '') + .replace(/[^a-z0-9\s-]/g, '').replace(/\s+-\s+/g, ' ') + .replace(/\s+/g, ' ').trim(); + + const normalizedOriginal = normalize(originalTitle); + const normalizedClean = normalize(cleanTitle); + const tokenize = (str) => (str || '').split(' ').filter(Boolean); + + const originalTokens = new Set(tokenize(normalizedOriginal)); + const cleanTokens = new Set(tokenize(normalizedClean)); + + let intersectionSize = 0; + for (const token of cleanTokens) { if (originalTokens.has(token)) intersectionSize += 1; } + + const largerSetSize = Math.max(1, Math.max(originalTokens.size, cleanTokens.size)); + const overlapScore = intersectionSize / largerSetSize; + + const hasBothYears = Boolean(releaseYear && year); + const yearMatches = hasBothYears ? parseInt(releaseYear) === year : true; + const exactTitleMatch = normalizedClean === normalizedOriginal; + const threshold = 0.7; + const partialLengthOk = cleanTokens.size <= originalTokens.size + 1; + const subsetCoverage = cleanTokens.size / Math.max(1, originalTokens.size); + const resultIsSubsetOfOriginal = Array.from(cleanTokens).every(t => originalTokens.has(t)) && subsetCoverage >= 0.75; + const shouldInclude = yearMatches && ( + exactTitleMatch || resultIsSubsetOfOriginal || (overlapScore >= threshold && partialLengthOk) + ); + + if (shouldInclude) { + filteredResults.push({ + title: cleanTitle, originalTitle: title, + link: link.startsWith('http') ? link : `${FSTREAM_BASE_URL}${link}`, + seasonNumber, year + }); + } + }); + + return filteredResults; + } catch (error) { + console.error(`Erreur lors du filtrage des resultats FStream: ${error.message}`); + return []; + } +} + +// === Routes === + +// GET /movie/:id +router.get('/movie/:id', async (req, res) => { + const { id } = req.params; + const cacheKey = generateFStreamCacheKey('movie', id); + + try { + const cachedData = await getFStreamFromCache(cacheKey); + if (cachedData) { + res.status(200).json(cachedData); + + // Background update + setImmediate(async () => { + try { + await getOrCreateFStreamRequest(`${cacheKey}_background`, async () => { + const tmdbDetails = await getFStreamTMDBDetails(id, 'movie'); + if (!tmdbDetails) return; + + const searchQuery = tmdbDetails.title; + let searchResults = await searchFStreamDirect(searchQuery); + let filteredResults = filterFStreamResults(searchResults, tmdbDetails.title, tmdbDetails.release_date?.split('-')[0]); + + if (filteredResults.length === 0) { + try { + const recentMovie = await findMovieInRecentFStream(tmdbDetails.title, tmdbDetails.release_date?.split('-')[0]); + if (recentMovie) { + const players = await getMoviePlayersForUrl(recentMovie.link); + if (players.total > 0) { + const response = { + success: true, source: 'FStream', type: 'movie', tmdb: tmdbDetails, + search: { query: tmdbDetails.title, results: 1, bestMatch: { title: recentMovie.title, originalTitle: `${recentMovie.title} (${tmdbDetails.release_date?.split('-')[0]})`, link: recentMovie.link, seasonNumber: null, year: parseInt(tmdbDetails.release_date?.split('-')[0]) } }, + players: players.organized, total: players.total, + metadata: { extractedAt: new Date().toISOString(), backgroundUpdate: true, foundInRecent: true } + }; + await saveFStreamToCache(cacheKey, response); + return; + } + } + } catch (recentError) { + console.error(`[FSTREAM BACKGROUND] Erreur lors de la recherche dans les recents: ${recentError.message}`); + } + + const errorResult = { success: false, error: 'Aucun resultat trouve', message: `Aucun contenu trouve pour "${tmdbDetails.title}" sur FStream`, search: { query: tmdbDetails.title, results: 0, checkedRecent: true }, timestamp: new Date().toISOString() }; + await saveFStreamToCache(cacheKey, errorResult); + return; + } + + let bestResult = null; + const tmdbYear = tmdbDetails.release_date?.split('-')[0]; + + if (tmdbYear) { + const yearMatches = filteredResults.filter(result => result.year === parseInt(tmdbYear)); + if (yearMatches.length > 0) { + bestResult = yearMatches[0]; + } else { + try { + const recentMovie = await findMovieInRecentFStream(tmdbDetails.title, tmdbDetails.release_date?.split('-')[0]); + if (recentMovie) { + const players = await getMoviePlayersForUrl(recentMovie.link); + if (players.total > 0) { + const response = { + success: true, source: 'FStream', type: 'movie', tmdb: tmdbDetails, + search: { query: tmdbDetails.title, results: 1, bestMatch: { title: recentMovie.title, originalTitle: `${recentMovie.title} (${tmdbDetails.release_date?.split('-')[0]})`, link: recentMovie.link, seasonNumber: null, year: parseInt(tmdbDetails.release_date?.split('-')[0]) } }, + players: players.organized, total: players.total, + metadata: { extractedAt: new Date().toISOString(), backgroundUpdate: true, foundInRecent: true } + }; + await saveFStreamToCache(cacheKey, response); + return; + } + } + } catch (recentError) { + console.error(`[FSTREAM BACKGROUND] Erreur lors de la recherche dans les recents: ${recentError.message}`); + } + const errorResult = { success: false, error: 'Aucune correspondance d\'annee', message: `Aucun contenu trouve avec l'annee ${tmdbYear} pour "${tmdbDetails.title}" sur FStream`, search: { query: tmdbDetails.title, results: filteredResults.length, year: tmdbYear, checkedRecent: true }, timestamp: new Date().toISOString() }; + await saveFStreamToCache(cacheKey, errorResult); + return; + } + } else { + bestResult = filteredResults[0]; + } + + if (!bestResult) { + const errorResult = { success: false, error: 'Aucun resultat valide', message: `Aucun resultat valide trouve pour "${tmdbDetails.title}" sur FStream`, search: { query: tmdbDetails.title, results: filteredResults.length }, timestamp: new Date().toISOString() }; + await saveFStreamToCache(cacheKey, errorResult); + return; + } + + const players = await getMoviePlayersForUrl(bestResult.link); + if (players.total === 0) return; + + const response = { + success: true, source: 'FStream', type: 'movie', tmdb: tmdbDetails, + search: { query: searchQuery, results: filteredResults.length, bestMatch: bestResult }, + players: players.organized, total: players.total, + metadata: { extractedAt: new Date().toISOString(), backgroundUpdate: true } + }; + await saveFStreamToCache(cacheKey, response); + return response; + }); + } catch (error) { /* background error, ignore */ } + }); + + return; + } + + // No cache - make request with deduplication + const result = await getOrCreateFStreamRequest(cacheKey, async () => { + const tmdbDetails = await getFStreamTMDBDetails(id, 'movie'); + if (!tmdbDetails) throw new Error('Contenu TMDB non trouve'); + + const searchQuery = tmdbDetails.title; + let searchResults = await searchFStreamDirect(searchQuery); + let filteredResults = filterFStreamResults(searchResults, tmdbDetails.title, tmdbDetails.release_date?.split('-')[0]); + + let bestResult = null; + const tmdbYear = tmdbDetails.release_date?.split('-')[0]; + + if (tmdbYear) { + const yearMatches = filteredResults.filter(result => result.year === parseInt(tmdbYear)); + if (yearMatches.length > 0) { + bestResult = yearMatches[0]; + } else { + const recentMovie = await findMovieInRecentFStream(tmdbDetails.title, tmdbYear); + if (recentMovie) { + bestResult = { title: recentMovie.title, originalTitle: `${recentMovie.title} (${tmdbYear})`, link: recentMovie.link, seasonNumber: null, year: parseInt(tmdbYear) }; + } else { + throw new Error(`Aucun resultat trouve avec l'annee ${tmdbYear} sur FStream`); + } + } + } else { + if (filteredResults.length > 0) bestResult = filteredResults[0]; + } + + if (filteredResults.length === 0 && !bestResult) { + const recentMovie = await findMovieInRecentFStream(tmdbDetails.title, tmdbYear); + if (recentMovie) { + bestResult = { title: recentMovie.title, originalTitle: `${recentMovie.title}${tmdbYear ? ` (${tmdbYear})` : ''}`, link: recentMovie.link, seasonNumber: null, year: tmdbYear ? parseInt(tmdbYear) : null }; + } else { + throw new Error('Aucun resultat trouve sur FStream'); + } + } + + if (!bestResult) throw new Error('Aucun resultat valide trouve sur FStream'); + + const players = await getMoviePlayersForUrl(bestResult.link); + if (players.total === 0) { + return res.status(404).json({ error: 'Aucun lecteur video trouve', searchQuery, bestResult: bestResult.title }); + } + + return { + success: true, source: 'FStream', type: 'movie', tmdb: tmdbDetails, + search: { query: searchQuery, results: filteredResults.length, bestMatch: bestResult }, + players: players.organized, total: players.total, + metadata: { extractedAt: new Date().toISOString() } + }; + }); + + await saveFStreamToCache(cacheKey, result); + res.status(200).json(result); + + } catch (error) { + console.error(`[FSTREAM MOVIE] Erreur: ${error.message}`); + const errorResult = { success: false, error: 'Erreur lors de la recuperation des sources FStream', message: error.message, timestamp: new Date().toISOString() }; + await saveFStreamToCache(cacheKey, errorResult); + res.status(500).json(errorResult); + } +}); + +// GET /movie/:id/clear-cache +router.get('/movie/:id/clear-cache', async (req, res) => { + const { id } = req.params; + const cacheKey = generateFStreamCacheKey('movie', id); + const cacheFilePath = path.join(CACHE_DIR.FSTREAM, `${cacheKey}.json`); + + try { + await fsp.unlink(cacheFilePath); + try { const redis = getRedis(); if (redis) await redis.del(`fstream:${cacheKey}`); } catch {} + console.log(`[FSTREAM Cache] Cache cleared for movie ${id}`); + res.json({ success: true, message: `Cache cleared for movie ${id}` }); + } catch (error) { + if (error.code === 'ENOENT') { + try { const redis = getRedis(); if (redis) await redis.del(`fstream:${cacheKey}`); } catch {} + res.status(404).json({ error: `No cache found for movie ${id}` }); + } else { + console.error(`[FSTREAM Cache] Error clearing cache for movie ${id}:`, error.message); + res.status(500).json({ error: 'Failed to clear cache' }); + } + } +}); + +// GET /tv/:id/season/:season/clear-cache +router.get('/tv/:id/season/:season/clear-cache', async (req, res) => { + const { id, season } = req.params; + const { episode } = req.query; + const cacheKey = generateFStreamCacheKey('tv', id, season, episode || null); + const cacheFilePath = path.join(CACHE_DIR.FSTREAM, `${cacheKey}.json`); + + try { + await fsp.unlink(cacheFilePath); + try { const redis = getRedis(); if (redis) await redis.del(`fstream:${cacheKey}`); } catch {} + console.log(`[FSTREAM Cache] Cache cleared for tv ${id} S${season}${episode ? ' E' + episode : ''}`); + res.json({ success: true, message: `Cache cleared for tv ${id} season ${season}${episode ? ' episode ' + episode : ''}` }); + } catch (error) { + if (error.code === 'ENOENT') { + try { const redis = getRedis(); if (redis) await redis.del(`fstream:${cacheKey}`); } catch {} + res.status(404).json({ error: `No cache found for tv ${id} season ${season}` }); + } else { + console.error(`[FSTREAM Cache] Error clearing cache for tv ${id}:`, error.message); + res.status(500).json({ error: 'Failed to clear cache' }); + } + } +}); + +// GET /tv/:id/season/:season +router.get('/tv/:id/season/:season', async (req, res) => { + const { id, season } = req.params; + const { episode } = req.query; + const cacheKey = generateFStreamCacheKey('tv', id, season, episode); + + try { + const cachedData = await getFStreamFromCache(cacheKey); + if (cachedData) { + res.status(200).json(cachedData); + + // Background update + setImmediate(async () => { + try { + await getOrCreateFStreamRequest(`${cacheKey}_background`, async () => { + const tmdbDetails = await getFStreamTMDBDetails(id, 'tv'); + if (!tmdbDetails) return; + + let searchQuery; + if (id === '259909') { searchQuery = 'Dexter : Resurrection - Saison 1'; } + else { searchQuery = `${tmdbDetails.title} - Saison ${season}`; } + + let searchResults = await searchFStreamDirect(searchQuery); + let filteredResults = filterFStreamResults(searchResults, tmdbDetails.title, tmdbDetails.release_date?.split('-')[0]); + + if (filteredResults.length === 0) { + const directSeasonsEarly = await fetchFStreamSeasonSearchResults(id, tmdbDetails.title); + if (directSeasonsEarly.length > 0) filteredResults = directSeasonsEarly; + + if (tmdbDetails.release_date) { + const year = tmdbDetails.release_date.split('-')[0]; + const fallbackQuery = `${tmdbDetails.title} (${year}) - Saison ${season}`; + try { + let fallbackSearchResults = await searchFStreamDirect(fallbackQuery); + let fallbackFilteredResults = filterFStreamResults(fallbackSearchResults, tmdbDetails.title, year); + if (fallbackFilteredResults.length > 0) filteredResults = fallbackFilteredResults; + } catch (fallbackError) { + console.log(`[FSTREAM TV BACKGROUND] Erreur lors de la recherche de fallback avec annee: ${fallbackError.message}`); + } + } + + if (filteredResults.length === 0 && tmdbDetails.name_no_lang && tmdbDetails.name_no_lang !== tmdbDetails.title) { + const noLangFallbackQuery = `${tmdbDetails.name_no_lang} - Saison ${season}`; + try { + let noLangSearchResults = await searchFStreamDirect(noLangFallbackQuery); + let noLangFilteredResults = filterFStreamResults(noLangSearchResults, tmdbDetails.name_no_lang, tmdbDetails.release_date?.split('-')[0]); + if (noLangFilteredResults.length > 0) { + filteredResults = noLangFilteredResults; + console.log(`[FSTREAM TV BACKGROUND] Fallback avec nom sans langue reussi: "${noLangFallbackQuery}"`); + } + } catch (noLangFallbackError) { + console.log(`[FSTREAM TV BACKGROUND] Erreur lors de la recherche de fallback avec nom sans langue: ${noLangFallbackError.message}`); + } + } + + if (filteredResults.length === 0) { + const directSeasons = await fetchFStreamSeasonSearchResults(id, tmdbDetails.title); + if (directSeasons.length > 0) filteredResults = directSeasons; + + if (filteredResults.length === 0) { + const releaseDate = tmdbDetails.release_date; + let shouldCheckRecent = false; + if (releaseDate) { + const releaseDateTime = new Date(releaseDate); + const now = new Date(); + const diffInDays = (now - releaseDateTime) / (1000 * 60 * 60 * 24); + if (diffInDays <= 2) shouldCheckRecent = true; + } + + if (shouldCheckRecent) { + try { + const recentSeries = await findSeriesInRecentFStream(tmdbDetails.title, tmdbDetails.release_date?.split('-')[0]); + if (recentSeries) { + const players = await getSeriesPlayersForUrl(recentSeries.link); + if (players.total > 0) { + const response = { + success: true, source: 'FStream', type: 'tv', tmdb: tmdbDetails, + search: { query: `${tmdbDetails.title} - Saison ${season}`, results: 1, bestMatch: { title: recentSeries.title, originalTitle: `${recentSeries.title} (${tmdbDetails.release_date?.split('-')[0]})`, link: recentSeries.link, seasonNumber: parseInt(season), year: parseInt(tmdbDetails.release_date?.split('-')[0]) } }, + episodes: players.episodes, total: players.total, + metadata: { season: parseInt(season), episode: episode ? parseInt(episode) : null, extractedAt: new Date().toISOString(), backgroundUpdate: true, foundInRecent: true } + }; + await saveFStreamToCache(cacheKey, response); + return; + } + } + } catch (recentError) { + console.error(`[FSTREAM TV BACKGROUND] Erreur lors de la recherche dans les recents: ${recentError.message}`); + } + } + + // Background update: ne pas écraser le cache avec une erreur + return; + } + } + } + + const requestedSeason = parseInt(season); + const bgTmdbYear = tmdbDetails.release_date ? parseInt(tmdbDetails.release_date.split('-')[0]) : null; + + // Trouver tous les resultats correspondant a la saison demandee + const seasonMatches = filteredResults.filter(result => result.seasonNumber && result.seasonNumber === requestedSeason); + let bestResult = null; + if (seasonMatches.length > 1 && bgTmdbYear) { + bestResult = seasonMatches.find(r => r.year === bgTmdbYear) || seasonMatches[0]; + } else if (seasonMatches.length === 1) { + bestResult = seasonMatches[0]; + } + + if (!bestResult) { + const titleSeasonMatches = filteredResults.filter(result => { + if (result.originalTitle) { + const seasonInTitle = result.originalTitle.match(/Saison\s+(\d+)/i); + if (seasonInTitle) return parseInt(seasonInTitle[1]) === requestedSeason; + } + return false; + }); + if (titleSeasonMatches.length > 1 && bgTmdbYear) { + bestResult = titleSeasonMatches.find(r => r.year === bgTmdbYear) || titleSeasonMatches[0]; + } else if (titleSeasonMatches.length === 1) { + bestResult = titleSeasonMatches[0]; + } + } + + // Fallback: rechercher sans le numero de saison (FStream retourne parfois des resultats differents) + if (!bestResult) { + try { + const noNumQuery = `${tmdbDetails.title} - Saison`; + const noNumResults = await searchFStreamDirect(noNumQuery); + const noNumFiltered = filterFStreamResults(noNumResults, tmdbDetails.title, tmdbDetails.release_date?.split('-')[0]); + const noNumSeasonMatches = noNumFiltered.filter(r => r.seasonNumber === requestedSeason); + if (noNumSeasonMatches.length > 0) { + bestResult = noNumSeasonMatches.length > 1 && bgTmdbYear ? (noNumSeasonMatches.find(r => r.year === bgTmdbYear) || noNumSeasonMatches[0]) : noNumSeasonMatches[0]; + filteredResults = noNumFiltered; + console.log(`[FSTREAM TV BACKGROUND] Fallback sans numero de saison reussi pour "${tmdbDetails.title}" saison ${requestedSeason}`); + } + } catch (e) { + console.log(`[FSTREAM TV BACKGROUND] Erreur fallback sans numero de saison: ${e.message}`); + } + } + + if (!bestResult) { + // Background update: ne pas écraser le cache avec une erreur + return; + } + + const players = await getSeriesPlayersForUrl(bestResult.link); + if (players.total === 0) return; + + let isAvailable = true; + if (tmdbDetails.release_date) { + const tmdbYearStr = tmdbDetails.release_date.split('-')[0]; + if (players.fromApi) { + if (bestResult.year && bestResult.year !== parseInt(tmdbYearStr)) { + isAvailable = false; + } + } else { + if (players.fstreamReleaseDate) { + if (players.fstreamReleaseDate !== tmdbYearStr) isAvailable = false; + } else { isAvailable = false; } + } + } + + const response = { + success: isAvailable, source: 'FStream', type: 'tv', tmdb: tmdbDetails, + search: { query: searchQuery, results: filteredResults.length, bestMatch: bestResult }, + episodes: isAvailable ? players.episodes : {}, total: isAvailable ? players.total : 0, + metadata: { season: parseInt(season), episode: episode ? parseInt(episode) : null, extractedAt: new Date().toISOString(), backgroundUpdate: true, fstreamReleaseDate: players.fstreamReleaseDate, dateValidation: { fstreamYear: players.fstreamReleaseDate, tmdbYear: tmdbDetails.release_date?.split('-')[0], isAvailable } } + }; + await saveFStreamToCache(cacheKey, response); + return response; + }); + } catch (error) { /* background error, ignore */ } + }); + + return; + } + + // No cache + const result = await getOrCreateFStreamRequest(cacheKey, async () => { + const tmdbDetails = await getFStreamTMDBDetails(id, 'tv'); + if (!tmdbDetails) throw new Error('Contenu TMDB non trouve'); + + let searchQuery; + if (id === '259909') { searchQuery = 'Dexter : Resurrection - Saison 1'; } + else { searchQuery = `${tmdbDetails.title} - Saison ${season}`; } + + let searchResults = await searchFStreamDirect(searchQuery); + let filteredResults = filterFStreamResults(searchResults, tmdbDetails.title, tmdbDetails.release_date?.split('-')[0]); + + if (filteredResults.length === 0) { + const directSeasonsEarly = await fetchFStreamSeasonSearchResults(id, tmdbDetails.title); + if (directSeasonsEarly.length > 0) { filteredResults = directSeasonsEarly; console.log(`[FSTREAM TV] Requete directe des saisons reussie (ajax - precoce)`); } + + if (tmdbDetails.release_date) { + const year = tmdbDetails.release_date.split('-')[0]; + const fallbackQuery = `${tmdbDetails.title} (${year}) - Saison ${season}`; + try { + let fallbackSearchResults = await searchFStreamDirect(fallbackQuery); + let fallbackFilteredResults = filterFStreamResults(fallbackSearchResults, tmdbDetails.title, year); + if (fallbackFilteredResults.length > 0) filteredResults = fallbackFilteredResults; + } catch (fallbackError) { + console.log(`[FSTREAM TV] Erreur lors de la recherche de fallback avec annee: ${fallbackError.message}`); + } + } + + if (filteredResults.length === 0 && tmdbDetails.name_no_lang && tmdbDetails.name_no_lang !== tmdbDetails.title) { + const noLangFallbackQuery = `${tmdbDetails.name_no_lang} - Saison ${season}`; + try { + let noLangSearchResults = await searchFStreamDirect(noLangFallbackQuery); + let noLangFilteredResults = filterFStreamResults(noLangSearchResults, tmdbDetails.name_no_lang, tmdbDetails.release_date?.split('-')[0]); + if (noLangFilteredResults.length > 0) { filteredResults = noLangFilteredResults; console.log(`[FSTREAM TV] Fallback avec nom sans langue reussi: "${noLangFallbackQuery}"`); } + } catch (noLangFallbackError) { + console.log(`[FSTREAM TV] Erreur lors de la recherche de fallback avec nom sans langue: ${noLangFallbackError.message}`); + } + } + + if (filteredResults.length === 0) { + const directSeasons = await fetchFStreamSeasonSearchResults(id, tmdbDetails.title); + if (directSeasons.length > 0) { filteredResults = directSeasons; console.log(`[FSTREAM TV] Requete directe des saisons reussie (ajax)`); } + } + + if (filteredResults.length === 0) throw new Error('Aucun resultat trouve sur FStream'); + } + + const requestedSeason = parseInt(season); + const tmdbYear = tmdbDetails.release_date ? parseInt(tmdbDetails.release_date.split('-')[0]) : null; + + // Trouver tous les resultats correspondant a la saison demandee + const seasonMatches = filteredResults.filter(result => result.seasonNumber && result.seasonNumber === requestedSeason); + + let bestResult = null; + if (seasonMatches.length > 1 && tmdbYear) { + // Prioriser le resultat dont l'annee correspond a l'annee TMDB + bestResult = seasonMatches.find(r => r.year === tmdbYear) || seasonMatches[0]; + } else if (seasonMatches.length === 1) { + bestResult = seasonMatches[0]; + } + + if (!bestResult) { + // Fallback: chercher dans le titre original + const titleSeasonMatches = filteredResults.filter(result => { + if (result.originalTitle) { + const seasonInTitle = result.originalTitle.match(/Saison\s+(\d+)/i); + if (seasonInTitle) return parseInt(seasonInTitle[1]) === requestedSeason; + } + return false; + }); + if (titleSeasonMatches.length > 1 && tmdbYear) { + bestResult = titleSeasonMatches.find(r => r.year === tmdbYear) || titleSeasonMatches[0]; + } else if (titleSeasonMatches.length === 1) { + bestResult = titleSeasonMatches[0]; + } + } + + // Fallback: rechercher sans le numero de saison (FStream retourne parfois des resultats differents) + if (!bestResult) { + try { + const noNumQuery = `${tmdbDetails.title} - Saison`; + const noNumResults = await searchFStreamDirect(noNumQuery); + const noNumFiltered = filterFStreamResults(noNumResults, tmdbDetails.title, tmdbDetails.release_date?.split('-')[0]); + const noNumSeasonMatches = noNumFiltered.filter(r => r.seasonNumber === requestedSeason); + if (noNumSeasonMatches.length > 0) { + bestResult = noNumSeasonMatches.length > 1 && tmdbYear ? (noNumSeasonMatches.find(r => r.year === tmdbYear) || noNumSeasonMatches[0]) : noNumSeasonMatches[0]; + filteredResults = noNumFiltered; + console.log(`[FSTREAM TV] Fallback sans numero de saison reussi pour "${tmdbDetails.title}" saison ${requestedSeason}`); + } + } catch (e) { + console.log(`[FSTREAM TV] Erreur fallback sans numero de saison: ${e.message}`); + } + } + + if (!bestResult) { + const availableSeasons = filteredResults + .filter(r => r.seasonNumber && r.title.toLowerCase().includes(tmdbDetails.title.toLowerCase().split(/[:\-]/)[0].trim().toLowerCase())) + .map(r => r.seasonNumber) + .filter((s, i, arr) => arr.indexOf(s) === i) + .sort((a, b) => a - b); + const seasonText = availableSeasons.length > 0 + ? `Saisons disponibles pour "${tmdbDetails.title}": ${availableSeasons.join(', ')}` + : `Aucune saison trouvee pour "${tmdbDetails.title}"`; + throw new Error(`Saison ${requestedSeason} non trouvee. ${seasonText}`); + } + + // Verifier la correspondance d'annee meme quand l'API est utilisee + if (tmdbYear && bestResult.year && bestResult.year !== tmdbYear) { + console.log(`[FSTREAM TV] Annee non correspondante: TMDB=${tmdbYear}, FStream=${bestResult.year} pour "${bestResult.title}"`); + } + + const players = await getSeriesPlayersForUrl(bestResult.link); + if (players.total === 0) throw new Error('Aucun lecteur video trouve'); + + let isAvailable = true; + if (tmdbDetails.release_date) { + const tmdbYearStr = tmdbDetails.release_date.split('-')[0]; + if (players.fromApi) { + // Quand l'API est utilisee, valider via l'annee du resultat de recherche + if (bestResult.year && bestResult.year !== parseInt(tmdbYearStr)) { + isAvailable = false; + } + } else { + if (players.fstreamReleaseDate) { + if (players.fstreamReleaseDate !== tmdbYearStr) isAvailable = false; + } else { isAvailable = false; } + } + } + + return { + success: isAvailable, source: 'FStream', type: 'tv', tmdb: tmdbDetails, + search: { query: searchQuery, results: filteredResults.length, bestMatch: bestResult }, + episodes: isAvailable ? players.episodes : {}, total: isAvailable ? players.total : 0, + metadata: { season: parseInt(season), episode: episode ? parseInt(episode) : null, extractedAt: new Date().toISOString(), fstreamReleaseDate: players.fstreamReleaseDate, dateValidation: { fstreamYear: players.fstreamReleaseDate, tmdbYear: tmdbDetails.release_date?.split('-')[0], isAvailable } } + }; + }); + + await saveFStreamToCache(cacheKey, result); + res.status(200).json(result); + + } catch (error) { + console.error(`[FSTREAM TV] Erreur: ${error.message}`); + const errorResult = { success: false, error: 'Erreur lors de la recuperation des sources FStream', message: error.message, timestamp: new Date().toISOString() }; + await saveFStreamToCache(cacheKey, errorResult); + res.status(500).json(errorResult); + } +}); + +// GET /test/recent +router.get('/test/recent', async (req, res) => { + try { + const recentMovies = await scrapeFStreamRecentMovies(); + res.status(200).json({ success: true, count: recentMovies.length, movies: recentMovies.slice(0, 10), timestamp: new Date().toISOString() }); + } catch (error) { + res.status(500).json({ success: false, error: error.message, timestamp: new Date().toISOString() }); + } +}); + +// GET /test/recent-series +router.get('/test/recent-series', async (req, res) => { + try { + const recentSeries = await scrapeFStreamRecentSeries(); + res.status(200).json({ success: true, count: recentSeries.length, series: recentSeries.slice(0, 10), timestamp: new Date().toISOString() }); + } catch (error) { + res.status(500).json({ success: false, error: error.message, timestamp: new Date().toISOString() }); + } +}); + +// GET /debug/ongoing +router.get('/debug/ongoing', async (req, res) => { + try { + const ongoingKeys = Array.from(ongoingFStreamRequests.keys()); + res.status(200).json({ success: true, ongoingRequests: ongoingKeys.length, keys: ongoingKeys, timestamp: new Date().toISOString() }); + } catch (error) { + res.status(500).json({ success: false, error: error.message }); + } +}); + +module.exports = router; diff --git a/API/Mainapi/routes/profiles.js b/API/Mainapi/routes/profiles.js new file mode 100644 index 0000000..5797a35 --- /dev/null +++ b/API/Mainapi/routes/profiles.js @@ -0,0 +1,294 @@ +/** + * Profile management routes. + * Extracted from server.js -- CRUD operations for user profiles. + * Mount point: app.use('/api/profiles', router) + */ + +const express = require('express'); +const router = express.Router(); +const fsp = require('fs').promises; +const { v4: uuidv4 } = require('uuid'); + +const { getAuthIfValid } = require('../middleware/auth'); +const { getPool } = require('../mysqlPool'); +const { + ensureSafeProfileId, + getOwnedProfile, + getProfileFilePath, + sanitizeProfileData +} = require('../utils/syncPolicy'); + +// Lazy imports from sync module to avoid circular dependencies +let _syncModule = null; +function getSyncModule() { + if (!_syncModule) _syncModule = require('./sync'); + return _syncModule; +} + +// === Routes === + +// GET / - Get all profiles for authenticated user +router.get('/', async (req, res) => { + try { + const auth = await getAuthIfValid(req); + if (!auth || !['oauth', 'bip39'].includes(auth.userType)) { + return res.status(401).json({ error: 'Unauthorized' }); + } + + const { readUserData } = getSyncModule(); + const userData = await readUserData(auth.userType, auth.userId); + const profiles = userData.profiles || []; + + res.status(200).json({ success: true, profiles }); + } catch (error) { + console.error('Error getting profiles:', error); + res.status(500).json({ error: 'Failed to get profiles' }); + } +}); + +// POST / - Create new profile (max 5 per user) +router.post('/', async (req, res) => { + try { + const auth = await getAuthIfValid(req); + if (!auth || !['oauth', 'bip39'].includes(auth.userType)) { + return res.status(401).json({ error: 'Unauthorized' }); + } + + const { name, avatar, ageRestriction } = req.body; + if (!name || !avatar) return res.status(400).json({ error: 'Name and avatar are required' }); + if (avatar && !avatar.startsWith('/avatars/') && avatar !== '') { + return res.status(400).json({ error: 'Invalid avatar URL. Must be a local path starting with /avatars/' }); + } + const validAgeRestrictions = [0, 7, 12, 16, 18]; + const ageRestrictionValue = validAgeRestrictions.includes(Number(ageRestriction)) ? Number(ageRestriction) : 0; + + const { readUserData, writeUserData } = getSyncModule(); + const userData = await readUserData(auth.userType, auth.userId); + const profiles = userData.profiles || []; + + if (profiles.length >= 5) return res.status(400).json({ error: 'Maximum 5 profiles allowed' }); + + const profileId = uuidv4(); + const newProfile = { + id: profileId, + name: name.trim(), + avatar, + ageRestriction: ageRestrictionValue, + createdAt: new Date().toISOString(), + isDefault: profiles.length === 0 + }; + + userData.profiles = [...profiles, newProfile]; + userData.lastUpdated = Date.now(); + + const success = await writeUserData(auth.userType, auth.userId, userData); + if (!success) return res.status(500).json({ error: 'Failed to create profile' }); + + res.status(200).json({ success: true, profile: newProfile }); + } catch (error) { + console.error('Error creating profile:', error); + res.status(500).json({ error: 'Failed to create profile' }); + } +}); + +// PUT /:profileId - Update profile (name, avatar) +router.put('/:profileId', async (req, res) => { + try { + const auth = await getAuthIfValid(req); + if (!auth || !['oauth', 'bip39'].includes(auth.userType)) { + return res.status(401).json({ error: 'Unauthorized' }); + } + + const profileId = ensureSafeProfileId(req.params.profileId); + const { name, avatar, ageRestriction } = req.body; + if (!name && !avatar && ageRestriction === undefined) return res.status(400).json({ error: 'Name, avatar, or ageRestriction is required' }); + if (avatar && !avatar.startsWith('/avatars/') && avatar !== '') { + return res.status(400).json({ error: 'Invalid avatar URL. Must be a local path starting with /avatars/' }); + } + + const { readUserData, writeUserData } = getSyncModule(); + const userData = await readUserData(auth.userType, auth.userId); + const profiles = userData.profiles || []; + + const profileIndex = profiles.findIndex(p => p.id === profileId); + if (profileIndex === -1) return res.status(404).json({ error: 'Profile not found' }); + + if (name) profiles[profileIndex].name = name.trim(); + if (avatar) profiles[profileIndex].avatar = avatar; + if (ageRestriction !== undefined) { + const validAgeRestrictions = [0, 7, 12, 16, 18]; + profiles[profileIndex].ageRestriction = validAgeRestrictions.includes(Number(ageRestriction)) ? Number(ageRestriction) : 0; + } + + userData.profiles = profiles; + userData.lastUpdated = Date.now(); + + const success = await writeUserData(auth.userType, auth.userId, userData); + if (!success) return res.status(500).json({ error: 'Failed to update profile' }); + + res.status(200).json({ success: true, profile: profiles[profileIndex] }); + } catch (error) { + console.error('Error updating profile:', error); + res.status(500).json({ error: 'Failed to update profile' }); + } +}); + +// DELETE /:profileId - Delete profile (except last one) +router.delete('/:profileId', async (req, res) => { + try { + const auth = await getAuthIfValid(req); + if (!auth || !['oauth', 'bip39'].includes(auth.userType)) { + return res.status(401).json({ error: 'Unauthorized' }); + } + + const profileId = ensureSafeProfileId(req.params.profileId); + const { readUserData, writeUserData, USERS_DIR } = getSyncModule(); + const userData = await readUserData(auth.userType, auth.userId); + const profiles = userData.profiles || []; + + const isLastProfile = profiles.length <= 1; + const profileIndex = profiles.findIndex(p => p.id === profileId); + if (profileIndex === -1) return res.status(404).json({ error: 'Profile not found' }); + + const wasDefault = profiles[profileIndex]?.isDefault; + profiles.splice(profileIndex, 1); + + if (isLastProfile) { + let defaultName = 'Profil'; + let defaultAvatar = '/avatars/disney/disney_avatar_1.png'; + + if (auth.userType === 'bip39' && userData.auth) { + try { + const authData = JSON.parse(userData.auth); + if (authData.userProfile) { + defaultName = authData.userProfile.username || 'Profil'; + defaultAvatar = authData.userProfile.avatar || defaultAvatar; + } + } catch (e) { + console.log('Could not parse auth data for new default profile'); + } + } + + const newProfileId = uuidv4(); + const newDefaultProfile = { + id: newProfileId, name: defaultName, avatar: defaultAvatar, + createdAt: new Date().toISOString(), isDefault: true + }; + profiles.push(newDefaultProfile); + } else if (wasDefault && profiles.length > 0) { + profiles[0].isDefault = true; + } + + userData.profiles = profiles; + userData.lastUpdated = Date.now(); + + const success = await writeUserData(auth.userType, auth.userId, userData); + if (!success) return res.status(500).json({ error: 'Failed to delete profile' }); + + // Delete profile data file + const profilePath = getProfileFilePath(USERS_DIR, auth.userType, auth.userId, profileId); + try { await fsp.unlink(profilePath); } catch (e) { /* Ignore if file doesn't exist */ } + + // Delete associated votes (likes/dislikes) for this profile + try { + const pool = getPool(); + if (pool) { + await pool.execute( + 'DELETE FROM likes WHERE user_id = ? AND user_type = ? AND profile_id = ?', + [auth.userId, auth.userType, profileId] + ); + } + } catch (e) { + console.error('Error deleting profile votes:', e.message); + } + + res.status(200).json({ success: true, newDefaultProfile: isLastProfile ? profiles[profiles.length - 1] : null }); + } catch (error) { + console.error('Error deleting profile:', error); + res.status(500).json({ error: 'Failed to delete profile' }); + } +}); + +// GET /:profileId/data - Get profile-specific data +router.get('/:profileId/data', async (req, res) => { + try { + const sync = getSyncModule(); + if (sync.isShuttingDown && sync.isShuttingDown()) return res.status(503).json({ error: 'Server is shutting down' }); + sync.startOperation(); + + try { + const auth = await getAuthIfValid(req); + if (!auth || !['oauth', 'bip39'].includes(auth.userType)) { + return res.status(401).json({ error: 'Unauthorized' }); + } + + const profileId = ensureSafeProfileId(req.params.profileId); + + const userData = await sync.readUserData(auth.userType, auth.userId); + getOwnedProfile(userData, profileId); + + const profileData = await sync.readProfileData(auth.userType, auth.userId, profileId); + res.status(200).json({ success: true, data: profileData }); + } finally { + sync.endOperation(); + } + } catch (error) { + console.error('Error getting profile data:', error); + res.status(500).json({ error: 'Failed to get profile data' }); + } +}); + +// POST /migrate - Migrate existing user data to default profile +router.post('/migrate', async (req, res) => { + try { + const auth = await getAuthIfValid(req); + if (!auth || !['oauth', 'bip39'].includes(auth.userType)) { + return res.status(401).json({ error: 'Unauthorized' }); + } + + const { userData } = req.body; + const { readUserData, writeUserData, writeProfileData } = getSyncModule(); + + const existingUserData = await readUserData(auth.userType, auth.userId); + if (existingUserData.profiles && existingUserData.profiles.length > 0) { + return res.status(400).json({ error: 'User already has profiles' }); + } + + let defaultName = 'Profil'; + let defaultAvatar = '/avatars/disney/disney_avatar_1.png'; + + if (auth.userType === 'bip39' && existingUserData.auth) { + try { + const authData = JSON.parse(existingUserData.auth); + if (authData.userProfile) { + defaultName = authData.userProfile.username || 'Profil'; + defaultAvatar = authData.userProfile.avatar || defaultAvatar; + } + } catch (e) { console.log('Could not parse auth data for default profile'); } + } + + const profileId = uuidv4(); + const defaultProfile = { + id: profileId, name: defaultName, avatar: defaultAvatar, + createdAt: new Date().toISOString(), isDefault: true + }; + + const { data: profileData } = sanitizeProfileData(userData); + + const profileSuccess = await writeProfileData(auth.userType, auth.userId, profileId, profileData); + if (!profileSuccess) return res.status(500).json({ error: 'Failed to save profile data' }); + + existingUserData.profiles = [defaultProfile]; + existingUserData.lastUpdated = Date.now(); + + const userSuccess = await writeUserData(auth.userType, auth.userId, existingUserData); + if (!userSuccess) return res.status(500).json({ error: 'Failed to save user data' }); + + res.status(200).json({ success: true, profile: defaultProfile }); + } catch (error) { + console.error('Error migrating profile:', error); + res.status(500).json({ error: 'Failed to migrate profile' }); + } +}); + +module.exports = router; diff --git a/API/Mainapi/routes/proxy.js b/API/Mainapi/routes/proxy.js new file mode 100644 index 0000000..9eb70a6 --- /dev/null +++ b/API/Mainapi/routes/proxy.js @@ -0,0 +1,313 @@ +/** + * Proxy route. + * Extracted from server.js -- raw HTML proxy with domain-specific headers. + * Mount point: app.use('/proxy', router) + */ + +const express = require('express'); +const router = express.Router(); +const axios = require('axios'); +const crypto = require('crypto'); +const path = require('path'); +const fsp = require('fs').promises; + +const { safeWriteJsonFile } = require('../utils/safeFile'); +const { CACHE_DIR } = require('../utils/cacheManager'); + +// === Routes === + +// GET /* - Proxy route for raw HTML (replaces old /proxy route) +router.get(/^\/(.*)/, async (req, res) => { + try { + // Extract the target URL after / + let targetUrl = req.url.slice(1); // Remove leading '/' + + // Decode the URL recursively if it's encoded (handles double/triple encoding) + try { + let decoded = targetUrl; + let previousDecoded = ''; + // Keep decoding until the URL doesn't change anymore (handles multiple encodings) + while (decoded !== previousDecoded) { + previousDecoded = decoded; + try { + decoded = decodeURIComponent(decoded); + } catch (e) { + // If decoding fails, break the loop + break; + } + } + targetUrl = decoded; + } catch (decodeError) { + // If decoding fails, use the original URL + console.warn('Failed to decode URL:', targetUrl, decodeError.message); + } + + // Fix recursive proxying issue - remove any localhost/proxy/ patterns + const localhostProxyPattern = /localhost(:\d+)?\/proxy\//i; + if (localhostProxyPattern.test(targetUrl)) { + console.log(`Detected recursive proxy request in: ${targetUrl}`); + targetUrl = targetUrl.replace(localhostProxyPattern, ''); + console.log(`Corrected to: ${targetUrl}`); + } + + // Check if the URL starts with http(s)://, if not, prepend https:// + if (!targetUrl.startsWith('http://') && !targetUrl.startsWith('https://')) { + targetUrl = 'https://' + targetUrl; + } + + // === TVDIRECT SPECIAL HANDLING === + if (targetUrl.includes('tvdirect.ddns')) { + try { + const cacheKey = crypto.createHash('md5').update(targetUrl).digest('hex'); + // Ensure directory exists + await fsp.mkdir(CACHE_DIR.TVDIRECT, { recursive: true }); + const cacheFile = path.join(CACHE_DIR.TVDIRECT, `${cacheKey}.json`); + + // Helper to fetch external resource + const fetchTvDirect = async () => { + console.log(`[TVDIRECT] Fetching ${targetUrl}`); + const resp = await axios.get(targetUrl, { + headers: { + 'User-Agent': 'stremio', + 'Accept': '*/*' + }, + responseType: 'text', + timeout: 15000 + }); + return { + data: resp.data, + headers: resp.headers, + timestamp: Date.now() + }; + }; + + // Try to read from cache + let cachedEntry = null; + try { + const fileContent = await fsp.readFile(cacheFile, 'utf8'); + cachedEntry = JSON.parse(fileContent); + } catch (e) { /* No cache or invalid */ } + + const CACHE_TTL = 24 * 60 * 60 * 1000; // 24 hours + const now = Date.now(); + + if (cachedEntry && cachedEntry.data) { + // Serve cached response + if (cachedEntry.headers && cachedEntry.headers['content-type']) { + res.setHeader('Content-Type', cachedEntry.headers['content-type']); + } + res.setHeader('Access-Control-Allow-Origin', '*'); + res.send(cachedEntry.data); + + // Check if stale for background update + if (now - cachedEntry.timestamp > CACHE_TTL) { + console.log(`[TVDIRECT] Cache stale for ${targetUrl}, updating in background...`); + // Background update (no await) + fetchTvDirect().then(async (newData) => { + await safeWriteJsonFile(cacheFile, newData); + console.log(`[TVDIRECT] Background update success for ${targetUrl}`); + }).catch(err => console.error(`[TVDIRECT] Background update failed: ${err.message}`)); + } + return; // Exit route + } + + // No cache, fetch synchronously + const newData = await fetchTvDirect(); + await safeWriteJsonFile(cacheFile, newData); + + if (newData.headers && newData.headers['content-type']) { + res.setHeader('Content-Type', newData.headers['content-type']); + } + res.setHeader('Access-Control-Allow-Origin', '*'); + res.send(newData.data); + return; // Exit route + } catch (error) { + console.error(`[TVDIRECT] Error handling request:`, error); + return res.status(502).json({ error: 'TVDirect proxy failed', details: error.message }); + } + } + + // Préparer les headers à forwarder + let refererOrigin; + let targetHost; + try { + const urlObj = new URL(targetUrl); + refererOrigin = urlObj.origin; + targetHost = urlObj.host; + } catch (urlError) { + // Si l'URL est invalide, utiliser une valeur par défaut + console.warn('Invalid URL for referer:', targetUrl, urlError.message); + refererOrigin = 'https://vmwesa.online'; + targetHost = 'vmwesa.online'; + } + + // Headers spécifiques pour vmwesa/vidmoly et certains CDN (ex: getromes.space) + const isVmwesa = /vmwesa\.online|vidmoly|getromes\.space/i.test(targetUrl); + + // Headers spécifiques pour dropcdn + const isDropcdn = /dropcdn/i.test(targetUrl); + + // Headers spécifiques pour serversicuro + const isServersicuro = /serversicuro/i.test(targetUrl); + + // Headers spécifiques pour coflix + const isCoflix = /coflix\.(bet|si|boo|io)/i.test(targetUrl); + + const headers = isCoflix ? { + 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8', + 'Accept-Language': 'fr-FR,fr;q=0.7', + 'Cache-Control': 'no-cache', + 'Pragma': 'no-cache', + 'Priority': 'u=0, i', + 'Referer': 'https://coflix.space/', + 'Sec-CH-UA': '"Brave";v="141", "Not?A_Brand";v="8", "Chromium";v="141"', + 'Sec-CH-UA-Mobile': '?0', + 'Sec-CH-UA-Platform': '"Windows"', + 'Sec-Fetch-Dest': 'iframe', + 'Sec-Fetch-Mode': 'navigate', + 'Sec-Fetch-Site': 'cross-site', + 'Sec-Fetch-Storage-Access': 'none', + 'Sec-GPC': '1', + 'Upgrade-Insecure-Requests': '1', + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36' + } : isVmwesa ? { + 'Accept': 'application/vnd.apple.mpegurl,application/x-mpegURL,*/*', + 'Accept-Encoding': 'gzip, deflate, br, zstd', + 'Accept-Language': 'fr-FR,fr;q=0.8', + 'Connection': 'keep-alive', + 'Host': targetHost, + 'Origin': 'https://vidmoly.net', + 'Referer': 'https://vidmoly.net/', + 'Sec-CH-UA': '"Not;A=Brand";v="99", "Brave";v="139", "Chromium";v="139"', + 'Sec-CH-UA-Mobile': '?0', + 'Sec-CH-UA-Platform': '"Windows"', + 'Sec-Fetch-Dest': 'empty', + 'Sec-Fetch-Mode': 'cors', + 'Sec-Fetch-Site': 'cross-site', + 'Sec-GPC': '1', + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36' + } : isDropcdn ? { + 'Accept': '*/*', + 'Accept-Encoding': 'gzip, deflate, br, zstd', + 'Accept-Language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7', + 'Connection': 'keep-alive', + 'Host': targetHost, + 'Origin': 'https://dropload.tv', + 'Referer': 'https://dropload.tv/', + 'Sec-CH-UA': '"Not;A=Brand";v="99", "Brave";v="139", "Chromium";v="139"', + 'Sec-CH-UA-Mobile': '?0', + 'Sec-CH-UA-Platform': '"Windows"', + 'Sec-Fetch-Dest': 'empty', + 'Sec-Fetch-Mode': 'cors', + 'Sec-Fetch-Site': 'cross-site', + 'Sec-GPC': '1', + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36' + } : isServersicuro ? { + 'Accept': '*/*', + 'Accept-Encoding': 'gzip, deflate, br, zstd', + 'Accept-Language': 'fr-FR,fr;q=0.8', + 'Connection': 'keep-alive', + 'Host': targetHost, + 'Origin': 'https://supervideo.cc', + 'Referer': 'https://supervideo.cc/', + 'Sec-CH-UA': '"Not;A=Brand";v="99", "Brave";v="139", "Chromium";v="139"', + 'Sec-CH-UA-Mobile': '?0', + 'Sec-CH-UA-Platform': '"Windows"', + 'Sec-Fetch-Dest': 'empty', + 'Sec-Fetch-Mode': 'cors', + 'Sec-Fetch-Site': 'cross-site', + 'Sec-GPC': '1', + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36' + } : { + 'User-Agent': req.headers['user-agent'] || 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', + 'Referer': refererOrigin, + 'Accept': req.headers['accept'] || '*/*', + 'Accept-Encoding': req.headers['accept-encoding'] || 'gzip, deflate, br', + 'Connection': 'keep-alive', + }; + // Forward Range header if present (important for video streaming) + if (req.headers['range']) { + headers['Range'] = req.headers['range']; + } + + // Détecter si c'est un .m3u8 (playlist HLS) + const isM3U8 = targetUrl.toLowerCase().includes('.m3u8') || (req.headers.accept && req.headers.accept.includes('application/vnd.apple.mpegurl')); + + // Faire la requête distante avec l'agent de streaming pour le proxy + const response = await axios({ + method: 'get', + url: targetUrl, + responseType: isM3U8 ? 'text' : 'stream', + headers, + timeout: 30000, + maxRedirects: 5, + validateStatus: status => true, // On gère nous-même les codes d'erreur + decompress: true // Disable automatic decompression for better performance + }); + + // Copier les headers utiles + Object.entries(response.headers).forEach(([key, value]) => { + // Éviter certains headers problématiques + if (!['transfer-encoding', 'connection', 'content-encoding'].includes(key.toLowerCase())) { + res.setHeader(key, value); + } + }); + + // CORS headers + res.setHeader('Access-Control-Allow-Origin', '*'); + res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS', 'DELETE'); + res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Range'); + + // Si c'est un .m3u8, retourner le contenu original sans modification + if (isM3U8 && typeof response.data === 'string') { + const contentType = response.headers['content-type'] || ''; + const bodyText = response.data; + + // Retourner le contenu M3U8 original sans modification + if (contentType) res.setHeader('content-type', contentType); + res.status(response.status).send(bodyText); + return; + } + + // Gestion du code de retour (206 pour Range, sinon code d'origine) + res.status(response.status); + + // Détruire le stream upstream si le client se déconnecte pour éviter les fuites mémoire + const upstream = response.data; + res.on('close', () => { + if (!upstream.destroyed) { + upstream.destroy(); + } + }); + + upstream.on('error', (err) => { + console.error('Proxy upstream error:', err.message); + if (!res.headersSent) { + res.status(502).json({ error: 'Upstream stream error', message: err.message }); + } + if (!upstream.destroyed) upstream.destroy(); + }); + + upstream.pipe(res); + } catch (error) { + console.error('Proxy error:', error.message); + if (error.response) { + res.status(error.response.status).json({ + error: `Target server responded with ${error.response.status}`, + message: error.message + }); + } else if (error.request) { + res.status(504).json({ + error: 'Gateway Timeout', + message: 'No response received from target server' + }); + } else { + res.status(500).json({ + error: 'Internal Server Error', + message: error.message + }); + } + } +}); + +module.exports = router; diff --git a/API/Mainapi/routes/purstream.js b/API/Mainapi/routes/purstream.js new file mode 100644 index 0000000..5f72683 --- /dev/null +++ b/API/Mainapi/routes/purstream.js @@ -0,0 +1,446 @@ +/** + * PurStream routes module. + * Proxy vers l'API PurStream pour récupérer les streams de films et séries. + * Résolution TMDB → PurStream ID via recherche par titre + poster. + * Cache fichier L2 + memoryCache L1 (pattern identique aux autres routes). + * Pattern stale-while-revalidate : on sert le cache, on update en background. + * + * Mounted at /api/purstream + */ + +const express = require('express'); +const axios = require('axios'); +const router = express.Router(); +const { generateCacheKey, CACHE_DIR } = require('../utils/cacheManager'); +const { fetchTmdbDetails, fetchTmdbImages } = require('../utils/tmdbCache'); +const { pickRandomProxy, getProxyAgent } = require('../utils/proxyManager'); + +const PURSTREAM_BASE = 'https://api.purstream.cc/api/v1'; +const PURSTREAM_CACHE_DIR = CACHE_DIR.PURSTREAM; + +// --------------------------------------------------------------------------- +// Dependencies injected via configure() +// --------------------------------------------------------------------------- +let TMDB_API_KEY; +let TMDB_API_URL; +let PROXY_SERVER_URL; +let verifyAccessKey; +let getFromCacheNoExpiration; +let saveToCache; +let shouldUpdateCache; + +function configure(deps) { + if (deps.TMDB_API_KEY) TMDB_API_KEY = deps.TMDB_API_KEY; + if (deps.TMDB_API_URL) TMDB_API_URL = deps.TMDB_API_URL; + if (deps.PROXY_SERVER_URL) PROXY_SERVER_URL = deps.PROXY_SERVER_URL; + if (deps.verifyAccessKey) verifyAccessKey = deps.verifyAccessKey; + if (deps.getFromCacheNoExpiration) getFromCacheNoExpiration = deps.getFromCacheNoExpiration; + if (deps.saveToCache) saveToCache = deps.saveToCache; + if (deps.shouldUpdateCache) shouldUpdateCache = deps.shouldUpdateCache; +} + +/** Wrap une URL m3u8 dans le proxy cinep si VIP et PROXY_SERVER_URL configuré */ +function wrapSourceUrl(url, isVip) { + if (isVip && PROXY_SERVER_URL && url) { + // PROXY_SERVER_URL = "https://proxy.movix.rodeo/proxy" → on veut la base sans /proxy + const serverBase = PROXY_SERVER_URL.replace(/\/proxy\/?$/, '').replace(/\/+$/, ''); + return `${serverBase}/cinep-proxy?url=${encodeURIComponent(url)}`; + } + return url; +} + +/** Fait une requête vers PurStream avec un proxy SOCKS5 aléatoire */ +async function purstreamRequest(urlPath) { + const proxy = pickRandomProxy(); + const agent = proxy ? getProxyAgent(proxy) : null; + + return axios({ + url: `${PURSTREAM_BASE}${urlPath}`, + method: 'get', + timeout: 10000, + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36', + 'Accept': 'application/json' + }, + ...(agent ? { httpAgent: agent, httpsAgent: agent, proxy: false } : {}), + decompress: true + }); +} + +// Marqueur pour les résultats négatifs cachés +const NOT_FOUND_MARKER = { __not_found: true }; + +// --------------------------------------------------------------------------- +// Résolution TMDB ID → PurStream ID +// --------------------------------------------------------------------------- +async function resolvePurstreamId(tmdbId, type) { + const cacheKey = generateCacheKey(`purstream_map_${type}_${tmdbId}`); + + const cached = await getFromCacheNoExpiration(PURSTREAM_CACHE_DIR, cacheKey); + + if (cached) { + if (cached.__not_found) { + const stale = await shouldUpdateCache(PURSTREAM_CACHE_DIR, cacheKey); + if (stale) { + backgroundUpdateMapping(tmdbId, type, cacheKey).catch(() => {}); + } + return null; + } + const stale = await shouldUpdateCache(PURSTREAM_CACHE_DIR, cacheKey); + if (stale) { + backgroundUpdateMapping(tmdbId, type, cacheKey).catch(() => {}); + } + return cached; + } + + return await fetchAndCacheMapping(tmdbId, type, cacheKey); +} + +/** Recherche et cache le mapping TMDB → PurStream */ +async function fetchAndCacheMapping(tmdbId, type, cacheKey) { + const tmdbData = await fetchTmdbDetails(TMDB_API_URL, TMDB_API_KEY, tmdbId, type, 'fr-FR'); + if (!tmdbData) { + console.warn(`[PURSTREAM] TMDB ${type}:${tmdbId} introuvable`); + await saveToCache(PURSTREAM_CACHE_DIR, cacheKey, NOT_FOUND_MARKER); + return null; + } + + const tmdbTitle = type === 'movie' ? tmdbData.title : tmdbData.name; + const tmdbOriginalTitle = type === 'movie' ? tmdbData.original_title : tmdbData.original_name; + if (!tmdbTitle) { + console.warn(`[PURSTREAM] TMDB ${type}:${tmdbId} n'a pas de titre`); + await saveToCache(PURSTREAM_CACHE_DIR, cacheKey, NOT_FOUND_MARKER); + return null; + } + + // Collecter TOUS les posters TMDB (toutes langues, cache Redis intégré) + const tmdbPosters = new Set(); + if (tmdbData.poster_path) tmdbPosters.add(tmdbData.poster_path); + if (tmdbData.backdrop_path) tmdbPosters.add(tmdbData.backdrop_path); + const imagesData = await fetchTmdbImages(TMDB_API_URL, TMDB_API_KEY, tmdbId, type); + if (imagesData?.posters) { + for (const p of imagesData.posters) { + if (p.file_path) tmdbPosters.add(p.file_path); + } + } + if (imagesData?.backdrops) { + for (const b of imagesData.backdrops) { + if (b.file_path) tmdbPosters.add(b.file_path); + } + } + + // Chercher sur PurStream (titre FR puis titre original si différent) + const searchQueries = [tmdbTitle]; + if (tmdbOriginalTitle && tmdbOriginalTitle !== tmdbTitle) { + searchQueries.push(tmdbOriginalTitle); + } + + let allItems = []; + let searchError = false; + for (const query of searchQueries) { + try { + const response = await purstreamRequest(`/search-bar/search/${encodeURIComponent(query)}`); + if (response.data?.type === 'success') { + const items = response.data.data?.items?.movies?.items || []; + for (const item of items) { + if (!allItems.some(existing => existing.id === item.id)) { + allItems.push(item); + } + } + } + } catch (err) { + searchError = true; + console.warn(`[PURSTREAM] Recherche échouée pour "${query}": ${err.response?.status || err.message}`); + } + } + + // Erreur réseau/429/5xx → ne PAS cacher (résultat temporaire) + if (allItems.length === 0 && searchError) { + return null; + } + + if (allItems.length === 0) { + await saveToCache(PURSTREAM_CACHE_DIR, cacheKey, NOT_FOUND_MARKER); + return null; + } + + // Extraire posters PurStream + const extractPosterPath = (url) => { + if (!url) return ''; + const m = url.match(/\/([^/]+\.jpg)$/); + return m ? `/${m[1]}` : ''; + }; + + // Matcher strictement par type + poster TMDB + const getPurstreamPosters = (item) => { + const posters = new Set(); + const p1 = extractPosterPath(item.large_poster_path); + const p2 = extractPosterPath(item.small_poster_path); + const p3 = extractPosterPath(item.wallpaper_poster_path); + if (p1) posters.add(p1); + if (p2) posters.add(p2); + if (p3) posters.add(p3); + return posters; + }; + + const posterMatch = (item) => { + if (tmdbPosters.size === 0) return false; + const purPosters = getPurstreamPosters(item); + for (const p of purPosters) { + if (tmdbPosters.has(p)) return true; + } + return false; + }; + + const best = allItems.find(item => item.type === type && posterMatch(item)); + + if (!best) { + console.warn(`[PURSTREAM] Aucun match pour ${type}:${tmdbId} "${tmdbTitle}"`); + await saveToCache(PURSTREAM_CACHE_DIR, cacheKey, NOT_FOUND_MARKER); + return null; + } + + const result = { purstream_id: best.id, title: best.title, type: best.type }; + await saveToCache(PURSTREAM_CACHE_DIR, cacheKey, result); + return result; +} + +/** Revalidation background du mapping — ne jamais écraser un mapping valide par un échec */ +async function backgroundUpdateMapping(tmdbId, type, cacheKey) { + const existing = await getFromCacheNoExpiration(PURSTREAM_CACHE_DIR, cacheKey); + const hasValidMapping = existing && !existing.__not_found && existing.purstream_id; + + try { + const result = await fetchAndCacheMapping(tmdbId, type, cacheKey); + if (!result && hasValidMapping) { + await saveToCache(PURSTREAM_CACHE_DIR, cacheKey, existing); + } + } catch (err) { + console.warn(`[PURSTREAM] BG mapping ${type}:${tmdbId} erreur: ${err.message}`); + if (hasValidMapping) { + await saveToCache(PURSTREAM_CACHE_DIR, cacheKey, existing); + } + } +} + +/** Fetch stream depuis PurStream, retourne les sources ou marqueur erreur */ +async function fetchStream(purstreamId, urlPath) { + try { + const response = await purstreamRequest(urlPath); + if (response.data?.type !== 'success') return null; + return response.data.data?.items || null; + } catch (err) { + console.warn(`[PURSTREAM] Erreur fetch stream purstream:${purstreamId}: ${err.response?.status || err.message}`); + return { __error: true, status: err.response?.status || 0 }; + } +} + +// --------------------------------------------------------------------------- +// GET /api/purstream/movie/:tmdbId/stream +// --------------------------------------------------------------------------- +router.get('/movie/:tmdbId/stream', async (req, res) => { + try { + const { tmdbId } = req.params; + if (!tmdbId || isNaN(tmdbId)) return res.status(400).json({ error: 'TMDB ID invalide' }); + + // Vérifier VIP pour proxifier les URLs + const accessKey = req.headers['x-access-key'] || null; + const vipStatus = verifyAccessKey ? await verifyAccessKey(accessKey) : { vip: false }; + const isVip = vipStatus.vip; + + const cacheKey = generateCacheKey(`purstream_stream_movie_${tmdbId}`); + const cached = await getFromCacheNoExpiration(PURSTREAM_CACHE_DIR, cacheKey); + + if (cached) { + if (cached.__not_found) { + const stale = await shouldUpdateCache(PURSTREAM_CACHE_DIR, cacheKey); + if (stale) backgroundUpdateStreamMovie(tmdbId, cacheKey).catch(() => {}); + return res.status(404).json({ error: 'Film non trouvé sur PurStream' }); + } + const stale = await shouldUpdateCache(PURSTREAM_CACHE_DIR, cacheKey); + if (stale) backgroundUpdateStreamMovie(tmdbId, cacheKey).catch(() => {}); + // Appliquer le proxy VIP au moment de la réponse (le cache stocke les URLs brutes) + const response = { ...cached, sources: cached.sources.map(s => ({ ...s, url: wrapSourceUrl(s.url, isVip) })) }; + return res.json(response); + } + + const mapping = await resolvePurstreamId(tmdbId, 'movie'); + if (!mapping) { + return res.status(404).json({ error: 'Film non trouvé sur PurStream' }); + } + + const streamData = await fetchStream(mapping.purstream_id, `/stream/${mapping.purstream_id}`); + + if (streamData?.__error) { + if (streamData.status === 404) { + await saveToCache(PURSTREAM_CACHE_DIR, cacheKey, NOT_FOUND_MARKER); + return res.status(404).json({ error: 'Film non trouvé sur PurStream' }); + } + return res.status(502).json({ error: 'Erreur temporaire PurStream' }); + } + + if (!streamData) { + return res.status(502).json({ error: 'Réponse invalide de PurStream' }); + } + + const sources = streamData.sources || []; + const result = { + purstream_id: mapping.purstream_id, + sources: sources.map(s => ({ url: s.stream_url, name: s.source_name, format: s.format })) + }; + + if (sources.length === 0) { + await saveToCache(PURSTREAM_CACHE_DIR, cacheKey, NOT_FOUND_MARKER); + return res.status(404).json({ error: 'Aucun stream disponible pour ce film' }); + } + + await saveToCache(PURSTREAM_CACHE_DIR, cacheKey, result); + // Retourner avec URLs proxifiées si VIP + const response = { ...result, sources: result.sources.map(s => ({ ...s, url: wrapSourceUrl(s.url, isVip) })) }; + res.json(response); + } catch (error) { + console.error('[PURSTREAM] Erreur stream film:', error.message); + res.status(502).json({ error: 'Erreur lors de la récupération du stream' }); + } +}); + +// --------------------------------------------------------------------------- +// GET /api/purstream/tv/:tmdbId/stream?season=X&episode=Y +// --------------------------------------------------------------------------- +router.get('/tv/:tmdbId/stream', async (req, res) => { + try { + const { tmdbId } = req.params; + const { season, episode } = req.query; + + if (!tmdbId || isNaN(tmdbId)) return res.status(400).json({ error: 'TMDB ID invalide' }); + if (!season || isNaN(season)) return res.status(400).json({ error: 'Le paramètre season est requis' }); + if (!episode || isNaN(episode)) return res.status(400).json({ error: 'Le paramètre episode est requis' }); + + // Vérifier VIP pour proxifier les URLs + const accessKey = req.headers['x-access-key'] || null; + const vipStatus = verifyAccessKey ? await verifyAccessKey(accessKey) : { vip: false }; + const isVip = vipStatus.vip; + + const cacheKey = generateCacheKey(`purstream_stream_tv_${tmdbId}_s${season}e${episode}`); + const cached = await getFromCacheNoExpiration(PURSTREAM_CACHE_DIR, cacheKey); + + if (cached) { + if (cached.__not_found) { + const stale = await shouldUpdateCache(PURSTREAM_CACHE_DIR, cacheKey); + if (stale) backgroundUpdateStreamTv(tmdbId, season, episode, cacheKey).catch(() => {}); + return res.status(404).json({ error: 'Épisode non trouvé sur PurStream' }); + } + const stale = await shouldUpdateCache(PURSTREAM_CACHE_DIR, cacheKey); + if (stale) backgroundUpdateStreamTv(tmdbId, season, episode, cacheKey).catch(() => {}); + const response = { ...cached, sources: cached.sources.map(s => ({ ...s, url: wrapSourceUrl(s.url, isVip) })) }; + return res.json(response); + } + + const mapping = await resolvePurstreamId(tmdbId, 'tv'); + if (!mapping) { + return res.status(404).json({ error: 'Série non trouvée sur PurStream' }); + } + + const streamData = await fetchStream(mapping.purstream_id, `/stream/${mapping.purstream_id}/episode?season=${Number(season)}&episode=${Number(episode)}`); + + if (streamData?.__error) { + if (streamData.status === 404) { + await saveToCache(PURSTREAM_CACHE_DIR, cacheKey, NOT_FOUND_MARKER); + return res.status(404).json({ error: 'Épisode non trouvé sur PurStream' }); + } + return res.status(502).json({ error: 'Erreur temporaire PurStream' }); + } + + if (!streamData) { + return res.status(502).json({ error: 'Réponse invalide de PurStream' }); + } + + const sources = streamData.sources || []; + const result = { + purstream_id: mapping.purstream_id, + season: streamData.season || Number(season), + episode: streamData.episode || Number(episode), + sources: sources.map(s => ({ url: s.stream_url, name: s.source_name, format: s.format })) + }; + + if (sources.length === 0) { + await saveToCache(PURSTREAM_CACHE_DIR, cacheKey, NOT_FOUND_MARKER); + return res.status(404).json({ error: 'Aucun stream disponible pour cet épisode' }); + } + + await saveToCache(PURSTREAM_CACHE_DIR, cacheKey, result); + const response = { ...result, sources: result.sources.map(s => ({ ...s, url: wrapSourceUrl(s.url, isVip) })) }; + res.json(response); + } catch (error) { + console.error('[PURSTREAM] Erreur stream série:', error.message); + res.status(502).json({ error: 'Erreur lors de la récupération du stream' }); + } +}); + +// --------------------------------------------------------------------------- +// Background updates — ne jamais écraser un cache valide par un échec +// --------------------------------------------------------------------------- +async function backgroundUpdateStreamMovie(tmdbId, cacheKey) { + const existing = await getFromCacheNoExpiration(PURSTREAM_CACHE_DIR, cacheKey); + const hasValidCache = existing && !existing.__not_found && existing.sources?.length > 0; + + try { + const mapping = await resolvePurstreamId(tmdbId, 'movie'); + if (!mapping) return; + + const streamData = await fetchStream(mapping.purstream_id, `/stream/${mapping.purstream_id}`); + + if (!streamData || streamData.__error) return; + + const sources = streamData.sources || []; + if (sources.length === 0 && hasValidCache) return; + + if (sources.length === 0) { + await saveToCache(PURSTREAM_CACHE_DIR, cacheKey, NOT_FOUND_MARKER); + return; + } + + const result = { + purstream_id: mapping.purstream_id, + sources: sources.map(s => ({ url: s.stream_url, name: s.source_name, format: s.format })) + }; + await saveToCache(PURSTREAM_CACHE_DIR, cacheKey, result); + } catch (err) { + // Silent fail — cache existant reste intact + } +} + +async function backgroundUpdateStreamTv(tmdbId, season, episode, cacheKey) { + const existing = await getFromCacheNoExpiration(PURSTREAM_CACHE_DIR, cacheKey); + const hasValidCache = existing && !existing.__not_found && existing.sources?.length > 0; + + try { + const mapping = await resolvePurstreamId(tmdbId, 'tv'); + if (!mapping) return; + + const streamData = await fetchStream(mapping.purstream_id, `/stream/${mapping.purstream_id}/episode?season=${Number(season)}&episode=${Number(episode)}`); + + if (!streamData || streamData.__error) return; + + const sources = streamData.sources || []; + if (sources.length === 0 && hasValidCache) return; + + if (sources.length === 0) { + await saveToCache(PURSTREAM_CACHE_DIR, cacheKey, NOT_FOUND_MARKER); + return; + } + + const result = { + purstream_id: mapping.purstream_id, + season: streamData.season || Number(season), + episode: streamData.episode || Number(episode), + sources: sources.map(s => ({ url: s.stream_url, name: s.source_name, format: s.format })) + }; + await saveToCache(PURSTREAM_CACHE_DIR, cacheKey, result); + } catch (err) { + // Silent fail — cache existant reste intact + } +} + +module.exports = router; +module.exports.configure = configure; diff --git a/API/Mainapi/routes/search.js b/API/Mainapi/routes/search.js new file mode 100644 index 0000000..c8a292d --- /dev/null +++ b/API/Mainapi/routes/search.js @@ -0,0 +1,236 @@ +/** + * Search routes module. + * Handles Darkino search with caching. + * + * Mounted at / (paths below include their full prefix). + */ + +const express = require('express'); +const router = express.Router(); +const { generateCacheKey } = require('../utils/cacheManager'); + +// --------------------------------------------------------------------------- +// Dependencies injected via configure() +// --------------------------------------------------------------------------- +let DARKINO_MAINTENANCE; +let DARKINOS_CACHE_DIR; +let axiosDarkinoRequest; +let getFromCacheNoExpiration; +let saveToCache; +let touchCacheEntry; +let shouldUpdateCache; + +function isEmptySearchResponse(data) { + return !Array.isArray(data?.results) || data.results.length === 0; +} + +function ensureValidSearchPayload(data) { + if (typeof data === 'string' && data.includes('Maintenance en cours')) { + throw new Error('Maintenance en cours - donnees invalides'); + } + + if (typeof data === 'string' || data === null || data === undefined) { + throw new Error('Reponse invalide - donnees non-JSON'); + } + + return data; +} + +function getTitlesResults(data) { + return Array.isArray(data?.pagination?.data) ? data.pagination.data : []; +} + +function getResultMergeKey(item, index) { + if (item?.model_type && item?.id !== undefined && item?.id !== null) { + return `${item.model_type}:${item.id}`; + } + + if (item?.type && item?.tmdb_id !== undefined && item?.tmdb_id !== null) { + return `${item.type}:tmdb:${item.tmdb_id}`; + } + + if (item?.imdb_id) { + return `imdb:${item.imdb_id}`; + } + + if (item?.name) { + return `name:${String(item.name).trim().toLowerCase()}`; + } + + return `index:${index}`; +} + +function mergeResults(...resultLists) { + const merged = []; + const seen = new Set(); + + for (const list of resultLists) { + const results = Array.isArray(list) ? list : []; + + results.forEach((item, index) => { + const key = getResultMergeKey(item, merged.length + index); + if (seen.has(key)) { + return; + } + + seen.add(key); + merged.push(item); + }); + } + + return merged; +} + +function buildMergedSearchResponse(title, searchData, titlesData) { + return { + results: mergeResults(searchData?.results, getTitlesResults(titlesData)), + query: searchData?.query || title, + loader: searchData?.loader || 'searchPage', + seo: searchData?.seo ?? titlesData?.seo ?? null + }; +} + +async function fetchMergedSearchData(title) { + let searchData = null; + let titlesData = null; + let searchError = null; + let titlesError = null; + + try { + const searchResponse = await axiosDarkinoRequest({ + method: 'get', + url: `/api/v1/search/${encodeURIComponent(title)}`, + params: { loader: 'searchPage' } + }); + + searchData = ensureValidSearchPayload(searchResponse.data); + } catch (error) { + searchError = error; + } + + try { + const titlesResponse = await axiosDarkinoRequest({ + method: 'get', + url: '/api/v1/titles', + params: { perPage: 15, query: title } + }); + + titlesData = ensureValidSearchPayload(titlesResponse.data); + } catch (error) { + titlesError = error; + } + + if (!searchData && !titlesData) { + throw searchError || titlesError || new Error('Erreur lors de la recherche'); + } + + return buildMergedSearchResponse(title, searchData, titlesData); +} + +/** + * Inject runtime dependencies that still live in server.js. + */ +function configure(deps) { + if (deps.DARKINO_MAINTENANCE !== undefined) DARKINO_MAINTENANCE = deps.DARKINO_MAINTENANCE; + if (deps.DARKINOS_CACHE_DIR) DARKINOS_CACHE_DIR = deps.DARKINOS_CACHE_DIR; + if (deps.axiosDarkinoRequest) axiosDarkinoRequest = deps.axiosDarkinoRequest; + if (deps.getFromCacheNoExpiration) getFromCacheNoExpiration = deps.getFromCacheNoExpiration; + if (deps.saveToCache) saveToCache = deps.saveToCache; + if (deps.touchCacheEntry) touchCacheEntry = deps.touchCacheEntry; + if (deps.shouldUpdateCache) shouldUpdateCache = deps.shouldUpdateCache; +} + +// --------------------------------------------------------------------------- +// GET /api/search -- search Darkino with caching +// --------------------------------------------------------------------------- +router.get('/api/search', async (req, res) => { + try { + const { title } = req.query; + if (!title) return res.status(400).json({ error: 'Le parametre title est requis' }); + const sanitizedTitle = String(title).replace(/\//g, '').trim(); + if (!sanitizedTitle) return res.status(400).json({ error: 'Le parametre title est invalide' }); + + // Generate cache key + const cacheKey = generateCacheKey(`api_search_${sanitizedTitle}`); + + // Check if results are in cache without expiration (stale-while-revalidate) + const cachedData = await getFromCacheNoExpiration(DARKINOS_CACHE_DIR, cacheKey); + let dataReturned = false; + + if (cachedData && !isEmptySearchResponse(cachedData)) { + res.status(200).json(cachedData); + dataReturned = true; + + // Update cache in background only if no error occurs + (async () => { + try { + const shouldUpdate_ = await shouldUpdateCache(DARKINOS_CACHE_DIR, cacheKey); + if (!shouldUpdate_) { + return; + } + + const freshData = await fetchMergedSearchData(sanitizedTitle); + + if (Array.isArray(cachedData?.results) && cachedData.results.length > 0 && isEmptySearchResponse(freshData)) { + await touchCacheEntry(DARKINOS_CACHE_DIR, cacheKey); + return; + } + + if (freshData) { + await saveToCache(DARKINOS_CACHE_DIR, cacheKey, freshData); + } + } catch (error) { + // Silent fail on background update + } + })(); + } else { + // Si en maintenance et pas de cache, erreur + if (DARKINO_MAINTENANCE) { + return res.status(200).json({ error: 'Service Darkino temporairement indisponible (maintenance)' }); + } + // No cache, get data synchronously + try { + const data = await fetchMergedSearchData(sanitizedTitle); + + if (data) { + await saveToCache(DARKINOS_CACHE_DIR, cacheKey, data); + res.status(200).json(data); + } else { + res.status(404).json({ error: 'Aucun resultat trouve' }); + } + } catch (error) { + if (error.response && error.response.status >= 500) { + if (dataReturned) return; + + try { + const fallbackCache = await getFromCacheNoExpiration(DARKINOS_CACHE_DIR, cacheKey); + if (fallbackCache && !isEmptySearchResponse(fallbackCache)) { + return res.status(200).json(fallbackCache); + } + } catch (_) { } + } + res.status(500).json({ error: 'Erreur lors de la recherche' }); + } + } + } catch (error) { + console.error(`Erreur API Darkino Search: ${error.response?.status || 'Erreur reseau'}`); + if (!res.headersSent) { + try { + const { title } = req.query; + const sanitizedTitle = String(title || '').replace(/\//g, '').trim(); + const cacheKey = generateCacheKey(`api_search_${sanitizedTitle}`); + const fallbackCache = await getFromCacheNoExpiration(DARKINOS_CACHE_DIR, cacheKey); + if (error.response && error.response.status >= 500 && fallbackCache && !isEmptySearchResponse(fallbackCache)) { + return res.status(200).json(fallbackCache); + } + } catch (_) { } + res.status(500).json({ error: 'Erreur lors de la recherche' }); + } + } +}); + +// --------------------------------------------------------------------------- +// Exports +// --------------------------------------------------------------------------- +module.exports = router; +module.exports.configure = configure; diff --git a/API/Mainapi/routes/sessions.js b/API/Mainapi/routes/sessions.js new file mode 100644 index 0000000..b9c3318 --- /dev/null +++ b/API/Mainapi/routes/sessions.js @@ -0,0 +1,95 @@ +/** + * Session management routes. + * Extracted from server.js -- user session listing and deletion. + * Mount point: app.use('/api/sessions', router) + */ + +const express = require('express'); +const router = express.Router(); + +const { getAuthIfValid } = require('../middleware/auth'); +const { getPool } = require('../mysqlPool'); + +// === Routes === + +// GET / - Get user sessions (JWT required, MySQL) +router.get('/', async (req, res) => { + try { + const auth = await getAuthIfValid(req); + if (!auth) { + return res.status(401).json({ success: false, error: 'Unauthorized' }); + } + const { userType, userId } = auth; + + // Only allow sessions for oauth, bip39 users + if (!['oauth', 'bip39'].includes(userType)) { + return res.status(400).json({ success: false, error: 'Type d\'utilisateur non supporté pour les sessions' }); + } + + const pool = getPool(); + if (!pool) { + return res.status(503).json({ success: false, error: 'Service temporairement indisponible' }); + } + + // Get sessions from MySQL + const [rows] = await pool.execute( + 'SELECT id, user_agent as userAgent, created_at as createdAt, accessed_at as accessedAt FROM user_sessions WHERE user_id = ? AND user_type = ? ORDER BY accessed_at DESC', + [userId, userType] + ); + + const sessions = rows.map(row => ({ + id: row.id, + userId: userId, + userAgent: row.userAgent, + createdAt: row.createdAt ? new Date(row.createdAt).toISOString() : null, + accessedAt: row.accessedAt ? new Date(row.accessedAt).toISOString() : null + })); + + res.status(200).json({ success: true, data: { count: sessions.length, items: sessions } }); + } catch (error) { + console.error('Error getting sessions:', error); + res.status(500).json({ success: false, error: 'Erreur lors de la récupération des sessions' }); + } +}); + +// POST /delete - Delete a specific session (JWT required; user can only delete own session, MySQL) +router.post('/delete', async (req, res) => { + try { + const auth = await getAuthIfValid(req); + if (!auth) { + return res.status(401).json({ success: false, error: 'Unauthorized' }); + } + const { userType, userId } = auth; + const { sessionId } = req.body; + + if (!sessionId) { + return res.status(400).json({ success: false, error: 'ID de session requis' }); + } + + if (!['oauth', 'bip39'].includes(userType)) { + return res.status(400).json({ success: false, error: 'Type d\'utilisateur non supporté pour les sessions' }); + } + + const pool = getPool(); + if (!pool) { + return res.status(503).json({ success: false, error: 'Service temporairement indisponible' }); + } + + // Delete session from MySQL + const [result] = await pool.execute( + 'DELETE FROM user_sessions WHERE id = ? AND user_id = ? AND user_type = ?', + [sessionId, userId, userType] + ); + + if (result.affectedRows === 0) { + return res.status(404).json({ success: false, error: 'Session non trouvée' }); + } + + res.status(200).json({ success: true, message: 'Session supprimée avec succès' }); + } catch (error) { + console.error('Error deleting session:', error); + res.status(500).json({ success: false, error: 'Erreur lors de la suppression de la session' }); + } +}); + +module.exports = router; diff --git a/API/Mainapi/routes/sync.js b/API/Mainapi/routes/sync.js new file mode 100644 index 0000000..ce6b127 --- /dev/null +++ b/API/Mainapi/routes/sync.js @@ -0,0 +1,606 @@ +/** + * Sync routes. + * Extracted from server.js -- user data sync endpoints and graceful shutdown logic. + * Mount point: app.use('/api', router) + */ + +const express = require('express'); +const rateLimit = require('express-rate-limit'); +const { ipKeyGenerator } = require('express-rate-limit'); +const path = require('path'); +const fsp = require('fs').promises; +const { v4: uuidv4 } = require('uuid'); + +const router = express.Router(); + +const { getAuthIfValid } = require('../middleware/auth'); +const { safeWriteJsonFile } = require('../utils/safeFile'); +const { logSyncErrorToDiscord } = require('../utils/discord'); +const { createRedisRateLimitStore } = require('../utils/redisRateLimitStore'); +const { + ALLOWED_SYNC_USER_TYPES, + SYNC_LIMITS, + SyncPolicyError, + assertUserDataSize, + ensureSafeProfileId, + ensureSafeUserId, + ensureValidUserType, + getOwnedProfile, + getProfileFilePath, + getUserDataFilePath, + getUtf8ByteLength, + sanitizeLegacySyncData, + sanitizeProfileData, + validateAndNormalizeOps +} = require('../utils/syncPolicy'); + +// === Data directories === +const USER_DATA_DIR = path.join(__dirname, '..', 'data'); +const GUESTS_DIR = path.join(USER_DATA_DIR, 'guests'); +const USERS_DIR = path.join(USER_DATA_DIR, 'users'); + +// Ensure directories exist +(async () => { + for (const dir of [USER_DATA_DIR, GUESTS_DIR, USERS_DIR]) { + try { + await fsp.access(dir); + } catch { + await fsp.mkdir(dir, { recursive: true }); + } + } +})(); + +const syncRateLimit = rateLimit({ + windowMs: 60 * 1000, + max: 180, + store: createRedisRateLimitStore({ prefix: 'rate-limit:sync:post:' }), + passOnStoreError: true, + standardHeaders: true, + legacyHeaders: false, + message: { + success: false, + error: 'Trop de synchronisations en peu de temps. Reessayez dans une minute.' + }, + keyGenerator: (req) => req.headers['cf-connecting-ip'] || req.headers['x-forwarded-for']?.split(',')[0].trim() || ipKeyGenerator(req.ip), + validate: { xForwardedForHeader: false, ip: false } +}); + +const statsRateLimit = rateLimit({ + windowMs: 60 * 1000, + max: 60, + store: createRedisRateLimitStore({ prefix: 'rate-limit:sync:stats:' }), + passOnStoreError: true, + standardHeaders: true, + legacyHeaders: false, + message: { + success: false, + error: 'Trop de requetes de statistiques. Reessayez dans une minute.' + }, + keyGenerator: (req) => req.headers['cf-connecting-ip'] || req.headers['x-forwarded-for']?.split(',')[0].trim() || ipKeyGenerator(req.ip), + validate: { xForwardedForHeader: false, ip: false } +}); + +// === Graceful Shutdown === +let isShuttingDown = false; +let activeOperations = 0; + +function startOperation() { + if (isShuttingDown) throw new Error('Server is shutting down'); + activeOperations++; +} + +function endOperation() { + if (activeOperations > 0) { + activeOperations--; + } + + if (isShuttingDown && activeOperations === 0) { + console.log('All operations completed, server can shutdown safely'); + process.exit(0); + } +} + +function waitForOperations() { + return new Promise((resolve) => { + if (activeOperations === 0) { + resolve(); + return; + } + + const checkInterval = setInterval(() => { + if (activeOperations === 0) { + clearInterval(checkInterval); + resolve(); + } + }, 100); + }); +} + +// Graceful shutdown est gere par server.js (cluster worker). +process.on('message', (msg) => { + if (msg === 'shutdown') { + isShuttingDown = true; + } +}); + +function normalizeStoredProfiles(data) { + if (data.profiles && Array.isArray(data.profiles)) { + data.profiles.forEach((profile) => { + if (profile.avatar && !profile.avatar.startsWith('/avatars/') && profile.avatar !== '') { + profile.avatar = '/avatars/disney/disney_avatar_1.png'; + } + }); + } + + return data; +} + +function safeParseStoredValue(rawValue, fallback) { + if (typeof rawValue !== 'string') return fallback; + try { + return JSON.parse(rawValue); + } catch { + return fallback; + } +} + +function createSyncStatsResponse(profileId, profileStats, legacyStats) { + return { + profileId, + profileBytes: profileStats.bytes, + profileKeyCount: profileStats.keyCount, + profileQuotaBytes: SYNC_LIMITS.maxProfileBytes, + legacySyncBytes: legacyStats.bytes, + legacySyncKeyCount: legacyStats.keyCount, + totalSyncBytes: profileStats.bytes + legacyStats.bytes + }; +} + +function applySyncOperation(serverData, op) { + const key = op.key; + const currentRaw = serverData[key]; + + switch (op.op) { + case 'set': + serverData[key] = op.value; + break; + + case 'remove': + delete serverData[key]; + break; + + case 'arrayAdd': { + const arr = safeParseStoredValue(currentRaw, []); + if (!Array.isArray(arr)) { + serverData[key] = JSON.stringify([op.value]); + break; + } + + let next = arr.slice(); + const exists = (item) => { + if (op.value && typeof op.value === 'object' && 'id' in op.value) { + return item && typeof item === 'object' && item.id === op.value.id; + } + + return JSON.stringify(item) === JSON.stringify(op.value); + }; + + if (!next.some(exists)) { + next.push(op.value); + } + + serverData[key] = JSON.stringify(next); + break; + } + + case 'arrayRemove': { + const arr = safeParseStoredValue(currentRaw, []); + if (!Array.isArray(arr)) { + serverData[key] = '[]'; + break; + } + + const next = arr.filter((item) => { + if (op.value && typeof op.value === 'object' && 'id' in op.value) { + return !(item && typeof item === 'object' && item.id === op.value.id); + } + + return JSON.stringify(item) !== JSON.stringify(op.value); + }); + + serverData[key] = JSON.stringify(next); + break; + } + + case 'arrayClear': + serverData[key] = '[]'; + break; + + case 'objPatch': { + const obj = safeParseStoredValue(currentRaw, {}); + if (!obj || typeof obj !== 'object' || Array.isArray(obj)) { + serverData[key] = JSON.stringify({}); + break; + } + + const next = { ...obj }; + const sets = op.delta?.set || {}; + const removes = op.delta?.remove || []; + + for (const [entryKey, entryValue] of Object.entries(sets)) { + if (entryValue && typeof entryValue === 'object' && !Array.isArray(entryValue) && entryValue.__arrayPatch) { + const patch = entryValue.__arrayPatch; + const currentArrayValue = Array.isArray(next[entryKey]) + ? next[entryKey] + : safeParseStoredValue(next[entryKey], []); + const currentArray = Array.isArray(currentArrayValue) ? currentArrayValue : []; + const byId = new Map(); + + currentArray.forEach((item) => { + if (item && typeof item === 'object' && item.id) { + byId.set(item.id, item); + } + }); + + (patch.add || []).forEach((item) => { + if (item && typeof item === 'object' && item.id) { + byId.set(item.id, item); + } + }); + + (patch.update || []).forEach((item) => { + if (item && typeof item === 'object' && item.id) { + byId.set(item.id, item); + } + }); + + (patch.remove || []).forEach((item) => { + if (item && typeof item === 'object' && item.id) { + byId.delete(item.id); + } + }); + + (patch.removeIds || []).forEach((id) => { + byId.delete(id); + }); + + next[entryKey] = Array.from(byId.values()); + } else { + next[entryKey] = entryValue; + } + } + + removes.forEach((entryKey) => { + delete next[entryKey]; + }); + + serverData[key] = JSON.stringify(next); + break; + } + } + + return serverData; +} + +function buildSyncLogContext(context) { + return { + userType: context.userType || null, + userId: context.userId || null, + profileId: context.profileId || null, + opsCount: context.opsCount || 0, + requestBytes: context.requestBytes || 0, + error: context.error || null + }; +} + +function normalizeLastUpdated(rawValue) { + if (typeof rawValue === 'string') { + const parsed = new Date(rawValue).getTime(); + return Number.isFinite(parsed) ? parsed : 0; + } + + if (typeof rawValue === 'number' && Number.isFinite(rawValue)) { + return rawValue; + } + + return 0; +} + +async function readUserData(userType, userId) { + const filePath = getUserDataFilePath({ usersDir: USERS_DIR, guestsDir: GUESTS_DIR }, userType, userId); + + try { + const fileContent = await fsp.readFile(filePath, 'utf8'); + const data = JSON.parse(fileContent); + return normalizeStoredProfiles(data && typeof data === 'object' ? data : {}); + } catch (error) { + if (error.code === 'ENOENT') return {}; + + console.error(`Erreur lors de la lecture des donnees utilisateur ${userType}:${userId}:`, error.message); + return {}; + } +} + +async function writeUserData(userType, userId, data) { + try { + const filePath = getUserDataFilePath({ usersDir: USERS_DIR, guestsDir: GUESTS_DIR }, userType, userId); + + if (!data || typeof data !== 'object' || Array.isArray(data)) { + throw new SyncPolicyError('Donnees utilisateur invalides', 400, 'INVALID_USER_DATA'); + } + + assertUserDataSize(data); + + const success = await safeWriteJsonFile(filePath, data); + if (!success) { + console.error(`Erreur de sauvegarde atomique pour ${userType}:${userId}`); + } + + return success; + } catch (error) { + console.error(`Erreur de sauvegarde pour ${userType}:${userId}:`, error.message); + return false; + } +} + +async function readProfileData(userType, userId, profileId) { + const profilePath = getProfileFilePath(USERS_DIR, userType, userId, profileId); + + try { + const fileContent = await fsp.readFile(profilePath, 'utf8'); + const parsed = JSON.parse(fileContent); + const { data, changed } = sanitizeProfileData(parsed); + + if (changed) { + safeWriteJsonFile(profilePath, data).catch((writeError) => { + console.error(`Erreur lors du nettoyage du profil ${profileId}:`, writeError.message); + }); + } + + return data; + } catch (error) { + if (error.code === 'ENOENT') return {}; + if (error instanceof SyncPolicyError) throw error; + + console.error(`Erreur lors de la lecture des donnees de profil ${userType}:${userId}:${profileId}:`, error.message); + return {}; + } +} + +async function writeProfileData(userType, userId, profileId, data) { + try { + const profilePath = getProfileFilePath(USERS_DIR, userType, userId, profileId); + + if (!data || typeof data !== 'object' || Array.isArray(data)) { + throw new SyncPolicyError('Donnees de profil invalides', 400, 'INVALID_PROFILE_DATA'); + } + + const { data: sanitizedData } = sanitizeProfileData(data); + const success = await safeWriteJsonFile(profilePath, sanitizedData); + + if (!success) { + console.error(`Erreur de sauvegarde atomique pour le profil ${profileId}`); + } + + return success; + } catch (error) { + console.error(`Erreur de sauvegarde du profil ${profileId}:`, error.message); + return false; + } +} + +// === Routes === + +// POST /sync +router.post('/sync', syncRateLimit, async (req, res) => { + let operationStarted = false; + const syncContext = { + userType: null, + userId: null, + profileId: null, + opsCount: 0, + requestBytes: 0 + }; + + try { + if (isShuttingDown) return res.status(503).json({ error: 'Server is shutting down' }); + startOperation(); + operationStarted = true; + + const contentLength = Number(req.headers['content-length'] || 0); + if (Number.isFinite(contentLength) && contentLength > SYNC_LIMITS.maxRequestBytes) { + return res.status(413).json({ success: false, error: 'Requete de synchronisation trop volumineuse' }); + } + + syncContext.requestBytes = getUtf8ByteLength(req.body || {}); + if (syncContext.requestBytes > SYNC_LIMITS.maxRequestBytes) { + return res.status(413).json({ success: false, error: 'Requete de synchronisation trop volumineuse' }); + } + + const auth = await getAuthIfValid(req); + if (!auth || !ALLOWED_SYNC_USER_TYPES.includes(auth.userType)) { + return res.status(401).json({ error: 'Unauthorized' }); + } + + const userType = ensureValidUserType(req.body?.userType || auth.userType); + if (auth.userType !== userType) { + return res.status(401).json({ error: 'Unauthorized' }); + } + + const finalUserId = ensureSafeUserId(auth.userId); + if (req.body?.userId && String(req.body.userId) !== finalUserId) { + return res.status(401).json({ error: 'UserId mismatch' }); + } + + const profileId = ensureSafeProfileId(req.body?.profileId); + const ops = validateAndNormalizeOps(req.body?.ops); + + syncContext.userType = userType; + syncContext.userId = finalUserId; + syncContext.profileId = profileId; + syncContext.opsCount = ops.length; + + const userData = await readUserData(userType, finalUserId); + getOwnedProfile(userData, profileId); + + const serverData = await readProfileData(userType, finalUserId, profileId); + ops.forEach((op) => applySyncOperation(serverData, op)); + + const { data: nextProfileData, stats: profileStats } = sanitizeProfileData(serverData); + + if (ops.length > 0) { + const writeSuccess = await writeProfileData(userType, finalUserId, profileId, nextProfileData); + if (!writeSuccess) { + console.error(`[SYNC] Echec de l'ecriture pour ${userType}:${finalUserId}:${profileId}`); + await logSyncErrorToDiscord('Echec de l\'ecriture des donnees de sync', buildSyncLogContext(syncContext)); + return res.status(500).json({ success: false, error: 'Failed to save data' }); + } + } + + return res.status(200).json({ + success: true, + stats: { + profileBytes: profileStats.bytes, + profileKeyCount: profileStats.keyCount, + profileQuotaBytes: SYNC_LIMITS.maxProfileBytes + } + }); + } catch (error) { + if (error instanceof SyncPolicyError) { + return res.status(error.status).json({ success: false, error: error.message, code: error.code }); + } + + console.error('Erreur de synchronisation:', error); + await logSyncErrorToDiscord('Exception lors de la synchronisation', buildSyncLogContext({ + ...syncContext, + error: error.message + })); + return res.status(500).json({ error: 'Failed to sync data' }); + } finally { + if (operationStarted) { + endOperation(); + } + } +}); + +// GET /sync/stats/:profileId +router.get('/sync/stats/:profileId', statsRateLimit, async (req, res) => { + let operationStarted = false; + + try { + if (isShuttingDown) return res.status(503).json({ error: 'Server is shutting down' }); + startOperation(); + operationStarted = true; + + const auth = await getAuthIfValid(req); + if (!auth || !ALLOWED_SYNC_USER_TYPES.includes(auth.userType)) { + return res.status(401).json({ error: 'Unauthorized' }); + } + + const userType = ensureValidUserType(auth.userType); + const userId = ensureSafeUserId(auth.userId); + const profileId = ensureSafeProfileId(req.params.profileId); + + const userData = await readUserData(userType, userId); + getOwnedProfile(userData, profileId); + + const profileData = await readProfileData(userType, userId, profileId); + const profileStats = sanitizeProfileData(profileData).stats; + const legacyStats = sanitizeLegacySyncData(userData).stats; + + return res.status(200).json({ + success: true, + stats: createSyncStatsResponse(profileId, profileStats, legacyStats) + }); + } catch (error) { + if (error instanceof SyncPolicyError) { + return res.status(error.status).json({ success: false, error: error.message, code: error.code }); + } + + console.error('Erreur de lecture des stats de sync:', error); + return res.status(500).json({ error: 'Failed to retrieve sync stats' }); + } finally { + if (operationStarted) { + endOperation(); + } + } +}); + +// GET /sync/:userType/:userId/:profileId? +router.get('/sync/:userType/:userId/:profileId?', async (req, res) => { + let operationStarted = false; + + try { + if (isShuttingDown) return res.status(503).json({ error: 'Server is shutting down' }); + startOperation(); + operationStarted = true; + + const userType = ensureValidUserType(req.params.userType); + const userId = ensureSafeUserId(req.params.userId); + const profileId = req.params.profileId ? ensureSafeProfileId(req.params.profileId) : null; + + const auth = await getAuthIfValid(req); + if (!auth || auth.userType !== userType || auth.userId !== userId) { + return res.status(401).json({ error: 'Unauthorized' }); + } + + const userData = await readUserData(userType, userId); + const hasProfiles = Array.isArray(userData?.profiles) && userData.profiles.length > 0; + let data = {}; + let lastUpdated = 0; + + if (!profileId && hasProfiles) { + const defaultProfile = userData.profiles.find((profile) => profile && profile.isDefault) || userData.profiles[0] || null; + return res.status(400).json({ + success: false, + error: 'ProfileId required for accounts with profiles', + code: 'PROFILE_ID_REQUIRED', + defaultProfileId: defaultProfile?.id || null + }); + } + + if (profileId) { + getOwnedProfile(userData, profileId); + data = await readProfileData(userType, userId, profileId); + } else { + data = sanitizeLegacySyncData(userData).data; + lastUpdated = normalizeLastUpdated(userData?.lastUpdated); + } + + return res.status(200).json({ + success: true, + data: { + ...data, + lastUpdated + } + }); + } catch (error) { + if (error instanceof SyncPolicyError) { + return res.status(error.status).json({ success: false, error: error.message, code: error.code }); + } + + console.error('Erreur de lecture:', error); + return res.status(500).json({ error: 'Failed to retrieve data' }); + } finally { + if (operationStarted) { + endOperation(); + } + } +}); + +// GET /guest/uuid +router.get('/guest/uuid', (req, res) => { + const uuid = uuidv4(); + res.status(200).json({ uuid }); +}); + +module.exports = router; +module.exports.isShuttingDown = () => isShuttingDown; +module.exports.startOperation = startOperation; +module.exports.endOperation = endOperation; +module.exports.waitForOperations = waitForOperations; +module.exports.readUserData = readUserData; +module.exports.writeUserData = writeUserData; +module.exports.readProfileData = readProfileData; +module.exports.writeProfileData = writeProfileData; +module.exports.USERS_DIR = USERS_DIR; diff --git a/API/Mainapi/routes/tmdb.js b/API/Mainapi/routes/tmdb.js new file mode 100644 index 0000000..ff7709f --- /dev/null +++ b/API/Mainapi/routes/tmdb.js @@ -0,0 +1,847 @@ +/** + * TMDB / IMDB routes module. + * Extracted from server.js -- handles TMDB lookups, IMDB/FrenchStream data, + * and related cache management. + * + * Mounted at /api (paths below are relative to that prefix). + */ + +const express = require('express'); +const router = express.Router(); +const axios = require('axios'); +const path = require('path'); +const fsp = require('fs').promises; +const { CACHE_DIR, generateCacheKey } = require('../utils/cacheManager'); +const { fetchTmdbDetails, searchTmdb } = require('../utils/tmdbCache'); +const { + applyCloneUrlsToPlayerLinks, + syncCloneLinksForPlayerLinks +} = require('../utils/cloneLinks'); + +// --------------------------------------------------------------------------- +// Dependencies injected via configure() +// --------------------------------------------------------------------------- +let TMDB_API_KEY; +let TMDB_API_URL; +let getFromCacheNoExpiration; +let saveToCache; +let shouldUpdateCacheFrenchStream; +let shouldUpdateCacheLecteurVideo; +// Coflix helpers (from coflix.js) +let searchCoflixByTitle; +let getMovieDataFromCoflix; +let getTvDataFromCoflix; +let filterEmmmmbedReaders; + +// FrenchStream helpers (from frenchstream.js) +let getFrenchStreamMovie; +let getFrenchStreamSeries; +let getFrenchStreamSeriesDetails; +let extractSeriesInfo; +let mergeSeriesParts; +let cleanTvCacheData; + +/** + * Inject runtime dependencies that still live in server.js or sibling modules. + */ +function configure(deps) { + if (deps.TMDB_API_KEY) TMDB_API_KEY = deps.TMDB_API_KEY; + if (deps.TMDB_API_URL) TMDB_API_URL = deps.TMDB_API_URL; + if (deps.getFromCacheNoExpiration) getFromCacheNoExpiration = deps.getFromCacheNoExpiration; + if (deps.saveToCache) saveToCache = deps.saveToCache; + if (deps.shouldUpdateCacheFrenchStream) shouldUpdateCacheFrenchStream = deps.shouldUpdateCacheFrenchStream; + if (deps.shouldUpdateCacheLecteurVideo) shouldUpdateCacheLecteurVideo = deps.shouldUpdateCacheLecteurVideo; + // Coflix + if (deps.searchCoflixByTitle) searchCoflixByTitle = deps.searchCoflixByTitle; + if (deps.getMovieDataFromCoflix) getMovieDataFromCoflix = deps.getMovieDataFromCoflix; + if (deps.getTvDataFromCoflix) getTvDataFromCoflix = deps.getTvDataFromCoflix; + if (deps.filterEmmmmbedReaders) filterEmmmmbedReaders = deps.filterEmmmmbedReaders; + + // FrenchStream + if (deps.getFrenchStreamMovie) getFrenchStreamMovie = deps.getFrenchStreamMovie; + if (deps.getFrenchStreamSeries) getFrenchStreamSeries = deps.getFrenchStreamSeries; + if (deps.getFrenchStreamSeriesDetails) getFrenchStreamSeriesDetails = deps.getFrenchStreamSeriesDetails; + if (deps.extractSeriesInfo) extractSeriesInfo = deps.extractSeriesInfo; + if (deps.mergeSeriesParts) mergeSeriesParts = deps.mergeSeriesParts; + if (deps.cleanTvCacheData) cleanTvCacheData = deps.cleanTvCacheData; +} + +function getCloneScope(type, id, season, episode) { + return { + mediaType: type, + tmdbId: Number(id) || 0, + seasonNumber: type === 'tv' ? parseInt(season, 10) || 0 : 0, + episodeNumber: type === 'tv' ? parseInt(episode, 10) || 0 : 0 + }; +} + +async function applyCloneUrlsToTmdbResult(result, type, id, season, episode) { + if (!result || typeof result !== 'object') { + return result; + } + + const cloneScope = getCloneScope(type, id, season, episode); + + if (type === 'movie' && Array.isArray(result.player_links)) { + return { + ...result, + player_links: await applyCloneUrlsToPlayerLinks({ + ...cloneScope, + playerLinks: result.player_links + }) + }; + } + + if (type === 'tv' && result.current_episode && Array.isArray(result.current_episode.player_links)) { + return { + ...result, + current_episode: { + ...result.current_episode, + player_links: await applyCloneUrlsToPlayerLinks({ + ...cloneScope, + playerLinks: result.current_episode.player_links + }) + } + }; + } + + return result; +} + +async function syncCloneUrlsOnTmdbResult(result, type, id, season, episode) { + if (!result || typeof result !== 'object') { + return result; + } + + const cloneScope = getCloneScope(type, id, season, episode); + + if (type === 'movie' && Array.isArray(result.player_links)) { + return { + ...result, + player_links: await syncCloneLinksForPlayerLinks({ + ...cloneScope, + playerLinks: result.player_links + }) + }; + } + + if (type === 'tv' && result.current_episode && Array.isArray(result.current_episode.player_links)) { + return { + ...result, + current_episode: { + ...result.current_episode, + player_links: await syncCloneLinksForPlayerLinks({ + ...cloneScope, + playerLinks: result.current_episode.player_links + }) + } + }; + } + + return result; +} + +// --------------------------------------------------------------------------- +// getTMDBDetails -- fetch TMDB details for a given ID and type +// --------------------------------------------------------------------------- +async function getTMDBDetails(id, type) { + try { + const data = await fetchTmdbDetails(TMDB_API_URL, TMDB_API_KEY, id, type, 'fr-FR'); + if (!data) return null; + + return { + id: data.id, + title: type === 'movie' ? data.title : data.name, + original_title: type === 'movie' ? data.original_title : data.original_name, + release_date: type === 'movie' ? data.release_date : data.first_air_date, + poster_path: data.poster_path, + backdrop_path: data.backdrop_path, + overview: data.overview, + vote_average: data.vote_average + }; + } catch (error) { + console.error(`Erreur lors de la recuperation des details TMDB pour ${id} (${type}):`, error); + return null; + } +} + +// --------------------------------------------------------------------------- +// findTvSeriesOnTMDB -- search TMDB for TV series and find the best match +// --------------------------------------------------------------------------- +async function findTvSeriesOnTMDB(title, releaseYear, overview) { + try { + // Variables pour stocker les informations de saison speciales + let seasonOffset = 0; + let isSeasonPart = false; + let originalTitle = title; + + // Remove "- Saison X" from the title + let cleanTitle = title.replace(/\s*-\s*Saison\s+\d+$/i, ''); + + // Handle special case for series like "Les Simpson Part 2 (Saison 1 - 29) - Saison 8" + const partMatch = cleanTitle.match(/Part\s+(\d+)\s*\(Saison\s+(\d+)\s*-\s*(\d+)\)/i); + if (partMatch) { + isSeasonPart = true; + const partNumber = parseInt(partMatch[1]); + const startSeason = parseInt(partMatch[2]); + const endSeason = parseInt(partMatch[3]); + + // Si c'est la partie 2+, on doit calculer le numero de saison reel + if (partNumber > 1) { + // Chercher la saison mentionnee dans le titre + const seasonMatch = title.match(/Saison\s+(\d+)$/i); + if (seasonMatch) { + // On calcule le decalage a partir des informations de saison + seasonOffset = endSeason - startSeason + 1; // Nombre total de saisons dans la partie 1 + } + } + + // Remove the part and season range info + cleanTitle = cleanTitle.replace(/\s*Part\s+\d+\s*\(Saison\s+\d+\s*-\s*\d+\)/i, ''); + } + + // Clean up any remaining parentheses + cleanTitle = cleanTitle.replace(/\([^)]*\)/g, '').trim(); + + // Search for the TV series on TMDB (cached via Redis) + const searchData = await searchTmdb(TMDB_API_URL, TMDB_API_KEY, 'tv', cleanTitle, + releaseYear ? { first_air_date_year: releaseYear } : {}); + + if (!searchData || !searchData.results || searchData.results.length === 0) { + return null; + } + + // Get the first few results + const potentialMatches = searchData.results.slice(0, 5); + + // Function to calculate similarity between two strings + const calculateSimilarity = (str1, str2) => { + if (!str1 || !str2) return 0; + + const s1 = str1.toLowerCase(); + const s2 = str2.toLowerCase(); + + // Calculate percentage match + let matches = 0; + const words1 = s1.split(/\s+/); + const words2 = s2.split(/\s+/); + + words1.forEach(word => { + if (words2.some(w => w.includes(word) || word.includes(w))) { + matches++; + } + }); + + return matches / Math.max(words1.length, 1); + }; + + // Find the best match by comparing title, release year, and overview + let bestMatch = null; + let highestScore = 0; + + for (const series of potentialMatches) { + // Calculate match score based on title similarity + const titleSimilarity = calculateSimilarity(cleanTitle, series.name); + + // Get detailed info for the series to compare overviews (cached via Redis) + const seriesDetails = await fetchTmdbDetails(TMDB_API_URL, TMDB_API_KEY, series.id, 'tv', 'en-US'); + if (!seriesDetails) continue; + + const overviewSimilarity = overview && seriesDetails.overview + ? calculateSimilarity(overview, seriesDetails.overview) + : 0; + + // Year match (exact match gives bonus) + const yearMatch = releaseYear && series.first_air_date ? + (parseInt(series.first_air_date.split('-')[0]) === parseInt(releaseYear) ? 1 : 0) : 0; + + // Calculate total score (weighted) + const totalScore = (titleSimilarity * 0.7) + (overviewSimilarity * 0.2) + (yearMatch * 0.1); + + if (totalScore > highestScore) { + highestScore = totalScore; + bestMatch = { + ...seriesDetails, + match_score: totalScore + }; + } + } + + // Si on a trouve une correspondance et qu'il s'agit d'une saison speciale + if (bestMatch && isSeasonPart) { + // Ajouter les informations relatives a la saison dans les donnees TMDB + bestMatch.is_season_part = true; + bestMatch.season_offset = seasonOffset; + bestMatch.original_title = originalTitle; + + // Si nous avons une saison specifique dans le titre + const seasonMatch = title.match(/Saison\s+(\d+)$/i); + if (seasonMatch) { + const titleSeason = parseInt(seasonMatch[1]); + bestMatch.title_season = titleSeason; + bestMatch.actual_season = seasonOffset + titleSeason - 1; + console.log(`Serie en parties: La saison ${titleSeason} dans le titre correspond a la saison ${bestMatch.actual_season} de la serie`); + } + } + + // Consider it a match if score is above threshold + return highestScore >= 0.3 ? bestMatch : null; + } catch (error) { + console.error('Error finding TV series on TMDB:', error); + return null; + } +} + +// =========================================================================== +// ROUTES (mounted at /api, so paths are relative) +// =========================================================================== + +// --------------------------------------------------------------------------- +// GET /tmdb/:type/:id -- retrieve Coflix links via TMDB ID +// --------------------------------------------------------------------------- +router.get('/tmdb/:type/:id', async (req, res) => { + const { id, type } = req.params; + + // Bloquer certains IDs TMDB specifiques + if (type === 'movie' && id === '771') { + return res.status(404).json({ error: 'Not found' }); + } + if (type === 'movie' && id === '1159559') { + return res.status(200).json({ message: 'Contenu non disponible' }); + } + const { season, episode } = req.query; + const cacheKey = generateCacheKey(`tmdb_links_${type}_${id}_${season || ''}_${episode || ''}`); + + try { + // 1. Verifier le cache sans expiration (stale-while-revalidate) + const cachedData = await getFromCacheNoExpiration(CACHE_DIR.COFLIX, cacheKey); + let dataReturned = false; + if (cachedData) { + const cachedDataWithClones = await applyCloneUrlsToTmdbResult(cachedData, type, id, season, episode); + res.json(filterEmmmmbedReaders(cachedDataWithClones)); + dataReturned = true; + + // Lancer la mise a jour en arriere-plan si necessaire + (async () => { + try { + const cachedCloneSync = await syncCloneUrlsOnTmdbResult(cachedDataWithClones, type, id, season, episode); + await saveToCache(CACHE_DIR.COFLIX, cacheKey, cachedCloneSync); + + const shouldUpdate = await shouldUpdateCacheLecteurVideo(CACHE_DIR.COFLIX, cacheKey); + if (!shouldUpdate) { + return; + } + await updateCache(); + } catch (err) { + console.error("Erreur non geree dans updateCache (TMDB):", err); + } + })(); + } + + // 3. Fonction pour recuperer les donnees fraiches et mettre a jour le cache + const updateCache = async () => { + try { + // Verifier que le type est valide + if (type !== 'movie' && type !== 'tv') { + if (!dataReturned) { + res.status(400).json({ message: 'Type de media non valide' }); + } + return; + } + + // Pour les series, verifier que la saison et l'episode sont fournis pour la mise a jour + if (type === 'tv' && (!season || !episode)) { + if (!dataReturned) { + res.status(400).json({ message: 'Parametres de saison/episode manquants' }); + } + return; + } + + // Recuperer les details TMDB + const tmdbDetails = await getTMDBDetails(id, type); + if (!tmdbDetails) { + if (!dataReturned) { + res.status(404).json({ message: 'Contenu non trouve sur TMDB' }); + } + return; + } + + // Extraire l'annee de la date de sortie + const releaseYear = tmdbDetails.release_date ? parseInt(tmdbDetails.release_date.split('-')[0]) : null; + + // Rechercher sur Coflix avec le titre international d'abord + let coflixResults = await searchCoflixByTitle(tmdbDetails.title, type, releaseYear); + let bestResults = coflixResults; + + // Si aucun resultat trouve avec le titre principal, essayer avec le titre original + if ((!coflixResults || !coflixResults.length || (coflixResults[0] && coflixResults[0].similarity < 0.8)) && tmdbDetails.original_title && tmdbDetails.original_title !== tmdbDetails.title) { + const originalResults = await searchCoflixByTitle(tmdbDetails.original_title, type, releaseYear); + + if (originalResults && originalResults.length > 0) { + if (!bestResults || !bestResults.length) { + bestResults = originalResults; + } else { + const bestSimilarity = Math.max( + bestResults[0]?.similarity || 0, + originalResults[0]?.similarity || 0 + ); + if (bestSimilarity === (originalResults[0]?.similarity || 0)) { + bestResults = originalResults; + } + } + } + } + + // Si toujours pas de bon resultat, essayer avec le titre francais localise + if ((!bestResults || !bestResults.length || (bestResults[0] && bestResults[0].similarity < 0.8))) { + try { + const frenchData = await fetchTmdbDetails(TMDB_API_URL, TMDB_API_KEY, id, type, 'fr-FR'); + + if (frenchData) { + const frenchTitle = type === 'movie' ? frenchData.title : frenchData.name; + if (frenchTitle && frenchTitle !== tmdbDetails.title && frenchTitle !== tmdbDetails.original_title) { + const frenchResults = await searchCoflixByTitle(frenchTitle, type, releaseYear); + + if (frenchResults && frenchResults.length > 0) { + if (!bestResults || !bestResults.length) { + bestResults = frenchResults; + } else { + const bestSimilarity = Math.max( + bestResults[0]?.similarity || 0, + frenchResults[0]?.similarity || 0 + ); + if (bestSimilarity === (frenchResults[0]?.similarity || 0)) { + bestResults = frenchResults; + } + } + } + } + } + } catch (error) { + console.log(`[TMDB API] Impossible de recuperer le titre francais pour ${id}`); + } + } + + // Utiliser les meilleurs resultats trouves + coflixResults = bestResults; + + // Gerer le cas ou aucun resultat n'est trouve sur Coflix + const similarityThreshold = 0.8; + + if (!coflixResults || !coflixResults.length || (coflixResults[0] && coflixResults[0].similarity < similarityThreshold)) { + const unavailableResult = { + message: 'Contenu non disponible', + tmdb_id: id, + tmdb_details: tmdbDetails + }; + await saveToCache(CACHE_DIR.COFLIX, cacheKey, unavailableResult); + if (!dataReturned) { + res.status(200).json(filterEmmmmbedReaders(unavailableResult)); + } + return; + } + + // Utiliser le premier resultat trouve + const coflixUrl = coflixResults[0].url; + + let result = { + tmdb_details: tmdbDetails + }; + + // Recuperer les donnees specifiques selon le type + if (type === 'movie') { + const movieData = await getMovieDataFromCoflix(coflixUrl); + result = { + ...result, + ...movieData + }; + } else if (type === 'tv') { + const seasonNum = parseInt(season); + const episodeNum = parseInt(episode); + const tvData = await getTvDataFromCoflix(coflixUrl, seasonNum, episodeNum); + result = { + ...result, + ...tvData + }; + } + + result = await syncCloneUrlsOnTmdbResult(result, type, id, season, episode); + + // 4. Verifier si les resultats sont valides avant de sauvegarder + const isEmptyResult = (type === 'movie' && (!result.player_links || result.player_links.length === 0)) || + (type === 'tv' && (!result.seasons || result.seasons.length === 0)); + + if (!isEmptyResult || !dataReturned) { + await saveToCache(CACHE_DIR.COFLIX, cacheKey, result); + } + + // Si les donnees n'avaient pas ete retournees initialement, les retourner maintenant + if (!dataReturned) { + res.json(filterEmmmmbedReaders(result)); + } + + } catch (updateError) { + if (updateError && updateError.isAxiosError) { + const url = updateError.config && updateError.config.url ? updateError.config.url : ''; + console.error( + `Erreur lors de la mise a jour du cache TMDB ${id} (${type}): [AxiosError] ${updateError.code || ''} ${updateError.message} ${url}` + ); + } else { + const msg = updateError && updateError.message + ? updateError.message + : (typeof updateError === 'string' + ? updateError + : JSON.stringify(updateError)); + console.error(`Erreur lors de la mise a jour du cache TMDB ${id} (${type}): ${msg}`); + } + if (!dataReturned) { + res.status(200).json({ + message: 'Contenu non disponible en raison d\'une erreur', + tmdb_id: id + }); + } + } + }; + + // Si pas de donnees en cache, faire la requete normale + if (!dataReturned) { + await updateCache(); + } + + } catch (error) { + console.error(`Erreur lors de la recuperation des liens TMDB ${id} (${type}):`, error); + if (!res.headersSent) { + res.status(200).json({ + message: 'Contenu non disponible en raison d\'une erreur', + tmdb_id: id + }); + } + } +}); + +// --------------------------------------------------------------------------- +// GET /imdb/:type/:id -- IMDB / FrenchStream data route +// --------------------------------------------------------------------------- + +// Cache directory for FrenchCloud data +const FRENCHCLOUD_CACHE_DIR = path.join(__dirname, '..', 'cache', 'frenchcloud'); +(async () => { + try { + await fsp.access(FRENCHCLOUD_CACHE_DIR); + } catch { + await fsp.mkdir(FRENCHCLOUD_CACHE_DIR, { recursive: true }); + } +})(); + +// Consolidated cache directory for links +const LINK_CACHE_DIR = path.join(__dirname, '..', 'cache', 'links'); +(async () => { + try { + await fsp.access(LINK_CACHE_DIR); + } catch { + await fsp.mkdir(LINK_CACHE_DIR, { recursive: true }); + } +})(); +const CACHE_EXPIRATION_6H = 6 * 60 * 60 * 1000; // 6 hours in milliseconds + +router.get('/imdb/:type/:id', async (req, res) => { + const { id, type } = req.params; + // Return 404 for specific blocked IMDB ids + const blockedImdbIds = new Set([ + 'tt7069210', + 'tt0325980', + 'tt0383574', + 'tt0449088', + 'tt1298650', + 'tt1790809', + 'tt0099785' + ]); + if (blockedImdbIds.has(id)) { + return res.status(404).json({ error: 'Not found' }); + } + const cacheKey = type === 'movie' ? + generateCacheKey(`imdb_movie_${id}`) : + generateCacheKey(`frenchstream_${id}`); + const cacheDir = LINK_CACHE_DIR; + + try { + // 1. Check cache without expiration + const cachedData = await getFromCacheNoExpiration(cacheDir, cacheKey); + let dataReturned = false; + if (cachedData) { + const dataToSend = type === 'tv' ? cleanTvCacheData(cachedData) : cachedData; + res.json(dataToSend); + dataReturned = true; + } + + // 3. Function to fetch fresh data and update cache + const updateCache = async () => { + try { + // Verifier si le cache doit etre mis a jour (pour TV uniquement) + if (type === 'tv') { + const shouldUpdate = await shouldUpdateCacheFrenchStream(cacheDir, cacheKey); + if (!shouldUpdate) { + return; + } + } + + let responseData = {}; + + if (type === 'movie') { + // --- Handle Movies (using FrenchStream scraping) --- + const movieData = await getFrenchStreamMovie(id); + if (movieData.error) { + responseData = { message: 'Contenu non disponible', french_stream_id: id, details: movieData.error }; + } else { + responseData = { + ...movieData + }; + } + + } else if (type === 'tv') { + // --- Handle TV Series (using FrenchStream ID and FrenchStream logic) --- + const frenchStreamId = id; + const seriesList = await getFrenchStreamSeries(frenchStreamId); + + if (!seriesList || (Array.isArray(seriesList) && seriesList.length === 0)) { + responseData = { message: 'Contenu non disponible', french_stream_id: frenchStreamId }; + } else if (seriesList.error) { + if (seriesList.error.includes('404')) { + responseData = { message: 'Contenu non disponible', french_stream_id: frenchStreamId }; + } else { + responseData = { error: 'Failed to retrieve series list from FrenchStream', details: seriesList.error, french_stream_id: frenchStreamId }; + } + } else { + const MAX_SERIES = 10; + const seriesToProcess = seriesList.slice(0, MAX_SERIES); + + await Promise.all(seriesToProcess.map(async (series) => { + if (series.link) { + try { + const seriesDetails = await getFrenchStreamSeriesDetails(series.link, series.title); + if (!seriesDetails.error) { + series.seasons = seriesDetails.seasons; + series.release_date = seriesDetails.release_date; + series.summary = seriesDetails.summary; + series.tmdb_data = seriesDetails.tmdb_data; + const { baseName, partNumber } = extractSeriesInfo(series.title); + series.baseName = baseName; + series.partNumber = partNumber; + } else { + console.warn(`Could not fetch details for series: ${series.title} (${series.link}), Error: ${seriesDetails.error}`); + series.seasons = []; + } + } catch (detailsError) { + console.error(`Exception fetching details for ${series.title} (${series.link}):`, detailsError); + series.seasons = []; + } + } else { + series.seasons = []; + } + })); + + // Group and Merge Series Parts + const seriesGroups = {}; + seriesToProcess.forEach(series => { + if (series.baseName) { + if (!seriesGroups[series.baseName]) { + seriesGroups[series.baseName] = []; + } + seriesGroups[series.baseName].push(series); + } + }); + + const mergedSeriesList = []; + for (const baseName in seriesGroups) { + const merged = mergeSeriesParts(seriesGroups[baseName]); + if (merged) { + mergedSeriesList.push(merged); + } + } + + // Clean the merged list for the final result + const cleanedSeries = cleanTvCacheData({ series: mergedSeriesList }); + + responseData = { + type: 'tv', + series: cleanedSeries.series + }; + } + } else { + console.error(`Type invalide pour la mise a jour du cache: ${type}`); + return; + } + + // 4. Save to cache (only if no error occurred during fetch) + if (!responseData.error) { + await saveToCache(cacheDir, cacheKey, responseData); + } + + // If data was not returned initially, return it now + if (!dataReturned) { + if (responseData.error) { + const statusCode = responseData.error.includes('No series found') ? 404 : 500; + res.status(statusCode).json(responseData); + } else if (responseData.message === 'Contenu non disponible') { + res.status(200).json(responseData); + } else { + res.json(responseData); + } + } + + } catch (updateError) { + console.error(`Erreur lors de la mise a jour du cache ${type} ${id}:`, updateError); + if (!dataReturned && !res.headersSent) { + if (updateError.message && updateError.message.includes('404')) { + res.status(200).json({ message: 'Contenu non disponible', french_stream_id: id }); + } else { + res.status(500).json({ error: 'Erreur lors de la mise a jour du cache', details: updateError.message }); + } + } + } + }; + + // Run cache update in the background + updateCache().catch(err => console.error(`Erreur non geree dans updateCache (${type} ${id}):`, err)); + + } catch (error) { + console.error(`Erreur initiale dans /api/imdb/${type}/${id}:`, error); + if (!res.headersSent) { + if (error.message && error.message.includes('404')) { + res.status(200).json({ message: 'Contenu non disponible', french_stream_id: id }); + } else { + res.status(500).json({ error: 'Erreur serveur interne lors du traitement initial', details: error.message }); + } + } + } +}); + +// --------------------------------------------------------------------------- +// GET /tmdb/cache/series/:id -- clear all Coflix cache for a TMDB series +// --------------------------------------------------------------------------- +router.get('/tmdb/cache/series/:id', async (req, res) => { + const { id } = req.params; + const cacheDir = CACHE_DIR.COFLIX; + + try { + await fsp.mkdir(cacheDir, { recursive: true }); + const files = await fsp.readdir(cacheDir); + + let removed = 0; + const removedFiles = []; + + for (const file of files) { + if (!file.endsWith('.json')) continue; + const fullPath = path.join(cacheDir, file); + + try { + const content = await fsp.readFile(fullPath, 'utf-8'); + const data = JSON.parse(content); + + const isSameId = data && String(data.tmdb_id) === String(id); + const isTvSeries = data && data.tmdb_details && (typeof data.tmdb_details.title === 'string' || typeof data.tmdb_details.original_title === 'string'); + + if (isSameId && isTvSeries) { + await fsp.unlink(fullPath); + removed++; + removedFiles.push(file); + } + } catch (parseError) { + continue; + } + } + + console.log(`Cache Coflix supprime pour la serie TMDB ${id}: ${removed} fichiers`); + res.json({ + message: `Cache Coflix supprime pour la serie TMDB ${id}`, + removed_files: removed, + files: removedFiles + }); + + } catch (error) { + console.error(`Erreur lors de la suppression du cache Coflix pour la serie ${id}: ${error.message}`); + res.status(500).json({ + error: 'Erreur lors de la suppression du cache Coflix', + message: error.message + }); + } +}); + +// --------------------------------------------------------------------------- +// DELETE /tmdb/cache/:type/:id -- delete specific Coflix cache entry +// --------------------------------------------------------------------------- +router.delete('/tmdb/cache/:type/:id', async (req, res) => { + const { id, type } = req.params; + const cacheKey = generateCacheKey(`tmdb_links_${type}_${id}_${req.query.season || ''}_${req.query.episode || ''}`); + const cacheFile = path.join(CACHE_DIR.COFLIX, `${cacheKey}.json`); + + try { + await fsp.unlink(cacheFile); + console.log(`Cache supprime pour TMDB ${type} ${id}`); + res.json({ message: `Cache supprime pour TMDB ${type} ${id}` }); + } catch (error) { + if (error.code === 'ENOENT') { + res.json({ message: `Aucun cache trouve pour TMDB ${type} ${id}` }); + } else { + console.error(`Erreur lors de la suppression du cache: ${error.message}`); + res.status(500).json({ error: 'Erreur lors de la suppression du cache' }); + } + } +}); + +// --------------------------------------------------------------------------- +// GET /SenpaiStream/tv/cache/:tmdbId -- clear SenpaiStream TV cache +// --------------------------------------------------------------------------- +router.get('/SenpaiStream/tv/cache/:tmdbId', async (req, res) => { + const { tmdbId } = req.params; + const cacheDir = path.join(__dirname, '..', 'cache', 'SenpaiStream'); + + try { + await fsp.mkdir(cacheDir, { recursive: true }); + const files = await fsp.readdir(cacheDir); + + let removed = 0; + for (const file of files) { + if (!file.endsWith('.json')) continue; + const fullPath = path.join(cacheDir, file); + try { + const content = await fsp.readFile(fullPath, 'utf-8'); + const data = JSON.parse(content); + const isSameId = data && String(data.tmdb_id) === String(tmdbId); + const isTvByFields = data && data.tmdb_details && (typeof data.tmdb_details.name === 'string' || typeof data.tmdb_details.original_name === 'string'); + const hasEpisodeFields = typeof data?.season !== 'undefined' && typeof data?.episode !== 'undefined'; + if (isSameId && (hasEpisodeFields || isTvByFields)) { + await fsp.unlink(fullPath); + removed++; + } + } catch (err) { + continue; + } + } + + return res.json({ + success: true, + tmdb_id: tmdbId, + removed, + cache_dir: cacheDir, + timestamp: new Date().toISOString() + }); + } catch (error) { + console.error(`[SenpaiStream TV CACHE CLEAR] Erreur: ${error.message}`); + return res.status(500).json({ + success: false, + error: 'Erreur lors de la suppression du cache SenpaiStream TV', + message: error.message, + tmdb_id: tmdbId, + timestamp: new Date().toISOString() + }); + } +}); + +// --------------------------------------------------------------------------- +// Exports +// --------------------------------------------------------------------------- +module.exports = router; +module.exports.configure = configure; +module.exports.getTMDBDetails = getTMDBDetails; +module.exports.findTvSeriesOnTMDB = findTvSeriesOnTMDB; diff --git a/API/Mainapi/routes/topstream.js b/API/Mainapi/routes/topstream.js new file mode 100644 index 0000000..a5cb726 --- /dev/null +++ b/API/Mainapi/routes/topstream.js @@ -0,0 +1,486 @@ +/** + * Top-Stream routes module. + * Scrapes top-stream.plus for movie/series search and embed extraction. + * + * Mounted at /api/topstream (paths below are relative to that prefix). + */ + +const express = require('express'); +const router = express.Router(); +const path = require('path'); +const fsp = require('fs').promises; +const axios = require('axios'); +const cheerio = require('cheerio'); +const { generateCacheKey } = require('../utils/cacheManager'); +const { fetchTmdbDetails } = require('../utils/tmdbCache'); + +const TOPSTREAM_BASE_URL = 'https://top-stream.plus'; +const BYPASS403_SERVER_URL = process.env.BYPASS403_SERVER_URL || ''; + +const topstreamHeaders = { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36', + 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', + 'Accept-Language': 'fr-FR,fr;q=0.9,en;q=0.8', + 'Accept-Encoding': 'gzip, deflate, br', + 'Referer': TOPSTREAM_BASE_URL, + 'DNT': '1', + 'Connection': 'keep-alive', + 'Upgrade-Insecure-Requests': '1' +}; + +// --------------------------------------------------------------------------- +// Dependencies injected via configure() +// --------------------------------------------------------------------------- +let TMDB_API_KEY; +let TMDB_API_URL; +let getFromCacheNoExpiration; +let saveToCache; +let shouldUpdateCache24h; + +function configure(deps) { + if (deps.TMDB_API_KEY) TMDB_API_KEY = deps.TMDB_API_KEY; + if (deps.TMDB_API_URL) TMDB_API_URL = deps.TMDB_API_URL; + if (deps.getFromCacheNoExpiration) getFromCacheNoExpiration = deps.getFromCacheNoExpiration; + if (deps.saveToCache) saveToCache = deps.saveToCache; + if (deps.shouldUpdateCache24h) shouldUpdateCache24h = deps.shouldUpdateCache24h; +} + +// --------------------------------------------------------------------------- +// Helper: build proxied embed URL +// --------------------------------------------------------------------------- +function proxyEmbedUrl(originalLink) { + const topstreamMatch = originalLink.match(/https?:\/\/(?:www\.)?top-stream\.plus(\/embed\/\d+)/); + if (topstreamMatch && BYPASS403_SERVER_URL) { + return `${BYPASS403_SERVER_URL}/proxy/https://top-stream.plus${topstreamMatch[1]}`; + } + return originalLink; +} + +// --------------------------------------------------------------------------- +// Helper: fetch a page from top-stream +// --------------------------------------------------------------------------- +async function fetchPage(url) { + const response = await axios.get(url, { + headers: topstreamHeaders, + timeout: 15000, + decompress: true + }); + if (response.status === 403) { + console.error('[TOPSTREAM] 403 Forbidden:', url); + } + return response.data; +} + +// --------------------------------------------------------------------------- +// Helper: resolve TMDB ID to title +// --------------------------------------------------------------------------- +async function getTmdbTitle(tmdbId, mediaType) { + const endpoint = mediaType === 'tv' ? 'tv' : 'movie'; + const data = await fetchTmdbDetails(TMDB_API_URL, TMDB_API_KEY, tmdbId, endpoint, 'fr-FR'); + if (!data) return { title: '', originalTitle: '', year: '' }; + const title = data.title || data.name || ''; + const originalTitle = data.original_title || data.original_name || ''; + const year = (data.release_date || data.first_air_date || '').substring(0, 4); + return { title, originalTitle, year }; +} + +// --------------------------------------------------------------------------- +// searchTopStream -- search for movies/series +// --------------------------------------------------------------------------- +async function searchTopStream(query) { + const searchUrl = `${TOPSTREAM_BASE_URL}/search/${encodeURIComponent(query)}`; + const html = await fetchPage(searchUrl); + const $ = cheerio.load(html); + + const results = []; + + $('div.relative.group.overflow-hidden').each((_, el) => { + const card = $(el); + const link = card.find('a').first(); + const href = link.attr('href') || ''; + + let type = 'movie'; + let slug = ''; + if (href.includes('/movie/')) { + type = 'movie'; + slug = href.split('/movie/').pop(); + } else if (href.includes('/tv-show/')) { + type = 'tv'; + slug = href.split('/tv-show/').pop(); + } else { + return; + } + + const img = card.find('img').first(); + const image = img.attr('src') || img.attr('data-src') || ''; + const title = img.attr('alt') || ''; + + const ratingEl = card.find('.absolute.right-3.top-3 span.text-xs'); + const rating = ratingEl.text().trim() || null; + + const infoDiv = card.find('.pt-4'); + const allSpans = infoDiv.find('span'); + + let duration = null; + let year = null; + let genre = null; + let typeLabel = null; + + allSpans.each((_, span) => { + const text = $(span).text().trim(); + if (text.match(/\d+h\d+|min/)) { + duration = text; + } else if (text.match(/^\d{4}$/)) { + year = parseInt(text); + } else if ($(span).hasClass('text-xxs')) { + typeLabel = text; + } else if (!duration && !year && text.length > 0) { + if (!genre) genre = text; + } + }); + + const h3Title = infoDiv.find('h3').text().trim() || title; + + results.push({ + title: h3Title, + slug, + type, + image, + rating: rating ? parseFloat(rating) : null, + year, + duration, + genre, + typeLabel + }); + }); + + return results; +} + +// --------------------------------------------------------------------------- +// getTopStreamEmbed -- extract embed URL from movie or episode page +// --------------------------------------------------------------------------- +async function getTopStreamEmbed(pageUrl) { + const html = await fetchPage(pageUrl); + const $ = cheerio.load(html); + + const videos = []; + let watchComponentFound = false; + let cover = null; + + $('*').each((_, el) => { + if (watchComponentFound) return; + const snapshot = $(el).attr('wire:snapshot'); + if (!snapshot) return; + + try { + const data = JSON.parse(snapshot); + if (data.memo && data.memo.name === 'watch-component') { + watchComponentFound = true; + cover = data.data?.cover || null; + + const videosData = data.data?.videos; + if (Array.isArray(videosData)) { + const extractLinks = (obj) => { + if (!obj) return; + if (Array.isArray(obj)) { + obj.forEach(item => extractLinks(item)); + } else if (typeof obj === 'object' && obj.link) { + videos.push({ + label: obj.label || 'Stream', + type: obj.type || 'mp4', + link: proxyEmbedUrl(obj.link) + }); + } + }; + extractLinks(videosData); + } + } + } catch (err) { + // skip + } + }); + + return { videos, cover }; +} + +// --------------------------------------------------------------------------- +// findAndGetEmbed -- search TopStream by title, find best match, get embed +// --------------------------------------------------------------------------- +async function findAndGetEmbed(tmdbId, mediaType, season, episode) { + const { title, originalTitle, year } = await getTmdbTitle(tmdbId, mediaType); + if (!title && !originalTitle) return null; + + const searchType = mediaType === 'tv' ? 'tv' : 'movie'; + let results = await searchTopStream(title); + let matchResults = results.filter(r => r.type === searchType); + + if (matchResults.length === 0 && originalTitle && originalTitle !== title) { + results = await searchTopStream(originalTitle); + matchResults = results.filter(r => r.type === searchType); + } + + if (matchResults.length === 0) return null; + + let bestMatch = matchResults[0]; + if (year) { + const yearNum = parseInt(year); + const yearMatch = matchResults.find(r => r.year === yearNum); + if (yearMatch) bestMatch = yearMatch; + } + + let pageUrl; + if (mediaType === 'tv') { + pageUrl = `${TOPSTREAM_BASE_URL}/episode/${bestMatch.slug}/${season}-${episode}`; + } else { + pageUrl = `${TOPSTREAM_BASE_URL}/movie/${bestMatch.slug}`; + } + + const embedResult = await getTopStreamEmbed(pageUrl); + return { + ...embedResult, + slug: bestMatch.slug, + matchedTitle: bestMatch.title, + matchedYear: bestMatch.year + }; +} + +// --------------------------------------------------------------------------- +// GET /film/:tmdbId +// --------------------------------------------------------------------------- +router.get('/film/:tmdbId', async (req, res) => { + const { tmdbId } = req.params; + const cacheKey = generateCacheKey(`topstream_film_${tmdbId}`); + const cacheDir = path.join(__dirname, '..', 'cache', 'topstream'); + + try { + await fsp.mkdir(cacheDir, { recursive: true }); + + const cachedData = await getFromCacheNoExpiration(cacheDir, cacheKey); + if (cachedData) { + res.json(cachedData); + const shouldUpdate = await shouldUpdateCache24h(cacheDir, cacheKey); + if (shouldUpdate) { + (async () => { + try { + const result = await findAndGetEmbed(tmdbId, 'movie'); + if (result) { + await saveToCache(cacheDir, cacheKey, { success: true, tmdbId, type: 'movie', ...result }); + } + } catch (err) { + if (err.response?.status === 403) console.error('[TOPSTREAM] 403 background film update:', tmdbId); + } + })(); + } + return; + } + + const result = await findAndGetEmbed(tmdbId, 'movie'); + + if (!result || result.videos.length === 0) { + const data = { success: false, tmdbId, error: 'Film non trouvé sur TopStream' }; + await saveToCache(cacheDir, cacheKey, data); + return res.status(404).json(data); + } + + const data = { success: true, tmdbId, type: 'movie', ...result }; + await saveToCache(cacheDir, cacheKey, data); + res.json(data); + + } catch (error) { + if (error.response?.status === 403) console.error('[TOPSTREAM] 403 Forbidden film:', tmdbId); + else console.error('[TOPSTREAM] Film error:', tmdbId, error.message); + res.status(500).json({ success: false, error: 'Erreur lors de la récupération du film', details: error.message }); + } +}); + +// --------------------------------------------------------------------------- +// GET /tv/:tmdbId?season=X&episode=Y +// --------------------------------------------------------------------------- +router.get('/tv/:tmdbId', async (req, res) => { + const { tmdbId } = req.params; + const season = parseInt(req.query.season); + const episode = parseInt(req.query.episode); + + if (!season || !episode) { + return res.status(400).json({ success: false, error: 'Les paramètres ?season= et ?episode= sont requis.' }); + } + + const cacheKey = generateCacheKey(`topstream_tv_${tmdbId}_${season}_${episode}`); + const cacheDir = path.join(__dirname, '..', 'cache', 'topstream'); + + try { + await fsp.mkdir(cacheDir, { recursive: true }); + + const cachedData = await getFromCacheNoExpiration(cacheDir, cacheKey); + if (cachedData) { + res.json(cachedData); + const shouldUpdate = await shouldUpdateCache24h(cacheDir, cacheKey); + if (shouldUpdate) { + (async () => { + try { + const result = await findAndGetEmbed(tmdbId, 'tv', season, episode); + if (result) { + await saveToCache(cacheDir, cacheKey, { success: true, tmdbId, type: 'tv', season, episode, ...result }); + } + } catch (err) { + if (err.response?.status === 403) console.error('[TOPSTREAM] 403 background TV update:', tmdbId, 'S' + season + 'E' + episode); + } + })(); + } + return; + } + + const result = await findAndGetEmbed(tmdbId, 'tv', season, episode); + + if (!result || result.videos.length === 0) { + const data = { success: false, tmdbId, season, episode, error: 'Épisode non trouvé sur TopStream' }; + await saveToCache(cacheDir, cacheKey, data); + return res.status(404).json(data); + } + + const data = { success: true, tmdbId, type: 'tv', season, episode, ...result }; + await saveToCache(cacheDir, cacheKey, data); + res.json(data); + + } catch (error) { + if (error.response?.status === 403) console.error('[TOPSTREAM] 403 Forbidden TV:', tmdbId, 'S' + season + 'E' + episode); + else console.error('[TOPSTREAM] TV error:', tmdbId, error.message); + res.status(500).json({ success: false, error: 'Erreur lors de la récupération de l\'épisode', details: error.message }); + } +}); + +// --------------------------------------------------------------------------- +// GET /search?q=... (conservé pour usage direct) +// --------------------------------------------------------------------------- +router.get('/search', async (req, res) => { + const query = req.query.q; + if (!query) { + return res.status(400).json({ success: false, error: 'Le paramètre ?q= est requis.' }); + } + + const cacheKey = generateCacheKey(`topstream_search_${query.toLowerCase().trim()}`); + const cacheDir = path.join(__dirname, '..', 'cache', 'topstream'); + + try { + await fsp.mkdir(cacheDir, { recursive: true }); + + const cachedData = await getFromCacheNoExpiration(cacheDir, cacheKey); + if (cachedData) { + res.json(cachedData); + const shouldUpdate = await shouldUpdateCache24h(cacheDir, cacheKey); + if (shouldUpdate) { + (async () => { + try { + const results = await searchTopStream(query); + await saveToCache(cacheDir, cacheKey, { success: true, results }); + } catch (err) { + if (err.response?.status === 403) console.error('[TOPSTREAM] 403 background search:', query); + } + })(); + } + return; + } + + const results = await searchTopStream(query); + const data = { success: true, results }; + await saveToCache(cacheDir, cacheKey, data); + res.json(data); + + } catch (error) { + if (error.response?.status === 403) console.error('[TOPSTREAM] 403 Forbidden search:', query); + else console.error('[TOPSTREAM] Search error:', query, error.message); + res.status(500).json({ success: false, error: 'Erreur lors de la recherche', details: error.message }); + } +}); + +// --------------------------------------------------------------------------- +// GET /movie/:slug (conservé pour usage direct par slug) +// --------------------------------------------------------------------------- +router.get('/movie/:slug', async (req, res) => { + const { slug } = req.params; + const cacheKey = generateCacheKey(`topstream_movie_${slug}`); + const cacheDir = path.join(__dirname, '..', 'cache', 'topstream'); + + try { + await fsp.mkdir(cacheDir, { recursive: true }); + + const cachedData = await getFromCacheNoExpiration(cacheDir, cacheKey); + if (cachedData) { + res.json(cachedData); + const shouldUpdate = await shouldUpdateCache24h(cacheDir, cacheKey); + if (shouldUpdate) { + (async () => { + try { + const result = await getTopStreamEmbed(`${TOPSTREAM_BASE_URL}/movie/${slug}`); + await saveToCache(cacheDir, cacheKey, { success: true, slug, type: 'movie', ...result }); + } catch (err) { + if (err.response?.status === 403) console.error('[TOPSTREAM] 403 background movie:', slug); + } + })(); + } + return; + } + + const result = await getTopStreamEmbed(`${TOPSTREAM_BASE_URL}/movie/${slug}`); + const data = { success: true, slug, type: 'movie', ...result }; + await saveToCache(cacheDir, cacheKey, data); + res.json(data); + + } catch (error) { + if (error.response?.status === 403) console.error('[TOPSTREAM] 403 Forbidden movie:', slug); + else console.error('[TOPSTREAM] Movie error:', slug, error.message); + res.status(500).json({ success: false, error: 'Erreur lors de la récupération du film', details: error.message }); + } +}); + +// --------------------------------------------------------------------------- +// GET /episode/:slug/:season-:episode (conservé pour usage direct par slug) +// --------------------------------------------------------------------------- +router.get('/episode/:slug/:seasonEpisode', async (req, res) => { + const { slug, seasonEpisode } = req.params; + + const match = seasonEpisode.match(/^(\d+)-(\d+)$/); + if (!match) { + return res.status(400).json({ success: false, error: 'Format invalide. Utilisez :season-:episode (ex: 5-1).' }); + } + + const season = parseInt(match[1]); + const episode = parseInt(match[2]); + const cacheKey = generateCacheKey(`topstream_episode_${slug}_${season}_${episode}`); + const cacheDir = path.join(__dirname, '..', 'cache', 'topstream'); + + try { + await fsp.mkdir(cacheDir, { recursive: true }); + + const cachedData = await getFromCacheNoExpiration(cacheDir, cacheKey); + if (cachedData) { + res.json(cachedData); + const shouldUpdate = await shouldUpdateCache24h(cacheDir, cacheKey); + if (shouldUpdate) { + (async () => { + try { + const result = await getTopStreamEmbed(`${TOPSTREAM_BASE_URL}/episode/${slug}/${season}-${episode}`); + await saveToCache(cacheDir, cacheKey, { success: true, slug, type: 'tv', season, episode, ...result }); + } catch (err) { + if (err.response?.status === 403) console.error('[TOPSTREAM] 403 background episode:', slug, 'S' + season + 'E' + episode); + } + })(); + } + return; + } + + const result = await getTopStreamEmbed(`${TOPSTREAM_BASE_URL}/episode/${slug}/${season}-${episode}`); + const data = { success: true, slug, type: 'tv', season, episode, ...result }; + await saveToCache(cacheDir, cacheKey, data); + res.json(data); + + } catch (error) { + if (error.response?.status === 403) console.error('[TOPSTREAM] 403 Forbidden episode:', slug, 'S' + season + 'E' + episode); + else console.error('[TOPSTREAM] Episode error:', slug, error.message); + res.status(500).json({ success: false, error: 'Erreur lors de la récupération de l\'épisode', details: error.message }); + } +}); + +module.exports = router; +module.exports.configure = configure; diff --git a/API/Mainapi/routes/vipDonations.js b/API/Mainapi/routes/vipDonations.js new file mode 100644 index 0000000..bd4c4fd --- /dev/null +++ b/API/Mainapi/routes/vipDonations.js @@ -0,0 +1,381 @@ +const express = require('express'); +const rateLimit = require('express-rate-limit'); +const { ipKeyGenerator } = require('express-rate-limit'); + +const { getPool } = require('../mysqlPool'); +const { isAdmin, getAuthIfValid } = require('../middleware/auth'); +const { createRedisRateLimitStore } = require('../utils/redisRateLimitStore'); +const { verifyTurnstileFromRequest } = require('../utils/turnstile'); +const { + createVipInvoice, + handlePaygateCallback, + fetchInvoiceByPublicId, + fetchInvoiceByGiftToken, + getVipInvoiceDetails, + listVipInvoices, + refreshInvoiceStatus, + forceValidateInvoice, + cancelInvoice, + serializePublicInvoice, + serializeAdminInvoice, + serializeGift, + unsealGift, + ensureVipDonationsTables, + getClientIp +} = require('../utils/vipDonations'); + +const router = express.Router(); + +const getRateLimitKey = (req) => req.headers['cf-connecting-ip'] + || req.headers['x-forwarded-for']?.split(',')[0].trim() + || ipKeyGenerator(req.ip); + +const getRequestBaseUrl = (req) => { + const forwardedProto = String(req.headers['x-forwarded-proto'] || '').split(',')[0].trim(); + const forwardedHost = String(req.headers['x-forwarded-host'] || '').split(',')[0].trim(); + const protocol = forwardedProto || req.protocol || 'https'; + const host = forwardedHost || req.get('host') || ''; + + return host ? `${protocol}://${host}`.replace(/\/+$/, '') : ''; +}; + +const createInvoiceRateLimit = rateLimit({ + windowMs: 15 * 60 * 1000, + max: 15, + store: createRedisRateLimitStore({ prefix: 'rate-limit:vip:create-invoice:' }), + passOnStoreError: true, + standardHeaders: true, + legacyHeaders: false, + keyGenerator: getRateLimitKey, + validate: { xForwardedForHeader: false, ip: false }, + message: { + success: false, + error: 'Trop de créations d\'invoice. Réessayez plus tard.' + } +}); + +const invoiceCheckRateLimit = rateLimit({ + windowMs: 15 * 60 * 1000, + max: 180, + store: createRedisRateLimitStore({ prefix: 'rate-limit:vip:invoice-check:' }), + passOnStoreError: true, + standardHeaders: true, + legacyHeaders: false, + keyGenerator: getRateLimitKey, + validate: { xForwardedForHeader: false, ip: false }, + message: { + success: false, + error: 'Trop de vérifications d\'invoice. Réessayez plus tard.' + } +}); + +const giftUnsealRateLimit = rateLimit({ + windowMs: 15 * 60 * 1000, + max: 20, + store: createRedisRateLimitStore({ prefix: 'rate-limit:vip:gift-unseal:' }), + passOnStoreError: true, + standardHeaders: true, + legacyHeaders: false, + keyGenerator: getRateLimitKey, + validate: { xForwardedForHeader: false, ip: false }, + message: { + success: false, + error: 'Trop de tentatives de descellement. Réessayez plus tard.' + } +}); + +router.post('/vip/invoices', createInvoiceRateLimit, async (req, res) => { + try { + const pool = getPool(); + const turnstileResult = await verifyTurnstileFromRequest(req, req.body?.turnstileToken); + if (!turnstileResult.valid) { + return res.status(turnstileResult.status).json({ + success: false, + error: turnstileResult.error + }); + } + + const auth = await getAuthIfValid(req); + const invoice = await createVipInvoice( + pool, + { + packEur: req.body?.pack_eur, + paymentMethod: req.body?.payment_method, + coin: req.body?.coin, + recipientMode: req.body?.recipient_mode, + payerEmail: req.body?.payer_email + }, + { + auth, + ipAddress: getClientIp(req), + callbackBaseUrl: getRequestBaseUrl(req) + } + ); + + return res.status(201).json({ + success: true, + invoice: serializePublicInvoice(invoice) + }); + } catch (error) { + console.error('VIP invoice create error:', error); + return res.status(400).json({ + success: false, + error: error.message || 'Impossible de créer l\'invoice VIP' + }); + } +}); + +router.get('/vip/paygate/callback', async (req, res) => { + try { + const pool = getPool(); + const invoice = await handlePaygateCallback(pool, req.query); + + return res.json({ + success: true, + invoice: serializePublicInvoice(invoice) + }); + } catch (error) { + console.error('VIP PayGate callback error:', error); + return res.status(error.statusCode || 400).json({ + success: false, + error: error.message || 'Callback PayGate invalide' + }); + } +}); + +router.get('/vip/invoices/:publicId', async (req, res) => { + try { + const pool = getPool(); + const invoice = await fetchInvoiceByPublicId(pool, req.params.publicId); + if (!invoice) { + return res.status(404).json({ + success: false, + error: 'Invoice introuvable' + }); + } + + return res.json({ + success: true, + invoice: serializePublicInvoice(invoice) + }); + } catch (error) { + console.error('VIP invoice fetch error:', error); + return res.status(500).json({ + success: false, + error: 'Impossible de récupérer l\'invoice' + }); + } +}); + +router.post('/vip/invoices/:publicId/check', invoiceCheckRateLimit, async (req, res) => { + try { + const pool = getPool(); + const invoice = await fetchInvoiceByPublicId(pool, req.params.publicId); + if (!invoice) { + return res.status(404).json({ + success: false, + error: 'Invoice introuvable' + }); + } + + const refreshedInvoice = await refreshInvoiceStatus(pool, invoice, { + actorType: 'system', + actorId: invoice.public_id + }); + + return res.json({ + success: true, + invoice: serializePublicInvoice(refreshedInvoice) + }); + } catch (error) { + console.error('VIP invoice check error:', error); + const pool = getPool(); + const invoice = await fetchInvoiceByPublicId(pool, req.params.publicId); + return res.status(502).json({ + success: false, + error: 'Vérification blockchain indisponible temporairement', + invoice: serializePublicInvoice(invoice) + }); + } +}); + +router.get('/vip/gifts/:giftToken', async (req, res) => { + try { + const pool = getPool(); + const invoice = await fetchInvoiceByGiftToken(pool, req.params.giftToken); + if (!invoice) { + return res.status(404).json({ + success: false, + error: 'Cadeau introuvable' + }); + } + + return res.json({ + success: true, + gift: serializeGift(invoice) + }); + } catch (error) { + console.error('VIP gift fetch error:', error); + return res.status(500).json({ + success: false, + error: 'Impossible de récupérer le cadeau' + }); + } +}); + +router.post('/vip/gifts/:giftToken/unseal', giftUnsealRateLimit, async (req, res) => { + try { + const pool = getPool(); + const turnstileResult = await verifyTurnstileFromRequest(req, req.body?.turnstileToken); + if (!turnstileResult.valid) { + return res.status(turnstileResult.status).json({ + success: false, + error: turnstileResult.error + }); + } + + const invoice = await fetchInvoiceByGiftToken(pool, req.params.giftToken); + if (!invoice) { + return res.status(404).json({ + success: false, + error: 'Cadeau introuvable' + }); + } + + const unsealedInvoice = await unsealGift( + pool, + req.params.giftToken, + getClientIp(req) + ); + + return res.json({ + success: true, + gift: serializeGift(unsealedInvoice) + }); + } catch (error) { + console.error('VIP gift unseal error:', error); + return res.status(409).json({ + success: false, + error: error.message || 'Impossible de desceller ce cadeau' + }); + } +}); + +router.get('/admin/vip-invoices', isAdmin, async (req, res) => { + try { + const pool = getPool(); + const result = await listVipInvoices(pool, { + status: req.query?.status ? String(req.query.status) : '', + search: req.query?.search ? String(req.query.search).trim() : '', + page: req.query?.page, + limit: req.query?.limit + }); + + return res.json({ + success: true, + invoices: result.items, + total: result.total, + page: result.page, + limit: result.limit, + hasMore: result.hasMore + }); + } catch (error) { + console.error('VIP admin invoices list error:', error); + return res.status(500).json({ + success: false, + error: 'Impossible de récupérer les invoices VIP' + }); + } +}); + +router.get('/admin/vip-invoices/:id', isAdmin, async (req, res) => { + try { + const pool = getPool(); + const details = await getVipInvoiceDetails(pool, req.params.id); + if (!details) { + return res.status(404).json({ + success: false, + error: 'Invoice introuvable' + }); + } + + return res.json({ + success: true, + ...details + }); + } catch (error) { + console.error('VIP admin invoice details error:', error); + return res.status(500).json({ + success: false, + error: 'Impossible de récupérer cette invoice' + }); + } +}); + +router.post('/admin/vip-invoices/:id/check', isAdmin, async (req, res) => { + try { + const pool = getPool(); + const refreshedInvoice = await refreshInvoiceStatus(pool, req.params.id, { + force: true, + actorType: 'admin', + actorId: req.admin?.userId || null + }); + + if (!refreshedInvoice) { + return res.status(404).json({ + success: false, + error: 'Invoice introuvable' + }); + } + + return res.json({ + success: true, + invoice: serializeAdminInvoice(refreshedInvoice) + }); + } catch (error) { + console.error('VIP admin invoice check error:', error); + return res.status(502).json({ + success: false, + error: 'Vérification blockchain indisponible temporairement' + }); + } +}); + +router.post('/admin/vip-invoices/:id/validate', isAdmin, async (req, res) => { + try { + const pool = getPool(); + const invoice = await forceValidateInvoice(pool, req.params.id, req.admin); + return res.json({ + success: true, + invoice: serializeAdminInvoice(invoice) + }); + } catch (error) { + console.error('VIP admin invoice validate error:', error); + return res.status(409).json({ + success: false, + error: error.message || 'Impossible de valider cette invoice' + }); + } +}); + +router.post('/admin/vip-invoices/:id/cancel', isAdmin, async (req, res) => { + try { + const pool = getPool(); + const invoice = await cancelInvoice(pool, req.params.id, req.admin); + return res.json({ + success: true, + invoice: serializeAdminInvoice(invoice) + }); + } catch (error) { + console.error('VIP admin invoice cancel error:', error); + return res.status(409).json({ + success: false, + error: error.message || 'Impossible d\'annuler cette invoice' + }); + } +}); + +module.exports = { + router, + ensureVipDonationsTables +}; diff --git a/API/Mainapi/routes/voirdrama.js b/API/Mainapi/routes/voirdrama.js new file mode 100644 index 0000000..d759f63 --- /dev/null +++ b/API/Mainapi/routes/voirdrama.js @@ -0,0 +1,441 @@ +/** + * VoirDrama routes module. + * Extracted from server.js -- handles drama TV series search and source extraction + * from the VoirDrama website. + * + * Mounted at /api/drama (paths below are relative to that prefix). + */ + +const express = require('express'); +const router = express.Router(); +const path = require('path'); +const fsp = require('fs').promises; +const axios = require('axios'); +const cheerio = require('cheerio'); +const { generateCacheKey } = require('../utils/cacheManager'); +const { fetchTmdbDetails } = require('../utils/tmdbCache'); + +// === VOIRDRAMA CONFIGURATION === +const VOIRDRAMA_BASE_URL = 'https://voirdrama.to'; + +// Impit — remplacement de got-scraping (Rust TLS fingerprint + HTTP/2 natif, pas de http2-wrapper) +let impitClient = null; +async function getImpitClient() { + if (!impitClient) { + const { Impit } = await import('impit'); + impitClient = new Impit({ browser: 'chrome' }); + } + return impitClient; +} + +async function impitFetch(url, options = {}) { + const client = await getImpitClient(); + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), 15000); + try { + const response = await client.fetch(url, { ...options, signal: controller.signal }); + const body = await response.text(); + return { statusCode: response.status, body }; + } finally { + clearTimeout(timeoutId); + } +} + +// --------------------------------------------------------------------------- +// Dependencies injected via configure() +// --------------------------------------------------------------------------- +let TMDB_API_KEY; +let TMDB_API_URL; +let getFromCacheNoExpiration; +let saveToCache; +let shouldUpdateCache24h; + +/** + * Inject runtime dependencies that still live in server.js. + */ +function configure(deps) { + if (deps.TMDB_API_KEY) TMDB_API_KEY = deps.TMDB_API_KEY; + if (deps.TMDB_API_URL) TMDB_API_URL = deps.TMDB_API_URL; + if (deps.getFromCacheNoExpiration) getFromCacheNoExpiration = deps.getFromCacheNoExpiration; + if (deps.saveToCache) saveToCache = deps.saveToCache; + if (deps.shouldUpdateCache24h) shouldUpdateCache24h = deps.shouldUpdateCache24h; +} + +// --------------------------------------------------------------------------- +// fetchDramaTvData -- search VoirDrama and extract episode sources +// --------------------------------------------------------------------------- +async function fetchDramaTvData(tmdbId, season, episode) { + try { + // 1. Get Series Name from TMDB (cached via Redis) + const tmdbData = await fetchTmdbDetails(TMDB_API_URL, TMDB_API_KEY, tmdbId, 'tv', 'fr-FR'); + if (!tmdbData) throw new Error('TMDB data not found'); + + const showName = tmdbData.name; + const seasonInt = parseInt(season); + const tmdbSeasons = tmdbData.seasons || []; + const targetSeason = tmdbSeasons.find(s => s.season_number === seasonInt); + const firstAirDate = (targetSeason && targetSeason.air_date) || tmdbData.first_air_date; + + // 2. Construct Search Query + // Si c'est saison 1, tu prends le nom direct, si c'est saison 2, 3 etc, tu mets ex : Culinary Class Wars 2 + let searchQuery = showName; + if (parseInt(season) > 1) { + searchQuery += ` ${season}`; + } + + // 3. Search on Voirdrama + const formData = new URLSearchParams(); + formData.append('action', 'ajaxsearchpro_search'); + formData.append('aspp', searchQuery); + formData.append('asid', '7'); + formData.append('asp_inst_id', '7_1'); + formData.append('options', 'aspf[vf__1]=vf&asp_gen[]=excerpt&asp_gen[]=content&asp_gen[]=title&filters_initial=1&filters_changed=0&qtranslate_lang=0¤t_page_id=510'); + + const searchResponse = await impitFetch(`${VOIRDRAMA_BASE_URL}/wp-admin/admin-ajax.php`, { + method: 'POST', + body: formData.toString(), + headers: { + 'content-type': 'application/x-www-form-urlencoded', + 'referer': VOIRDRAMA_BASE_URL + '/', + }, + }); + + // 4. Parse Search Result + const rawData = searchResponse.body; + // Extract HTML part between markers + // ___ASPSTART_HTML___ ... ___ASPEND_HTML___ + const htmlMatch = rawData.match(/___ASPSTART_HTML___([\s\S]*?)___ASPEND_HTML___/); + + if (!htmlMatch) { + console.log(`[VOIRDRAMA] Structure de réponse de recherche invalide ou pas de résultats HTML (statusCode=${searchResponse.statusCode}, bodyLength=${rawData?.length}, body=${rawData?.substring(0, 500)})`); + return { success: false, error: 'Film/Série non trouvé sur Voirdrama' }; + } + + const $ = cheerio.load(htmlMatch[1]); + + let bestLink = null; + let fallbackLink = $('div.asp_content h3 a.asp_res_url').first().attr('href'); + + if (!firstAirDate) { + bestLink = fallbackLink; + } else { + // Month map for parsing "Dec 12, 2025" + const monthsMap = { + 'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', 'May': '05', 'Jun': '06', + 'Jul': '07', 'Aug': '08', 'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12' + }; + + // Try to find a date match + const candidates = []; + $('div.item').each((i, el) => { + const link = $(el).find('a.asp_res_url').attr('href'); + const dateText = $(el).find('.summary-content').text().trim(); + + if (link) { + candidates.push({ link, dateText }); + } + }); + + for (const candidate of candidates) { + const { link, dateText } = candidate; + let matched = false; + + // 1. Try to check date from search result if present + if (dateText) { + const parts = dateText.split(/[\s,]+/); + if (parts.length >= 3) { + const mStr = parts[0].substring(0, 3); + const dStr = parts[1]; + const yStr = parts[2]; + const month = monthsMap[mStr]; + + if (month && dStr && yStr) { + const day = dStr.padStart(2, '0'); + const formattedDate = `${yStr}-${month}-${day}`; + if (formattedDate === firstAirDate) { + bestLink = link; + matched = true; + } + } + } + } + + if (matched) break; + + // 2. If no match yet (or no dateText), fetch the page to check the date + if (!bestLink) { + try { + const pageResponse = await impitFetch(link); + const $page = cheerio.load(pageResponse.body); + + let pageDateFound = false; + + $page('.summary-content').each((_, el) => { + const txt = $(el).text().trim(); + // Try parsing this text + const parts = txt.split(/[\s,]+/); + if (parts.length >= 3) { + const mStr = parts[0].substring(0, 3); + const dStr = parts[1]; + const yStr = parts[2]; + const month = monthsMap[mStr]; + if (month && dStr && yStr) { + const day = dStr.padStart(2, '0'); + const fDate = `${yStr}-${month}-${day}`; + if (fDate === firstAirDate) { + pageDateFound = true; + return false; + } + } + } + }); + + if (pageDateFound) { + bestLink = link; + break; + } + + } catch (err) { + // Check next candidate + } + } + } + } + + // Fallback if no specific date match found + if (!bestLink) { + return { success: false, error: 'Série non trouvée sur Voirdrama (Aucune date correspondante)' }; + } + + // 5. Construct Episode URL + // Format: https://voirdrama.to/drama/slug/ -> https://voirdrama.to/drama/slug/slug-episode-vostfr/ + // Remove trailing slash if present + const cleanLink = bestLink.replace(/\/$/, ''); + const slug = cleanLink.split('/').pop(); + + const paddedEpisode = episode.toString().padStart(2, '0'); + // Note: User example had slug repeated: /slug/slug-01-vostfr/ + const episodeUrl = `${cleanLink}/${slug}-${paddedEpisode}-vostfr/`; + + // 6. Fetch Episode Page + const episodeResponse = await impitFetch(episodeUrl); + + // 7. Extract Sources + const episodeHtml = episodeResponse.body; + const sourcesMatch = episodeHtml.match(/var thisChapterSources = ({[\s\S]*?});/); + + if (!sourcesMatch) { + return { success: false, error: 'Sources non trouvées sur la page de l\'épisode' }; + } + + const sourcesJson = JSON.parse(sourcesMatch[1]); + const sources = []; + + for (const [key, value] of Object.entries(sourcesJson)) { + // 1. Clean Name + let name = key; + try { + name = JSON.parse(`"${key}"`); // Decode unicode if needed + } catch (e) { } + + // Remove "☰", "LECTEUR", numbers and extra spaces + name = name.replace(/[☰]/g, '').replace(/LECTEUR\s*\d+/i, '').trim(); + + // Map common abbreviated names if possible + if (name === 'VIDM') name = 'Vidmoly'; + if (name === 'RU') name = 'Ok.ru'; + if (name === 'VOE') name = 'Voe'; + if (name === 'UQLOAD') name = 'Uqload'; + if (name === 'UPSTREAM') name = 'Upstream'; + if (name === 'DOOD') name = 'Doodstream'; + + + // 2. Extract Link + let url = null; + + // Look for iframe src specifically to avoid script tags + const iframeMatch = value.match(/<iframe[^>]+src="([^"]+)"/i); + if (iframeMatch) { + url = iframeMatch[1]; + } else { + // Fallback: try to find http links that look like video embeds + const urlMatch = value.match(/https?:\/\/[^"\s']+/); + if (urlMatch) { + const candidate = urlMatch[0]; + // Exclude recaptcha, google api, and local admin-ajax + if (!candidate.includes('google.com/recaptcha') && !candidate.includes('admin-ajax.php')) { + url = candidate; + } + } + } + + // 3. Filter and Add + if (url) { + sources.push({ + name: name, + link: url, + // raw: value // Optional: keep raw for debug if needed, but user didn't ask for it + }); + } + } + + return { + success: true, + data: sources, + tmdbId: tmdbId, + season: season, + episode: episode + }; + + } catch (error) { + console.error('[VOIRDRAMA] Error:', error.message); + return { success: false, error: error.message }; + } +} + +// --------------------------------------------------------------------------- +// GET /:type/:tmdbid +// Route /api/drama/:type/:tmdbid +// Options: season (saison), episode (episode) +// --------------------------------------------------------------------------- +router.get('/:type/:tmdbid', async (req, res) => { + const { type, tmdbid } = req.params; + const { season, episode } = req.query; + + if (type !== 'tv') { + return res.status(400).json({ + success: false, + error: 'Ce point de terminaison ne supporte que type=tv pour le moment avec saison/episode' + }); + } + + if (!season || !episode) { + return res.status(400).json({ + success: false, + error: 'Les paramètres ?season= et ?episode= sont requis.' + }); + } + + const cacheKey = generateCacheKey(`voirdrama_${tmdbid}_${season}_${episode}`); + const cacheDir = path.join(__dirname, '..', 'cache', 'voirdrama'); + + try { + await fsp.mkdir(cacheDir, { recursive: true }); + + // Stale-while-revalidate: return cached data immediately + const cachedData = await getFromCacheNoExpiration(cacheDir, cacheKey); + let dataReturned = false; + + if (cachedData) { + // Return cached data immediately + if (!cachedData.success) { + res.status(404).json(cachedData); + } else { + res.json(cachedData); + } + dataReturned = true; + + // Background update if cache should be updated + const shouldUpdate = await shouldUpdateCache24h(cacheDir, cacheKey); + if (shouldUpdate) { + // Background update (non-blocking) + (async () => { + try { + const freshData = await fetchDramaTvData(tmdbid, season, episode); + await saveToCache(cacheDir, cacheKey, freshData); + } catch (bgError) { + console.error(`[VOIRDRAMA] Background update error:`, bgError.message); + } + })(); + } + return; + } + + // No cache - fetch fresh data + const result = await fetchDramaTvData(tmdbid, season, episode); + + // Save to cache (both success and error results) + await saveToCache(cacheDir, cacheKey, result); + + if (!result.success) { + return res.status(404).json(result); + } + + res.json(result); + + } catch (error) { + console.error('[API DRAMA] Error:', error); + res.status(500).json({ + success: false, + error: 'Erreur interne', + details: error.message + }); + } +}); + +// --------------------------------------------------------------------------- +// DELETE /:type/:tmdbid/cache +// Supprime le cache d'une saison entière (ou d'un épisode spécifique) +// Ex: DELETE /api/drama/tv/68398/cache?season=2 +// Ex: DELETE /api/drama/tv/68398/cache?season=2&episode=3 +// --------------------------------------------------------------------------- +router.delete('/:type/:tmdbid/cache', async (req, res) => { + const { tmdbid } = req.params; + const { season, episode } = req.query; + + if (!season) { + return res.status(400).json({ success: false, error: 'Le paramètre ?season= est requis.' }); + } + + const cacheDir = path.join(__dirname, '..', 'cache', 'voirdrama'); + const deletedFiles = []; + const errors = []; + + try { + if (episode) { + // Supprimer un épisode spécifique + const cacheKey = generateCacheKey(`voirdrama_${tmdbid}_${season}_${episode}`); + const filePath = path.join(cacheDir, `${cacheKey}.json`); + try { + await fsp.unlink(filePath); + deletedFiles.push(`S${season}E${episode}`); + } catch (err) { + if (err.code !== 'ENOENT') errors.push(err.message); + } + } else { + // Supprimer toute la saison — tester tous les épisodes de 1 à 200 + const prefix = `voirdrama_${tmdbid}_${season}_`; + for (let ep = 1; ep <= 200; ep++) { + const cacheKey = generateCacheKey(`${prefix}${ep}`); + const filePath = path.join(cacheDir, `${cacheKey}.json`); + try { + await fsp.unlink(filePath); + deletedFiles.push(`S${season}E${ep}`); + } catch (err) { + if (err.code !== 'ENOENT') errors.push(err.message); + } + } + } + + if (deletedFiles.length > 0) { + return res.json({ + success: true, + message: `Cache voirdrama supprimé pour ${tmdbid} saison ${season}`, + deleted: deletedFiles, + errors: errors.length > 0 ? errors : undefined + }); + } else { + return res.status(404).json({ + success: false, + error: `Aucun cache trouvé pour ${tmdbid} saison ${season}` + }); + } + } catch (error) { + console.error('[VOIRDRAMA] Cache delete error:', error); + return res.status(500).json({ success: false, error: 'Erreur serveur' }); + } +}); + +module.exports = router; +module.exports.configure = configure; +module.exports.fetchDramaTvData = fetchDramaTvData; diff --git a/API/Mainapi/routes/wiflix.js b/API/Mainapi/routes/wiflix.js new file mode 100644 index 0000000..3c3c5e0 --- /dev/null +++ b/API/Mainapi/routes/wiflix.js @@ -0,0 +1,909 @@ +/** + * Wiflix routes. + * Extracted from server.js -- Wiflix search, player extraction, and routes. + * Mount point: app.use('/api/wiflix', router) + */ + +const express = require("express"); +const router = express.Router(); +const axios = require("axios"); +const cheerio = require("cheerio"); +const path = require("path"); +const fsp = require("fs").promises; + +const { memoryCache } = require("../config/redis"); +const { + CACHE_DIR, + generateCacheKey, + saveToCache, +} = require("../utils/cacheManager"); +const { getProxyAgent, pickNextSocks5Proxy } = require("../utils/proxyManager"); +const { + fetchTmdbDetails, + fetchTmdbSeason, + fetchTmdbFrenchReleaseYear, +} = require("../utils/tmdbCache"); + +const TMDB_API_KEY = process.env.TMDB_API_KEY || ""; +const TMDB_API_URL = "https://api.themoviedb.org/3"; +const WIFLIX_BASE_URL = "https://flemmix.golf"; + +// === Cache helpers (local, since getFromCacheNoExpiration is not yet in cacheManager) === +const getFromCacheNoExpiration = async (cacheDir, key) => { + try { + const memKey = `${cacheDir}:${key}`; + const memData = await memoryCache.get(memKey); + if (memData) return memData; + + const cacheFilePath = path.join(cacheDir, `${key}.json`); + let fileContent; + try { + fileContent = await fsp.readFile(cacheFilePath, "utf8"); + } catch (e) { + if (e.code === "ENOENT") return null; + throw e; + } + + const cacheData = JSON.parse(fileContent); + if ( + typeof cacheData === "string" || + cacheData === null || + cacheData === undefined + ) { + try { + await fsp.unlink(cacheFilePath); + } catch {} + return null; + } + + await memoryCache.set(memKey, cacheData); + return cacheData; + } catch (error) { + if (error.code === "ENOENT") return null; + console.error( + `Erreur lors de la recuperation du cache pour ${key}:`, + error, + ); + return null; + } +}; + +// === Utility Functions === +const normalizeString = (str) => { + if (!str) return ""; + return str + .toLowerCase() + .normalize("NFD") + .replace(/[\u0300-\u036f]/g, "") + .replace(/[^\w\s]/g, " ") + .replace(/\s+/g, " ") + .trim(); +}; + +const getLevenshteinSimilarity = (str1, str2) => { + const s1 = normalizeString(str1); + const s2 = normalizeString(str2); + if (s1 === s2) return 1; + if (s1.length === 0 || s2.length === 0) return 0; + + const matrix = []; + for (let i = 0; i <= s2.length; i++) { + matrix[i] = [i]; + } + for (let j = 0; j <= s1.length; j++) { + matrix[0][j] = j; + } + + for (let i = 1; i <= s2.length; i++) { + for (let j = 1; j <= s1.length; j++) { + if (s2.charAt(i - 1) === s1.charAt(j - 1)) { + matrix[i][j] = matrix[i - 1][j - 1]; + } else { + matrix[i][j] = Math.min( + matrix[i - 1][j - 1] + 1, + matrix[i][j - 1] + 1, + matrix[i - 1][j] + 1, + ); + } + } + } + + const maxLength = Math.max(s1.length, s2.length); + return maxLength === 0 + ? 1 + : (maxLength - matrix[s2.length][s1.length]) / maxLength; +}; + +function formatNextUpdate(ms) { + if (ms <= 0) return 'imminent'; + const totalSeconds = Math.ceil(ms / 1000); + const minutes = Math.floor(totalSeconds / 60); + const seconds = totalSeconds % 60; + if (minutes > 0) return `${minutes}m ${seconds}s`; + return `${seconds}s`; +} + +// === Search === +async function searchWiflixMovie(title, baseUrl = WIFLIX_BASE_URL) { + const searchUrl = `${baseUrl}/`; + const payload = `do=search&subaction=search&story=${encodeURIComponent(title)}`; + const searchHeaders = { + "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", + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", + "Accept-Language": "fr-FR,fr;q=0.9,en;q=0.8", + "Content-Type": "application/x-www-form-urlencoded", + "Referer": baseUrl + "/", + "Origin": baseUrl, + }; + try { + const proxyErrors = []; + let responseBody = null; + + // Utiliser le prochain proxy SOCKS5 pour répartir les requêtes sur tout le pool + const proxy = await pickNextSocks5Proxy(); + if (proxy) { + const proxyLabel = `${proxy.host}:${proxy.port}`; + const agent = getProxyAgent(proxy); + if (!agent) { + proxyErrors.push(`${proxyLabel}: agent indisponible`); + } else { + try { + const res = await axios({ + url: searchUrl, + method: "POST", + data: payload, + headers: searchHeaders, + timeout: 5000, + httpAgent: agent, + httpsAgent: agent, + proxy: false, + responseType: "text", + decompress: true, + }); + responseBody = res.data; + console.log(`[WIFLIX SEARCH] OK via ${proxyLabel}`); + } catch (err) { + proxyErrors.push(`${proxyLabel}: ${err.message}`); + console.log(`[WIFLIX SEARCH] ${proxyLabel} échoué: ${err.message}`); + } + } + } + + // Fallback direct (sans proxy) + if (responseBody === null) { + try { + const res = await axios({ + url: searchUrl, + method: "POST", + data: payload, + headers: searchHeaders, + timeout: 5000, + responseType: "text", + decompress: true, + }); + responseBody = res.data; + console.log(`[WIFLIX SEARCH] OK direct`); + } catch (err) { + proxyErrors.push(`direct: ${err.message}`); + return { url: null, debugHtml: `Toutes les tentatives ont échoué:\n${proxyErrors.join('\n')}` }; + } + } + + if (!responseBody || responseBody.includes('Un instant, s\'il vous plaît')) { + return { url: null, debugHtml: responseBody || `Proxies échoués:\n${proxyErrors.join('\n')}` }; + } + + const $ = cheerio.load(responseBody); + const movBlocks = $("#dle-content div.mov"); + if (movBlocks.length === 0) return { url: null, debugHtml: responseBody }; + + let bestMatch = null; + let bestSimilarity = 0; + + movBlocks.each((_, block) => { + const $block = $(block); + const $titleLink = $block.find("a.mov-t"); + if (!$titleLink.length) return; + + const href = $titleLink.attr("href"); + if (!href) return; + + const resultTitle = $titleLink.text().trim(); + if (!resultTitle || resultTitle.length < 2) return; + + const resultTitleLower = resultTitle.toLowerCase(); + const hasBlockSai = $block.find(".block-sai").length > 0; + const isSeries = + href.includes("/serie-") || + resultTitleLower.includes("saison") || + /saison-\d+/i.test(href) || + hasBlockSai; + const searchIsSeries = title.toLowerCase().includes("saison"); + + if (searchIsSeries && !isSeries) return; + if (!searchIsSeries && isSeries) return; + + if (searchIsSeries) { + const searchSeasonMatch = title.match(/saison\s+(\d+)/i); + if (searchSeasonMatch) { + const searchSeason = parseInt(searchSeasonMatch[1]); + + let resultSeasonNum = null; + const titleSeasonMatch = resultTitle.match(/saison\s+(\d+)/i); + if (titleSeasonMatch) { + resultSeasonNum = parseInt(titleSeasonMatch[1]); + } + if (resultSeasonNum === null) { + const blockSaiText = $block.find(".block-sai").text().trim(); + const saiMatch = + blockSaiText.match(/saison\s+(\d+)/i) || + blockSaiText.match(/^(\d+)/); + if (saiMatch) { + resultSeasonNum = parseInt(saiMatch[1]); + } + } + if (resultSeasonNum === null) { + const urlSeasonMatch = href.match(/saison-(\d+)/i); + if (urlSeasonMatch) { + resultSeasonNum = parseInt(urlSeasonMatch[1]); + } + } + + if (resultSeasonNum === null || searchSeason !== resultSeasonNum) + return; + } + } + + const cleanSearchTitle = title + .toLowerCase() + .replace(/\s+saison\s+\d+/g, "") + .trim(); + const cleanResultTitle = resultTitle + .toLowerCase() + .replace(/\s+saison\s+\d+/g, "") + .trim(); + + let similarity = 0; + if (cleanResultTitle === cleanSearchTitle) { + similarity = 1.0; + } else { + similarity = getLevenshteinSimilarity( + cleanResultTitle, + cleanSearchTitle, + ); + } + + let fullUrl = href; + if (fullUrl && !fullUrl.startsWith("http")) { + fullUrl = fullUrl.startsWith("/") + ? `${baseUrl}${fullUrl}` + : `${baseUrl}/${fullUrl}`; + } + + if (similarity >= 0.85 && similarity > bestSimilarity) { + bestSimilarity = similarity; + bestMatch = fullUrl ? encodeURI(fullUrl) : fullUrl; + } + }); + + return { url: bestMatch, debugHtml: bestMatch ? null : responseBody }; + } catch (error) { + if (error.response?.status === 403) { + console.error( + `[WIFLIX SEARCH] 403 Forbidden pour "${title}" sur ${searchUrl}`, + ); + } + return { url: null, debugHtml: error.response?.data || `Erreur: ${error.message}` }; + } +} + +// === Release Date Extraction === +function extractWiflixReleaseDate($) { + try { + const releaseDateElement = $( + "body > div:first-child > div > div > div > div > div > article > div:first-child > div:nth-child(2) > ul > li:nth-child(2) > div:nth-child(2)", + ); + if (releaseDateElement.length > 0) { + const dateText = releaseDateElement.text().trim(); + const yearMatch = dateText.match(/(\d{4})/); + if (yearMatch) return parseInt(yearMatch[1]); + } + + const fallbackSelectors = [ + "div.mov-desc", + ".mov-desc", + 'li:contains("Annee") + li', + 'li:contains("Date") + li', + ]; + for (const selector of fallbackSelectors) { + const element = $(selector); + if (element.length > 0) { + const text = element.text().trim(); + const yearMatch = text.match(/(\d{4})/); + if (yearMatch) return parseInt(yearMatch[1]); + } + } + return null; + } catch (error) { + console.error("[WIFLIX] Erreur lors de l'extraction de la date:", error); + return null; + } +} + +// === Player Extraction === +async function extractWiflixPlayers(pageUrl) { + try { + let rawHtml = null; + const proxy = await pickNextSocks5Proxy(); + if (proxy) { + const agent = getProxyAgent(proxy); + if (!agent) { + console.log( + `[WIFLIX PLAYERS] ${proxy.host}:${proxy.port} ignore: agent indisponible`, + ); + } else { + try { + const res = await axios({ + url: pageUrl, + method: "GET", + headers: { + "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", + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", + "Accept-Language": "fr-FR,fr;q=0.9,en;q=0.8", + }, + timeout: 5000, + httpAgent: agent, + httpsAgent: agent, + proxy: false, + responseType: "text", + decompress: true, + }); + rawHtml = res.data; + console.log(`[WIFLIX PLAYERS] OK via ${proxy.host}:${proxy.port}`); + } catch (err) { + console.log( + `[WIFLIX PLAYERS] ${proxy.host}:${proxy.port} echoue: ${err.message}`, + ); + } + } + } + if (!rawHtml) { + // Fallback direct + const res = await axios({ url: pageUrl, method: "GET", timeout: 5000, responseType: "text", decompress: true }); + rawHtml = res.data; + } + const $ = cheerio.load(rawHtml); + const players = []; + const releaseYear = extractWiflixReleaseDate($); + + const episodeDivs = $( + 'div[class*="ep"][class*="vf"], div[class*="ep"][class*="vs"]', + ); + + if (episodeDivs.length > 0) { + episodeDivs.each((index, element) => { + const $episodeDiv = $(element); + const episodeClass = $episodeDiv.attr("class"); + const episodeMatch = episodeClass.match(/ep(\d+)(vf|vs)/); + if (episodeMatch) { + const episodeNumber = parseInt(episodeMatch[1]); + const type = episodeMatch[2] === "vf" ? "VF" : "VOSTFR"; + $episodeDiv.find("a[onclick]").each((linkIndex, linkElement) => { + const $link = $(linkElement); + const onclick = $link.attr("onclick"); + const $span = $link.find("span.clichost"); + if (onclick && $span.length) { + const match = onclick.match(/loadVideo\('(.+?)'\)/); + if (match && match[1]) { + let processedUrl = match[1]; + const name = $span.text().trim(); + if (processedUrl.includes("tipfly.xyz")) { + const tipflyMatch = processedUrl.match( + /tipfly\.xyz\/em-?\d+-(.+)/, + ); + if (tipflyMatch && tipflyMatch[1]) + processedUrl = `https://oneupload.net/embed-${tipflyMatch[1]}.html`; + } else if ( + name.toLowerCase() === "voe" || + processedUrl.includes("jilliandescribecompany.com") + ) { + processedUrl = processedUrl.replace( + /^https?:\/\/[^/]+/, + "https://voe.sx", + ); + } + const domainMatch = processedUrl.match( + /https?:\/\/(?:www\.)?([^\/]+)/, + ); + const domainName = domainMatch ? domainMatch[1] : name; + players.push({ + name: domainName, + url: processedUrl, + episode: episodeNumber, + type, + }); + } + } + }); + } + }); + } else { + const filmLinks = $(".tabs-sel a[onclick]"); + filmLinks.each((index, element) => { + const $link = $(element); + const onclick = $link.attr("onclick"); + const $span = $link.find("span"); + if (onclick && $span.length) { + const match = onclick.match(/loadVideo\('(.+?)'\)/); + if (match && match[1]) { + let processedUrl = match[1]; + const name = $span.text().trim(); + let type = "VF"; + if (name.toLowerCase().includes("vostfr")) type = "VOSTFR"; + if (processedUrl.includes("tipfly.xyz")) { + const tipflyMatch = processedUrl.match( + /tipfly\.xyz\/em-?\d+-(.+)/, + ); + if (tipflyMatch && tipflyMatch[1]) + processedUrl = `https://oneupload.net/embed-${tipflyMatch[1]}.html`; + } else if ( + name.toLowerCase() === "voe" || + processedUrl.includes("jilliandescribecompany.com") + ) { + processedUrl = processedUrl.replace( + /^https?:\/\/[^/]+/, + "https://voe.sx", + ); + } + const domainMatch = processedUrl.match( + /https?:\/\/(?:www\.)?([^\/]+)/, + ); + const domainName = domainMatch ? domainMatch[1] : name; + players.push({ + name: domainName, + url: processedUrl, + episode: 1, + type, + }); + } + } + }); + } + + return { players, releaseYear, debugHtml: players.length === 0 ? rawHtml : null }; + } catch (error) { + return { players: [], releaseYear: null, debugHtml: error.response?.data || null }; + } +} + +function categorizeWiflixPlayers(players) { + const vf = []; + const vostfr = []; + players.forEach((player) => { + if (player.type === "VOSTFR") vostfr.push(player); + else vf.push(player); + }); + return { vf, vostfr }; +} + +// === Data Fetching === +async function fetchWiflixMovieData(tmdbId, cachedData = null) { + try { + const tmdbData = await fetchTmdbDetails( + TMDB_API_URL, + TMDB_API_KEY, + tmdbId, + "movie", + "fr-FR", + ); + + if (!tmdbData) { + if (cachedData) return cachedData; + return { + success: false, + error: "Film non trouve sur TMDB", + tmdb_id: tmdbId, + }; + } + + const originalData = tmdbData; + const titlesToTry = [ + tmdbData.title, + originalData.original_title, + originalData.title, + ] + .filter(Boolean) + .filter((title, index, arr) => arr.indexOf(title) === index); + + let movieUrl = null; + let searchDebugHtml = null; + for (const title of titlesToTry) { + const searchResult = await searchWiflixMovie(title); + if (searchResult.url) { movieUrl = searchResult.url; break; } + searchDebugHtml = searchResult.debugHtml; + } + + if (!movieUrl) + return { + success: false, + error: "Film non trouve sur Wiflix", + tmdb_id: tmdbId, + titles_tried: titlesToTry, + debugHtml: searchDebugHtml, + }; + + const extractionResult = await extractWiflixPlayers(movieUrl); + const players = extractionResult.players; + const wiflixReleaseYear = extractionResult.releaseYear; + + if (players.length === 0) + return { + success: false, + error: "Aucun lecteur video trouve", + tmdb_id: tmdbId, + wiflix_url: movieUrl, + debugHtml: extractionResult.debugHtml, + }; + + if (wiflixReleaseYear) { + const frReleaseYear = await fetchTmdbFrenchReleaseYear( + TMDB_API_URL, + TMDB_API_KEY, + tmdbId, + ); + const tmdbReleaseYear = + frReleaseYear || + (tmdbData.release_date + ? new Date(tmdbData.release_date).getFullYear() + : null); + if (tmdbReleaseYear && wiflixReleaseYear !== tmdbReleaseYear) { + console.log( + `[WIFLIX MOVIE] Date mismatch: TMDB ${tmdbReleaseYear}${frReleaseYear ? " (FR)" : ""} vs Wiflix ${wiflixReleaseYear} pour ${tmdbData.title}`, + ); + return { + success: false, + error: "Film non disponible sur Wiflix (date de sortie differente)", + tmdb_id: tmdbId, + wiflix_url: movieUrl, + tmdb_release_year: tmdbReleaseYear, + wiflix_release_year: wiflixReleaseYear, + }; + } + } + + const categorizedPlayers = categorizeWiflixPlayers(players); + return { + success: true, + tmdb_id: tmdbId, + title: tmdbData.title, + original_title: originalData.original_title, + wiflix_url: movieUrl, + players: { vf: categorizedPlayers.vf, vostfr: categorizedPlayers.vostfr }, + cache_timestamp: new Date().toISOString(), + }; + } catch (error) { + console.error( + `[WIFLIX MOVIE] Erreur dans fetchWiflixMovieData: ${error.message}`, + ); + if (cachedData) { + console.log( + `[WIFLIX] Cache preserve malgre l'erreur pour movie ${tmdbId}`, + ); + return cachedData; + } + return { + success: false, + error: "Erreur lors de la recuperation des donnees Wiflix", + message: error.message, + tmdb_id: tmdbId, + }; + } +} + +async function fetchWiflixTvData(tmdbId, season, cachedData = null) { + try { + const [tmdbData, seasonData] = await Promise.all([ + fetchTmdbDetails(TMDB_API_URL, TMDB_API_KEY, tmdbId, "tv", "fr-FR"), + fetchTmdbSeason(TMDB_API_URL, TMDB_API_KEY, tmdbId, season, "fr-FR"), + ]); + const originalData = tmdbData; + + if (!tmdbData || !seasonData) { + if (cachedData) return cachedData; + return { + success: false, + error: "Serie ou saison non trouvee sur TMDB", + tmdb_id: tmdbId, + season, + }; + } + + const titlesToTry = [ + tmdbData.name, + originalData.original_name, + originalData.name, + ] + .filter(Boolean) + .filter((title, index, arr) => arr.indexOf(title) === index); + + let seriesUrl = null; + let searchDebugHtml = null; + for (const title of titlesToTry) { + const searchResult = await searchWiflixMovie(`${title} saison ${season}`); + if (searchResult.url) { seriesUrl = searchResult.url; break; } + searchDebugHtml = searchResult.debugHtml; + } + + if (!seriesUrl) + return { + success: false, + error: "Serie non trouvee sur Wiflix", + tmdb_id: tmdbId, + season, + titles_tried: titlesToTry, + debugHtml: searchDebugHtml, + }; + + const extractionResult = await extractWiflixPlayers(seriesUrl); + const players = extractionResult.players; + const wiflixReleaseYear = extractionResult.releaseYear; + + if (players.length === 0) + return { + success: false, + error: "Aucun lecteur video trouve", + tmdb_id: tmdbId, + season, + wiflix_url: seriesUrl, + debugHtml: extractionResult.debugHtml, + }; + + if (wiflixReleaseYear) { + const tmdbReleaseYear = seasonData.air_date + ? new Date(seasonData.air_date).getFullYear() + : null; + if (tmdbReleaseYear && wiflixReleaseYear !== tmdbReleaseYear) { + console.log( + `[WIFLIX TV] Date mismatch: TMDB Season ${season} (${tmdbReleaseYear}) vs Wiflix ${wiflixReleaseYear} pour ${tmdbData.name}`, + ); + return { + success: false, + error: "Serie non disponible sur Wiflix (date de sortie differente)", + tmdb_id: tmdbId, + season, + wiflix_url: seriesUrl, + tmdb_release_year: tmdbReleaseYear, + wiflix_release_year: wiflixReleaseYear, + }; + } + } + + const episodes = {}; + players.forEach((player) => { + const episodeNum = player.episode; + if (!episodes[episodeNum]) episodes[episodeNum] = { vf: [], vostfr: [] }; + if (player.type === "VOSTFR") episodes[episodeNum].vostfr.push(player); + else episodes[episodeNum].vf.push(player); + }); + + return { + success: true, + tmdb_id: tmdbId, + title: tmdbData.name, + original_title: originalData.original_name, + season: parseInt(season), + wiflix_url: seriesUrl, + episodes, + cache_timestamp: new Date().toISOString(), + }; + } catch (error) { + console.error(`[WIFLIX TV] Erreur: ${error.message}`); + if (cachedData) { + console.log( + `[WIFLIX] Cache preserve malgre l'erreur pour tv ${tmdbId} saison ${season}`, + ); + return cachedData; + } + return { + success: false, + error: "Erreur lors de la recuperation des donnees Wiflix", + message: error.message, + tmdb_id: tmdbId, + season, + }; + } +} + +// === Background Cache Update === +const updateWiflixCache = async ( + cacheDir, + cacheKey, + type, + tmdbId, + season = null, +) => { + try { + const existingCache = await getFromCacheNoExpiration(cacheDir, cacheKey); + let attempts = 0; + const maxAttempts = 1; + let lastError = null; + + while (attempts < maxAttempts) { + try { + let newData; + if (type === "movie") + newData = await fetchWiflixMovieData(tmdbId, existingCache); + else if (type === "tv") + newData = await fetchWiflixTvData(tmdbId, season, existingCache); + else throw new Error(`Type non supporte: ${type}`); + + if ( + typeof newData === "string" && + newData.includes("Maintenance en cours") + ) + throw new Error("Maintenance en cours - donnees invalides"); + if ( + typeof newData === "string" || + newData === null || + newData === undefined + ) + throw new Error("Donnees invalides - non-JSON"); + + if (newData) { + const isFailedResult = newData.success === false; + if (isFailedResult && existingCache?.success) return; + if (newData.success) { + const { debugHtml: _dh, ...cacheableData } = newData; + await saveToCache(cacheDir, cacheKey, cacheableData); + } else { + await saveToCache(cacheDir, cacheKey, newData); + } + return; + } + break; + } catch (error) { + attempts++; + lastError = error; + if (error.response && error.response.status === 403) break; + if ( + (error.response && error.response.status >= 500) || + !error.response + ) { + const delay = 2000 * attempts; + await new Promise((resolve) => setTimeout(resolve, delay)); + } else { + break; + } + } + } + } catch (error) { + // Background error, ignore + } +}; + +// === Routes === + +// GET /movie/:tmdbId +router.get("/movie/:tmdbId", async (req, res) => { + const { tmdbId } = req.params; + const cacheKey = generateCacheKey(`wiflix_movie_${tmdbId}`); + const cacheDir = path.join(__dirname, "..", "cache", "wiflix"); + + try { + await fsp.mkdir(cacheDir, { recursive: true }); + + const cachedData = await getFromCacheNoExpiration(cacheDir, cacheKey); + let dataReturned = false; + + if (cachedData) { + const RECENT_UPDATE_THRESHOLD = cachedData.success === false + ? 5 * 60 * 1000 + : 1 * 60 * 60 * 1000; + const cachePath = path.join(cacheDir, `${cacheKey}.json`); + let nextUpdateIn = null; + let shouldSkipUpdate = false; + try { + const stats = await fsp.stat(cachePath); + const remaining = RECENT_UPDATE_THRESHOLD - (Date.now() - stats.mtime.getTime()); + if (remaining > 0) { + shouldSkipUpdate = true; + nextUpdateIn = formatNextUpdate(remaining); + } else { + nextUpdateIn = 'imminent'; + } + } catch (e) {} + + res.status(200).json({ ...cachedData, next_update_in: nextUpdateIn }); + dataReturned = true; + + if (!shouldSkipUpdate) + updateWiflixCache(cacheDir, cacheKey, "movie", tmdbId); + } + + if (!dataReturned) { + const result = await fetchWiflixMovieData(tmdbId, null); + if (result.success) { + const { debugHtml: _dh, ...cacheableResult } = result; + await saveToCache(cacheDir, cacheKey, cacheableResult); + res.json({ ...cacheableResult, next_update_in: '60m 0s' }); + } else { + await saveToCache(cacheDir, cacheKey, result); + res.status(404).json(result); + } + } + } catch (error) { + console.error(`[WIFLIX MOVIE] Erreur: ${error.message}`); + res + .status(500) + .json({ + success: false, + error: "Erreur lors de la recuperation des donnees Wiflix", + message: error.message, + tmdb_id: tmdbId, + }); + } +}); + +// GET /tv/:tmdbId/:season +router.get("/tv/:tmdbId/:season", async (req, res) => { + const { tmdbId, season } = req.params; + const cacheKey = generateCacheKey(`wiflix_tv_${tmdbId}_${season}`); + const cacheDir = path.join(__dirname, "..", "cache", "wiflix"); + + try { + await fsp.mkdir(cacheDir, { recursive: true }); + + const cachedData = await getFromCacheNoExpiration(cacheDir, cacheKey); + let dataReturned = false; + + if (cachedData) { + const RECENT_UPDATE_THRESHOLD = cachedData.success === false + ? 5 * 60 * 1000 + : 1 * 60 * 60 * 1000; + const cachePath = path.join(cacheDir, `${cacheKey}.json`); + let nextUpdateIn = null; + let shouldSkipUpdate = false; + try { + const stats = await fsp.stat(cachePath); + const remaining = RECENT_UPDATE_THRESHOLD - (Date.now() - stats.mtime.getTime()); + if (remaining > 0) { + shouldSkipUpdate = true; + nextUpdateIn = formatNextUpdate(remaining); + } else { + nextUpdateIn = 'imminent'; + } + } catch (e) {} + + res.json({ ...cachedData, next_update_in: nextUpdateIn }); + dataReturned = true; + + if (!shouldSkipUpdate) + updateWiflixCache(cacheDir, cacheKey, "tv", tmdbId, season); + } + + if (!dataReturned) { + const result = await fetchWiflixTvData(tmdbId, season, null); + if (result.success) { + const { debugHtml: _dh, ...cacheableResult } = result; + await saveToCache(cacheDir, cacheKey, cacheableResult); + res.json({ ...cacheableResult, next_update_in: '60m 0s' }); + } else { + await saveToCache(cacheDir, cacheKey, result); + res.status(404).json(result); + } + } + } catch (error) { + console.error(`[WIFLIX TV] Erreur: ${error.message}`); + res + .status(500) + .json({ + success: false, + error: "Erreur lors de la recuperation des donnees Wiflix", + message: error.message, + tmdb_id: tmdbId, + season, + }); + } +}); + +module.exports = router; diff --git a/API/Mainapi/server.js b/API/Mainapi/server.js new file mode 100644 index 0000000..51ac52b --- /dev/null +++ b/API/Mainapi/server.js @@ -0,0 +1,170 @@ +const cluster = require('cluster'); +const os = require('os'); +require('dotenv').config(); + +// === CLUSTER MODE CONFIGURATION (au tout début pour éviter que le master charge tout) === +const NUM_WORKERS = parseInt(process.env.NUM_WORKERS) || 6; // 6 coeurs physiques sur le serveur + +if (cluster.isPrimary ?? cluster.isMaster) { + // === MODE MASTER — ne charge RIEN d'autre (pas de MySQL, Redis, Express, etc.) === + console.log(`🚀 Master process ${process.pid} démarré en mode cluster`); + console.log(`📊 Création de ${NUM_WORKERS} workers...`); + + for (let i = 0; i < NUM_WORKERS; i++) { + const worker = cluster.fork(); + console.log(`✅ Worker ${worker.process.pid} créé (${i + 1}/${NUM_WORKERS})`); + } + + // Anti-fork-bomb : limiter les redémarrages rapides + const workerRestarts = new Map(); // pid -> [timestamps] + const MAX_RESTARTS = 5; + const RESTART_WINDOW_MS = 60000; // 1 minute + let isShuttingDown = false; // Flag pour empêcher le redémarrage des workers pendant le shutdown + + cluster.on('exit', (worker, code, signal) => { + if (signal) { + console.warn(`⚠️ Worker ${worker.process.pid} tué par le signal ${signal}`); + } else if (code !== 0) { + console.error(`❌ Worker ${worker.process.pid} terminé avec le code ${code}`); + } else { + console.log(`ℹ️ Worker ${worker.process.pid} terminé normalement`); + } + + // Ne pas redémarrer les workers si le master est en cours d'arrêt + if (isShuttingDown) { + console.log(`🛑 Shutdown en cours — worker ${worker.process.pid} ne sera pas redémarré`); + return; + } + + // Vérifier le taux de redémarrage pour éviter la boucle infinie + const now = Date.now(); + const restarts = workerRestarts.get('global') || []; + const recentRestarts = restarts.filter(t => now - t < RESTART_WINDOW_MS); + recentRestarts.push(now); + workerRestarts.set('global', recentRestarts); + + if (recentRestarts.length > MAX_RESTARTS) { + console.error(`🚨 Trop de redémarrages (${recentRestarts.length} en ${RESTART_WINDOW_MS / 1000}s) — arrêt du fork`); + return; + } + + console.log(`🔄 Redémarrage d'un nouveau worker...`); + const newWorker = cluster.fork(); + console.log(`✅ Nouveau worker ${newWorker.process.pid} créé`); + }); + + // Graceful shutdown master + const shutdownMaster = () => { + isShuttingDown = true; + console.log('\n🛑 Signal de fermeture reçu par le master...'); + console.log('📤 Envoi du signal de fermeture à tous les workers...'); + for (const id in cluster.workers) { + cluster.workers[id].send('shutdown'); + } + let workersAlive = Object.keys(cluster.workers).length; + const checkInterval = setInterval(() => { + workersAlive = Object.keys(cluster.workers).length; + if (workersAlive === 0) { + clearInterval(checkInterval); + console.log('✅ Tous les workers sont arrêtés. Arrêt du master.'); + process.exit(0); + } + }, 100); + setTimeout(() => { + console.warn('⚠️ Timeout atteint (30s). Arrêt forcé du master.'); + process.exit(1); + }, 30000); + }; + + process.on('SIGTERM', shutdownMaster); + process.on('SIGINT', shutdownMaster); + + console.log(` +╔═══════════════════════════════════════════════════════╗ +║ 🎯 Mode Cluster Actif ║ +║ 👷 Workers: ${NUM_WORKERS.toString().padEnd(42, ' ')}║ +║ 🔒 Redis Locks: Verrous distribués entre workers ║ +║ ⚛️ Atomic writes: Garantis entre les processus ║ +╚═══════════════════════════════════════════════════════╝ + `); + + // Le master ne fait RIEN d'autre — pas de require express, mysql, etc. + return; +} + +// ============================================================================= +// === WORKER PROCESS ONLY (below) ============================================= +// ============================================================================= + +process.env.UV_THREADPOOL_SIZE = 8; // 8 threads libuv par worker (6 workers x 8 = 48 threads total) + +const http = require('http'); +const { app } = require('./app'); +const { redis } = require('./config/redis'); +const { shutdownCycleTLS, refreshProxyScrapeProxies } = require('./utils/proxyManager'); +const { getPool } = require('./mysqlPool'); + +const PORT = 25565; + +// --------------------------------------------------------------------------- +// startServer — create HTTP server with retry logic +// --------------------------------------------------------------------------- +const startServer = async (retries = 3) => { + try { + await refreshProxyScrapeProxies({ force: false, silent: false }); + } catch (error) { + console.warn(`[PROXYSCRAPE] Initialisation incomplete avant listen: ${error.message}`); + } + + const server = http.createServer(app); + + // Configure Keep-Alive settings + server.keepAliveTimeout = 65000; // 65 secondes + server.headersTimeout = 66000; // 66 secondes + server.maxRequestsPerSocket = 0; // Illimité + server.requestTimeout = 300000; // 5 minutes timeout to prevent hung sockets + + // Backlog increased to 4096 to handle burst connections + server.listen(PORT, '0.0.0.0', 4096, () => { + console.log(`Serveur démarré sur le port ${PORT} - Process ${process.pid}`); + console.log(`Proxy service available at http://localhost:${PORT}/proxy/`); + console.log(`Keep-Alive configuré: timeout=${server.keepAliveTimeout}ms, max=1000`); + console.log(`Performance tuning: UV_THREADPOOL_SIZE=${process.env.UV_THREADPOOL_SIZE}, RequestTimeout=${server.requestTimeout}ms`); + }); + + server.on('error', (err) => { + console.error('Erreur de démarrage:', err); + if (retries > 0) { + console.log(`Redémarrage... (${retries} restantes)`); + setTimeout(() => startServer(retries - 1), 5000); + } else { + console.error('Échec du démarrage après plusieurs tentatives'); + process.exit(1); + } + }); + + return server; +}; + +// === DÉMARRAGE DU WORKER === +startServer().then(() => { + console.log(`✅ Worker ${process.pid} - Serveur démarré sur le port ${PORT}`); +}).catch((error) => { + console.error(`❌ Worker ${process.pid} - Échec du démarrage:`, error); + process.exit(1); +}); + +// Graceful shutdown worker — cleanup all resources +const shutdownWorker = async () => { + console.log(`\n🛑 Worker ${process.pid} - Signal de fermeture reçu...`); + try { await redis.quit(); } catch { /* ignore */ } + try { await shutdownCycleTLS(); } catch { /* ignore */ } + try { const pool = getPool(); if (pool) await pool.end(); } catch { /* ignore */ } + process.exit(0); +}; + +process.on('SIGTERM', shutdownWorker); +process.on('SIGINT', shutdownWorker); +process.on('message', (msg) => { + if (msg === 'shutdown') shutdownWorker(); +}); diff --git a/API/Mainapi/serverold.js b/API/Mainapi/serverold.js new file mode 100644 index 0000000..8eb5931 --- /dev/null +++ b/API/Mainapi/serverold.js @@ -0,0 +1,16418 @@ +const cluster = require('cluster'); +const os = require('os'); +require('dotenv').config(); + +// === CLUSTER MODE CONFIGURATION (au tout début pour éviter que le master charge tout) === +const NUM_WORKERS = parseInt(process.env.NUM_WORKERS) || 6; // 6 cœurs physiques sur le serveur + +if (cluster.isPrimary ?? cluster.isMaster) { + // === MODE MASTER — ne charge RIEN d'autre (pas de MySQL, Redis, Express, etc.) === + console.log(`🚀 Master process ${process.pid} démarré en mode cluster`); + console.log(`📊 Création de ${NUM_WORKERS} workers...`); + + for (let i = 0; i < NUM_WORKERS; i++) { + const worker = cluster.fork(); + console.log(`✅ Worker ${worker.process.pid} créé (${i + 1}/${NUM_WORKERS})`); + } + + // Anti-fork-bomb : limiter les redémarrages rapides + const workerRestarts = new Map(); // pid -> [timestamps] + const MAX_RESTARTS = 5; + const RESTART_WINDOW_MS = 60000; // 1 minute + let isShuttingDown = false; // Flag pour empêcher le redémarrage des workers pendant le shutdown + + cluster.on('exit', (worker, code, signal) => { + if (signal) { + console.warn(`⚠️ Worker ${worker.process.pid} tué par le signal ${signal}`); + } else if (code !== 0) { + console.error(`❌ Worker ${worker.process.pid} terminé avec le code ${code}`); + } else { + console.log(`ℹ️ Worker ${worker.process.pid} terminé normalement`); + } + + // Ne pas redémarrer les workers si le master est en cours d'arrêt + if (isShuttingDown) { + console.log(`🛑 Shutdown en cours — worker ${worker.process.pid} ne sera pas redémarré`); + return; + } + + // Vérifier le taux de redémarrage pour éviter la boucle infinie + const now = Date.now(); + const restarts = workerRestarts.get('global') || []; + const recentRestarts = restarts.filter(t => now - t < RESTART_WINDOW_MS); + recentRestarts.push(now); + workerRestarts.set('global', recentRestarts); + + if (recentRestarts.length > MAX_RESTARTS) { + console.error(`🚨 Trop de redémarrages (${recentRestarts.length} en ${RESTART_WINDOW_MS / 1000}s) — arrêt du fork`); + return; + } + + console.log(`🔄 Redémarrage d'un nouveau worker...`); + const newWorker = cluster.fork(); + console.log(`✅ Nouveau worker ${newWorker.process.pid} créé`); + }); + + // Graceful shutdown master + const shutdownMaster = () => { + isShuttingDown = true; + console.log('\n🛑 Signal de fermeture reçu par le master...'); + console.log('📤 Envoi du signal de fermeture à tous les workers...'); + for (const id in cluster.workers) { + cluster.workers[id].send('shutdown'); + } + let workersAlive = Object.keys(cluster.workers).length; + const checkInterval = setInterval(() => { + workersAlive = Object.keys(cluster.workers).length; + if (workersAlive === 0) { + clearInterval(checkInterval); + console.log('✅ Tous les workers sont arrêtés. Arrêt du master.'); + process.exit(0); + } + }, 100); + setTimeout(() => { + console.warn('⚠️ Timeout atteint (30s). Arrêt forcé du master.'); + process.exit(1); + }, 30000); + }; + + process.on('SIGTERM', shutdownMaster); + process.on('SIGINT', shutdownMaster); + + console.log(` +╔═══════════════════════════════════════════════════════╗ +║ 🎯 Mode Cluster Actif ║ +║ 👷 Workers: ${NUM_WORKERS.toString().padEnd(42, ' ')}║ +║ 🔒 Redis Locks: Verrous distribués entre workers ║ +║ ⚛️ Atomic writes: Garantis entre les processus ║ +╚═══════════════════════════════════════════════════════╝ + `); + + // Le master ne fait RIEN d'autre — pas de require express, mysql, etc. + return; +} + +// === CODE WORKER UNIQUEMENT (ci-dessous) === +process.env.UV_THREADPOOL_SIZE = 8; // 8 threads libuv par worker (6 workers × 8 = 48 threads total) +const express = require('express'); +const cors = require('cors'); +const compression = require('compression'); +const axios = require('axios'); +const { wrapper } = require('axios-cookiejar-support'); +const tough = require('tough-cookie'); +const cheerio = require('cheerio'); +const fsp = require('fs').promises; +const path = require('path'); +const crypto = require('crypto'); +const { Buffer } = require('buffer'); +const { v4: uuidv4 } = require('uuid'); +const bip39 = require('bip39'); +const { HttpsProxyAgent } = require('https-proxy-agent'); +const { HttpProxyAgent } = require('http-proxy-agent'); +const { SocksProxyAgent } = require('socks-proxy-agent'); +const iconv = require('iconv-lite'); +const chardet = require('chardet'); +const Redis = require('ioredis'); +const http = require('http'); +const https = require('https'); + +// === DISCORD WEBHOOK POUR LES ERREURS DE SYNC === +const SYNC_ERROR_WEBHOOK = process.env.DISCORD_SYNC_ERROR_WEBHOOK_URL; + +async function logSyncErrorToDiscord(errorMessage, context = {}) { + if (!SYNC_ERROR_WEBHOOK) return; // Skip if webhook not configured + try { + const embed = { + title: '❌ Erreur de Sync', + color: 0xff0000, + description: errorMessage, + fields: [ + { name: 'User Type', value: context.userType || 'N/A', inline: true }, + { name: 'User ID', value: context.userId ? `\`${context.userId.substring(0, 8)}...\`` : 'N/A', inline: true }, + { name: 'Profile ID', value: context.profileId ? `\`${context.profileId.substring(0, 8)}...\`` : 'N/A', inline: true }, + ], + timestamp: new Date().toISOString(), + footer: { text: 'Movix Sync API' } + }; + + if (context.error) { + embed.fields.push({ name: 'Détails Erreur', value: `\`\`\`${String(context.error).substring(0, 500)}\`\`\``, inline: false }); + } + + if (context.payload) { + // Tronquer le payload pour éviter de dépasser la limite Discord (1024 chars par field) + const payloadStr = JSON.stringify(context.payload, null, 2); + const truncatedPayload = payloadStr.length > 900 ? payloadStr.substring(0, 900) + '\n... (tronqué)' : payloadStr; + embed.fields.push({ name: 'Payload Requête', value: `\`\`\`json\n${truncatedPayload}\`\`\``, inline: false }); + } + + await axios.post(SYNC_ERROR_WEBHOOK, { embeds: [embed] }, { timeout: 5000 }).catch(() => { }); + } catch (e) { + // Silently fail - don't break sync if webhook fails + } +} + +// === REDIS CACHE POUR OPTIMISER LES PERFORMANCES === +const redis = new Redis({ + host: process.env.REDIS_HOST, + port: parseInt(process.env.REDIS_PORT), + password: process.env.REDIS_PASSWORD, + retryDelayOnFailover: 100, + maxRetriesPerRequest: 3, + lazyConnect: true +}); + +redis.on('connect', () => console.log('[Redis] Connecté')); +redis.on('error', (err) => console.error('[Redis] Erreur:', err.message)); + +// === REDIS DISTRIBUTED LOCK (remplace proper-lockfile) === +// Utilise SET NX EX pour un verrou atomique avec TTL auto-expiration. +// Plus fiable que les lockfiles filesystem (pas de .lock orphelins, fonctionne en cluster). +const LOCK_PREFIX = 'lock:'; +const LOCK_DEFAULT_TTL = 10; // secondes — TTL auto-expiration du verrou +const LOCK_RETRY_DELAY = 100; // ms entre chaque tentative +const LOCK_MAX_RETRIES = 50; // 50 × 100ms = 5s max d'attente + +/** + * Acquiert un verrou distribué Redis sur une clé donnée. + * @param {string} resourceKey - Identifiant unique de la ressource (ex: chemin de fichier) + * @param {object} opts - Options : ttl (sec), retries, retryDelay (ms) + * @returns {Promise<{release: Function}|null>} - Objet avec release(), ou null si échec + */ +async function acquireRedisLock(resourceKey, opts = {}) { + const ttl = opts.ttl || LOCK_DEFAULT_TTL; + const retries = opts.retries ?? LOCK_MAX_RETRIES; + const retryDelay = opts.retryDelay || LOCK_RETRY_DELAY; + const lockKey = LOCK_PREFIX + resourceKey; + const lockValue = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; + + for (let attempt = 0; attempt <= retries; attempt++) { + try { + // SET key value NX EX ttl — atomique, ne set que si la clé n'existe pas + const result = await redis.set(lockKey, lockValue, 'EX', ttl, 'NX'); + if (result === 'OK') { + // Verrou acquis — retourner une fonction release sécurisée + return { + release: async () => { + try { + // Script Lua atomique : ne supprime que si la valeur correspond (évite de libérer le lock d'un autre process) + const luaScript = ` + if redis.call("get", KEYS[1]) == ARGV[1] then + return redis.call("del", KEYS[1]) + else + return 0 + end + `; + await redis.eval(luaScript, 1, lockKey, lockValue); + } catch (e) { + console.warn(`[RedisLock] Erreur release ${resourceKey}:`, e.message); + } + } + }; + } + } catch (err) { + // Redis indisponible — on abandonne immédiatement + console.warn(`[RedisLock] Redis indisponible pour ${resourceKey}:`, err.message); + return null; + } + + // Attendre avant de réessayer + if (attempt < retries) { + await new Promise(r => setTimeout(r, retryDelay)); + } + } + + // Timeout — impossible d'acquérir le verrou + console.warn(`[RedisLock] Timeout: impossible d'acquérir le verrou pour ${resourceKey} après ${retries} tentatives`); + return null; +} + +// Wrapper autour de Redis pour garder l'interface memoryCache (get/set avec JSON auto) +const memoryCache = { + async get(key) { + try { + const data = await redis.get(key); + return data ? JSON.parse(data) : undefined; + } catch { return undefined; } + }, + async set(key, value, ttl = 300) { + try { + await redis.set(key, JSON.stringify(value), 'EX', ttl); + } catch { /* ignore */ } + } +}; + +// === LIMITEUR DE CONCURRENCE (p-limit style) === +// Fonction pour limiter le nombre de promesses exécutées en parallèle +function createConcurrencyLimiter(concurrency) { + const queue = []; + let activeCount = 0; + + const next = () => { + activeCount--; + if (queue.length > 0) { + queue.shift()(); + } + }; + + const run = async (fn) => { + activeCount++; + try { + return await fn(); + } finally { + next(); + } + }; + + const enqueue = (fn) => { + return new Promise((resolve, reject) => { + const task = () => run(fn).then(resolve, reject); + if (activeCount < concurrency) { + task(); + } else { + queue.push(task); + } + }); + }; + + return enqueue; +} + +// Limiteurs pré-configurés pour différents cas d'usage +const limitConcurrency5 = createConcurrencyLimiter(5); // Pour les requêtes réseau légères +const limitConcurrency3 = createConcurrencyLimiter(3); // Pour les requêtes réseau lourdes +const limitConcurrency10 = createConcurrencyLimiter(10); // Pour les opérations I/O locales + +// === CACHE POUR LES AGENTS PROXY === +const proxyAgentCache = new Map(); +const darkinoProxyAgentCache = new Map(); + +// Initialize global agent keep-alive for better performance +http.globalAgent.keepAlive = true; +https.globalAgent.keepAlive = true; +const writeFileAtomic = require('write-file-atomic'); +bip39.setDefaultWordlist('french'); + + +// === MYSQL DATABASE CONNECTION === +const mysql = require('mysql2/promise'); +const wrappedRoutes = require('./wrappedRoutes'); // Wrapped Routes +const { verifyAccessKey, vipMiddleware, invalidateVipCache, invalidateAllVipCache } = require('./checkVip'); +// === JWT AUTHENTICATION HELPERS === +const jwt = require('jsonwebtoken'); +const JWT_SECRET = process.env.JWT_SECRET; +if (!JWT_SECRET) { + console.error("FATAL: JWT_SECRET is not defined in .env"); + process.exit(1); +} +function issueJwt(userType, userId, sessionId) { + // Issue a token without expiration (no exp claim) + return jwt.sign({ sub: userId, userType, sessionId }, JWT_SECRET, { algorithm: 'HS256' }); +} + +// ===== FONCTIONS SÉCURISÉES POUR LES ÉCRITURES DE FICHIERS ===== + +/** + * Écriture sécurisée avec verrou de fichier et écriture atomique + * @param {string} filePath - Chemin du fichier à écrire + * @param {string|Buffer} data - Données à écrire + * @param {object} options - Options pour l'écriture + * @returns {Promise<boolean>} - Succès de l'opération + */ +async function safeWriteFile(filePath, data, options = {}) { + const defaultOptions = { + encoding: 'utf8', + mode: 0o644, + lockTtl: 10, // TTL du verrou Redis en secondes + retries: 3, + retryDelay: 100 + }; + + const finalOptions = { ...defaultOptions, ...options }; + let lock = null; + + try { + // Créer le répertoire parent si nécessaire + await fsp.mkdir(path.dirname(filePath), { recursive: true }); + + // Tentative d'acquisition du verrou Redis (avec fallback si échec) + // Clé de lock basée sur le chemin absolu normalisé + const lockResource = path.resolve(filePath).replace(/\\/g, '/'); + lock = await acquireRedisLock(lockResource, { + ttl: finalOptions.lockTtl, + retries: finalOptions.retries * 10, // plus de tentatives car Redis est rapide + retryDelay: finalOptions.retryDelay + }); + + if (!lock) { + // Redis indisponible ou timeout — on continue l'écriture sans verrou + console.warn(`[SafeWriteFile] AVERTISSEMENT: Impossible de verrouiller ${path.basename(filePath)} via Redis, écriture forcée sans verrou.`); + } + + // Écrire le fichier de manière atomique (même si le lock a échoué) + // flush: false désactive fsync pour améliorer les performances sur software RAID + await writeFileAtomic(filePath, data, { + encoding: finalOptions.encoding, + mode: finalOptions.mode, + fsync: false // Désactiver fsync pour perf sur software RAID OVH + }); + + return true; + } catch (error) { + console.error(`[SafeWriteFile] Échec pour ${filePath}:`, error.message, error.code || ''); + return false; + } finally { + // Libérer le verrou Redis si acquis + if (lock) { + try { + await lock.release(); + } catch (releaseError) { + console.error(`[SafeWriteFile] Erreur release Redis lock pour ${filePath}:`, releaseError); + } + } + } +} + +/** + * Écriture sécurisée de données JSON avec verrou de fichier et écriture atomique + * @param {string} filePath - Chemin du fichier à écrire + * @param {object} data - Objet JSON à écrire + * @param {object} options - Options pour l'écriture + * @returns {Promise<boolean>} - Succès de l'opération + */ +async function safeWriteJsonFile(filePath, data, options = {}) { + const jsonOptions = { + ...options, + encoding: 'utf8' + }; + + try { + const jsonString = JSON.stringify(data); + return await safeWriteFile(filePath, jsonString, jsonOptions); + } catch (error) { + console.error(`Erreur lors de la sérialisation JSON pour ${filePath}:`, error); + return false; + } +} + +/** + * Lecture sécurisée avec verrou de fichier + * @param {string} filePath - Chemin du fichier à lire + * @param {object} options - Options pour la lecture + * @returns {Promise<object|null>} - Données lues ou null en cas d'erreur + */ +async function safeReadJsonFile(filePath, options = {}) { + const defaultOptions = { + encoding: 'utf8', + retries: 2, + retryDelay: 50 + }; + + const finalOptions = { ...defaultOptions, ...options }; + + // Petite boucle de retry en cas d'accès concurrentiel très rare + for (let attempt = 0; attempt <= finalOptions.retries; attempt++) { + try { + const fileContent = await fsp.readFile(filePath, finalOptions.encoding); + try { + return JSON.parse(fileContent); + } catch (parseError) { + // Si JSON temporairement invalide, réessayer brièvement + if (attempt < finalOptions.retries) { + await new Promise(r => setTimeout(r, finalOptions.retryDelay)); + continue; + } + console.error(`Erreur de parse JSON pour ${filePath}:`, parseError); + return null; + } + } catch (error) { + if (error.code === 'ENOENT') { + return null; // Fichier absent + } + if (attempt < finalOptions.retries) { + await new Promise(r => setTimeout(r, finalOptions.retryDelay)); + continue; + } + console.error(`Erreur lors de la lecture de ${filePath}:`, error); + return null; + } + } + return null; +} + +const DARKINO_MAINTENANCE = false; // Passe à true pour activer le mode maintenance + + +// Base URLs +const COFLIX_BASE_URL = 'https://coflix.ninja'; +const COFLIX_SEARCH_URL = `${COFLIX_BASE_URL}/?s=`; + +// Anime Sama API Configuration +const ANIME_SAMA_URL = "https://anime-sama.tv/"; +const ANIME_SAMA_CACHE_DIR = path.join(__dirname, 'cache', 'anime-sama'); + +const TMDB_API_KEY = process.env.TMDB_API_KEY || ''; +const TMDB_API_URL = 'https://api.themoviedb.org/3'; + + +// === PROXY CONFIGURATION === + +const ENABLE_DARKINO_PROXY = true; // Passe à false pour désactiver le proxy pour Darkino +const ENABLE_COFLIX_PROXY = true; // Passe à false pour désactiver le proxy pour Coflix +const ENABLE_FRENCH_STREAM_PROXY = true; // Active/désactive le proxy pour French-Stref +const ENABLE_LECTEURVIDEO_PROXY = true; // Active/désactive le proxy pour LecteurVideo +const ENABLE_FSTREAM_PROXY = true; // Active/désactive le proxy pour FStream +const ENABLE_ANIME_PROXY = true; // Active/désactive le proxy pour AnimeSama (via Cloudflare Workers) +const ENABLE_WIFLIX_PROXY = true; // Active/désactive le proxy pour Wiflix + +// Constante pour l'enhancement Darkino +const darkiworld_premium = false; // Passe à false pour désactiver l'enhancement Darkino + +// === DARKINO 403 COOLDOWN === +// Cooldown de 5 minutes après une erreur 403 (Cloudflare challenge) +const DARKINO_403_COOLDOWN_MS = 5 * 60 * 1000; // 5 minutes +let darkino403CooldownUntil = 0; // Timestamp jusqu'auquel on ne fait plus de requêtes + +// === CPASMAL CONFIGURATION === +const CPASMAL_BASE_URL = 'https://www.cpasmal.rip'; + +const cpasmalJar = new tough.CookieJar(null, { rejectPublicSuffixes: false }); + +// === CPASMAL GLOBAL CONCURRENCY LIMITER (Semaphore) === +// Limite le nombre de requêtes Cpasmal simultanées pour éviter de bloquer le serveur +const CPASMAL_MAX_CONCURRENT = 4; // Max 4 requêtes Cpasmal en parallèle +let cpasmalActivRequests = 0; +const cpasmalQueue = []; + +async function acquireCpasmalSlot() { + return new Promise((resolve) => { + const tryAcquire = () => { + if (cpasmalActivRequests < CPASMAL_MAX_CONCURRENT) { + cpasmalActivRequests++; + resolve(); + } else { + cpasmalQueue.push(tryAcquire); + } + }; + tryAcquire(); + }); +} + +function releaseCpasmalSlot() { + cpasmalActivRequests--; + if (cpasmalQueue.length > 0) { + const next = cpasmalQueue.shift(); + next(); + } +} + +// Cache pour les agents SOCKS5 Cpasmal (Keep-Alive) +const cpasmalAgentCache = new Map(); + +function getCpasmalAgent(proxy) { + if (!proxy) return null; + const cacheKey = `${proxy.type}:${proxy.host}:${proxy.port}:${proxy.auth}`; + + if (cpasmalAgentCache.has(cacheKey)) { + return cpasmalAgentCache.get(cacheKey); + } + + // Configuration Keep-Alive optimisée + const agentOpts = { + keepAlive: true, + keepAliveMsecs: 15000, // 15s keep-alive + maxSockets: 50, + maxFreeSockets: 10, + timeout: 30000 + }; + + let agent; + if (proxy.type === 'socks5' || proxy.type === 'socks5h') { + const info = { + hostname: proxy.host, + port: proxy.port, + protocol: 'socks:', + tls: { rejectUnauthorized: false }, + ...agentOpts + }; + + // Auth handling + if (proxy.auth) { + const parts = proxy.auth.split(':'); + info.username = parts[0]; // Correction: userId -> username + info.password = parts[1]; + } + + agent = new SocksProxyAgent(info); + } + + if (agent) { + cpasmalAgentCache.set(cacheKey, agent); + } + return agent; +} + +// Fonction pour faire des requêtes vers Cpasmal avec rotation de proxies SOCKS5 +async function axiosCpasmalRequest(config) { + const urlStr = config.url || ''; + + // Constante pour Cpasmal Base URL si relative + const baseURL = CPASMAL_BASE_URL; + + // Headers par défaut + const defaultHeaders = { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', + 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', + 'Accept-Language': 'fr-FR,fr;q=0.9,en;q=0.8', + 'Accept-Encoding': 'gzip, deflate, br', + 'Connection': 'keep-alive', + ...(config.headers || {}) + }; + + // Gestion des cookies (récupération) + // Gestion des cookies (récupération manuelle pour compatibilité avec proxy agent) + if (urlStr || config.baseURL) { + try { + // Reconstitution approximative de l'URL pour les cookies + const targetUrl = urlStr.startsWith('http') ? urlStr : (config.baseURL || baseURL) + urlStr; + const cookieString = await cpasmalJar.getCookieString(targetUrl); + if (cookieString) { + defaultHeaders['Cookie'] = cookieString; + } + } catch (err) { + console.error('[Cpasmal CookieJar] Error getting cookies:', err); + } + } + + // Choix d'un proxy SOCKS5h aléatoire (une seule fois) + const proxy = pickRandomProxyOrNone(); + const agent = getCpasmalAgent(proxy); + + try { + if (process.env.DEBUG_CPASMAL === 'true') console.time(`[Cpasmal] Request ${urlStr} (Proxy: ${proxy ? proxy.host : 'Direct'})`); + + const response = await axios({ + ...config, + headers: defaultHeaders, + httpAgent: agent, + httpsAgent: agent, + proxy: false, + timeout: config.timeout || 5000, + decompress: true + }); + + if (process.env.DEBUG_CPASMAL === 'true') console.timeEnd(`[Cpasmal] Request ${urlStr} (Proxy: ${proxy ? proxy.host : 'Direct'})`); + + // Gestion des cookies (sauvegarde manuelle) + if (response.headers['set-cookie']) { + const cookies = response.headers['set-cookie']; + const url = response.config.url; + try { + if (Array.isArray(cookies)) { + for (const cookie of cookies) { + await cpasmalJar.setCookie(cookie, url); + } + } else { + await cpasmalJar.setCookie(cookies, url); + } + } catch (err) { + console.error('[Cpasmal CookieJar] Error setting cookies:', err); + } + } + + return response; + } catch (error) { + // Ajouter infos debug + error.cpasmalUrl = urlStr; + error.cpasmalProxy = proxy ? `${proxy.host}:${proxy.port}` : 'Direct'; + + // Propager l'erreur immédiatement + throw error; + } +} + + + +// === CLOUDFLARE WORKERS PROXIES CONFIGURATION === +const CLOUDFLARE_WORKERS_PROXIES = (process.env.CLOUDFLARE_WORKERS_PROXIES || '') + .split(',') + .map(proxy => proxy.trim()) + .filter(Boolean); + +// === CACHE POUR LES PROXIES CLOUDFLARE EN ERREUR === +// Cache pour mémoriser les proxies en erreur (429, 500, timeout, etc.) +// Les proxies en erreur seront ignorés pendant PROXY_ERROR_COOLDOWN_MS millisecondes +const proxyErrorCache = new Map(); // Map<proxyUrl, { errorTime: timestamp, errorCode: number|string, errorCount: number }> +const PROXY_ERROR_COOLDOWN_MS = 60000; // 60 secondes de cooldown pour un proxy en erreur +const PROXY_ERROR_COOLDOWN_429_MS = 120000; // 2 minutes de cooldown spécifique pour erreur 429 (rate limit) +const PROXY_ERROR_COOLDOWN_5XX_MS = 90000; // 1.5 minutes pour les erreurs serveur (500, 502, 503, 504) +const MAX_CONSECUTIVE_ERRORS = 3; // Nombre max d'erreurs consécutives avant cooldown prolongé +const PROXY_EXTENDED_COOLDOWN_MS = 300000; // 5 minutes de cooldown prolongé si trop d'erreurs consécutives + +/** + * Marque un proxy comme étant en erreur + * @param {string} proxyUrl - URL du proxy + * @param {number|string} errorCode - Code d'erreur (429, 500, 'timeout', etc.) + */ +function markProxyAsErrored(proxyUrl, errorCode) { + const existing = proxyErrorCache.get(proxyUrl); + const errorCount = existing ? existing.errorCount + 1 : 1; + + proxyErrorCache.set(proxyUrl, { + errorTime: Date.now(), + errorCode, + errorCount + }); + + // Log seulement si DEBUG activé + if (process.env.DEBUG_PROXY) { + console.log(`[PROXY CACHE] Proxy marqué en erreur: ${proxyUrl} (code: ${errorCode}, count: ${errorCount})`); + } +} + +/** + * Vérifie si un proxy est actuellement en cooldown (à éviter) + * @param {string} proxyUrl - URL du proxy + * @returns {boolean} - true si le proxy doit être ignoré + */ +function isProxyInCooldown(proxyUrl) { + const errorInfo = proxyErrorCache.get(proxyUrl); + if (!errorInfo) return false; + + const now = Date.now(); + const timeSinceError = now - errorInfo.errorTime; + + // Déterminer le cooldown approprié selon le type d'erreur et le nombre d'erreurs + let cooldownMs; + if (errorInfo.errorCount >= MAX_CONSECUTIVE_ERRORS) { + cooldownMs = PROXY_EXTENDED_COOLDOWN_MS; + } else if (errorInfo.errorCode === 429) { + cooldownMs = PROXY_ERROR_COOLDOWN_429_MS; + } else if (errorInfo.errorCode >= 500 && errorInfo.errorCode < 600) { + cooldownMs = PROXY_ERROR_COOLDOWN_5XX_MS; + } else { + cooldownMs = PROXY_ERROR_COOLDOWN_MS; + } + + // Si le cooldown est passé, supprimer l'entrée du cache + if (timeSinceError >= cooldownMs) { + proxyErrorCache.delete(proxyUrl); + return false; + } + + return true; +} + +/** + * Retourne la liste des proxies disponibles (non en cooldown) + * @param {string[]} allProxies - Liste de tous les proxies + * @returns {string[]} - Liste des proxies disponibles + */ +function getAvailableProxies(allProxies) { + const available = allProxies.filter(proxy => !isProxyInCooldown(proxy)); + + // Si tous les proxies sont en cooldown, on réinitialise le cache et on retourne tous les proxies + // pour éviter de bloquer complètement le service + if (available.length === 0) { + if (process.env.DEBUG_PROXY) { + console.log('[PROXY CACHE] Tous les proxies sont en cooldown, réinitialisation du cache'); + } + proxyErrorCache.clear(); + return allProxies; + } + + return available; +} + +/** + * Réinitialise le compteur d'erreurs d'un proxy après un succès + * @param {string} proxyUrl - URL du proxy + */ +function markProxyAsHealthy(proxyUrl) { + proxyErrorCache.delete(proxyUrl); +} + +/** + * Construit l'URL proxy en fonction du type de proxy + * Les proxies se terminant par '/' attendent l'URL encodée + * Les proxies se terminant par '?' attendent l'URL non-encodée + * @param {string} proxyUrl - URL du proxy Cloudflare + * @param {string} targetUrl - URL cible à proxyer + * @returns {string} - URL finale à appeler + */ +function buildProxiedUrl(proxyUrl, targetUrl) { + if (proxyUrl.endsWith('/')) { + // Proxy qui attend l'URL encodée (ex: cors-worker-1) + return proxyUrl + encodeURIComponent(targetUrl); + } else { + // Proxy qui attend l'URL en query string (ex: ?url=...) + return proxyUrl + targetUrl; + } +} + +// Fonction pour faire une requête avec fallback CORS en cas d'erreur 429 +async function makeRequestWithCorsFallback(targetUrl, options = {}) { + const { timeout = 7000, headers = {}, decompress = true, ...otherOptions } = options; + + // Filtrer les proxies disponibles (non en cooldown) + const availableProxies = getAvailableProxies(CLOUDFLARE_WORKERS_PROXIES); + + // Utiliser directement les proxies Cloudflare Workers disponibles + let lastError = null; + + for (let i = 0; i < availableProxies.length; i++) { + const currentProxy = availableProxies[i]; + try { + // Construire l'URL complète : proxy Cloudflare + URL cible (encodage si nécessaire) + const finalProxyUrl = buildProxiedUrl(currentProxy, targetUrl); + + const response = await axios.get(finalProxyUrl, { + headers: { + 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', + 'accept-language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7', + 'priority': 'u=1, i', + 'sec-ch-ua': '"Chromium";v="140", "Not=A?Brand";v="24", "Brave";v="140"', + 'sec-ch-ua-mobile': '?0', + 'sec-ch-ua-platform': '"Windows"', + 'sec-fetch-dest': 'document', + 'sec-fetch-mode': 'navigate', + 'sec-fetch-site': 'cross-site', + 'sec-gpc': '1', + 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36', + ...headers + }, + timeout, + decompress, + ...otherOptions + }); + + // Succès : marquer le proxy comme sain + markProxyAsHealthy(currentProxy); + return response; + } catch (proxyError) { + lastError = proxyError; + const statusCode = proxyError.response?.status; + const errorCode = statusCode || proxyError.code || 'unknown'; + + // En cas d'erreur 400 ou 403, arrêt immédiat sans réessayer avec d'autres proxies + if (statusCode === 400 || statusCode === 403) { + throw proxyError; + } + + // Marquer le proxy en erreur pour les codes 429, 5xx, timeout, etc. + if (statusCode === 429 || (statusCode >= 500 && statusCode < 600) || proxyError.code === 'ECONNABORTED' || proxyError.code === 'ETIMEDOUT') { + markProxyAsErrored(currentProxy, errorCode); + } + + // Si c'est le dernier proxy et qu'on a une erreur, throw l'erreur + if (i === availableProxies.length - 1) { + throw proxyError; + } + // Sinon continuer avec le prochain proxy (429, etc.) + } + } + + // Si on arrive ici, tous les proxies ont échoué + throw lastError || new Error('Tous les proxies ont échoué'); +} + +// Fonction pour faire une requête Coflix avec les proxies Cloudflare Workers (comme Anime Sama) +async function makeCoflixRequest(targetUrl, options = {}) { + const { timeout = 15000, headers = {}, decompress = true, ...otherOptions } = options; + + // Nettoyer l'URL pour éviter les espaces indésirables + const cleanTargetUrl = targetUrl.trim(); + + // Filtrer les proxies disponibles (non en cooldown) + const availableProxies = getAvailableProxies(CLOUDFLARE_WORKERS_PROXIES); + + // Headers pour les requêtes Coflix via proxy + const coflixProxyHeaders = { + 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', + 'accept-encoding': 'gzip, deflate, br', + 'accept-language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7', + 'cache-control': 'no-cache', + 'pragma': 'no-cache', + 'sec-ch-ua': '"Chromium";v="140", "Not=A?Brand";v="24", "Brave";v="140"', + 'sec-ch-ua-mobile': '?0', + 'sec-ch-ua-platform': '"Windows"', + 'sec-fetch-dest': 'document', + 'sec-fetch-mode': 'navigate', + 'sec-fetch-site': 'cross-site', + 'sec-gpc': '1', + 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36', + ...coflixHeaders, + ...headers + }; + + // Supprimer les headers liés à l'IP d'origine pour éviter de les transmettre + const headersToRemove = ['X-Forwarded-For', 'X-Real-IP', 'X-Client-IP', 'CF-Connecting-IP', 'True-Client-IP', 'X-Original-Forwarded-For']; + const cleanHeaders = { ...coflixProxyHeaders }; + headersToRemove.forEach(header => { + delete cleanHeaders[header]; + delete cleanHeaders[header.toLowerCase()]; + }); + + // Choisir un proxy SOCKS5h aléatoire + const socks5Proxy = pickRandomProxyOrNone(); + const proxyAgent = socks5Proxy ? getProxyAgent(socks5Proxy) : null; + + // Utiliser les proxies Cloudflare Workers avec le proxy SOCKS5h + let lastError = null; + + // Essayer chaque proxy Cloudflare séquentiellement + for (let i = 0; i < availableProxies.length; i++) { + const cloudflareProxy = availableProxies[i]; + const proxiedUrl = buildProxiedUrl(cloudflareProxy, cleanTargetUrl); + + try { + if (process.env.DEBUG_COFLIX) console.log(`[Coflix] Tentative avec ${cloudflareProxy}`); + + const response = await axios({ + url: proxiedUrl, + headers: cleanHeaders, + timeout, + decompress: true, + responseType: 'text', + responseEncoding: 'utf8', + ...otherOptions, + ...(proxyAgent ? { httpAgent: proxyAgent, httpsAgent: proxyAgent, proxy: false } : {}) + }); + + // Succès : marquer le proxy comme sain + markProxyAsHealthy(cloudflareProxy); + return response; + } catch (error) { + if (process.env.DEBUG_COFLIX) console.log(`[Coflix] Échec avec ${cloudflareProxy}: ${error.message}`); + + lastError = error; + const statusCode = error.response?.status; + const errorCode = statusCode || error.code || 'unknown'; + + // En cas d'erreur 429 (Too Many Requests), marquer le proxy et essayer le suivant + if (statusCode === 429) { + markProxyAsErrored(cloudflareProxy, 429); + continue; + } + + // En cas d'erreur 5xx, marquer le proxy et essayer le suivant + if (statusCode >= 500 && statusCode < 600) { + markProxyAsErrored(cloudflareProxy, statusCode); + continue; + } + + // En cas de timeout, marquer le proxy et essayer le suivant + if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') { + markProxyAsErrored(cloudflareProxy, errorCode); + continue; + } + + // Pour les erreurs 400, 403, arrêter immédiatement + if (process.env.DEBUG_COFLIX) console.error(`[Coflix] Erreur fatale avec le proxy ${cloudflareProxy}:`, error.message); + throw error; + } + } + + // Si on arrive ici, tous les proxies ont échoué + if (lastError) throw lastError; + throw new Error('Tous les proxies ont échoué (Coflix)'); +} + + +// Fonction pour faire une requête LecteurVideo avec les proxies SOCKS5h +async function makeLecteurVideoRequest(targetUrl, options = {}) { + const { timeout = 15000, headers = {}, decompress = true, ...otherOptions } = options; + + // Nettoyer l'URL pour éviter les espaces indésirables + const cleanTargetUrl = targetUrl.trim(); + + // Choisir un proxy SOCKS5h aléatoire + const socks5Proxy = pickRandomProxyOrNone(); + const proxyAgent = socks5Proxy ? getProxyAgent(socks5Proxy) : null; + + if (!proxyAgent) { + throw new Error('[LECTEURVIDEO] Aucun proxy SOCKS5h disponible'); + } + + try { + const response = await axios.get(cleanTargetUrl, { + headers: { + 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8', + 'accept-language': 'fr-FR,fr;q=0.7', + 'cache-control': 'no-cache', + 'pragma': 'no-cache', + 'priority': 'u=0, i', + 'referer': 'https://coflix.observer/', + 'sec-ch-ua': '"Brave";v="141", "Not?A_Brand";v="8", "Chromium";v="141"', + 'sec-ch-ua-mobile': '?0', + 'sec-ch-ua-platform': '"Windows"', + 'sec-fetch-dest': 'iframe', + 'sec-fetch-mode': 'navigate', + 'sec-fetch-site': 'cross-site', + 'sec-fetch-storage-access': 'none', + 'sec-gpc': '1', + 'upgrade-insecure-requests': '1', + 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36', + 'cookie': 'cf_clearance=1kltmqQs5IZMXJLw00AYOhoSBjiJhCtM5X8AnVAHR48-1761680096-1.2.1.1-.4wtj_F1hyRvbwTFTbCDdU4z8W0QI0uR11.zNGsr9rE2ZEUzjw_Rjf_xyAFB2OGWrPIJ4f7eSQuUgEU2oZ8x6yfhHoFAcJ.kpsoujC1OGVVA2tnUA9oaLftSRA8jYHg3fcH4uNkhCqrhtnEDwgiHMO3zn.7rXXG_uBQyAPXg0PF2eIxUDpVDom0eUFX.ktljbXrYm9A.idFTvper_DLi_AYvB_nFf0jFQhyWJnAsXjI', + ...headers + }, + timeout: 7000, + decompress: true, + responseType: 'text', + responseEncoding: 'utf8', + httpAgent: proxyAgent, + httpsAgent: proxyAgent, + proxy: false, + ...otherOptions + }); + + return response; + } catch (error) { + const errorCode = error.response?.status || error.code || 'unknown'; + console.error(`[LECTEURVIDEO] erreur: ${errorCode}`); + throw error; + } +} + +// Utilitaires pour le cache +const CACHE_DIR = { + ANIME_SAMA: ANIME_SAMA_CACHE_DIR, + COFLIX: path.join(__dirname, 'cache', 'coflix'), + FSTREAM: path.join(__dirname, 'cache', 'fstream'), + CPASMAL: path.join(__dirname, 'cache', 'cpasmal'), + TVDIRECT: path.join(__dirname, 'cache', 'tvdirect'), + PURSTREAM: path.join(__dirname, 'cache', 'purstream'), + CINEPULSE: path.join(__dirname, 'cache', 'cinepulse'), + NOCTAFLIX: path.join(__dirname, 'cache', 'noctaflix'), + DRAGIV: path.join(__dirname, 'cache', 'dragiv'), + FTV: path.join(__dirname, 'cache', 'ftv') +}; + +// Créer les dossiers de cache s'ils n'existent pas +(async () => { + for (const dir of Object.values(CACHE_DIR)) { + try { + await fsp.access(dir); + } catch { + await fsp.mkdir(dir, { recursive: true }); + } + } +})(); + +// Fonction pour générer une clé de cache basée sur les paramètres +const generateCacheKey = (params) => { + const stringParams = typeof params === 'string' ? params : JSON.stringify(params); + return crypto.createHash('md5').update(stringParams).digest('hex'); +}; + +// Fonction pour corriger le type de stream basé sur l'URL +const correctStreamType = (streamData) => { + if (streamData && streamData.url && streamData.url.includes('.mp4')) { + return { + ...streamData, + type: 'mp4' + }; + } + return streamData; +}; + +// Fonction pour vérifier si une donnée est en cache avec expiration de 8h +const getFromCacheWithExpiration = async (cacheDir, key, expirationHours = 8) => { + try { + // 1. Vérifier le cache mémoire (L1) (rapide) + // Si c'est en mémoire (TTL 5 min), c'est forcément valide (< 8h) + const memKey = `${cacheDir}:${key}`; + const memData = await memoryCache.get(memKey); + if (memData) { + if (process.env.DEBUG_CACHE) console.log(`[Cache] Memory hit for ${key}`); + return memData; + } + + // 2. Vérifier le cache fichier (L2) (lent) + const cacheFilePath = path.join(cacheDir, `${key}.json`); + let stats; + try { + stats = await fsp.stat(cacheFilePath); + } catch (e) { + if (e.code === 'ENOENT') return null; + throw e; + } + + const now = Date.now(); + const fileTime = stats.mtime.getTime(); + const expirationTime = expirationHours * 60 * 60 * 1000; // en millisecondes + + // Vérifier si le cache a expiré + if (now - fileTime > expirationTime) { + return null; + } + + const fileContent = await fsp.readFile(cacheFilePath, 'utf8'); + const cacheData = JSON.parse(fileContent); + + // Mettre à jour le cache mémoire pour les prochaines fois + await memoryCache.set(memKey, cacheData); + + return cacheData; + } catch (error) { + if (error.code === 'ENOENT') { + return null; + } + console.error(`Erreur lors de la récupération du cache pour ${key}:`, error); + return null; + } +}; + +// Fonction pour normaliser les URLs Anime-Sama avec le domaine actuel +const normalizeAnimeSamaUrls = (data) => { + if (!data) return data; + + const currentDomain = ANIME_SAMA_URL.replace(/\/$/, ''); // Enlever le slash final + + // Fonction pour valider une URL de player + const isValidPlayerUrl = (url) => { + if (typeof url !== 'string' || url.length === 0) return false; + if (!url.startsWith('http://') && !url.startsWith('https://')) return false; + if (!url.includes('.')) return false; + const invalidPatterns = ['_self', 'containerSamedi', 'élite', 'Sectes', 'prouesses', 'discord.gg']; + if (invalidPatterns.some(pattern => url.includes(pattern))) return false; + return true; + }; + + // Fonction récursive pour remplacer les URLs dans les objets/tableaux + const replaceUrls = (obj, key = null) => { + if (typeof obj === 'string') { + // Retirer le préfixe proxy.movix.club/proxy/ ou proxy.movix.site/proxy/ + let cleanedUrl = obj.replace(/https:\/\/proxy\.movix\.(club|site)\/proxy\//gi, ''); + // Remplacer tous les anciens domaines anime-sama par le domaine actuel + return cleanedUrl.replace(/https?:\/\/anime-sama\.[a-z]+/gi, currentDomain); + } + + if (Array.isArray(obj)) { + // Si c'est le tableau "players", filtrer les URLs invalides + // Seulement si les éléments sont des strings (anime-sama) + // Pour FrenchStream/IMDB, les players sont des objets {name, link} + if (key === 'players') { + return obj + .map(item => replaceUrls(item)) + .filter(item => { + // Si c'est un objet avec un link (FrenchStream), le garder + if (item && typeof item === 'object' && item.link) { + return true; + } + // Si c'est une string (anime-sama), valider l'URL + return isValidPlayerUrl(item); + }); + } + // Si c'est le tableau "streaming_links", traiter chaque élément puis filtrer les vides + if (key === 'streaming_links') { + return obj + .map(item => { + // Traiter l'objet streaming_link (qui contient language et players) + const processed = replaceUrls(item); + return processed; + }) + .filter(item => item && item.players && item.players.length > 0); + } + return obj.map(item => replaceUrls(item)); + } + + if (obj && typeof obj === 'object') { + const newObj = {}; + for (const [k, value] of Object.entries(obj)) { + newObj[k] = replaceUrls(value, k); + } + return newObj; + } + + return obj; + }; + + return replaceUrls(data); +}; + +// Fonction pour vérifier si une donnée est en cache sans vérifier la date d'expiration +const getFromCacheNoExpiration = async (cacheDir, key) => { + try { + // 1. Vérifier le cache mémoire (L1) + const memKey = `${cacheDir}:${key}`; + const memData = await memoryCache.get(memKey); + if (memData) { + // Normaliser les URLs pour le cache mémoire aussi (sécurité) + const normalizedMemData = normalizeAnimeSamaUrls(memData); + return normalizedMemData; + } + + const cacheFilePath = path.join(cacheDir, `${key}.json`); + let fileContent; + try { + fileContent = await fsp.readFile(cacheFilePath, 'utf8'); + } catch (e) { + if (e.code === 'ENOENT') return null; + throw e; + } + + const cacheData = JSON.parse(fileContent); + + // Validation: s'assurer que les données en cache ne sont pas du texte "Maintenance en cours" + if (typeof cacheData === 'string' && cacheData.includes('Maintenance en cours')) { + console.error(`Cache invalide détecté pour ${key} - contient "Maintenance en cours"`); + // Supprimer le cache invalide + try { + await fsp.unlink(cacheFilePath); + } catch (unlinkError) { } + return null; + } + + // Validation: s'assurer que les données en cache sont bien du JSON valide et pas du texte brut + if (typeof cacheData === 'string' || cacheData === null || cacheData === undefined) { + console.error(`Cache invalide détecté pour ${key} - données non-JSON ou nulles`); + try { + await fsp.unlink(cacheFilePath); + } catch (unlinkError) { } + return null; + } + + // Normaliser les URLs Anime-Sama dans les données du cache + const normalizedData = normalizeAnimeSamaUrls(cacheData); + + // Mettre en cache mémoire + await memoryCache.set(memKey, normalizedData); + + return normalizedData; + } catch (error) { + if (error.code === 'ENOENT') { + return null; + } + console.error(`Erreur lors de la récupération du cache pour ${key}:`, error); + return null; + } +}; + +// Fonction pour sauvegarder des données en cache +const saveToCache = async (cacheDir, key, data) => { + try { + const cacheFilePath = path.join(cacheDir, `${key}.json`); + + // OPTIMISATION: Utiliser write-file-atomic directement sans lockfile + // lockfile (utilisé dans safeWriteFile) ajoute 50-100ms de latence par écriture + // Pour des fichiers de cache temporaires, atomic write suffit largement + await writeFileAtomic(cacheFilePath, JSON.stringify(data), { encoding: 'utf8', fsync: false }); + + // Mettre aussi en cache mémoire pour éviter les lectures disque + await memoryCache.set(`${cacheDir}:${key}`, data); + return true; + } catch (error) { + console.error(`Erreur lors de la sauvegarde en cache pour ${key}:`, error); + return false; + } +}; + +// Déduplication des sources : préférer les liens avec m3u8 valide et langue MULTI quand disponible +const deduplicateSourcesWithPreference = (sources = []) => { + const normalizeLang = (value) => (typeof value === 'string' ? value.trim().toLowerCase() : ''); + + const mergeMissingFields = (main, other) => { + const merged = { ...main }; + for (const field of ['language', 'quality', 'sub', 'provider', 'm3u8', 'src']) { + if ((merged[field] === undefined || merged[field] === null || merged[field] === '') && other[field]) { + merged[field] = other[field]; + } + } + return merged; + }; + + const choosePreferred = (current, candidate) => { + if (!current) return { ...candidate }; + if (!candidate) return { ...current }; + + const currentLang = normalizeLang(current.language); + const candidateLang = normalizeLang(candidate.language); + + let winner = current; + let loser = candidate; + + if (!current.m3u8 && candidate.m3u8) { + winner = candidate; + loser = current; + } else if (current.m3u8 && !candidate.m3u8) { + winner = current; + loser = candidate; + } else if (candidateLang === 'multi' && currentLang !== 'multi') { + winner = candidate; + loser = current; + } else if (currentLang === 'multi' && candidateLang !== 'multi') { + winner = current; + loser = candidate; + } else if (!current.language && candidate.language) { + winner = candidate; + loser = current; + } + + return mergeMissingFields(winner, loser); + }; + + const byKey = new Map(); + for (const source of sources) { + if (!source) continue; + const key = source.m3u8 || source.src; + if (!key) continue; + const existing = byKey.get(key); + const chosen = choosePreferred(existing, source); + byKey.set(key, chosen); + } + + const bySrc = new Map(); + const result = []; + for (const entry of byKey.values()) { + const srcKey = entry.src || entry.m3u8; + if (!srcKey) continue; + const existing = bySrc.get(srcKey); + const chosen = choosePreferred(existing, entry); + bySrc.set(srcKey, chosen); + if (!existing) { + result.push(chosen); + } else { + const index = result.findIndex(item => (item.src || item.m3u8) === srcKey); + if (index !== -1) { + result[index] = chosen; + } + } + } + + return result; +}; + +// Fonction pour vérifier si une donnée FStream est en cache +const getFStreamFromCache = async (cacheKey) => { + try { + const cacheFilePath = path.join(CACHE_DIR.FSTREAM, `${cacheKey}.json`); + const cacheData = JSON.parse(await fsp.readFile(cacheFilePath, 'utf8')); + + + return cacheData.data; + } catch (error) { + if (error.code === 'ENOENT') { + return null; + } + console.error(`[FSTREAM CACHE] Erreur lors de la récupération du cache pour ${cacheKey}:`, error); + return null; + } +}; + +// === CACHE EN MÉMOIRE POUR ÉVITER LES REQUÊTES DUPLIQUÉES === +// Map pour stocker les promesses en cours d'exécution +const ongoingFStreamRequests = new Map(); + +// Fonction pour obtenir ou créer une requête FStream partagée +const getOrCreateFStreamRequest = async (cacheKey, requestFunction) => { + // Si une requête est déjà en cours pour cette clé, retourner la promesse existante + if (ongoingFStreamRequests.has(cacheKey)) { + const existingPromise = ongoingFStreamRequests.get(cacheKey); + + // Appliquer un timeout global de 6 secondes même pour les promesses partagées + return Promise.race([ + existingPromise, + new Promise((_, reject) => { + setTimeout(() => { + reject(new Error('timeout of 6000ms exceeded')); + }, 8000); + }) + ]); + } + + // Créer une nouvelle promesse et la stocker + const requestPromise = (async () => { + try { + // Appliquer un timeout global de 6 secondes + const result = await Promise.race([ + requestFunction(), + new Promise((_, reject) => { + setTimeout(() => { + reject(new Error('timeout of 6000ms exceeded')); + }, 8000 + ); + }) + ]); + return result; + } finally { + // Nettoyer la promesse une fois terminée (succès ou échec) + ongoingFStreamRequests.delete(cacheKey); + } + })(); + + // Stocker la promesse + ongoingFStreamRequests.set(cacheKey, requestPromise); + + return await requestPromise; +}; + +// Nettoyage automatique des requêtes expirées (toutes les 5 minutes) +setInterval(() => { + const now = Date.now(); + let cleaned = 0; + + // Parcourir et nettoyer les entrées qui pourraient être "coincées" + for (const [key, promise] of ongoingFStreamRequests) { + // Si la promesse existe depuis plus de 10 minutes, la supprimer + if (promise.createdAt && (now - promise.createdAt > 10 * 60 * 1000)) { + ongoingFStreamRequests.delete(key); + cleaned++; + } + } + + if (cleaned > 0) { + console.log(`[FSTREAM DEDUP] Nettoyage automatique: ${cleaned} requêtes expirées supprimées`); + } +}, 5 * 60 * 1000); // Toutes les 5 minutes + +// Fonction pour sauvegarder des données FStream en cache +const saveFStreamToCache = async (cacheKey, data) => { + try { + const cacheFilePath = path.join(CACHE_DIR.FSTREAM, `${cacheKey}.json`); + const cacheData = { + data: data + }; + + // Utiliser l'écriture atomique pour les fichiers de cache FStream + await writeFileAtomic(cacheFilePath, JSON.stringify(cacheData), 'utf8'); + // Mettre aussi en cache mémoire + await memoryCache.set(`fstream:${cacheKey}`, cacheData); + return true; + } catch (error) { + console.error(`[FSTREAM CACHE] Erreur lors de la sauvegarde en cache pour ${cacheKey}:`, error); + return false; + } +}; + +// Fonction pour générer une clé de cache FStream +const generateFStreamCacheKey = (type, id, season = null, episode = null) => { + const params = { type, id, season, episode }; + return crypto.createHash('md5').update(JSON.stringify(params)).digest('hex'); +}; + +// Fonction pour nettoyer le cache FStream +const clearFStreamCache = async () => { + try { + const cacheDir = CACHE_DIR.FSTREAM; + const files = await fsp.readdir(cacheDir); + + for (const file of files) { + if (file.endsWith('.json')) { + await fsp.unlink(path.join(cacheDir, file)); + } + } + + return { success: true, deletedFiles: files.length }; + } catch (error) { + console.error(`[FSTREAM CACHE] Erreur lors du nettoyage: ${error.message}`); + return { success: false, error: error.message }; + } +}; + + +const app = express(); +const PORT = 25565; + +// Initialize Socket.IO later in the startServer function +let io; + +// Enable gzip compression for all responses +app.use(compression({ + level: 1, // Balanced compression level (1-9, higher = more compression, slower) + threshold: 1024, // Only compress responses > 1KB + filter: (req, res) => { + // Don't compress if client doesn't accept it + if (req.headers['x-no-compression']) return false; + return compression.filter(req, res); + } +})); + +// Cors Configuration (Restricted in production) +app.use(cors({ + origin: (origin, callback) => { + const allowedDomains = [ + 'movix.blog', + 'movix.club', + 'movix.site', + 'movix11.pages.dev', + 'nakios.site', + 'cinezo.site' + ]; + + // Allow requests with no origin (like mobile apps or curl requests) + if (!origin) return callback(null, true); + + // Allow all localhost requests (http and https) + if (origin.match(/^https?:\/\/localhost(:[0-9]+)?$/)) { + return callback(null, true); + } + + // Check if origin matches allowed domains (allows http, https, and subdomains) + const isAllowed = allowedDomains.some(domain => { + // Allow exact match (http/s) or subdomain + return origin === `https://${domain}` || + origin === `http://${domain}` || + origin.endsWith(`.${domain}`); + }); + + if (isAllowed) { + callback(null, true); + } else { + callback(new Error('Not allowed by CORS')); + } + }, + methods: ['GET', 'POST', 'OPTIONS', 'PUT', 'DELETE', 'PATCH', 'HEAD'], + allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Accept', 'Origin', 'X-No-Compression', 'Access-Control-Request-Headers', 'baggage', 'sentry-trace', 'x-profile-id', 'x-access-key'], + credentials: true, + optionsSuccessStatus: 204 +})); + +// Security headers (minimal set — replaces Helmet) +app.use((req, res, next) => { + res.setHeader('X-Content-Type-Options', 'nosniff'); + res.setHeader('X-Frame-Options', 'DENY'); + res.setHeader('X-XSS-Protection', '0'); // Disabled per OWASP recommendation (use CSP instead) + res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin'); + res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()'); + next(); +}); + +// Middleware pour ajouter les headers Keep-Alive +app.use((req, res, next) => { + res.setHeader('Connection', 'keep-alive'); + res.setHeader('Keep-Alive', 'timeout=60, max=1000'); + next(); +}); + +// Middleware de restriction de domaine et réponse fake pour route spécifique +app.use((req, res, next) => { + // Autoriser les endpoints LiveTV pour l'extension + if (req.path.startsWith('/api/livetv/')) { + return next(); + } + + const allowedDomains = [ + 'localhost:3000', + 'movix.blog', + 'movix.club', + 'movix.site', + 'movix11.pages.dev', + 'nakios.site', + 'cinezo.site' + ]; + + const origin = req.get('origin'); + const referer = req.get('referer'); + + let isAllowed = false; + + // Strict domain verification + const checkDomain = (url) => { + try { + if (!url) return false; + const hostname = new URL(url).hostname; + // Allow exact matches or subdomains if needed (here we list full domains) + return allowedDomains.some(domain => { + // Handle localhost with port special case if needed, or just match hostname + if (domain.includes(':')) return url.includes(domain); + return hostname === domain || hostname.endsWith('.' + domain); + }); + } catch (e) { + return false; + } + }; + + if (origin) { + if (checkDomain(origin)) isAllowed = true; + } else if (referer) { + if (checkDomain(referer)) isAllowed = true; + } + + // Si autorisé, on continue + if (isAllowed) { + return next(); + } + + // Si non autorisé + // Route spécifique accessible mais avec fausse réponse + if (req.path.startsWith('/api/imdb/movie')) { + return res.json({ + "iframe_src": "https://movixfakesite.vercel.app/", + "player_links": [ + { + "player": "supervideo", + "link": "https://movixfakesite.vercel.app/", + "is_hd": false + }, + { + "player": "dropload", + "link": "https://movixfakesite.vercel.app/", + "is_hd": false + }, + { + "player": "mixdrop", + "link": "https://movixfakesite.vercel.app/", + "is_hd": false + } + ] + }); + } else if (req.path.startsWith('/api/imdb/tv')) { + return res.json({ + "type": "tv", + "series": [ + { + "title": "Stranger Things - Saison 5", + "audio_type": "VF", + "episode_count": 1, + "release_date": "2016", + "summary": "Quand un jeune garçon disparaît, une petite ville découvre une affaire mystérieuse, des expériences secrètes, des forces surnaturelles terrifiantes... et une fillette.", + "tmdb_data": { + "id": 66732, + "name": "Stranger Things", + "overview": "When a young boy vanishes, a small town uncovers a mystery involving secret experiments, terrifying supernatural forces, and one strange little girl.", + "first_air_date": "2016-07-15", + "poster_path": "/uOOtwVbSr4QDjAGIifLDwpb2Pdl.jpg", + "backdrop_path": "/8zbAoryWbtH0DKdev8abFAjdufy.jpg", + "vote_average": 8.59, + "match_score": 0.8818181818181817 + }, + "seasons": [ + { + "number": 1, + "title": "Saison 1", + "episodes": [ + { + "number": "1", + "versions": { + "vf": { + "title": "Episode 1", + "players": [ + { + "name": "Supervideo", + "link": "https://movixfakesite.vercel.app/" + } + ] + } + } + } + ] + } + ] + } + ] + }); + } + + // Bloquer toutes les autres routes + return res.status(404).json({ error: 'Not Found' }); +}); + +app.use(express.json({ limit: '30mb' })); // Reduced from 1000mb to prevent abuse + +// Error handler for JSON parsing errors (malformed requests like URL-encoded form data) +app.use((err, req, res, next) => { + if (err.type === 'entity.parse.failed') { + // Silently handle malformed JSON requests (likely bots or scanners) + return res.status(400).json({ + success: false, + error: 'Invalid JSON body' + }); + } + next(err); +}); + + +// Configuration de la connexion MySQL +const dbConfig = { + host: process.env.DB_HOST, + port: parseInt(process.env.DB_PORT || '3306'), + user: process.env.DB_USER, + password: process.env.DB_PASSWORD, + database: process.env.DB_NAME, + waitForConnections: true, + connectionLimit: 300, + queueLimit: 0, + enableKeepAlive: true, + keepAliveInitialDelay: 0 +}; + +// Pool de connexions MySQL +let pool; +(async () => { + try { + pool = mysql.createPool(dbConfig); + console.log('✅ MySQL connection pool created successfully'); + + // Test de connexion + const connection = await pool.getConnection(); + console.log('✅ MySQL connection test successful'); + connection.release(); + + // Créer la table user_sessions si elle n'existe pas + await pool.execute(` + CREATE TABLE IF NOT EXISTS user_sessions ( + id VARCHAR(255) PRIMARY KEY, + user_id VARCHAR(255) NOT NULL, + user_type ENUM('oauth', 'bip39') NOT NULL, + device TEXT, + user_agent TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + accessed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + INDEX idx_user_sessions_user (user_id, user_type), + INDEX idx_user_sessions_accessed (accessed_at) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci + `); + console.log('✅ Table user_sessions initialized successfully'); + + // Initialiser le pool partagé pour les routes de commentaires + const { initPool } = require('./mysqlPool'); + await initPool(); + console.log('✅ MySQL shared pool for comments initialized successfully'); + + // Initialize Wishboard routes + const { createWishboardRouter } = require('./wishboardRoutes'); + const wishboardRouter = createWishboardRouter(pool, redis); + app.use('/api/wishboard', wishboardRouter); + app.use('/api/admin/wishboard', wishboardRouter); + console.log('✅ Wishboard routes initialized successfully'); + + // Initialize Link Submissions routes (user-submitted streaming links) + const { createLinkSubmissionsRouter } = require('./linkSubmissionsRoutes'); + const linkSubmissionsRouter = createLinkSubmissionsRouter(pool, redis); + app.use('/api/link-submissions', linkSubmissionsRouter); + // Create link_submissions table if not exists + await pool.execute(` + CREATE TABLE IF NOT EXISTS link_submissions ( + id INT AUTO_INCREMENT PRIMARY KEY, + user_id VARCHAR(255) NOT NULL, + profile_id VARCHAR(255) NOT NULL, + tmdb_id INT NOT NULL, + media_type ENUM('movie', 'tv') NOT NULL, + season_number INT DEFAULT NULL, + episode_number INT DEFAULT NULL, + url VARCHAR(2048) NOT NULL, + source_name VARCHAR(100) DEFAULT NULL, + status ENUM('pending', 'approved', 'rejected') DEFAULT 'pending', + rejection_reason TEXT DEFAULT NULL, + reviewed_by VARCHAR(255) DEFAULT NULL, + reviewed_at DATETIME DEFAULT NULL, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + INDEX idx_ls_status (status), + INDEX idx_ls_profile (profile_id), + INDEX idx_ls_tmdb (tmdb_id, media_type), + INDEX idx_ls_created (created_at) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci + `); + console.log('✅ Link Submissions routes initialized successfully'); + + // Initialize Top 10 routes (public ranking) + const { router: top10Router, initTop10Routes } = require('./top10Routes'); + initTop10Routes(pool, redis); + app.use('/api/top10', top10Router); + console.log('✅ Top 10 routes initialized successfully'); + + // Initialize Wrapped routes (Movix Wrapped 2026 data collection) + const { router: wrappedRouter, initWrappedRoutes, initTables: initWrappedTables } = require('./wrappedRoutes'); + initWrappedRoutes(pool, redis); + await initWrappedTables(); + app.use('/api/wrapped', wrappedRouter); + console.log('✅ Wrapped routes initialized successfully'); + } catch (error) { + console.error('❌ MySQL connection error:', error.message); + } +})(); + +// Middleware pour vérifier si l'utilisateur est admin +async function isAdmin(req, res, next) { + try { + // Vérifier si le pool MySQL est initialisé + if (!pool) { + console.error('❌ MySQL pool not initialized'); + return res.status(503).json({ success: false, error: 'Service temporairement indisponible - Base de données en cours d\'initialisation' }); + } + + // Vérifier le JWT + const auth = await getAuthIfValid(req); + if (!auth) { + return res.status(401).json({ success: false, error: 'Non autorisé - Token invalide' }); + } + + const { userId, userType } = auth; + + // Vérifier si l'utilisateur est dans la table admins + const [rows] = await pool.execute( + 'SELECT * FROM admins WHERE user_id = ? AND auth_type = ?', + [userId, userType === 'bip39' ? 'bip-39' : userType] + ); + + if (rows.length === 0) { + return res.status(403).json({ success: false, error: 'Accès refusé - Droits admin requis' }); + } + + // Récupérer le rôle (par défaut 'admin' si non défini) + const role = rows[0].role || 'admin'; + + // Ajouter les infos admin à la requête (avec le rôle) + req.admin = { userId, userType, adminId: rows[0].id, role }; + next(); + } catch (error) { + console.error('❌ Admin verification error:', error); + return res.status(500).json({ success: false, error: 'Erreur lors de la vérification admin' }); + } +} + +// Middleware pour vérifier si l'utilisateur est uploader ou admin (pour les liens de streaming) +async function isUploaderOrAdmin(req, res, next) { + try { + // Vérifier si le pool MySQL est initialisé + if (!pool) { + console.error('❌ MySQL pool not initialized'); + return res.status(503).json({ success: false, error: 'Service temporairement indisponible - Base de données en cours d\'initialisation' }); + } + + // Vérifier le JWT + const auth = await getAuthIfValid(req); + if (!auth) { + return res.status(401).json({ success: false, error: 'Non autorisé - Token invalide' }); + } + + const { userId, userType } = auth; + + // Vérifier si l'utilisateur est dans la table admins (admin ou uploader) + const [rows] = await pool.execute( + 'SELECT * FROM admins WHERE user_id = ? AND auth_type = ?', + [userId, userType === 'bip39' ? 'bip-39' : userType] + ); + + if (rows.length === 0) { + return res.status(403).json({ success: false, error: 'Accès refusé - Droits requis' }); + } + + // Récupérer le rôle (par défaut 'admin' si non défini) + const role = rows[0].role || 'admin'; + + // Autoriser les rôles 'admin' et 'uploader' + if (role !== 'admin' && role !== 'uploader') { + return res.status(403).json({ success: false, error: 'Accès refusé - Droits insuffisants' }); + } + + // Ajouter les infos admin à la requête (avec le rôle) + req.admin = { userId, userType, adminId: rows[0].id, role }; + next(); + } catch (error) { + console.error('❌ Admin/Uploader verification error:', error); + return res.status(500).json({ success: false, error: 'Erreur lors de la vérification des droits' }); + } +} + + +async function getAuthIfValid(req) { + try { + const authHeader = req.headers['authorization'] || req.headers['Authorization']; + if (!authHeader || !authHeader.toLowerCase().startsWith('bearer ')) return null; + const token = authHeader.split(' ')[1]; + const payload = jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] }); + const { userType, sub: userId, sessionId } = payload; + if (!['oauth', 'bip39'].includes(userType) || !userId || !sessionId) return null; + + // Vérification de session via MySQL avec 3 tentatives + let hasSession = false; + + for (let attempt = 1; attempt <= 3; attempt++) { + try { + if (!pool) { + console.warn('[AUTH] MySQL pool not ready, attempt', attempt); + if (attempt < 3) { + await new Promise(resolve => setTimeout(resolve, 500)); + continue; + } + return null; + } + + const [rows] = await pool.execute( + 'SELECT id FROM user_sessions WHERE id = ? AND user_id = ? AND user_type = ?', + [sessionId, userId, userType] + ); + hasSession = rows.length > 0; + + if (hasSession) { + break; // Session trouvée, sortir de la boucle + } + + if (attempt < 3) { + console.log(`[AUTH] Tentative ${attempt}/3 échouée pour userType=${userType}, userId=${userId}, sessionId=${sessionId} - nouvelle tentative dans 0.5s`); + await new Promise(resolve => setTimeout(resolve, 500)); + } + } catch (error) { + console.error(`[AUTH] Erreur lors de la tentative ${attempt}/3:`, error.message); + if (attempt < 3) { + await new Promise(resolve => setTimeout(resolve, 500)); + } + } + } + + if (!hasSession) { + console.warn(`[AUTH] Session manquante après 3 tentatives pour userType=${userType}, userId=${userId}, sessionId=${sessionId}`); + return null; + } + + // Update last access as activity signal (fire-and-forget, pas de await) + updateSessionAccess(userType, userId, sessionId); + return { userType, userId, sessionId }; + } catch { + return null; + } +} + + +app.use(express.urlencoded({ extended: true, limit: '5mb' })); // Reduced from 1000mb to prevent abuse + +// Routes de commentaires +const commentsRoutes = require('./commentsRoutes'); +app.use('/api/comments', commentsRoutes); + +// Routes de likes +const likesRoutes = require('./likesRoutes'); +app.use('/api/likes', likesRoutes); + +// Routes Shared Lists (Listes partagées) +const sharedListsRoutes = require('./sharedListsRoutes'); +app.use('/api/shared-lists', sharedListsRoutes); + +// Routes Live TV (TV en Direct) +const liveTvRoutes = require('./liveTvRoutes'); +app.use('/api/livetv', liveTvRoutes); + +// Routes Cpasmal +// Helper to sort links +function sortCpasmalLinks(links) { + const priority = ['voe', 'uqload']; + return links.sort((a, b) => { + const indexA = priority.indexOf(a.server); + const indexB = priority.indexOf(b.server); + + if (indexA !== -1 && indexB !== -1) return indexA - indexB; + if (indexA !== -1) return -1; + if (indexB !== -1) return 1; + return 0; + }); +} + +// Helper to get TMDB details +async function getTmdbDetails(tmdbId, type) { + try { + const url = `${TMDB_API_URL}/${type}/${tmdbId}?api_key=${TMDB_API_KEY}&language=fr-FR`; + const response = await axios.get(url); + return response.data; + } catch (error) { + console.error(`Error fetching TMDB details for ${type}/${tmdbId}:`, error.message); + return null; + } +} + +// Helper to search on Cpasmal +// Scores search results from a single search query and returns { bestMatch, bestScore } +function _scoreCpasmalResults($, items, title, year, type, normalize) { + let bestMatch = null; + let bestScore = -1; + + items.each((i, el) => { + const $el = $(el); + const link = $el.find('a.th-img').attr('href'); + const titleText = $el.find('.th-desc .th-capt').text().trim(); + const yearText = $el.find('.th-desc .th-year').text().trim(); + const isSerie = $el.find('.th-Serie').length > 0; + const isMovie = $el.find('.th-Film').length > 0; + + // Check type - strict filtering + if (type === 'movie' && !isMovie) return; + if (type === 'tv' && !isSerie) return; + + const normTitle = normalize(title); + const normTitleText = normalize(titleText); + + // Calculate match score + let score = 0; + let titleMatchQuality = 'none'; // Track title match quality for year bonus scaling + + // Exact title match (highest priority) - 100 points + if (normTitleText === normTitle) { + score += 100; + titleMatchQuality = 'exact'; + } + // Title starts with search term (good match) - score depends on length ratio + else if (normTitleText.startsWith(normTitle + ' ')) { + const lengthRatio = normTitle.length / normTitleText.length; + if (lengthRatio >= 0.75) { + score += 50; + titleMatchQuality = 'strong'; + } else if (lengthRatio >= 0.60) { + score += 25; + titleMatchQuality = 'moderate'; + } else { + score += 5; + titleMatchQuality = 'weak'; + } + } + // Title ends with search term - score depends on length ratio (like "starts with") + else if (normTitleText.endsWith(' ' + normTitle)) { + const lengthRatio = normTitle.length / normTitleText.length; + if (lengthRatio >= 0.75) { + score += 50; + titleMatchQuality = 'strong'; + } else if (lengthRatio >= 0.60) { + score += 25; + titleMatchQuality = 'moderate'; + } else { + score += 5; + titleMatchQuality = 'weak'; + } + } + // Search term is contained but not at start/end (likely a different movie) - 5 points + else if (normTitleText.includes(normTitle)) { + score += 5; + titleMatchQuality = 'weak'; + } + // Search term contains the result title (less likely to be correct) - 3 points + else if (normTitle.includes(normTitleText)) { + score += 3; + titleMatchQuality = 'weak'; + } + // No match at all - skip + else { + return; + } + + // Year matching bonus points - scaled by title match quality + if (year && yearText) { + const yearDiff = Math.abs(parseInt(yearText) - parseInt(year)); + const isWeakTitle = (titleMatchQuality === 'weak'); + if (yearDiff === 0) { + score += isWeakTitle ? 10 : 50; + } else if (yearDiff === 1) { + score += isWeakTitle ? 5 : 20; + } else if (yearDiff > 5) { + score -= 30; + } else { + score -= 10; + } + } + + if (process.env.DEBUG_CPASMAL) { + console.log(`[Cpasmal] Candidate: "${titleText}" (${yearText}) - Score: ${score}`); + } + + if (score > bestScore && score > 0) { + bestScore = score; + bestMatch = link; + } + }); + + return { bestMatch, bestScore }; +} + +// Run a single cpasmal search query across multiple pages, return { bestMatch, bestScore } +async function _runCpasmalSearch(searchQuery, title, year, type, normalize, maxPages) { + let bestMatch = null; + let bestScore = -1; + let page = 1; + + while (page <= maxPages) { + try { + const searchUrl = `${CPASMAL_BASE_URL}/index.php?do=search&subaction=search&search_start=${page}&full_search=0&story=${encodeURIComponent(searchQuery)}`; + const response = await axiosCpasmalRequest({ method: 'get', url: searchUrl }); + const $ = cheerio.load(response.data); + + const items = $('div.thumb'); + if (items.length === 0) break; + + const result = _scoreCpasmalResults($, items, title, year, type, normalize); + if (result.bestScore > bestScore) { + bestScore = result.bestScore; + bestMatch = result.bestMatch; + } + + // If we already found an exact match, no need to search more pages + if (bestScore >= 100) break; + + page++; + } catch (error) { + console.error(`Error searching Cpasmal page ${page}:`, error.message); + break; + } + } + + return { bestMatch, bestScore }; +} + +async function searchCpasmal(title, year, type) { + // Prepare search query: normalize spaces (remove non-breaking spaces) and keep colons + let searchQuery = title.replace(/\u00A0/g, ' ').replace(/\s+/g, ' ').trim(); + + // Normalize function for title comparison + const normalize = (str) => str.toLowerCase().replace(/[:\s\-.,!?'"()]+/g, ' ').replace(/\s+/g, ' ').trim(); + + if (process.env.DEBUG_CPASMAL) console.time(`[Cpasmal] Search ${title}`); + + // === Strategy 1: Search by title only (2 pages) === + let { bestMatch, bestScore } = await _runCpasmalSearch(searchQuery, title, year, type, normalize, 2); + + if (process.env.DEBUG_CPASMAL) { + console.log(`[Cpasmal] Strategy 1 (title only "${searchQuery}"): best score = ${bestScore}`); + } + + // === Strategy 2: If no good match, retry with "title year" to narrow results === + // This helps for generic titles like "Urgences" where the search returns thematically + // related results instead of the exact show + if (bestScore < 20 && year) { + const searchQueryWithYear = `${searchQuery} ${year}`; + if (process.env.DEBUG_CPASMAL) { + console.log(`[Cpasmal] Strategy 2: retrying with "${searchQueryWithYear}"`); + } + const result2 = await _runCpasmalSearch(searchQueryWithYear, title, year, type, normalize, 1); + if (result2.bestScore > bestScore) { + bestScore = result2.bestScore; + bestMatch = result2.bestMatch; + } + if (process.env.DEBUG_CPASMAL) { + console.log(`[Cpasmal] Strategy 2 (title+year "${searchQueryWithYear}"): best score = ${bestScore}`); + } + } + + // === Strategy 3: If still no good match, try full_search=1 (exact title match mode) === + if (bestScore < 20) { + if (process.env.DEBUG_CPASMAL) { + console.log(`[Cpasmal] Strategy 3: retrying with full_search=1`); + } + try { + const fullSearchUrl = `${CPASMAL_BASE_URL}/index.php?do=search&subaction=search&search_start=1&full_search=1&story=${encodeURIComponent(searchQuery)}`; + const response = await axiosCpasmalRequest({ method: 'get', url: fullSearchUrl }); + const $ = cheerio.load(response.data); + const items = $('div.thumb'); + if (items.length > 0) { + const result3 = _scoreCpasmalResults($, items, title, year, type, normalize); + if (result3.bestScore > bestScore) { + bestScore = result3.bestScore; + bestMatch = result3.bestMatch; + } + } + } catch (error) { + console.error(`Error in Cpasmal full_search:`, error.message); + } + if (process.env.DEBUG_CPASMAL) { + console.log(`[Cpasmal] Strategy 3 (full_search=1): best score = ${bestScore}`); + } + } + + if (process.env.DEBUG_CPASMAL) { + console.timeEnd(`[Cpasmal] Search ${title}`); + console.log(`[Cpasmal] Final best match score: ${bestScore}`); + } + + // Only return a match if the score is high enough (at least 20 points) + // This filters out poor matches like "The King's Avatar" for "Avatar" + return bestScore >= 20 ? bestMatch : null; +} + +// Helper to extract links from a movie page +async function extractMovieLinks(url) { + if (process.env.DEBUG_CPASMAL) console.time(`[Cpasmal] ExtractMovieLinks ${url}`); + try { + const response = await axiosCpasmalRequest({ method: 'get', url: url }); + const $ = cheerio.load(response.data); + const links = { vf: [], vostfr: [] }; + let cpasmalYear = null; + + // Extraire l'année de sortie depuis la page cpasmal + // XPath: /html/body/div[1]/div/div[2]/div/main/div/div/article/div[2]/div[2]/ul/li[2] + // Chercher dans la liste des infos pour "Date de sortie" + $('article ul li').each((i, el) => { + const $el = $(el); + const infoLabel = $el.find('span.info').text().trim().toLowerCase(); + if (infoLabel.includes('date de sortie') || infoLabel.includes('année') || infoLabel.includes('annee')) { + const infoValue = $el.find('span.infos').text().trim(); + const yearMatch = infoValue.match(/(\d{4})/); + if (yearMatch) { + cpasmalYear = yearMatch[1]; + } + } + }); + + // Si pas trouvé, chercher avec d'autres sélecteurs + if (!cpasmalYear) { + const infosList = $('div.content-info ul li, div.shortpost-info ul li, .fx-info ul li'); + infosList.each((i, el) => { + const text = $(el).text().toLowerCase(); + if (text.includes('date de sortie') || text.includes('année') || text.includes('annee')) { + const yearMatch = text.match(/(\d{4})/); + if (yearMatch) { + cpasmalYear = yearMatch[1]; + } + } + }); + } + + if (process.env.DEBUG_CPASMAL) { + console.log(`[Cpasmal] Extracted year from page: ${cpasmalYear}`); + } + + const linkElements = $('.liens-c .lien'); + + // Collect all tasks first + const tasks = []; + + for (let i = 0; i < linkElements.length; i++) { + const el = linkElements[i]; + const onclick = $(el).attr('onclick'); + // onclick="getxfield('22847', 'netu_vostfr', 'be4b6239bc8f19d5832c98acfe10ba78'); return false;" + if (onclick && onclick.includes('getxfield')) { + const match = onclick.match(/getxfield\('([^']*)',\s*'([^']*)',\s*'([^']*)'\)/); + if (match) { + const [_, id, xfield, token] = match; + const isVostfr = xfield.includes('vostfr'); + const isVf = xfield.includes('vf'); + + // Prepare the task + const ajaxUrl = `${CPASMAL_BASE_URL}/engine/ajax/getxfield.php?id=${id}&xfield=${xfield}&token=${token}`; + tasks.push({ ajaxUrl, xfield, isVostfr, isVf }); + } + } + } + + // Execute requests in batches to avoid Event Loop blocking + const results = []; + const BATCH_SIZE = 3; // Réduit de 5 à 3 pour moins de charge + + for (let i = 0; i < tasks.length; i += BATCH_SIZE) { + const batch = tasks.slice(i, i + BATCH_SIZE); + const batchResults = await Promise.all(batch.map(async (task) => { + await acquireCpasmalSlot(); // Attendre un slot disponible + try { + const ajaxResponse = await axiosCpasmalRequest({ method: 'get', url: task.ajaxUrl }); + const iframeMatch = ajaxResponse.data.match(/src="([^"]+)"/); + if (iframeMatch) { + return { + server: task.xfield.split('_')[0], + url: iframeMatch[1], + isVostfr: task.isVostfr, + isVf: task.isVf + }; + } + return null; + } catch (err) { + console.error(`Error fetching link for ${task.xfield}:`, err.message); + return null; + } finally { + releaseCpasmalSlot(); // Libérer le slot + } + })); + results.push(...batchResults); + // Délai augmenté pour laisser respirer l'event loop (50ms -> 300ms) + if (i + BATCH_SIZE < tasks.length) await new Promise(resolve => setTimeout(resolve, 300)); + } + + // Process results + for (const result of results) { + if (result) { + const linkData = { server: result.server, url: result.url }; + if (result.isVostfr) links.vostfr.push(linkData); + if (result.isVf) links.vf.push(linkData); + } + } + + links.vf = sortCpasmalLinks(links.vf); + links.vostfr = sortCpasmalLinks(links.vostfr); + if (process.env.DEBUG_CPASMAL) { + console.timeEnd(`[Cpasmal] ExtractMovieLinks ${url}`); + console.log(`[Cpasmal] Found ${links.vf.length} VF and ${links.vostfr.length} VOSTFR links`); + } + return { links, cpasmalYear }; + } catch (error) { + console.error('Error extracting movie links:', error.message); + return { links: { vf: [], vostfr: [] }, cpasmalYear: null }; + } +} + +// Helper to extract links from a series episode +async function extractSeriesLinks(seriesUrl, seasonNumber, episodeNumber) { + if (process.env.DEBUG_CPASMAL) console.time(`[Cpasmal] ExtractSeriesLinks ${seriesUrl}`); + try { + const response = await axiosCpasmalRequest({ method: 'get', url: seriesUrl }); + let $ = cheerio.load(response.data); + + // Find season link + let seasonUrl = null; + $('.th-seas').each((i, el) => { + const text = $(el).find('.th-count').text().trim(); // "saison 2" + if (text.toLowerCase().includes(`saison ${seasonNumber}`)) { + seasonUrl = $(el).closest('a').attr('href'); + } + }); + + if (!seasonUrl) { + return { vf: [], vostfr: [] }; + } + + // Construct episode URL + const episodeUrl = `${seasonUrl.replace('.html', '')}/${episodeNumber}-episode.html`; + + // Fetch episode page + const epResponse = await axiosCpasmalRequest({ method: 'get', url: episodeUrl }); + $ = cheerio.load(epResponse.data); + + const links = { vf: [], vostfr: [] }; + const linkElements = $('.liens-c .lien'); + + // Collect all tasks first + const tasks = []; + + for (let i = 0; i < linkElements.length; i++) { + const el = linkElements[i]; + const onclick = $(el).attr('onclick'); + // onclick="playEpisode(this, '129422', 'netu_vf')" + if (onclick && onclick.includes('playEpisode')) { + const match = onclick.match(/playEpisode\(this,\s*'([^']*)',\s*'([^']*)'\)/); + if (match) { + const [_, id, xfield] = match; + const isVostfr = xfield.includes('vostfr'); + const isVf = xfield.includes('vf'); + + // Post data + const ajaxUrl = `${CPASMAL_BASE_URL}/engine/inc/serial/app/ajax/Season.php`; + const params = new URLSearchParams(); + params.append('id', id); + params.append('xfield', xfield); + params.append('action', 'playEpisode'); + + tasks.push({ ajaxUrl, data: params.toString(), xfield, isVostfr, isVf }); + } + } + } + + // Execute requests in batches + const results = []; + const BATCH_SIZE = 3; // Réduit de 5 à 3 pour moins de charge + + for (let i = 0; i < tasks.length; i += BATCH_SIZE) { + const batch = tasks.slice(i, i + BATCH_SIZE); + const batchResults = await Promise.all(batch.map(async (task) => { + await acquireCpasmalSlot(); // Attendre un slot disponible + try { + const ajaxResponse = await axiosCpasmalRequest({ + method: 'post', + url: task.ajaxUrl, + data: task.data, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-Requested-With': 'XMLHttpRequest' + } + }); + + const iframeMatch = ajaxResponse.data.match(/src="([^"]+)"/); + if (iframeMatch) { + return { + server: task.xfield.split('_')[0], + url: iframeMatch[1], + isVostfr: task.isVostfr, + isVf: task.isVf + }; + } + return null; + } catch (err) { + console.error(`Error fetching link for ${task.xfield}:`, err.message); + return null; + } finally { + releaseCpasmalSlot(); // Libérer le slot + } + })); + results.push(...batchResults); + // Délai augmenté pour laisser respirer l'event loop (50ms -> 300ms) + if (i + BATCH_SIZE < tasks.length) await new Promise(resolve => setTimeout(resolve, 300)); + } + + // Process results + for (const result of results) { + if (result) { + const linkData = { server: result.server, url: result.url }; + if (result.isVostfr) links.vostfr.push(linkData); + if (result.isVf) links.vf.push(linkData); + } + } + + links.vf = sortCpasmalLinks(links.vf); + links.vostfr = sortCpasmalLinks(links.vostfr); + if (process.env.DEBUG_CPASMAL) { + console.timeEnd(`[Cpasmal] ExtractSeriesLinks ${seriesUrl}`); + console.log(`[Cpasmal] Found ${links.vf.length} VF and ${links.vostfr.length} VOSTFR links`); + } + return links; + + } catch (error) { + console.error('Error extracting series links:', error.message); + return { vf: [], vostfr: [] }; + } +} + +// === DATA FETCHING FUNCTIONS === + +async function fetchCpasmalMovieData(tmdbId, throwOnError = true) { + const tmdbData = await getTmdbDetails(tmdbId, 'movie'); + if (!tmdbData) { + if (throwOnError) throw new Error('Movie not found on TMDB'); + return null; + } + + const title = tmdbData.title; + const tmdbYear = tmdbData.release_date ? tmdbData.release_date.split('-')[0] : null; + + const cpasmalUrl = await searchCpasmal(title, tmdbYear, 'movie'); + if (!cpasmalUrl) { + if (throwOnError) throw new Error('Movie not found on Cpasmal'); + return null; + } + + const { links, cpasmalYear } = await extractMovieLinks(cpasmalUrl); + + // Validation post-match : rejeter si l'année cpasmal ne correspond pas à l'année TMDB + if (cpasmalYear && tmdbYear && cpasmalYear !== tmdbYear) { + if (process.env.DEBUG_CPASMAL) { + console.log(`[Cpasmal] Post-match year mismatch: TMDB=${tmdbYear}, Cpasmal=${cpasmalYear} - rejecting match`); + } + if (throwOnError) throw new Error('Movie not found on Cpasmal (year mismatch)'); + return null; + } + + // Utiliser l'année de cpasmal si disponible, sinon celle de TMDB + const year = cpasmalYear || tmdbYear; + return { title, year, cpasmalUrl, links }; +} + +async function fetchCpasmalTvData(tmdbId, season, episode, throwOnError = true) { + const tmdbData = await getTmdbDetails(tmdbId, 'tv'); + if (!tmdbData) { + if (throwOnError) throw new Error('TV Show not found on TMDB'); + return null; + } + + const title = tmdbData.name; + const year = tmdbData.first_air_date ? tmdbData.first_air_date.split('-')[0] : null; + + const cpasmalUrl = await searchCpasmal(title, year, 'tv'); + if (!cpasmalUrl) { + if (throwOnError) throw new Error('TV Show not found on Cpasmal'); + return null; + } + + if (process.env.DEBUG_CPASMAL) console.log(`[Cpasmal] Start Search & Extract for Movie ${tmdbId}`); + const links = await extractSeriesLinks(cpasmalUrl, season, episode); + if (process.env.DEBUG_CPASMAL) console.log(`[Cpasmal] End Search & Extract for Movie ${tmdbId}`); + return { title, year, cpasmalUrl, links }; +} + +// === CPASMAL REQUEST DEDUPLICATION === +// Map pour stocker les promesses en cours d'exécution (éviter les requêtes dupliquées) +const ongoingCpasmalRequests = new Map(); + +// Fonction pour obtenir ou créer une requête Cpasmal partagée (évite de bloquer le serveur) +const getOrCreateCpasmalRequest = async (cacheKey, requestFunction) => { + // Si une requête est déjà en cours pour cette clé, retourner la promesse existante + if (ongoingCpasmalRequests.has(cacheKey)) { + return ongoingCpasmalRequests.get(cacheKey); + } + + // Créer une nouvelle promesse avec timeout global + const requestPromise = (async () => { + try { + const result = await Promise.race([ + requestFunction(), + new Promise((_, reject) => { + setTimeout(() => { + reject(new Error('Cpasmal request timeout')); + }, 15000); // 15s max pour toute la requête + }) + ]); + return result; + } finally { + // Nettoyer la promesse une fois terminée + ongoingCpasmalRequests.delete(cacheKey); + } + })(); + + ongoingCpasmalRequests.set(cacheKey, requestPromise); + return requestPromise; +}; + +// === BACKGROUND UPDATE === + +const updateCpasmalCache = async (cacheKey, type, ...args) => { + try { + // Vérifier si le cache doit être mis à jour + const shouldUpdate = await shouldUpdateCache(CACHE_DIR.CPASMAL, cacheKey); + if (!shouldUpdate) { + return; // Ne pas mettre à jour le cache s'il est récent + } + + // Récupérer le cache existant pour le préserver en cas d'erreur + const existingCache = await getFromCacheNoExpiration(CACHE_DIR.CPASMAL, cacheKey); + + let newData; + if (type === 'movie') { + newData = await fetchCpasmalMovieData(args[0], false); // throwOnError = false + } else if (type === 'tv') { + newData = await fetchCpasmalTvData(args[0], args[1], args[2], false); // throwOnError = false + } + + // Ne pas mettre à jour le cache si on n'a pas de nouvelles données ET qu'un cache existe déjà + if (!newData && existingCache) { + return; // Garder le cache existant + } + + if (newData) { + // Utilisation de fsp.writeFile direct au lieu de safeWriteJsonFile pour éviter atomic writes + await fsp.writeFile(path.join(CACHE_DIR.CPASMAL, `${cacheKey}.json`), JSON.stringify(newData), 'utf-8'); + await memoryCache.set(`cpasmal:${cacheKey}`, newData); + if (process.env.DEBUG_CPASMAL) console.log(`[Cpasmal Cache] Updated background cache for ${cacheKey}`); + } + } catch (error) { + // En cas d'erreur, ne pas toucher au cache existant + // console.error(`[Cpasmal Cache] Background update failed for ${cacheKey}:`, error.message); + } +}; + +app.get('/api/cpasmal/movie/:tmdbid', async (req, res) => { + const { tmdbid } = req.params; + const cacheKey = generateCacheKey(`movie_${tmdbid}`); + + if (process.env.DEBUG_CPASMAL) { + const used = process.memoryUsage().heapUsed / 1024 / 1024; + console.log(`[Cpasmal API] Start /movie/${tmdbid} - Memory: ${Math.round(used * 100) / 100} MB`); + console.time(`[Cpasmal API] Total /movie/${tmdbid}`); + } + + try { + // 1. Try cache + const cachedData = await getFromCacheNoExpiration(CACHE_DIR.CPASMAL, cacheKey); + if (cachedData) { + if (cachedData.notFound) { + res.status(404).json({ error: 'Movie not found on Cpasmal (Cached)' }); + } else { + res.json(cachedData); + } + + // Background update if old + const cacheFilePath = path.join(CACHE_DIR.CPASMAL, `${cacheKey}.json`); + try { + const stats = await fsp.stat(cacheFilePath); + const age = Date.now() - stats.mtime.getTime(); + if (age > 20 * 60 * 1000) { // 20 minutes + updateCpasmalCache(cacheKey, 'movie', tmdbid); + } + } catch (e) { /* ignore */ } + return; + } + + // 2. Fetch fresh with deduplication (prevents multiple simultaneous requests from blocking) + const data = await getOrCreateCpasmalRequest(cacheKey, () => fetchCpasmalMovieData(tmdbid, false)); + + if (!data) { + // Content not found - Cache this state because we had no cache before + const notFoundData = { notFound: true, tmdbId: tmdbid, timestamp: Date.now() }; + await fsp.writeFile(path.join(CACHE_DIR.CPASMAL, `${cacheKey}.json`), JSON.stringify(notFoundData), 'utf-8'); + if (process.env.DEBUG_CPASMAL) console.log(`[Cpasmal API] Caching 'Not Found' for /movie/${tmdbid}`); + if (process.env.DEBUG_CPASMAL) console.timeEnd(`[Cpasmal API] Total /movie/${tmdbid}`); + return res.status(404).json({ error: 'Movie not found on Cpasmal' }); + } + + // Utilisation de fsp.writeFile direct au lieu de safeWriteJsonFile pour éviter atomic writes + await fsp.writeFile(path.join(CACHE_DIR.CPASMAL, `${cacheKey}.json`), JSON.stringify(data), 'utf-8'); + await memoryCache.set(`cpasmal:movie:${tmdbid}`, data); + res.json(data); + if (process.env.DEBUG_CPASMAL) console.timeEnd(`[Cpasmal API] Total /movie/${tmdbid}`); + + } catch (error) { + if (error.message && error.message.includes('not found')) { + return res.status(404).json({ error: error.message }); + } + res.status(500).json({ error: 'Internal Server Error' }); + } +}); + +// Route pour supprimer le cache d'un film cpasmal +app.get('/api/cpasmal/movie/:tmdbid/clear-cache', async (req, res) => { + const { tmdbid } = req.params; + const cacheKey = generateCacheKey(`movie_${tmdbid}`); + const cacheFilePath = path.join(CACHE_DIR.CPASMAL, `${cacheKey}.json`); + + try { + await fsp.unlink(cacheFilePath); + console.log(`[Cpasmal Cache] Cache cleared for movie ${tmdbid}`); + res.json({ success: true, message: `Cache cleared for movie ${tmdbid}` }); + } catch (error) { + if (error.code === 'ENOENT') { + res.status(404).json({ error: `No cache found for movie ${tmdbid}` }); + } else { + console.error(`[Cpasmal Cache] Error clearing cache for movie ${tmdbid}:`, error.message); + res.status(500).json({ error: 'Failed to clear cache' }); + } + } +}); + +app.get('/api/cpasmal/tv/:tmdbid/:season/:episode', async (req, res) => { + const { tmdbid, season, episode } = req.params; + const cacheKey = generateCacheKey(`tv_${tmdbid}_s${season}_e${episode}`); + + try { + // 1. Try cache + const cachedData = await getFromCacheNoExpiration(CACHE_DIR.CPASMAL, cacheKey); + if (cachedData) { + if (cachedData.notFound) { + res.status(404).json({ error: 'TV Show not found on Cpasmal (Cached)' }); + } else { + res.json(cachedData); + } + + // Background update if old + const cacheFilePath = path.join(CACHE_DIR.CPASMAL, `${cacheKey}.json`); + try { + const stats = await fsp.stat(cacheFilePath); + const age = Date.now() - stats.mtime.getTime(); + if (age > 20 * 60 * 1000) { // 20 minutes + updateCpasmalCache(cacheKey, 'tv', tmdbid, season, episode); + } + } catch (e) { /* ignore */ } + return; + } + + // 2. Fetch fresh with deduplication (prevents multiple simultaneous requests from blocking) + const data = await getOrCreateCpasmalRequest(cacheKey, () => fetchCpasmalTvData(tmdbid, season, episode, false)); + + if (!data) { + // Content not found - Cache this state + const notFoundData = { notFound: true, tmdbId: tmdbid, season, episode, timestamp: Date.now() }; + await fsp.writeFile(path.join(CACHE_DIR.CPASMAL, `${cacheKey}.json`), JSON.stringify(notFoundData), 'utf-8'); + return res.status(404).json({ error: 'TV Show not found on Cpasmal' }); + } + + // Utilisation de fsp.writeFile direct au lieu de safeWriteJsonFile pour éviter atomic writes + await fsp.writeFile(path.join(CACHE_DIR.CPASMAL, `${cacheKey}.json`), JSON.stringify(data), 'utf-8'); + await memoryCache.set(`cpasmal:tv:${tmdbid}:${season}:${episode}`, data); + res.json(data); + + } catch (error) { + if (error.message && error.message.includes('not found')) { + return res.status(404).json({ error: error.message }); + } + res.status(500).json({ error: 'Internal Server Error' }); + } +}); + +const frembedHeaders = { + 'Accept': '*/*', + 'Accept-Language': 'fr-FR,fr;q=0.9', + 'Origin': 'https://frembed.top', + 'Referer': 'https://frembed.top', + 'Host': 'api.frembed.top', + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36' +}; + +const axiosFrembed = axios.create({ + baseURL: 'https://api.frembed.icu', + timeout: 10000, // Reduced from 30s to 10s to prevent blocking + headers: frembedHeaders, + decompress: true +}); + +// Configuration Darkino - Headers complets comme dans le script Python qui fonctionne +const darkiHeaders = { + 'accept': 'application/json', + 'accept-encoding': 'gzip, deflate, br', + 'accept-language': 'fr-FR,fr;q=0.6', + 'cache-control': 'no-cache', + 'cookie': 'remember_web_3dc7a913ef5fd4b890ecabe3487085573e16cf82=eyJpdiI6IjNmdEJVb3Z2WWM5U0J5NzEvUmIxUmc9PSIsInZhbHVlIjoicUFPT0lTR3RIbWZFYWg0Z0hjMEUvZGpUc0daVlAyYlk1SkNTbU1Nb2I1MDJveFpCY1VTTnUrMlNRVDJNczN3dEpudTB2RDNPN2l5WkJWT2lRZTBqcUYyNXczNWlJU1J5YnZ2Rk1pZ1cwN3djbytkVVJaeStaSHVjYW1HcWpVQmVwY1VBT0VNSXhkODdETHo3bjdDVEl3WG5vUE5IcHB1b0ljRkV3a0dBc0tuOFJxWXZsMEpwQUxwY2hMY2x6WmxMZGdsTFU0b3B5REFuY1ZwYm5VTDBjWEdPdERhelllbXM2d0VDdGZFNHAyND0iLCJtYWMiOiIyODJlNmYzYjM0MjViNmExNTVlMmVhN2Y4MWY0ZjZhNzdhZmNiMTAxNjYzZTQxZWVjYWVkYzM1MzNiMjhiZmNjIiwidGFnIjoiIn0%3D; SERVERID=S1; connected=1; dbruser=1; XSRF-TOKEN=eyJpdiI6IlQ1Vmh1VS90WTVUWHdVdG5VOVc3WEE9PSIsInZhbHVlIjoidmZQd2Mra1RlL0w0NUZCUmp2ZS9aOFdyM3ZWMU5uYjVLcHZpU3RXQXVHcHhhR0daVGhJU0tTNDRwenNXSW9JNG5RR1ZBVjVLUkE3ayttZXdZSmlUZHFwOGJkWG40YnEvNGt4ajFwTG94YnZyS0VnUnAxNmpzOTRURlpodXRsNjUiLCJtYWMiOiJmY2Y2NTkzZWZiODI3MWRjYTMwYmRjN2FmMTEyNTdhMWMwYjY5OGFkZjdhNTJhMDg2ZDI3MTY5NWQ1ZWIwNzg1IiwidGFnIjoiIn0%3D; darkiworld_session=eyJpdiI6IlVxMDU0bjZPU243azdtTStCVzdBM1E9PSIsInZhbHVlIjoidTdURU5hb0FpN0JMdW5qZUlFZWE2ckxkcWhQVlJYZWI1a2NkR2JpaFBHMFc5Z04ySGFLbE1lTENlR0U5ODBvZ1d0TkdpNGtxUTVaZ3NzUW1wVG11TVl0OGxoZDQyeHkvYnYvUkRBS3YxdTgwdk5FbUpxcDBVcUJiNEpjNDJaTnciLCJtYWMiOiJlNTY2NDRhYjRkMjczZWYyYzU2Yjg1Njk3YmQ3NGI0ZmJlZmU2ODdjZGIxNjI3ZGY0Y2Q0YmEyNzVjNmRjNGRhIiwidGFnIjoiIn0%3D', + 'pragma': 'no-cache', + 'priority': 'u=1, i', + 'sec-ch-ua': '"Brave";v="143", "Chromium";v="143", "Not A(Brand";v="24"', + 'sec-ch-ua-mobile': '?0', + 'sec-ch-ua-platform': '"Windows"', + 'sec-fetch-dest': 'empty', + 'sec-fetch-mode': 'cors', + 'sec-fetch-site': 'same-origin', + 'sec-gpc': '1', + 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36', + 'x-xsrf-token': 'eyJpdiI6IlQ1Vmh1VS90WTVUWHdVdG5VOVc3WEE9PSIsInZhbHVlIjoidmZQd2Mra1RlL0w0NUZCUmp2ZS9aOFdyM3ZWMU5uYjVLcHZpU3RXQXVHcHhhR0daVGhJU0tTNDRwenNXSW9JNG5RR1ZBVjVLUkE3ayttZXdZSmlUZHFwOGJkWG40YnEvNGt4ajFwTG94YnZyS0VnUnAxNmpzOTRURlpodXRsNjUiLCJtYWMiOiJmY2Y2NTkzZWZiODI3MWRjYTMwYmRjN2FmMTEyNTdhMWMwYjY5OGFkZjdhNTJhMDg2ZDI3MTY5NWQ1ZWIwNzg1IiwidGFnIjoiIn0=' +}; + +// Configuration Coflix with reduced timeout +const coflixHeaders = { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', + 'Referer': 'https://coflix.observer' +}; + +const axiosCoflix = axios.create({ + baseURL: COFLIX_BASE_URL, + timeout: 15000, // 15 seconds timeout + headers: coflixHeaders, + decompress: true +}); + +const cookieJar = new tough.CookieJar(); + + +cookieJar.setCookieSync('remember_web_3dc7a913ef5fd4b890ecabe3487085573e16cf82=eyJpdiI6ImlUSnZySE1CRDg1dVNDcUo0Wm85dGc9PSIsInZhbHVlIjoiQnVQMFZYancwV0kxZEkzWEFmSHZyR3MxZ2Q4VEk2U044K1g1NG5EblljYmNmdU1BZzNBNDdVZlF3QlhmYnBNY0xPeHMxd2dSTG9JNTN2aEtEL05OekIxWFFWQXJkdGUrWWlvRzVHQzdLK2hHZ0thU3UvTHJpZHNPanpJQmJzMk5TTjFjVkY4NGMrQXVFcnJaQ0ZqOTZMUWwwZFh5UW8rZkI1TXZxL254ekEvTjdQaURKdnIxcXNwY0I4VGZwaGQrMzRtNVZHRUN3YVpGQ3dacmFLMDZ2V0RuVnl2YUJuYjRMZTRPa3hyK0IzST0iLCJtYWMiOiI1ZjNiNjRhYjc0NWM4NmZjZDU2YWE1ZTZmNTgyYzU0MWYwM2EwZTI4ZjM1ZTU0YWRlYTFlOGNjMTk5NDIyM2JmIiwidGFnIjoiIn0%3D', 'https://darkiworld2026.com'); +cookieJar.setCookieSync('SERVERID=S1', 'https://darkiworld2026.com'); +cookieJar.setCookieSync('XSRF-TOKEN=eyJpdiI6IllVSmNUN3J3cEVTdWErMlBySzhkNmc9PSIsInZhbHVlIjoiR3hmSmluY0dQYlI0cHFENjJlZUtTR3BYOGhZQVlqUysrcHlIeTVqK2R6aU1FZEhjeWgvTDJKLy9KM2t1WHZ1M0l4Wk5KY3ZBM1RqV3lnNVV4RVJaNmdOR2c5QzI3WnpYSUh5OXpybDBwSUtneWdZR1lhcUdNK0lwalhBUilmNTEiLCJtYWMiOiI2MTNlZTk4Nzk2NTAxN2VhY2FjNmQ2NmJhMTQzZmZlNzMzYTg2YTQ0ZWU0M2VjOTA1ODhlN2Y0YTMxMTIyNzE4IiwidGFnIjoiIn0%3D', 'https://darkiworld2026.com'); +cookieJar.setCookieSync('darkiworld_session=eyJpdiI6IlVHUmIzbWNrWlUwc0dRaGtoLzFManc9PSIsInZhbHVlIjoiNSswRnRHc085cWJ3RmRwU0xjNm1UVVRLbTJkVVdiYjVkTFVtY3htS1habVBlMmkyZVVFQlEzem9hL1Jab3RhRnZEaEU5ZmpudkJONnFUUEw3dFpzdTNibUYyZzZZWmhyeFhvYnBid0RPQ0V6cHlYSEFjYW53R05vc3Y3TkhNcEgiLCJtYWMiOiJlMDZjNjlkMDIzNGU2Y2E1MGExODVkNTgzYzBhYzhhNjg0MmU2MGU3MWI4ODkzMTNmMzIzZDA4MGM5MDgwMTg3IiwidGFnIjoiIn0%3D', 'https://darkiworld2026.com'); + + +const axiosDarkino = wrapper(axios.create({ + baseURL: 'https://darkiworld2026.com', + timeout: 5000, + jar: cookieJar, + withCredentials: true, + headers: darkiHeaders +})); + +axiosDarkino.interceptors.response.use(null, async (error) => { + // Create retry config if it doesn't exist + if (!error.config) { + // If the config doesn't exist, we can't retry. This usually happens due to proxy issues. + return Promise.reject(error); + } + + if (typeof error.config.__retryCount === 'undefined') { + error.config.__retryCount = 0; + } + + // Keep max retries at 1 to prevent server overload + if (error.config.__retryCount < 1) { + error.config.__retryCount++; + + // Use a more reasonable backoff with shorter delays + const delay = Math.min(1000 * Math.pow(1.5, error.config.__retryCount), 5000) + (Math.random() * 500); + // Suppression du log de retry + //console.log(`Retry attempt ${error.config.__retryCount} for ${error.config.url} after ${Math.round(delay)}ms delay`); + + // For Cloudflare 403 or 522 errors, don't retry as they won't succeed without solving the challenge + if (error.response && (error.response.status === 403 || error.response.status === 522)) { + //console.log(`Cloudflare protection (${error.response.status}) detected, not retrying`); + return Promise.reject(error); + } + + // Only retry for server errors or network issues, not for 403 Forbidden + if ((error.response && error.response.status >= 500) || !error.response) { + //console.log(`Server error (${error.response?.status || 'network error'}), retrying...`); + await new Promise(resolve => setTimeout(resolve, delay)); + return axiosDarkino(error.config); + } + + // Standard retry for other errors + await new Promise(resolve => setTimeout(resolve, delay)); + return axiosDarkino(error.config); + } + + // If we exhausted retries, reject with the original error + //console.log(`Max retries (${error.config.__retryCount}) reached for ${error.config.url}`); + return Promise.reject(error); +}); + +app.get('/movies/check/:id', async (req, res) => { + try { + const { id } = req.params; + const response = await axiosFrembed.get(`/movies/check?id=${id}`); + res.status(200).json(response.data); + } catch (error) { + console.error(`Erreur Frembed: ${error.response?.status || 'Erreur réseau'}`); + res.status(500).json({ error: 'Erreur lors de la vérification du film' }); + } +}); + +app.get('/movies', async (req, res) => { + try { + const { page = 1, limit = 100, order = 'popular' } = req.query; + const response = await axiosFrembed.get('/movies', { params: { order, limit, page } }); + res.status(200).json(response.data); + } catch (error) { + console.error(`Erreur Frembed: ${error.response?.status || 'Erreur réseau'}`); + res.status(500).json({ error: 'Erreur lors de la récupération des films' }); + } +}); + +app.get('/tv/check/:id', async (req, res) => { + try { + const { id } = req.params; + const { sa, epi } = req.query; + const response = await axiosFrembed.get('/tv/check', { params: { id, sa, epi } }); + res.status(200).json(response.data); + } catch (error) { + console.error(`Erreur Frembed: ${error.response?.status || 'Erreur réseau'}`); + res.status(500).json({ error: 'Erreur lors de la vérification de la série' }); + } +}); + +app.get('/tv', async (req, res) => { + try { + const { page = 1, limit = 100, order = 'popular' } = req.query; + const response = await axiosFrembed.get('/tv', { params: { order, limit, page } }); + res.status(200).json(response.data); + } catch (error) { + console.error(`Erreur Frembed: ${error.response?.status || 'Erreur réseau'}`); + res.status(500).json({ error: 'Erreur lors de la récupération des séries' }); + } +}); + +app.get('/api/search', async (req, res) => { + + try { + const { title } = req.query; + if (!title) return res.status(400).json({ error: 'Le paramètre title est requis' }); + const sanitizedTitle = String(title).replace(/\//g, '').trim(); + if (!sanitizedTitle) return res.status(400).json({ error: 'Le paramètre title est invalide' }); + + // Generate cache key + const cacheKey = generateCacheKey(`api_search_${sanitizedTitle}`); + + // Check if results are in cache without expiration (stale-while-revalidate) + const cachedData = await getFromCacheNoExpiration(DARKINOS_CACHE_DIR, cacheKey); + let dataReturned = false; + + if (cachedData) { + // console.log(`Résultats de recherche pour "${title}" récupérés du cache`); + res.status(200).json(cachedData); // Return cached data immediately + dataReturned = true; + + // Update cache in background only if no error occurs + (async () => { + try { + // Vérifier si le cache doit être mis à jour + const shouldUpdate = await shouldUpdateCache(DARKINOS_CACHE_DIR, cacheKey); + if (!shouldUpdate) { + return; // Ne pas mettre à jour le cache + } + + const response = await axiosDarkinoRequest({ method: 'get', url: `/api/v1/search/${encodeURIComponent(sanitizedTitle)}`, params: { loader: 'searchPage' } }); + + // Validation: s'assurer que la réponse est du JSON valide et non du texte "Maintenance en cours" + if (typeof response.data === 'string' && response.data.includes('Maintenance en cours')) { + throw new Error('Maintenance en cours - pas de mise à jour du cache'); + } + + // Vérifier que c'est bien un objet JSON et non du texte brut + if (typeof response.data === 'string' || response.data === null || response.data === undefined) { + throw new Error('Réponse invalide - pas de mise à jour du cache'); + } + + // Si on a des données valides, sauvegarder dans le cache + if (response.data) { + await saveToCache(DARKINOS_CACHE_DIR, cacheKey, response.data); + } + } catch (error) { + // Silent fail on background update + } + })(); + } else { + // Si en maintenance et pas de cache, erreur + if (DARKINO_MAINTENANCE) { + return res.status(200).json({ error: 'Service Darkino temporairement indisponible (maintenance)' }); + } + // No cache, get data synchronously + try { + const fetchFunction = async () => { + const response = await axiosDarkinoRequest({ method: 'get', url: `/api/v1/search/${encodeURIComponent(sanitizedTitle)}`, params: { loader: 'searchPage' } }); + + // Validation: s'assurer que la réponse est du JSON valide et non du texte "Maintenance en cours" + if (typeof response.data === 'string' && response.data.includes('Maintenance en cours')) { + console.error('Darkino API retourne "Maintenance en cours" - ne pas sauvegarder en cache'); + throw new Error('Maintenance en cours - données invalides'); + } + + // Vérifier que c'est bien un objet JSON et non du texte brut + if (typeof response.data === 'string' || response.data === null || response.data === undefined) { + console.error('Darkino API retourne une réponse invalide (non-JSON) - ne pas sauvegarder en cache'); + throw new Error('Réponse invalide - données non-JSON'); + } + + return response.data; + }; + + // Use the updateDarkinosCache function for data fetching with proper retry behavior + const data = await fetchFunction(); + + // If we got data, save it to cache and return + if (data) { + await saveToCache(DARKINOS_CACHE_DIR, cacheKey, data); + res.status(200).json(data); + } else { + res.status(404).json({ error: 'Aucun résultat trouvé' }); + } + } catch (error) { + if (error.response && error.response.status >= 500) { + // Si on a déjà retourné des données (cache), on ne fait RIEN + if (dataReturned) return; + + try { + const fallbackCache = await getFromCacheNoExpiration(DARKINOS_CACHE_DIR, cacheKey); + if (fallbackCache) { + return res.status(200).json(fallbackCache); + } + } catch (_) { } + } + res.status(500).json({ error: 'Erreur lors de la recherche' }); + } + } + } catch (error) { + console.error(`Erreur API Darkino Search: ${error.response?.status || 'Erreur réseau'}`); + if (!res.headersSent) { + try { + const { title } = req.query; + const sanitizedTitle = String(title || '').replace(/\//g, '').trim(); + const cacheKey = generateCacheKey(`api_search_${sanitizedTitle}`); + const fallbackCache = await getFromCacheNoExpiration(DARKINOS_CACHE_DIR, cacheKey); + if (error.response && error.response.status >= 500 && fallbackCache) { + return res.status(200).json(fallbackCache); + } + } catch (_) { } + res.status(500).json({ error: 'Erreur lors de la recherche' }); + } + } +}); + + + +// Function to validate if an m3u8 URL is accessible +const validateM3u8Url = async (m3u8Url, useProxy = false) => { + if (!m3u8Url) return { isValid: false, quality: null }; + + let proxy = null; + let agent = null; + if (useProxy && ENABLE_DARKINO_PROXY) { + proxy = pickRandomProxyOrNone(); + agent = getProxyAgent(proxy); + if (proxy) { + // console.log(`[PROXY] Utilisation du proxy ${proxy.host}:${proxy.port} pour valider m3u8`); + } else { + // console.log(`[PROXY] Pas de proxy utilisé pour valider m3u8`); + } + } + + try { + // console.log(`[VALIDATE_M3U8] Validating m3u8 URL: ${m3u8Url}`); + const response = await axios.get(m3u8Url, { + headers: { + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:134.0) Gecko/20100101 Firefox/134.0", + "Accept": "*/*", + "Accept-Language": "en-US,en;q=0.5", + "Sec-Fetch-Dest": "empty", + "Sec-Fetch-Mode": "cors", + "Sec-Fetch-Site": "cross-site" + }, + timeout: 2000, // 5 second timeout for validation + validateStatus: (status) => status === 200, // Only accept 200 status + decompress: true, + ...(agent ? { httpsAgent: agent, httpAgent: agent } : {}) + }); + + // Check if the response has the expected m3u8 content + const contentType = response.headers['content-type']; + const isValidContent = contentType && ( + contentType.includes('application/vnd.apple.mpegurl') || + contentType.includes('application/x-mpegurl') || + contentType.includes('audio/mpegurl') || + contentType.includes('text/plain') // Some servers use text/plain for m3u8 + ); + + // Also check content for m3u8 signature + const isValidM3u8 = response.data && + (typeof response.data === 'string' && + (response.data.includes('#EXTM3U') || + response.data.includes('#EXT-X-VERSION'))); + + const isValid = isValidContent || isValidM3u8; + + // If valid, detect quality directly from the response content + let quality = null; + if (isValid && response.data && typeof response.data === 'string') { + const content = response.data; + + // Look for resolution information in the m3u8 content + const resolutionMatch = content.match(/RESOLUTION=(\d+x\d+)/i); + if (resolutionMatch) { + const resolution = resolutionMatch[1]; + const [width, height] = resolution.split('x').map(Number); + + // Determine quality based on resolution + if (width >= 3840 || height >= 2160) quality = "4K"; + else if (width >= 1920 || height >= 1080) quality = "1080p"; + else if (width >= 1280 || height >= 720) quality = "720p"; + else if (width >= 854 || height >= 480) quality = "480p"; + else if (width >= 640 || height >= 360) quality = "360p"; + else quality = `${height}p`; + } else { + // Look for quality indicators in stream names + const qualityMatch = content.match(/(\d+p|4k|hd|sd)/gi); + if (qualityMatch) { + const qualityStr = qualityMatch[0].toLowerCase(); + if (qualityStr.includes('4k')) quality = "4K"; + else if (qualityStr.includes('1080p') || qualityStr.includes('hd')) quality = "1080p"; + else if (qualityStr.includes('720p')) quality = "720p"; + else if (qualityStr.includes('480p')) quality = "480p"; + else if (qualityStr.includes('360p')) quality = "360p"; + else quality = qualityStr.toUpperCase(); + } + } + } + + // console.log(`[VALIDATE_M3U8] URL: ${m3u8Url}, ContentType: ${contentType}, isValidContent: ${isValidContent}, isValidM3u8: ${isValidM3u8}, Quality: ${quality}`); + return { isValid, quality }; + } catch (error) { + return { isValid: false, quality: null }; + } +}; + +// Modify extractM3u8Url function +const extractM3u8Url = async (darkiboxUrl) => { + try { + let proxy = null; + let agent = null; // Proxy désactivé pour l'extraction M3U8 + const axiosPromise = axios.get(darkiboxUrl, { + + ...(agent ? { httpsAgent: agent, httpAgent: agent } : {}), + + }); + + const timeoutPromise = new Promise((_, reject) => + + setTimeout(() => reject(new Error("Request timed out (manual)")), 4500) + + ); + + const response = await Promise.race([axiosPromise, timeoutPromise]); + const htmlContent = response.data; + const playerConfigMatch = htmlContent.match(/sources:\s*\[\s*{\s*src:\s*"([^"]+)"/); + if (playerConfigMatch && playerConfigMatch[1]) { + const m3u8Url = playerConfigMatch[1]; + // Validate the m3u8 URL before returning it + const validation = await validateM3u8Url(m3u8Url, false); + return validation.isValid ? { url: m3u8Url, quality: validation.quality } : null; + } + return null; + } catch (error) { + // Ne pas logger les erreurs 500/403 pour EXTRACT_M3U8 + if (!error.response || (error.response.status !== 500 && error.response.status !== 403)) { + if (error.message.includes("Request timed out")) { + console.error(`[EXTRACT_M3U8] Timeout (8s) lors de l'extraction depuis ${darkiboxUrl} - serveur trop lent`); + } else { + console.error(`[EXTRACT_M3U8] Error processing ${darkiboxUrl}: ${error.response?.status || 'Erreur réseau'}`, error.message); + } + } + return null; + } +}; + +// Créer un répertoire pour le cache Darkinos si nécessaire +const DARKINOS_CACHE_DIR = path.join(__dirname, 'cache', 'darkinos'); +(async () => { + try { + await fsp.access(DARKINOS_CACHE_DIR); + } catch { + await fsp.mkdir(DARKINOS_CACHE_DIR, { recursive: true }); + } +})(); + +// Créer un répertoire pour le cache des téléchargements et décodages +const DOWNLOAD_CACHE_DIR = path.join(__dirname, 'cache', 'darkinodownloadlink'); +(async () => { + try { + await fsp.access(DOWNLOAD_CACHE_DIR); + } catch { + await fsp.mkdir(DOWNLOAD_CACHE_DIR, { recursive: true }); + } +})(); + +// Créer un répertoire pour le cache des vidéos externes +const EXTERNAL_VIDEOS_CACHE_DIR = path.join(__dirname, 'cache', 'external_videos'); +(async () => { + try { + await fsp.access(EXTERNAL_VIDEOS_CACHE_DIR); + } catch { + await fsp.mkdir(EXTERNAL_VIDEOS_CACHE_DIR, { recursive: true }); + } +})(); + +// Fonction utilitaire pour vérifier si un fichier de cache a été modifié dans les 40 dernières minutes +const shouldUpdateCache = async (cacheDir, cacheKey) => { + const cacheFilePath = path.join(cacheDir, `${cacheKey}.json`); + try { + const stats = await fsp.stat(cacheFilePath); + const now = Date.now(); + const fileAge = now - stats.mtime.getTime(); + const fortyMinutes = 40 * 60 * 1000; // 40 minutes en millisecondes + + if (fileAge < fortyMinutes) { + return false; // Ne pas mettre à jour le cache + } + return true; // Mettre à jour le cache + } catch (error) { + // Si le fichier n'existe pas ou erreur de lecture, continuer avec la mise à jour + return true; + } +}; + +// Fonction pour vérifier si le cache French-Stream doit être mis à jour (20 minutes) +const shouldUpdateCacheFrenchStream = async (cacheDir, cacheKey) => { + const cacheFilePath = path.join(cacheDir, `${cacheKey}.json`); + try { + const stats = await fsp.stat(cacheFilePath); + const now = Date.now(); + const fileAge = now - stats.mtime.getTime(); + const twentyMinutes = 3 * 60 * 60 * 1000; // 3 heures en millisecondes + + if (fileAge < twentyMinutes) { + return false; // Ne pas mettre à jour le cache + } + return true; // Mettre à jour le cache + } catch (error) { + // Si le fichier n'existe pas ou erreur de lecture, continuer avec la mise à jour + return true; + } +}; + +// Fonction pour vérifier si le cache LecteurVideo doit être mis à jour (2 heures) +const shouldUpdateCacheLecteurVideo = async (cacheDir, cacheKey) => { + const cacheFilePath = path.join(cacheDir, `${cacheKey}.json`); + try { + const stats = await fsp.stat(cacheFilePath); + const now = Date.now(); + const fileAge = now - stats.mtime.getTime(); + const twoHours = 2 * 60 * 60 * 1000; // 2 heures en millisecondes + + if (fileAge < twoHours) { + return false; // Ne pas mettre à jour le cache + } + return true; // Mettre à jour le cache + } catch (error) { + // Si le fichier n'existe pas ou erreur de lecture, continuer avec la mise à jour + return true; + } +}; + +// Fonction pour vérifier si le cache doit être mis à jour (24 heures) - utilisée pour la route decode +const shouldUpdateCache24h = async (cacheDir, cacheKey) => { + const cacheFilePath = path.join(cacheDir, `${cacheKey}.json`); + try { + const stats = await fsp.stat(cacheFilePath); + const now = Date.now(); + const fileAge = now - stats.mtime.getTime(); + const twentyFourHours = 24 * 60 * 60 * 1000; // 24 heures en millisecondes + + if (fileAge < twentyFourHours) { + return false; // Ne pas mettre à jour le cache + } + return true; // Mettre à jour le cache + } catch (error) { + // Si le fichier n'existe pas ou erreur de lecture, continuer avec la mise à jour + return true; + } +}; + +// Fonction pour mettre à jour le cache en arrière-plan +const updateDarkinosCache = async (cacheKey, fetchFunction) => { + try { + //console.log(`Mise à jour du cache en arrière-plan pour ${cacheKey}`); + + // Vérifier si le fichier a été modifié dans les 40 dernières minutes + const shouldUpdate = await shouldUpdateCache(DARKINOS_CACHE_DIR, cacheKey); + if (!shouldUpdate) { + //console.log(`Cache ${cacheKey} modifié il y a moins de 40 minutes, pas de mise à jour en arrière-plan`); + return; // Ne pas mettre à jour le cache + } + + // Try up to 2 times maximum with a backoff delay + let attempts = 0; + const maxAttempts = 1; + let lastError = null; + + while (attempts < maxAttempts) { + try { + const newData = await fetchFunction(); + + // Validation: s'assurer que les données ne sont pas du texte "Maintenance en cours" + if (typeof newData === 'string' && newData.includes('Maintenance en cours')) { + console.error(`Données invalides (Maintenance en cours) pour ${cacheKey} - ne pas mettre à jour le cache`); + throw new Error('Maintenance en cours - données invalides'); + } + + // Vérifier que c'est bien un objet JSON et non du texte brut + if (typeof newData === 'string' || newData === null || newData === undefined) { + console.error(`Données invalides (non-JSON) pour ${cacheKey} - ne pas mettre à jour le cache`); + throw new Error('Données invalides - non-JSON'); + } + + if (newData) { + await saveToCache(DARKINOS_CACHE_DIR, cacheKey, newData); + //console.log(`Cache mis à jour pour ${cacheKey}`); + return; + } + // If we got here with no data but no error, break the loop + break; + } catch (error) { + attempts++; + lastError = error; + + // If it's a Cloudflare 403 error, don't retry + if (error.response && error.response.status === 403) { + //console.log(`Cloudflare protection (403) détectée pour ${cacheKey}, abandon des tentatives`); + break; + } + + // Only retry server errors or network issues + if ((error.response && error.response.status >= 500) || !error.response) { + const delay = 2000 * attempts; + //console.log(`Erreur lors de la tentative ${attempts}/${maxAttempts} pour ${cacheKey}. Nouvel essai dans ${delay/1000} secondes...`); + await new Promise(resolve => setTimeout(resolve, delay)); + } else { + // For other errors, don't retry + break; + } + } + } + + // If we got here, all attempts failed - don't update cache + if (lastError) { + // Ne pas mettre à jour le cache en cas d'erreur + return; + } + } catch (error) { + console.error(`Erreur Darkino cache: ${error.response?.status || 'Erreur réseau'}`); + // Ne pas mettre à jour le cache en cas d'erreur + } +}; + +// Fonction pour mettre à jour le cache LecteurVideo en arrière-plan (similaire à DarkiWorld) +const updateLecteurVideoCache = async (cacheKey, fetchFunction) => { + try { + //console.log(`Mise à jour du cache LecteurVideo en arrière-plan pour ${cacheKey}`); + + // Vérifier si le fichier a été modifié dans les 2 dernières heures + const shouldUpdate = await shouldUpdateCacheLecteurVideo(CACHE_DIR.COFLIX, cacheKey); + if (!shouldUpdate) { + //console.log(`Cache LecteurVideo ${cacheKey} modifié il y a moins de 2 heures, pas de mise à jour en arrière-plan`); + return; // Ne pas mettre à jour le cache + } + + // Try up to 1 time maximum + let attempts = 0; + const maxAttempts = 1; + let lastError = null; + + while (attempts < maxAttempts) { + try { + const newData = await fetchFunction(); + + // Validation: s'assurer que les données ne sont pas vides ou invalides + if (typeof newData === 'string' && newData.includes('Maintenance en cours')) { + console.error(`Données invalides (Maintenance en cours) pour ${cacheKey} - ne pas mettre à jour le cache`); + throw new Error('Maintenance en cours - données invalides'); + } + + // Vérifier que c'est bien un objet JSON et non du texte brut + if (typeof newData === 'string' || newData === null || newData === undefined) { + console.error(`Données invalides (non-JSON) pour ${cacheKey} - ne pas mettre à jour le cache`); + throw new Error('Données invalides - non-JSON'); + } + + if (newData) { + await saveToCache(CACHE_DIR.COFLIX, cacheKey, newData); + //console.log(`Cache LecteurVideo mis à jour pour ${cacheKey}`); + return; + } + // If we got here with no data but no error, break the loop + break; + } catch (error) { + attempts++; + lastError = error; + console.error(`Erreur lors de la mise à jour du cache LecteurVideo pour ${cacheKey} (tentative ${attempts}/${maxAttempts}):`, error.message); + + if (attempts < maxAttempts) { + // Attendre un peu avant de réessayer + await new Promise(resolve => setTimeout(resolve, 1000 * attempts)); + } + } + } + + if (lastError) { + console.error(`Échec de la mise à jour du cache LecteurVideo pour ${cacheKey} après ${maxAttempts} tentatives:`, lastError.message); + } + } catch (error) { + console.error(`Erreur générale lors de la mise à jour du cache LecteurVideo pour ${cacheKey}:`, error); + } +}; + +// Fonction pour mettre à jour le cache Wiflix en arrière-plan +const updateWiflixCache = async (cacheDir, cacheKey, type, tmdbId, season = null) => { + try { + // Récupérer le cache existant pour le préserver en cas d'erreur + const existingCache = await getFromCacheNoExpiration(cacheDir, cacheKey); + + // Try up to 2 times maximum with a backoff delay + let attempts = 0; + const maxAttempts = 1; + let lastError = null; + + while (attempts < maxAttempts) { + try { + let newData; + + // Appeler la fonction appropriée selon le type, en passant le cache existant + if (type === 'movie') { + newData = await fetchWiflixMovieData(tmdbId, existingCache); + } else if (type === 'tv') { + newData = await fetchWiflixTvData(tmdbId, season, existingCache); + } else { + throw new Error(`Type non supporté: ${type}`); + } + + // Validation: s'assurer que les données ne sont pas invalides + if (typeof newData === 'string' && newData.includes('Maintenance en cours')) { + console.error(`Données invalides (Maintenance en cours) pour ${cacheKey} - ne pas mettre à jour le cache`); + throw new Error('Maintenance en cours - données invalides'); + } + + // Vérifier que c'est bien un objet JSON et non du texte brut + if (typeof newData === 'string' || newData === null || newData === undefined) { + console.error(`Données invalides (non-JSON) pour ${cacheKey} - ne pas mettre à jour le cache`); + throw new Error('Données invalides - non-JSON'); + } + + if (newData) { + // Vérifier si les nouvelles données sont valides avant de mettre à jour + // Ne pas mettre à jour si les données indiquent un échec ET qu'un cache existait + const isFailedResult = newData.success === false; + + if (isFailedResult && existingCache) { + return; // Ne pas mettre à jour le cache avec des données d'échec + } + + await saveToCache(cacheDir, cacheKey, newData); + //console.log(`Cache Wiflix mis à jour pour ${cacheKey}`); + return; + } + // If we got here with no data but no error, break the loop + break; + } catch (error) { + attempts++; + lastError = error; + + // If it's a Cloudflare 403 error, don't retry + if (error.response && error.response.status === 403) { + //console.log(`Cloudflare protection (403) détectée pour ${cacheKey}, abandon des tentatives`); + break; + } + + // Only retry server errors or network issues + if ((error.response && error.response.status >= 500) || !error.response) { + const delay = 2000 * attempts; + //console.log(`Erreur lors de la tentative ${attempts}/${maxAttempts} pour ${cacheKey}. Nouvel essai dans ${delay/1000} secondes...`); + await new Promise(resolve => setTimeout(resolve, delay)); + } else { + // For other errors, don't retry + break; + } + } + } + + // If we got here, all attempts failed - don't update cache + if (lastError) { + // Ne pas mettre à jour le cache en cas d'erreur + return; + } + } catch (error) { + console.error(`Erreur Wiflix cache: ${error.response?.status || 'Erreur réseau'}`); + // Ne pas mettre à jour le cache en cas d'erreur + } +}; +app.get('/api/films/download/:id', async (req, res) => { + if (DARKINO_MAINTENANCE) { + return res.status(200).json({ error: 'Service Darkino temporairement indisponible (maintenance)' }); + } + try { + const { id } = req.params; + const cacheKey = generateCacheKey(`films_download_${id}`); + const cachedData = await getFromCacheNoExpiration(DARKINOS_CACHE_DIR, cacheKey); + const M3U8_CACHE_EXPIRY = 8 * 60 * 60 * 1000; // 8 hours in milliseconds + + let dataReturned = false; + if (cachedData && cachedData.sources !== undefined) { + const now = Date.now(); + const needM3u8Refresh = !cachedData.m3u8Timestamp || (now - cachedData.m3u8Timestamp > M3U8_CACHE_EXPIRY); + let sourcesWithM3u8; + if (!needM3u8Refresh && cachedData.sourcesWithM3u8) { + sourcesWithM3u8 = cachedData.sourcesWithM3u8; + const validSources = sourcesWithM3u8.filter(source => source.m3u8); + if (validSources.length === 0) { + // Aucun m3u8 valide dans le cache, on force la ré-extraction + sourcesWithM3u8 = await Promise.all( + cachedData.sources.map(async (source, idx) => { + const m3u8Result = await extractM3u8Url(source.src); + if (m3u8Result) { + return { + ...source, + m3u8: m3u8Result.url, + quality: m3u8Result.quality || source.quality + }; + } + return { ...source, m3u8: null }; + }) + ); + const newCacheData = { + ...cachedData, + sourcesWithM3u8: sourcesWithM3u8, + m3u8Timestamp: Date.now() + }; + await saveToCache(DARKINOS_CACHE_DIR, cacheKey, newCacheData); + } + } else { + sourcesWithM3u8 = await Promise.all( + cachedData.sources.map(async (source, idx) => { + const m3u8Result = await extractM3u8Url(source.src); + if (m3u8Result) { + return { + ...source, + m3u8: m3u8Result.url, + quality: m3u8Result.quality || source.quality + }; + } + return { ...source, m3u8: null }; + }) + ); + const newCacheData = { + ...cachedData, + sourcesWithM3u8: sourcesWithM3u8, + m3u8Timestamp: Date.now() + }; + await saveToCache(DARKINOS_CACHE_DIR, cacheKey, newCacheData); + } + const dedupedSources = deduplicateSourcesWithPreference(sourcesWithM3u8); + // Filtrer les sources avec m3u8: null avant de retourner + const filteredSources = dedupedSources.filter(source => source.m3u8); + // Retourner les sources dédupliquées et filtrées + res.status(200).json({ sources: filteredSources }); + dataReturned = true; + (async () => { + try { + // Vérifier si le cache doit être mis à jour + const shouldUpdate = await shouldUpdateCache(DARKINOS_CACHE_DIR, cacheKey); + if (!shouldUpdate) { + return; // Ne pas mettre à jour le cache + } + + await refreshDarkinoSessionIfNeeded(); + const response = await axiosDarkinoRequest({ method: 'get', url: `/api/v1/titles/${id}/download` }); + let freshSources = response.data.alternative_videos || []; + if (response.data.video) { + freshSources.unshift(response.data.video); + } + if (freshSources.length > 0) { + const basicSources = freshSources.map(source => ({ + src: source.src, + language: source.language, + quality: source.quality, + sub: source.sub + })); + const currentCacheData = await getFromCacheNoExpiration(DARKINOS_CACHE_DIR, cacheKey) || {}; + if (JSON.stringify(basicSources) !== JSON.stringify(currentCacheData.sources)) { + await saveToCache(DARKINOS_CACHE_DIR, cacheKey, { sources: basicSources }); + } + } + } catch (refreshError) { + } + })(); + return; + } + // Si pas de cache valide, comportement normal (requête Darkino) + const maxRetries = 3; + let retryCount = 0; + let response; + let success = false; + await refreshDarkinoSessionIfNeeded(); + while (!success && retryCount < maxRetries) { + try { + response = await axiosDarkinoRequest({ method: 'get', url: `/api/v1/titles/${id}/download` }); + success = true; + } catch (error) { + if (error.response?.data?.message === "Il y a eu un problème. Veuillez réessayer plus tard.") { + throw error; + } + + // Arrêter immédiatement sur les erreurs 500/403 + if (error.response && (error.response.status === 500 || error.response.status === 403)) { + throw error; + } + + retryCount++; + if (retryCount >= maxRetries) { + throw error; + } + if (!error.response) { + const delay = Math.min(2000 * Math.pow(1.5, retryCount), 5000) + (Math.random() * 500); + await new Promise(resolve => setTimeout(resolve, delay)); + } else { + throw error; + } + } + } + let sources = response.data.alternative_videos || []; + if (response.data.video) { + sources.unshift(response.data.video); + } + const basicSources = sources.map(source => ({ + src: source.src, + language: source.language, + quality: source.quality, + sub: source.sub + })); + + // --- DARKIBOX ENHANCEMENT START --- + if (darkiworld_premium) { + try { + // 1. Fetch all links for the film + const darkiboxLiensResp = await axiosDarkinoRequest({ method: 'get', url: `/api/v1/liens?perPage=100&title_id=${id}&loader=linksdl&season=1&filters=&paginate=preferLengthAware` }); + const darkiboxEntries = (darkiboxLiensResp.data?.pagination?.data || []).filter( + entry => entry.host && entry.host.id_host === 2 && entry.host.name === 'darkibox' + ); + const darkiboxIds = darkiboxEntries.map(entry => entry.id); + if (darkiboxIds.length > 0) { + // 2. POST to download-premium with all darkibox IDs + const darkiboxDownloadResp = await axiosDarkinoRequest({ method: 'post', url: `/api/v1/download-premium/${darkiboxIds.join(',')}` }); + const darkiboxLinks = (darkiboxDownloadResp.data?.liens || []).filter(l => l.lien && l.lien.includes('darkibox.com')); + // 3. For each link, extract m3u8 + const darkiboxSources = await Promise.all(darkiboxLinks.map(async (lienObj) => { + // Extraire l'ID du lien darkibox + let idMatch = lienObj.lien.match(/(?:\/d\/|\/)([a-z0-9]{12,})/i); + let darkiboxId = idMatch ? idMatch[1] : null; + let m3u8Url = null; + let embedUrl = null; + if (darkiboxId) { + embedUrl = `https://darkibox.com/embed-${darkiboxId}.html`; + m3u8Url = await extractM3u8Url(embedUrl); + } + // Find the original entry for quality/language info + const meta = darkiboxEntries.find(e => e.id === lienObj.id); + return m3u8Url ? { + src: embedUrl, // Toujours l'embed comme src + m3u8: m3u8Url, + language: (meta?.langues_compact && meta.langues_compact.length > 0) ? meta.langues_compact.map(l => l.name).join(', ') : undefined, + quality: meta?.qual?.qual, + sub: (meta?.subs_compact && meta.subs_compact.length > 0) ? meta.subs_compact.map(s => s.name).join(', ') : undefined, + provider: 'darkibox' + } : null; + })); + // Only keep valid ones + const validDarkiboxSources = darkiboxSources.filter(Boolean); + // Merge with basicSources (but don't duplicate by src) + for (const src of validDarkiboxSources) { + if (!basicSources.some(s => s.src === src.src)) { + basicSources.push(src); + } + } + } + } catch (err) { + console.error('[DARKIBOX] Error enhancing darkibox links:', err.message); + } + } + // --- DARKIBOX ENHANCEMENT END --- + + // Extract and cache m3u8 URLs + let sourcesWithM3u8 = await Promise.all( + basicSources.map(async (source, idx) => { + if (source.m3u8) { + // If m3u8 already exists, validate it and get quality + const validation = await validateM3u8Url(source.m3u8, false); + if (validation.isValid) { + return { + ...source, + m3u8: source.m3u8, + quality: validation.quality || source.quality + }; + } else { + return { ...source, m3u8: null }; + } + } else { + const m3u8Result = await extractM3u8Url(source.src); + if (m3u8Result) { + return { + ...source, + m3u8: m3u8Result.url, + quality: m3u8Result.quality || source.quality + }; + } + return { ...source, m3u8: null }; + } + }) + ); + // Retry extraction if no valid sources (up to 2 more times) + let validSources = sourcesWithM3u8.filter(source => source.m3u8); + let m3u8RetryCount = 0; + while (validSources.length === 0 && m3u8RetryCount < 2) { + m3u8RetryCount++; + await new Promise(r => setTimeout(r, 500)); + sourcesWithM3u8 = await Promise.all( + basicSources.map(async (source, idx) => { + if (source.m3u8) { + // If m3u8 already exists, validate it and get quality + const validation = await validateM3u8Url(source.m3u8, false); + if (validation.isValid) { + return { + ...source, + m3u8: source.m3u8, + quality: validation.quality || source.quality + }; + } else { + return { ...source, m3u8: null }; + } + } else { + const m3u8Result = await extractM3u8Url(source.src); + if (m3u8Result) { + return { + ...source, + m3u8: m3u8Result.url, + quality: m3u8Result.quality || source.quality + }; + } + return { ...source, m3u8: null }; + } + }) + ); + validSources = sourcesWithM3u8.filter(source => source.m3u8); + } + const dedupedSources = deduplicateSourcesWithPreference(sourcesWithM3u8); + // Save both the basic sources and the sources with m3u8 + await saveToCache(DARKINOS_CACHE_DIR, cacheKey, { + sources: basicSources, + sourcesWithM3u8: sourcesWithM3u8, + m3u8Timestamp: Date.now() + }); + // Filtrer les sources avec m3u8: null avant de retourner + const filteredSources = dedupedSources.filter(source => source.m3u8); + // Retourner les sources dédupliquées et filtrées + res.status(200).json({ sources: filteredSources }); + } catch (error) { + res.status(500).json({ error: 'Erreur lors de la récupération des liens de téléchargement' }); + } +}); +app.get('/api/series/download/:titleId/season/:seasonId/episode/:episodeId', async (req, res) => { + if (DARKINO_MAINTENANCE) { + return res.status(200).json({ error: 'Service Darkino temporairement indisponible (maintenance)' }); + } + try { + const { titleId, seasonId, episodeId } = req.params; + //console.log(`[API/SERIES/DOWNLOAD] Request for ${titleId}/${seasonId}/${episodeId}`); + const cacheKey = generateCacheKey(`series_download_${titleId}_${seasonId}_${episodeId}`); + const cachedData = await getFromCacheNoExpiration(DARKINOS_CACHE_DIR, cacheKey); + if (cachedData) { + // console.log(`[API/SERIES/DOWNLOAD] Cached data content:`, JSON.stringify(cachedData, null, 2)); + } + const M3U8_CACHE_EXPIRY = 8 * 60 * 60 * 1000; // 8 hours in milliseconds + + let dataReturned = false; + if (cachedData && cachedData.sources !== undefined) { + // console.log(`[API/SERIES/DOWNLOAD] Found cached data for ${cacheKey}`); + const now = Date.now(); + const needM3u8Refresh = !cachedData.m3u8Timestamp || + (now - cachedData.m3u8Timestamp > M3U8_CACHE_EXPIRY); + // console.log(`[API/SERIES/DOWNLOAD] M3U8 cache for ${cacheKey} needs refresh: ${needM3u8Refresh}`); + + let sourcesWithM3u8; + let validSources = []; + + // Check if we have a non-expired m3u8 cache + if (!needM3u8Refresh && cachedData.sourcesWithM3u8) { + sourcesWithM3u8 = cachedData.sourcesWithM3u8; + validSources = sourcesWithM3u8.filter(source => source.m3u8); + } + + // If the cache is expired OR if the non-expired cache has no valid links, re-extract. + if (needM3u8Refresh || validSources.length === 0) { + // console.log(`[API/SERIES/DOWNLOAD] Re-extracting m3u8. Reason: ${needM3u8Refresh ? 'cache expired' : 'no valid m3u8 in cache'}.`); + sourcesWithM3u8 = await Promise.all( + cachedData.sources.map(async (source) => { + const m3u8Result = await extractM3u8Url(source.src); + if (m3u8Result) { + return { + ...source, + m3u8: m3u8Result.url, + quality: m3u8Result.quality || source.quality + }; + } + return { ...source, m3u8: null }; + }) + ); + + const newCacheData = { + ...cachedData, + sourcesWithM3u8: sourcesWithM3u8, + m3u8Timestamp: Date.now() + }; + await saveToCache(DARKINOS_CACHE_DIR, cacheKey, newCacheData); + validSources = sourcesWithM3u8.filter(source => source.m3u8); // Recalculate valid sources + } + + // console.log(`[API/SERIES/DOWNLOAD] Sending ${validSources.length} sources from cache for ${titleId}/${seasonId}/${episodeId}`); + const dedupedSources = deduplicateSourcesWithPreference(validSources); + const filteredSources = dedupedSources.filter(source => source.m3u8); + res.status(200).json({ sources: filteredSources }); + dataReturned = true; + + (async () => { + try { + // Vérifier si le cache doit être mis à jour + const shouldUpdate = await shouldUpdateCache(DARKINOS_CACHE_DIR, cacheKey); + if (!shouldUpdate) { + return; // Ne pas mettre à jour le cache + } + + await refreshDarkinoSessionIfNeeded(); + const response = await axiosDarkinoRequest({ method: 'get', url: `/api/v1/titles/${titleId}/season/${seasonId}/episode/${episodeId}/download`, headers: darkiHeaders }); + let freshSources = response.data.alternative_videos || []; + if (response.data.video) { + freshSources.unshift(response.data.video); + } + // Filtrer les sources pour l'épisode demandé + freshSources = freshSources.filter(source => { + return !source.episode || source.episode.toString() === episodeId.toString(); + }); + if (freshSources.length > 0) { + const basicSources = freshSources.map(source => ({ + src: source.src, + language: source.language, + quality: source.quality, + sub: source.sub + })); + + const currentCacheData = await getFromCacheNoExpiration(DARKINOS_CACHE_DIR, cacheKey) || {}; + if (JSON.stringify(basicSources) !== JSON.stringify(currentCacheData.sources)) { + await saveToCache(DARKINOS_CACHE_DIR, cacheKey, { sources: basicSources }); + // console.log(`[API/SERIES/DOWNLOAD] Background cache updated for ${cacheKey}`); + } + } + } catch (refreshError) { + // Silent fail on background refresh + } + })(); + return; + } + // Si pas de cache valide, comportement normal (requête Darkino) + // console.log(`[API/SERIES/DOWNLOAD] No valid cache for ${cacheKey}, fetching from Darkino...`); + const maxRetries = 3; + let retryCount = 0; + let response; + let success = false; + await refreshDarkinoSessionIfNeeded(); + while (!success && retryCount < maxRetries) { + try { + console.log(`Tentative ${retryCount + 1}/${maxRetries} pour récupérer les données de ${titleId}/season/${seasonId}/episode/${episodeId}`); + response = await axiosDarkinoRequest({ method: 'get', url: `/api/v1/titles/${titleId}/season/${seasonId}/episode/${episodeId}/download`, headers: darkiHeaders }); + //console.log(`[API/SERIES/DOWNLOAD] Darkino response data:`, JSON.stringify(response.data, null, 2)); + success = true; + } catch (error) { + // Check if the error response contains the specific message that indicates we shouldn't retry + if (error.response?.data?.message === "Il y a eu un problème. Veuillez réessayer plus tard.") { + console.log(`Erreur Darkino définitive: ${error.response.data.message}. Arrêt des tentatives.`); + throw error; + } + + // Arrêter immédiatement sur les erreurs 500/403 + if (error.response && (error.response.status === 500 || error.response.status === 403)) { + throw error; + } + + retryCount++; + if (retryCount >= maxRetries) { + throw error; + } + const delay = Math.min(2000 * Math.pow(2, retryCount), 30000) + (Math.random() * 1000); + console.log(`Erreur lors de la tentative ${retryCount}. Nouvel essai dans ${Math.round(delay / 1000)} secondes...`); + await new Promise(resolve => setTimeout(resolve, delay)); + } + } + let sources = response.data.alternative_videos || []; + if (response.data.video) { + sources.unshift(response.data.video); + } + // Filtrer les sources pour l'épisode demandé + sources = sources.filter(source => { + return !source.episode || source.episode.toString() === episodeId.toString(); + }); + // console.log(`[API/SERIES/DOWNLOAD] Got ${sources.length} sources from Darkino for ${cacheKey}`); + const basicSources = sources.map(source => ({ + src: source.src, + language: source.language, + quality: source.quality, + sub: source.sub + })); + + // --- DARKIBOX ENHANCEMENT START --- + if (darkiworld_premium) { + try { + // 1. Paginer intelligemment pour trouver l'épisode + const darkiboxEntries = await findDarkiboxEntriesForEpisode({ titleId, seasonId, episodeId, perPage: 100, maxPages: 10 }); + const darkiboxIds = darkiboxEntries.map(entry => entry.id); + if (darkiboxIds.length > 0) { + // 2. POST to download-premium with all darkibox IDs + const darkiboxDownloadResp = await axiosDarkinoRequest({ method: 'post', url: `/api/v1/download-premium/${darkiboxIds.join(',')}` }); + const darkiboxLinks = (darkiboxDownloadResp.data?.liens || []).filter(l => l.lien && l.lien.includes('darkibox.com')); + // 3. For each link, extract m3u8 + const darkiboxSources = await Promise.all(darkiboxLinks.map(async (lienObj) => { + // Extraire l'ID du lien darkibox + let idMatch = lienObj.lien.match(/(?:\/d\/|\/)([a-z0-9]{12,})/i); + let darkiboxId = idMatch ? idMatch[1] : null; + let m3u8Url = null; + let embedUrl = null; + if (darkiboxId) { + embedUrl = `https://darkibox.com/embed-${darkiboxId}.html`; + m3u8Url = await extractM3u8Url(embedUrl); + } + // Find the original entry for quality/language info + const meta = darkiboxEntries.find(e => e.id === lienObj.id); + return m3u8Url ? { + src: embedUrl, // Toujours l'embed comme src + m3u8: m3u8Url, + language: (meta?.langues_compact && meta.langues_compact.length > 0) ? meta.langues_compact.map(l => l.name).join(', ') : undefined, + quality: meta?.qual?.qual, + sub: (meta?.subs_compact && meta.subs_compact.length > 0) ? meta.subs_compact.map(s => s.name).join(', ') : undefined, + provider: 'darkibox' + } : null; + })); + // Only keep valid ones + const validDarkiboxSources = darkiboxSources.filter(Boolean); + // Merge with basicSources (but don't duplicate by src) + for (const src of validDarkiboxSources) { + if (!basicSources.some(s => s.src === src.src)) { + basicSources.push(src); + } + } + } + } catch (err) { + console.error('[DARKIBOX] Error enhancing darkibox links (series):', err.message); + } + } + // --- DARKIBOX ENHANCEMENT END --- + + // Extract and cache m3u8 URLs + let sourcesWithM3u8 = await Promise.all( + basicSources.map(async (source) => { + if (source.m3u8) { + // If m3u8 already exists, validate it and get quality + const validation = await validateM3u8Url(source.m3u8, false); + if (validation.isValid) { + return { + ...source, + m3u8: source.m3u8, + quality: validation.quality || source.quality + }; + } else { + return { ...source, m3u8: null }; + } + } else { + const m3u8Result = await extractM3u8Url(source.src); + if (m3u8Result) { + return { + ...source, + m3u8: m3u8Result.url, + quality: m3u8Result.quality || source.quality + }; + } + return { ...source, m3u8: null }; + } + }) + ); + // Retry extraction if no valid sources (up to 2 more times) + let validSources = sourcesWithM3u8.filter(source => source.m3u8); + let m3u8RetryCount = 0; + while (validSources.length === 0 && m3u8RetryCount < 2) { + m3u8RetryCount++; + await new Promise(r => setTimeout(r, 500)); + sourcesWithM3u8 = await Promise.all( + basicSources.map(async (source) => { + if (source.m3u8) { + // If m3u8 already exists, validate it and get quality + const validation = await validateM3u8Url(source.m3u8, false); + if (validation.isValid) { + return { + ...source, + m3u8: source.m3u8, + quality: validation.quality || source.quality + }; + } else { + return { ...source, m3u8: null }; + } + } else { + const m3u8Result = await extractM3u8Url(source.src); + if (m3u8Result) { + return { + ...source, + m3u8: m3u8Result.url, + quality: m3u8Result.quality || source.quality + }; + } + return { ...source, m3u8: null }; + } + }) + ); + validSources = sourcesWithM3u8.filter(source => source.m3u8); + } + // Déduplication des sources par m3u8 (prioritaire) puis src + const seenM3u8 = new Set(); + const seenSrc = new Set(); + const dedupedSources = []; + for (const source of sourcesWithM3u8) { + const key = source.m3u8 || source.src; + if (!key) continue; + if (!seenM3u8.has(key)) { + seenM3u8.add(key); + dedupedSources.push(source); + } + } + // Déduplication supplémentaire sur src (pour éviter les doublons d'URL) + const finalSources = []; + for (const source of dedupedSources) { + if (!seenSrc.has(source.src)) { + seenSrc.add(source.src); + finalSources.push(source); + } + } + // Save both the basic sources and the sources with m3u8 + await saveToCache(DARKINOS_CACHE_DIR, cacheKey, { + sources: basicSources, + sourcesWithM3u8: sourcesWithM3u8, + m3u8Timestamp: Date.now() + }); + // Filtrer les sources avec m3u8: null avant de retourner + const filteredSources = finalSources.filter(source => source.m3u8 !== null); + // Retourner les sources dédupliquées et filtrées + res.status(200).json({ sources: filteredSources }); + } catch (error) { + console.error(`Erreur Darkino: ${error.response?.status || 'Erreur réseau'}`); + try { + const contentType = error.response?.headers?.['content-type'] || ''; + const body = error.response?.data; + if (body) { + const isHtml = typeof body === 'string' + ? body.includes('<html') || contentType.includes('text/html') + : contentType.includes('text/html'); + const serialized = typeof body === 'string' ? body : JSON.stringify(body); + const snippet = serialized?.slice(0, 2000); + if (isHtml) { + console.error('Page HTML de l\'erreur (extrait):\n', snippet); + } else { + console.error('Corps de la réponse d\'erreur (extrait):\n', snippet); + } + } + } catch (logErr) { + console.error('Impossible d\'afficher le corps de la réponse d\'erreur:', logErr); + } + res.status(500).json({ error: 'Erreur lors de la récupération des liens de téléchargement' }); + } +}); + +// Function to search for a TV series on TMDB and find the best match +async function findTvSeriesOnTMDB(title, releaseYear, overview) { + try { + // Variables pour stocker les informations de saison spéciales + let seasonOffset = 0; + let isSeasonPart = false; + let originalTitle = title; + + // Remove "- Saison X" from the title + let cleanTitle = title.replace(/\s*-\s*Saison\s+\d+$/i, ''); + + // Handle special case for series like "Les Simpson Part 2 (Saison 1 - 29) - Saison 8" + const partMatch = cleanTitle.match(/Part\s+(\d+)\s*\(Saison\s+(\d+)\s*-\s*(\d+)\)/i); + if (partMatch) { + isSeasonPart = true; + const partNumber = parseInt(partMatch[1]); + const startSeason = parseInt(partMatch[2]); + const endSeason = parseInt(partMatch[3]); + + // console.log(`Série en parties détectée: Part ${partNumber}, Saisons ${startSeason}-${endSeason}`); + + // Si c'est la partie 2+, on doit calculer le numéro de saison réel + if (partNumber > 1) { + // Chercher la saison mentionnée dans le titre + const seasonMatch = title.match(/Saison\s+(\d+)$/i); + if (seasonMatch) { + const seasonInTitle = parseInt(seasonMatch[1]); + + // On calcule le décalage à partir des informations de saison + seasonOffset = endSeason - startSeason + 1; // Nombre total de saisons dans la partie 1 + + // console.log(`Saison dans le titre: ${seasonInTitle}, Offset calculé: ${seasonOffset}`); + // console.log(`La vraie saison devrait être: ${seasonOffset + seasonInTitle - 1}`); + } + } + + // Remove the part and season range info + cleanTitle = cleanTitle.replace(/\s*Part\s+\d+\s*\(Saison\s+\d+\s*-\s*\d+\)/i, ''); + } + + // Clean up any remaining parentheses + cleanTitle = cleanTitle.replace(/\([^)]*\)/g, '').trim(); + + // console.log(`Searching TMDB for TV series: "${cleanTitle}" (Original: "${title}")`); + + // Construct the API URL for logging + const tmdbSearchUrl = `${TMDB_API_URL}/search/tv?api_key=${TMDB_API_KEY}&query=${encodeURIComponent(cleanTitle)}&language=fr-FR${releaseYear ? '&first_air_date_year=' + releaseYear : ''}`; + // console.log(`TMDB API Call URL: ${tmdbSearchUrl}`); + + // Search for the TV series on TMDB + const searchResponse = await axios.get(`${TMDB_API_URL}/search/tv`, { + params: { + api_key: TMDB_API_KEY, + query: cleanTitle, + language: 'fr-FR', // Search in French + first_air_date_year: releaseYear // Filter by year if available + } + }); + + if (!searchResponse.data.results || searchResponse.data.results.length === 0) { + // console.log(`No results found on TMDB for "${cleanTitle}"`); + return null; + } + + // Log the raw TMDB search results for debugging + // console.log(`TMDB Search Results for "${cleanTitle}":`, JSON.stringify(searchResponse.data.results.map(r => ({ id: r.id, name: r.name, first_air_date: r.first_air_date })), null, 2)); + + // Get the first few results + const potentialMatches = searchResponse.data.results.slice(0, 5); + + // Function to calculate similarity between two strings + const calculateSimilarity = (str1, str2) => { + if (!str1 || !str2) return 0; + + const s1 = str1.toLowerCase(); + const s2 = str2.toLowerCase(); + + // Calculate percentage match + let matches = 0; + const words1 = s1.split(/\s+/); + const words2 = s2.split(/\s+/); + + words1.forEach(word => { + if (words2.some(w => w.includes(word) || word.includes(w))) { + matches++; + } + }); + + return matches / Math.max(words1.length, 1); + }; + + // Find the best match by comparing title, release year, and overview + let bestMatch = null; + let highestScore = 0; + + for (const series of potentialMatches) { + // Calculate match score based on title similarity + const titleSimilarity = calculateSimilarity(cleanTitle, series.name); + + // Get detailed info for the series to compare overviews + const detailsResponse = await axios.get(`${TMDB_API_URL}/tv/${series.id}`, { + params: { + api_key: TMDB_API_KEY + } + }); + + const overviewSimilarity = overview && detailsResponse.data.overview + ? calculateSimilarity(overview, detailsResponse.data.overview) + : 0; + + // Year match (exact match gives bonus) + const yearMatch = releaseYear && series.first_air_date ? + (parseInt(series.first_air_date.split('-')[0]) === parseInt(releaseYear) ? 1 : 0) : 0; + + // Calculate total score (weighted) + // Reduce overview weight, increase title weight + const totalScore = (titleSimilarity * 0.7) + (overviewSimilarity * 0.2) + (yearMatch * 0.1); + + // console.log(`TMDB Match: "${series.name}", Score: ${totalScore.toFixed(2)} (Title: ${titleSimilarity.toFixed(2)}, Overview: ${overviewSimilarity.toFixed(2)}, Year: ${yearMatch})`); + + if (totalScore > highestScore) { + highestScore = totalScore; + bestMatch = { + ...detailsResponse.data, + match_score: totalScore + }; + } + } + + // Si on a trouvé une correspondance et qu'il s'agit d'une saison spéciale + if (bestMatch && isSeasonPart) { + // Ajouter les informations relatives à la saison dans les données TMDB + bestMatch.is_season_part = true; + bestMatch.season_offset = seasonOffset; + bestMatch.original_title = originalTitle; + + // Si nous avons une saison spécifique dans le titre + const seasonMatch = title.match(/Saison\s+(\d+)$/i); + if (seasonMatch) { + const titleSeason = parseInt(seasonMatch[1]); + bestMatch.title_season = titleSeason; + bestMatch.actual_season = seasonOffset + titleSeason - 1; + console.log(`Série en parties: La saison ${titleSeason} dans le titre correspond à la saison ${bestMatch.actual_season} de la série`); + } + } + + // Consider it a match if score is above threshold + return highestScore >= 0.3 ? bestMatch : null; + } catch (error) { + console.error('Error finding TV series on TMDB:', error); + return null; + } +} +// Middleware commun de logging +app.use((req, res, next) => { + const start = Date.now(); + res.on('finish', () => { + // Skip logging for POST /api/sync and GET /api/guest/uuid + if ((req.method === 'POST') || (req.method === 'GET')) { + return; + } + console.log(`${req.method} ${req.path} - ${res.statusCode} - ${Date.now() - start}ms`); + }); + next(); +}); + +// Gestion des erreurs unifiée +app.use((err, req, res, next) => { + if (err.message !== 'Not allowed by CORS') { + console.error('Erreur globale:', err); + } + res.status(500).json({ + error: 'Erreur serveur interne', + message: err.message, + path: req.path + }); +}); + +// Fonction utilitaire pour formater les erreurs Coflix de manière propre +function formatCoflixError(error, context = '') { + if (error && error.isAxiosError) { + const url = error.config && error.config.url ? error.config.url : ''; + const statusCode = error.response ? error.response.status : ''; + const statusText = error.response ? error.response.statusText : ''; + + // Ne pas logger les erreurs 400 + if (statusCode === 400) { + return ''; + } + + return `[AxiosError] ${error.code || ''} ${error.message} ${statusCode ? `(${statusCode} ${statusText})` : ''} ${url}`; + } else { + const msg = error && error.message + ? error.message + : (typeof error === 'string' ? error : JSON.stringify(error)); + return msg; + } +} +// Gestion améliorée de l'arrêt +let isShuttingDown = false; + + + +// Le système de graceful shutdown est maintenant géré plus bas dans le fichier +// Function to start the server with retry logic +const startServer = async (retries = 3) => { + // Create HTTP server with Express + const server = http.createServer(app); + + // Configure Keep-Alive settings + server.keepAliveTimeout = 65000; // 65 secondes + server.headersTimeout = 66000; // 66 secondes + + // Configure additional keep-alive settings + // Configure additional keep-alive settings + server.maxRequestsPerSocket = 0; // Illimité + server.requestTimeout = 300000; // 5 minutes timeout to prevent hung sockets + + // Start the server + // Backlog increased to 4096 to handle burst connections + server.listen(PORT, '0.0.0.0', 4096, () => { + console.log('Connecté à la base de données MySQL'); + + // Init Wrapped Routes + wrappedRoutes.initWrappedRoutes(pool, redis); + wrappedRoutes.initTables(); // Create tables if not exist + + // Init Top 10 Routes + const top10RoutesModule = require('./top10Routes'); + top10RoutesModule.initTop10Routes(pool, redis); + + // Mount Wrapped Routes if not already mounted (to avoid duplicates on retry) + // Checking if route is already in the stack + const isWrappedMounted = app._router && app._router.stack && app._router.stack.some(layer => + layer.regexp && layer.regexp.toString().includes('wrapped') + ); + + if (!isWrappedMounted) { + app.use('/api/wrapped', wrappedRoutes.router); + console.log('[Wrapped] Routes mounted /api/wrapped'); + } + + // Mount Top 10 Routes if not already mounted + const isTop10Mounted = app._router && app._router.stack && app._router.stack.some(layer => + layer.regexp && layer.regexp.toString().includes('top10') + ); + + if (!isTop10Mounted) { + app.use('/api/top10', top10RoutesModule.router); + console.log('[Top10] Routes mounted /api/top10'); + } + + // Start server + console.log(`Serveur démarré sur le port ${PORT} - Process ${process.pid}`); + console.log(`Proxy service available at http://localhost:${PORT}/proxy/`); + console.log(`Keep-Alive configuré: timeout=${server.keepAliveTimeout}ms, max=1000`); + console.log(`Performance tuning: UV_THREADPOOL_SIZE=${process.env.UV_THREADPOOL_SIZE}, RequestTimeout=${server.requestTimeout}ms`); + }); + + server.on('error', (err) => { + console.error('Erreur de démarrage:', err); + if (retries > 0) { + console.log(`Redémarrage... (${retries} restantes)`); + setTimeout(() => startServer(retries - 1), 5000); + } else { + console.error('Échec du démarrage après plusieurs tentatives'); + process.exit(1); + } + }); + + return server; +}; + +// === DÉMARRAGE DU WORKER === +startServer().then(() => { + console.log(`✅ Worker ${process.pid} - Serveur démarré sur le port ${PORT}`); +}).catch((error) => { + console.error(`❌ Worker ${process.pid} - Échec du démarrage:`, error); + process.exit(1); +}); + +// Graceful shutdown worker +const shutdownWorker = async () => { + console.log(`\n🛑 Worker ${process.pid} - Signal de fermeture reçu...`); + try { await redis.quit(); } catch { /* ignore */ } + process.exit(0); +}; + +process.on('SIGTERM', shutdownWorker); +process.on('SIGINT', shutdownWorker); +process.on('message', (msg) => { + if (msg === 'shutdown') shutdownWorker(); +}); + + +// Utility functions for zipVarlen and splitAndStrip +const zipVarlen = (...arrays) => { + const maxLength = Math.max(...arrays.map(arr => arr.length)); + const result = []; + + for (let i = 0; i < maxLength; i++) { + result.push(arrays.map(arr => i < arr.length ? arr[i] : [])); + } + + return result; +}; + +const splitAndStrip = (str, delimiter) => { + return str.split(delimiter).map(item => item.trim()).filter(item => item); +}; + +const removeQuotes = (str) => { + if (typeof str !== 'string') return str; + return str.replace(/^["'](.*)["']$/, '$1'); +}; + +const safeFilename = (str) => { + return str.replace(/[^a-zA-Z0-9\s\-_]/g, '').trim(); +}; + +// Language constants for Anime Sama +const LANG = { + VOSTFR: 'VOSTFR', + VF: 'VF', + VOST_ENG: 'VOSTEng', + VOST_SPA: 'VOSTSpa', + VJ: 'VJ' // Ajout VJ +}; + +const LANG_ID = { + VOSTFR: 'vostfr', + VF: 'vf', + VOST_ENG: 'vosteng', + VOST_SPA: 'vostspa', + VJ: 'vj' // Ajout VJ +}; + +const flags = { + 'VOSTFR': '🇯🇵', + 'VF': '🇫🇷', + 'VOSTEng': '🇬🇧', + 'VOSTSpa': '🇪🇸', + 'VJ': '🇯🇵' // Ajout VJ (drapeau japonais par défaut) +}; + +const id2lang = { + 'vostfr': LANG.VOSTFR, + 'vf': LANG.VF, + 'vosteng': LANG.VOST_ENG, + 'vostspa': LANG.VOST_SPA, + 'vj': LANG.VJ // Ajout VJ +}; + +const lang2ids = { + [LANG.VOSTFR]: [LANG_ID.VOSTFR], + [LANG.VF]: [LANG_ID.VF], + [LANG.VOST_ENG]: [LANG_ID.VOST_ENG], + [LANG.VOST_SPA]: [LANG_ID.VOST_SPA], + [LANG.VJ]: [LANG_ID.VJ] // Ajout VJ +}; + +const langIds = ['vostfr', 'vf', 'vosteng', 'vostspa', 'vj', 'va', 'vf1', 'vf2', 'vkr']; // Ajout 'vj' + +// Helper function to validate player URLs - filters out garbage data like _self, containerSamedi, random text +const isValidPlayerUrl = (url) => { + if (typeof url !== 'string' || url.length === 0) return false; + // Must start with http:// or https:// + if (!url.startsWith('http://') && !url.startsWith('https://')) return false; + // Must contain a dot (domain) + if (!url.includes('.')) return false; + // Filter out known garbage patterns + const invalidPatterns = ['_self', 'containerSamedi', 'élite', 'Sectes', 'prouesses', 'discord.gg']; + if (invalidPatterns.some(pattern => url.includes(pattern))) return false; + return true; +}; + +// Players class for Anime Sama +class Players { + constructor(availables = []) { + this.availables = availables; + this._best = null; + this.index = 1; + } + + get best() { + if (!this._best) { + this.setBest(); + } + return this._best; + } + + setBest(prefers = [], bans = []) { + if (!this.availables.length) { + return; + } + + // Try preferred players first + for (const prefer of prefers) { + for (const player of this.availables) { + if (player.includes(prefer)) { + this._best = player; + return; + } + } + } + + // Try to find a player that isn't banned + for (let i = this.index; i < this.availables.length + this.index; i++) { + const candidate = this.availables[i % this.availables.length]; + if (bans.every(ban => !candidate.includes(ban))) { + this._best = candidate; + return; + } + } + + // Default to first player if none match criteria + if (!this._best) { + console.warn(`WARNING: No suitable player found. Defaulting to ${this.availables[0]}`); + this._best = this.availables[0]; + } + } +} + +class Languages { + constructor(players, preferLanguages = []) { + this.players = players; + this.preferLanguages = preferLanguages; + + // Remove empty players + Object.keys(this.players).forEach(langId => { + if (!this.players[langId].availables.length) { + delete this.players[langId]; + } + }); + + if (Object.keys(this.players).length === 0) { + console.warn('WARNING: No player available'); + } + + // Group players by language + this.availables = {}; + for (const langId in this.players) { + const lang = id2lang[langId]; + if (!this.availables[lang]) { + this.availables[lang] = []; + } + this.availables[lang].push(this.players[langId]); + } + } + + get best() { + // Try preferred languages first + for (const preferLanguage of this.preferLanguages) { + if (this.availables[preferLanguage]) { + for (const player of this.availables[preferLanguage]) { + if (player.availables.length) { + return player.best; + } + } + } + } + + // Try any available language + for (const language in this.availables) { + for (const player of this.availables[language]) { + if (player.availables.length) { + console.warn(`WARNING: Language preference not respected. Defaulting to ${language}`); + return player.best; + } + } + } + + return null; + } + + setBest(...args) { + for (const langId in this.players) { + this.players[langId].setBest(...args); + } + } +} + +class Episode { + constructor(languages, serieName = "", seasonName = "", episodeName = "", index = 1) { + this.languages = languages; + this.serieName = serieName; + this.seasonName = seasonName; + this.episodeName = episodeName; + this._index = index; + + this.name = this.episodeName; + this.fancyName = this.name; + + // Add language flags to the name + for (const lang in this.languages.availables) { + this.fancyName += ` ${flags[lang]}`; + } + + this.index = this._index; + + // Extract season number + const seasonNumberMatch = seasonName.match(/\d+/); + this.seasonNumber = seasonNumberMatch ? parseInt(seasonNumberMatch[0]) : 0; + + this.longName = `${this.seasonName} - ${this.episodeName}`; + this.shortName = `${this.serieName} S${this.seasonNumber.toString().padStart(2, '0')}E${this.index.toString().padStart(2, '0')}`; + } + + get index() { + return this._index; + } + + set index(value) { + this._index = value; + for (const langId in this.languages.players) { + this.languages.players[langId].index = this._index; + } + } + + toString() { + return this.fancyName; + } +} +// Season class for Anime Sama +class Season { + constructor(url, name = "", serieName = "", client = null) { + // S'assurer que l'URL se termine par / pour éviter les problèmes de concaténation + const normalizedUrl = url.endsWith('/') ? url : url + '/'; + this.pages = langIds.map(lang => normalizedUrl + lang + "/"); + this.siteUrl = url.split('/').slice(0, 3).join('/') + '/'; + + this.name = name || url.split('/').slice(-2)[0]; + this.serieName = serieName || url.split('/').slice(-3)[0]; + + this.client = client || axiosAnimeSama; + } + + async _getPlayersLinksFrom(page) { + try { + // Aller directement vers episodes.js sans proxy (fichier JS sans protection Cloudflare) + const episodesUrl = page + 'episodes.js'; + const episodesJsResponse = await axiosAnimeSama({ + method: 'get', + url: episodesUrl, + timeout: 10000 + }); + + if (episodesJsResponse.status !== 200) { + return []; + } + + const episodesJs = episodesJsResponse.data; + + // Détecter si la réponse est une page HTML 404 déguisée (status 200 mais contenu HTML) + if (typeof episodesJs === 'string' && ( + episodesJs.includes('<!doctype html>') || + episodesJs.includes('<!DOCTYPE html>') || + episodesJs.includes('<html') || + episodesJs.includes('Page introuvable') || + episodesJs.includes('Accès Introuvable') + )) { + return []; + } + + // Vérifier que le contenu ressemble à du JavaScript valide (doit contenir des tableaux) + if (typeof episodesJs !== 'string' || !episodesJs.includes('[')) { + return []; + } + + // Extract player links from JS + const playersList = episodesJs.split('[').slice(1); + const playersListLinks = playersList.map(player => { + const matches = player.match(/'(.+?)'/g); + if (!matches) return []; + + const allLinks = matches.map(link => { + let cleanLink = link.replace(/'/g, ''); + // Remove duplicate proxy prefixes + const proxyPrefix = 'https://proxy.liyao.space/------'; + if (cleanLink.startsWith(proxyPrefix)) { + cleanLink = cleanLink.substring(proxyPrefix.length); + } + return cleanLink; + }); + + // Filtrer et logger les URLs invalides + const validLinks = allLinks.filter(isValidPlayerUrl); + const invalidLinks = allLinks.filter(link => !isValidPlayerUrl(link)); + if (invalidLinks.length > 0) { + } + + return validLinks; + }); + + const result = zipVarlen(...playersListLinks); + return result; + } catch (error) { + // Ne logger que si ce n'est pas une erreur 404 (langue inexistante) + if (!error.response || error.response.status !== 404) { + const episodesUrl = page + 'episodes.js'; + } else { + } + return []; + } + } + + async episodes(existingEpisodes = null) { + //console.log(`Getting episode list for ${this.name}`); + // Get episodes from all language pages + const episodesPagesPromises = this.pages.map(page => this._getPlayersLinksFrom(page)); + const episodesPages = await Promise.all(episodesPagesPromises); + const episodesInSeason = Math.max(...episodesPages.map(ep => ep.length)); + + // Générer des noms d'épisodes numérotés sans faire de requêtes supplémentaires + const padding = episodesInSeason.toString().length; + const episodeNames = Array.from({ length: episodesInSeason }, (_, i) => + `Episode ${(i + 1).toString().padStart(padding, '0')}` + ); + + // Create Episode objects with simple numbered names + const episodeObjs = episodeNames.map((name, index) => { + // Pour chaque épisode, récupérer les players de chaque langue + const playersLinks = episodesPages.map(pages => pages[index] || []); + + const languages = new Languages( + Object.fromEntries( + langIds.map((langId, i) => [langId, new Players(playersLinks[i])]) + ) + ); + return new Episode(languages, this.serieName, this.name, name, index + 1); + }); + + if (!existingEpisodes) { + return episodeObjs.map(ep => ({ + name: ep.name, + serie_name: ep.serieName, + season_name: ep.seasonName, + index: ep.index, + streaming_links: Object.entries(ep.languages.players).map(([langId, players]) => ({ + language: langId, + players: (Array.isArray(players.availables) ? players.availables : []).filter(isValidPlayerUrl) + })).filter(link => link.players.length > 0) + })); + } + // Sinon, fusionne avec les épisodes existants (par index) + return episodeObjs.map((ep, idx) => { + const oldEp = existingEpisodes[idx]; + if (!oldEp) { + return { + name: ep.name, + serie_name: ep.serieName, + season_name: ep.seasonName, + index: ep.index, + streaming_links: Object.entries(ep.languages.players).map(([langId, players]) => ({ + language: langId, + players: (Array.isArray(players.availables) ? players.availables : []).filter(isValidPlayerUrl) + })).filter(link => link.players.length > 0) + }; + } + // Fusionne les streaming_links par langue + const oldLinks = oldEp.streaming_links || []; + // On reconstitue les nouveaux liens à partir de ep.languages.players + const newLinks = Object.entries(ep.languages.players).map(([langId, players]) => ({ + language: langId, + players: (Array.isArray(players.availables) ? players.availables : []).filter(isValidPlayerUrl) + })); + const mergedLinks = mergeStreamingLinks(oldLinks, newLinks); + // On retourne un objet Episode-like avec les infos fusionnées + return { + name: ep.name, + serie_name: ep.serieName, + season_name: ep.seasonName, + index: ep.index, + streaming_links: mergedLinks.filter(link => link.players && link.players.length > 0) + }; + }); + } +} + +// Catalogue class for Anime Sama +class Catalogue { + constructor(url, name = "", client = null, additionalData = null) { + // Convert URLs to always use the current ANIME_SAMA_URL + if (url.startsWith('/')) { + // Relative URL + this.url = ANIME_SAMA_URL + url.substring(1); + } else if (url.startsWith('http')) { + // Absolute URL - replace domain with current ANIME_SAMA_URL + try { + const urlObj = new URL(url); + // Take pathname and search query + let path = urlObj.pathname; + if (path.startsWith('/')) path = path.substring(1); + this.url = ANIME_SAMA_URL + path + urlObj.search; + } catch (e) { + console.error("Error parsing URL in Catalogue constructor:", url); + this.url = url; + } + } else { + // Other URLs + this.url = url.endsWith('/') ? url : url + '/'; + } + this.name = name || url.split('/').slice(-2)[0]; + this.siteUrl = url.split('/').slice(0, 3).join('/') + '/'; + this.client = client || axiosAnimeSama; + + // Add additional data if provided + if (additionalData) { + this.image = additionalData.image || ''; + this.alternative_names = additionalData.alternative_names || []; + this.alternative_names_string = additionalData.alternative_names_string || ''; + } else { + this.image = ''; + this.alternative_names = []; + this.alternative_names_string = ''; + } + } + + async seasons() { + + try { + const response = await axiosAnimeSamaRequest({ + method: 'get', + url: this.url + }); + const responseData = response.data; + + // Extract seasons using regex - preserve original HTML order + // The order of panneauAnime() calls in the HTML determines the display order + const seasonsMatches = responseData.match(/panneauAnime\("(.+?)", *"(.+?)(?:vostfr|vf)"\);/g) || []; + + const seasons = []; + for (const match of seasonsMatches) { + const [_, name, link] = match.match(/panneauAnime\("(.+?)", *"(.+?)(?:vostfr|vf)"\);/) || []; + + if (name && link) { + // Extraire le nom de l'anime depuis this.url (ex: gachiakuta depuis /catalogue/gachiakuta/) + const urlParts = this.url.split('/'); + const animeNameFromUrl = urlParts[urlParts.length - 2] || urlParts[urlParts.length - 1]; // Prendre le dernier segment avant le / + + // Si le link contient le nom de l'anime au début, l'enlever + let normalizedLink = link; + if (animeNameFromUrl && normalizedLink.startsWith(animeNameFromUrl)) { + // Enlever le nom de l'anime du début du link + normalizedLink = normalizedLink.substring(animeNameFromUrl.length); + } + + // S'assurer que le link commence par / + if (!normalizedLink.startsWith('/')) { + normalizedLink = '/' + normalizedLink; + } + + // Construire l'URL complète : baseUrl + / + nom_anime + normalizedLink + const baseUrl = this.url.endsWith('/') ? this.url.slice(0, -1) : this.url; + const seasonUrl = baseUrl + normalizedLink; + + seasons.push( + new Season( + seasonUrl, + name, + this.name, + this.client + ) + ); + } + } + + // Return seasons in their original HTML order (no sorting) + return seasons; + } catch (error) { + console.error(`Error getting seasons for ${this.name}:`, error.message); + return []; + } + } +} +// Anime Sama class +class AnimeSama { + constructor(siteUrl) { + this.siteUrl = siteUrl; + this.client = axiosAnimeSama; + } + + async search(query, forceNoCache = false) { + + try { + // Check cache first, unless forceNoCache is true + const cacheKey = generateCacheKey(query); + if (!forceNoCache) { + const cachedResults = await getFromCacheNoExpiration(ANIME_SAMA_CACHE_DIR, cacheKey); + if (cachedResults) { + return cachedResults.map(result => + new Catalogue(result.url, result.name, this.client, result) + ); + } + } + + const requestUrl = `${this.siteUrl}template-php/defaut/fetch.php`; + const requestData = `query=${encodeURIComponent(query)}`; + console.log(`\n[AnimeSama Search] DEBUG INFO:`); + console.log(`[AnimeSama Search] Query: ${query}`); + console.log(`[AnimeSama Search] URL: ${requestUrl}`); + console.log(`[AnimeSama Search] Payload: ${requestData}`); + + const response = await axiosAnimeSamaRequest({ + method: 'post', + url: requestUrl, + data: requestData, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + } + }); + + if (response.status !== 200) { + return []; + } + + const responseData = response.data; + + // Parse the HTML response to extract detailed information + const results = this.parseSearchResults(responseData); + + // Save to cache + await saveToCache(ANIME_SAMA_CACHE_DIR, cacheKey, results); + + return results.map(result => + new Catalogue(result.url, result.name, this.client, result) + ); + } catch (error) { + console.error(`\n[AnimeSama Search] ERROR FAIL:`); + console.error(`[AnimeSama Search] Query: ${query}`); + console.error(`[AnimeSama Search] Error Message: ${error.message}`); + if (error.response) { + console.error(`[AnimeSama Search] Status Code: ${error.response.status}`); + console.error(`[AnimeSama Search] Response Data:`, JSON.stringify(error.response.data, null, 2)); + } + if (error.config) { + console.error(`[AnimeSama Search] Request Config URL:`, error.config.url); + } + return []; + } + } + + parseSearchResults(htmlData) { + const results = []; + + try { + // Use cheerio to parse HTML more reliably + const $ = cheerio.load(htmlData); + + // Find all anime result links + $('a').each((_, element) => { + const $link = $(element); + const href = $link.attr('href'); + + // Skip if no href or not an anime catalogue link + if (!href || !href.includes('/catalogue/')) { + return; + } + + // Extract image information + const $img = $link.find('img'); + const imageUrl = $img.attr('src') || ''; + + // Extract title from h3 + const $title = $link.find('h3'); + const mainTitle = $title.text().trim(); + + // Extract alternative names from p tag + const $altNames = $link.find('p'); + const alternativeNames = $altNames.text().trim(); + + // Split alternative names by comma and clean them + const altNamesArray = alternativeNames + ? alternativeNames.split(',').map(name => name.trim()).filter(name => name.length > 0) + : []; + + if (mainTitle && href) { + results.push({ + url: href, + name: mainTitle, + image: imageUrl, + alternative_names: altNamesArray, + alternative_names_string: alternativeNames + }); + } + }); + + // Fallback to regex parsing if cheerio parsing fails or returns no results + if (results.length === 0) { + console.log('Cheerio parsing returned no results, falling back to regex parsing'); + return this.parseSearchResultsRegex(htmlData); + } + + console.log(`Parsed ${results.length} anime results with enhanced data`); + return results; + + } catch (error) { + console.error('Error parsing search results with cheerio:', error.message); + // Fallback to regex parsing + return this.parseSearchResultsRegex(htmlData); + } + } + + parseSearchResultsRegex(htmlData) { + try { + // Extract links and names using regex (fallback method) + const links = (htmlData.match(/href="(.+?)"/g) || []).map(link => + link.replace(/href="|"/g, '') + ); + + const names = (htmlData.match(/>(.+?)<\/h3>/g) || []).map(name => + name.replace(/>(.*?)<\/h3>/g, '$1') + ); + + return links.map((link, index) => ({ + url: link, + name: names[index] || '', + image: '', + alternative_names: [], + alternative_names_string: '' + })); + } catch (error) { + console.error('Error in regex parsing fallback:', error.message); + return []; + } + } +} +// Episode cache for Anime Sama - Unified cache per anime +class EpisodeCache { + constructor(cacheDir = ANIME_SAMA_CACHE_DIR, ttl = 3600) { + this.cacheDir = cacheDir; + this.ttl = ttl * 1000; // Convert to milliseconds + } + + _getCachePath(serieName) { + // Clean names to avoid issues with special characters + const safeSerie = safeFilename(serieName); + return path.join(this.cacheDir, `${safeSerie}.json`); + } + + async getAnimeData(serieName) { + const cachePath = this._getCachePath(serieName); + + try { + const fileContent = await fsp.readFile(cachePath, 'utf-8'); + const data = normalizeAnimeSamaUrls(JSON.parse(fileContent)); + + // Check if cache is expired + if (Date.now() - data.timestamp > this.ttl) { + return null; + } + + return data.seasons || {}; + } catch (error) { + if (error.code !== 'ENOENT') { + console.error('Error reading cache:', error); + } + return null; + } + } + + async getEpisodes(serieName, seasonName) { + const animeData = await this.getAnimeData(serieName); + if (!animeData) return null; + + const seasonData = animeData[seasonName]; + return seasonData ? seasonData.episodes : null; + } + + async saveAnimeData(serieName, seasonsData) { + const cachePath = this._getCachePath(serieName); + + const data = { + timestamp: Date.now(), + seasons: seasonsData + }; + + try { + // Utiliser l'écriture atomique pour les fichiers de cache + await writeFileAtomic(cachePath, JSON.stringify(data), 'utf-8'); + await memoryCache.set(`anime:${serieName}`, data); + } catch (error) { + console.error('Error saving cache:', error); + } + } + + async saveEpisodes(serieName, seasonName, episodesData) { + // Get existing anime data or create new + let animeData = await this.getAnimeData(serieName) || {}; + + // Update the specific season + animeData[seasonName] = { + timestamp: Date.now(), + episodes: episodesData + }; + + // Save the updated anime data + await this.saveAnimeData(serieName, animeData); + } +} + +// Configure Anime Sama axios client +const axiosAnimeSama = axios.create({ + timeout: 30000, + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' + }, + + decompress: true +}); +// Configure episode cache +const episodeCache = new EpisodeCache(ANIME_SAMA_CACHE_DIR, 3600); +// Add Anime Sama API routes +app.get('/anime/search/:query', async (req, res) => { + try { + const { query } = req.params; + const cacheKey = generateCacheKey(query); + const animeCacheDir = ANIME_SAMA_CACHE_DIR; + let cachedResults = await getFromCacheNoExpiration(animeCacheDir, cacheKey); + let dataReturned = false; + + // Si pas de cache, faire la recherche Anime Sama, mettre en cache, retourner le résultat + if (!cachedResults || !Array.isArray(cachedResults) || cachedResults.length === 0) { + try { + const client = new AnimeSama(ANIME_SAMA_URL); + const searchResults = await client.search(query, false); + // search() retourne des Catalogue, on les serialize pour le cache + const serializedResults = searchResults.map(cat => ({ + url: cat.url, + name: cat.name, + image: cat.image, + alternative_names: cat.alternative_names, + alternative_names_string: cat.alternative_names_string + })); + await saveToCache(animeCacheDir, cacheKey, serializedResults); + cachedResults = serializedResults; + // On continue pour retourner la structure complète (avec saisons/épisodes) + } catch (err) { + console.error('Erreur scraping Anime Sama:', err); + return res.status(500).json({ error: 'Erreur lors de la recherche Anime Sama' }); + } + } + + // Lister tous les fichiers de cache d'anime + const allCacheFiles = await fsp.readdir(animeCacheDir).catch(() => []); + + // Pour chaque anime du cache principal (avec limitation de concurrence) + const animesWithSeasons = await Promise.all(cachedResults.map(anime => limitConcurrency10(async () => { + // On cherche le fichier de cache unifié pour cet anime + const safeAnimeName = anime.name.replace(/[^a-zA-Z0-9\s\-_]/g, '').trim(); + const animeFile = `${safeAnimeName}.json`; + + let saisons = []; + + // Vérifier si le fichier de cache unifié existe + if (allCacheFiles.includes(animeFile)) { + try { + const animeContent = await fsp.readFile(path.join(animeCacheDir, animeFile), 'utf-8'); + const animeCache = normalizeAnimeSamaUrls(JSON.parse(animeContent)); + + // Convertir les saisons du cache unifié en format attendu + if (animeCache.seasons) { + saisons = Object.entries(animeCache.seasons).map(([seasonName, seasonData]) => ({ + name: seasonName, + episodes: seasonData.episodes || [], + episodeCount: (seasonData.episodes || []).length, + cacheFile: animeFile, + timestamp: seasonData.timestamp || animeCache.timestamp || null + })); + } + } catch (e) { + console.error(`Error reading unified cache for ${anime.name}:`, e.message); + } + } else { + // Fallback: chercher les anciens fichiers de cache séparés pour migration + const seasonFiles = allCacheFiles.filter(f => f.startsWith(safeAnimeName + '_') && f !== cacheKey + '.json'); + + saisons = (await Promise.all(seasonFiles.map(async seasonFile => { + try { + const seasonContent = await fsp.readFile(path.join(animeCacheDir, seasonFile), 'utf-8'); + const seasonCache = normalizeAnimeSamaUrls(JSON.parse(seasonContent)); + return { + name: seasonFile.replace(safeAnimeName + '_', '').replace('.json', ''), + episodes: seasonCache.episodes || [], + episodeCount: (seasonCache.episodes || []).length, + cacheFile: seasonFile, + timestamp: seasonCache.timestamp || null + }; + } catch (e) { + return null; + } + }))).filter(Boolean); + } + + // Fonction pour préserver l'ordre d'origine des saisons depuis la page HTML + // L'ordre d'affichage sur la page anime-sama reflète l'ordre voulu par le site + const sortSeasons = (seasons) => { + // Ne pas trier - préserver l'ordre d'origine de la page HTML + // L'ordre des appels panneauAnime() dans le HTML détermine l'ordre d'affichage + return seasons; + }; + + return { + ...anime, + seasons: sortSeasons(saisons) + }; + }))); + + // Réponse immédiate avec tout le cache + // --- FILTRAGE FINAL DES LECTEURS INDÉSIRABLES AVANT RÉPONSE --- + const unwantedUrls = [ + 'https://video.sibnet.ru/shell.php?videoid=', + 'https://vidmoly.to/embed-.html', + 'https://sendvid.com/embed/', + 'https://vk.com/video_ext.php?oid=&hd=3' + ]; + animesWithSeasons.forEach(anime => { + if (anime.seasons && Array.isArray(anime.seasons)) { + anime.seasons.forEach(season => { + if (season.episodes && Array.isArray(season.episodes)) { + // Filtrage des URLs indésirables dans les players + season.episodes.forEach(ep => { + if (ep.streaming_links && Array.isArray(ep.streaming_links)) { + ep.streaming_links.forEach(linkObj => { + if (linkObj.players && Array.isArray(linkObj.players)) { + linkObj.players = linkObj.players.filter(url => !unwantedUrls.includes(url)); + } + }); + } + }); + // Retirer les épisodes qui n'ont aucun lecteur + season.episodes = season.episodes.filter(ep => + Array.isArray(ep.streaming_links) && + ep.streaming_links.some(linkObj => Array.isArray(linkObj.players) && linkObj.players.length > 0) + ); + // Mettre à jour le episodeCount après filtrage + season.episodeCount = season.episodes.length; + } + }); + + // Retirer les saisons qui n'ont aucun épisode + anime.seasons = anime.seasons.filter(season => + Array.isArray(season.episodes) && season.episodes.length > 0 + ); + } + }); + // --- FIN FILTRAGE FINAL --- + res.json(animesWithSeasons); + dataReturned = true; + + // --- Mise à jour en arrière-plan --- + (async () => { + const client = new AnimeSama(ANIME_SAMA_URL); + + for (const anime of animesWithSeasons) { + let catalogueObj = null; + try { + catalogueObj = new Catalogue(anime.url, anime.name, client.client, anime); + } catch (e) { + continue; + } + if (!catalogueObj) continue; + + let seasonsList = []; + try { + seasonsList = await catalogueObj.seasons(); + } catch (e) { + continue; + } + + + // Utiliser le cache unifié pour cet anime + const safeAnimeName = anime.name.replace(/[^a-zA-Z0-9\s\-_]/g, '').trim(); + const animeCacheFile = `${safeAnimeName}.json`; + const animeCachePath = path.join(animeCacheDir, animeCacheFile); + + // Charger le cache unifié existant + let existingAnimeCache = {}; + try { + const animeContent = await fsp.readFile(animeCachePath, 'utf-8'); + const animeData = JSON.parse(animeContent); + existingAnimeCache = animeData.seasons || {}; + } catch (e) { + // Pas de cache existant, continuer avec un objet vide + } + + // Vérifier si le cache a été mis à jour récemment (moins de 1 heure) + const RECENT_UPDATE_THRESHOLD = 1 * 60 * 60 * 1000; // 1 heure en millisecondes + let shouldSkipAnime = false; + try { + const stats = await fsp.stat(animeCachePath); + const timeSinceLastUpdate = Date.now() - stats.mtime.getTime(); + if (timeSinceLastUpdate < RECENT_UPDATE_THRESHOLD) { + shouldSkipAnime = true; + } + } catch (e) { + // Fichier n'existe pas, continuer normalement + } + + if (shouldSkipAnime) continue; + + let animeDataUpdated = false; + const updatedAnimeCache = { ...existingAnimeCache }; + + for (const seasonObj of seasonsList) { + const safeSeasonName = seasonObj.name.replace(/[^a-zA-Z0-9\s\-_]/g, '').trim(); + let cachedEpisodes = null; + let shouldUpdate = false; + + try { + // Récupérer les épisodes en cache pour cette saison + const seasonCache = existingAnimeCache[seasonObj.name]; + if (seasonCache && seasonCache.episodes) { + cachedEpisodes = seasonCache.episodes; + + // Vérifier d'abord s'il y a potentiellement de nouveaux contenus avant de scraper + // Scrape uniquement les langues manquantes ! + const scrapedEpisodes = await seasonObj.episodes(cachedEpisodes); + + // Vérifier s'il y a vraiment des changements significatifs + const hasNewEpisodes = scrapedEpisodes.length > cachedEpisodes.length; + const hasNewLang = scrapedEpisodes.some((ep, idx) => { + const oldEp = cachedEpisodes[idx]; + if (!oldEp) return true; // Nouvel épisode + const oldLangs = (oldEp.streaming_links || []).map(l => l.language); + const newLangs = (ep.streaming_links || []).map(l => l.language); + return newLangs.some(l => !oldLangs.includes(l)); // Nouvelle langue + }); + + // Vérifier s'il y a de nouveaux lecteurs pour les langues existantes + const hasNewPlayers = scrapedEpisodes.some((ep, idx) => { + const oldEp = cachedEpisodes[idx]; + if (!oldEp) return false; // Déjà couvert par hasNewEpisodes + + return (ep.streaming_links || []).some(newLink => { + const oldLink = (oldEp.streaming_links || []).find(ol => ol.language === newLink.language); + if (!oldLink) return false; // Déjà couvert par hasNewLang + + const oldPlayers = Array.isArray(oldLink.players) ? oldLink.players : []; + const newPlayers = Array.isArray(newLink.players) ? newLink.players : []; + return newPlayers.length > oldPlayers.length || + newPlayers.some(player => !oldPlayers.includes(player)); + }); + }); + + // Ne mettre à jour que s'il y a vraiment du nouveau contenu + if (hasNewEpisodes || hasNewLang || hasNewPlayers) { + shouldUpdate = true; + cachedEpisodes = scrapedEpisodes; + } else { + } + } else { + // Pas de cache pour cette saison, on scrape tout + shouldUpdate = true; + cachedEpisodes = await seasonObj.episodes(); + } + } catch (e) { + // Erreur lors du scraping, on scrape tout + shouldUpdate = true; + cachedEpisodes = await seasonObj.episodes(); + } + + if (shouldUpdate) { + try { + // --- FILTRAGE DES LECTEURS INDÉSIRABLES (pour la mise à jour du cache) --- + const unwantedUrls = [ + 'https://video.sibnet.ru/shell.php?videoid=', + 'https://vidmoly.to/embed-.html', + 'https://sendvid.com/embed/', + 'https://vk.com/video_ext.php?oid=&hd=3' + ]; + const episodesData = cachedEpisodes.map(episode => ({ + name: episode.name, + serie_name: episode.serie_name || episode.serieName, + season_name: episode.season_name || episode.seasonName, + index: episode.index, + streaming_links: (episode.streaming_links || []).map(linkObj => ({ + language: linkObj.language, + players: Array.isArray(linkObj.players) + ? linkObj.players.filter(url => !unwantedUrls.includes(url)) + : linkObj.players + })) + })); + // --- FIN FILTRAGE --- + + // Mettre à jour le cache unifié pour cette saison + updatedAnimeCache[seasonObj.name] = { + timestamp: Date.now(), + episodes: episodesData + }; + animeDataUpdated = true; + + } catch (e) { + console.error(`Erreur lors du scraping de la saison ${seasonObj.name} (${anime.name}):`, e.message); + } + } + } + + // Sauvegarder le cache unifié si des mises à jour ont été effectuées + if (animeDataUpdated) { + try { + const unifiedCacheData = { + timestamp: Date.now(), + seasons: updatedAnimeCache + }; + await writeFileAtomic(animeCachePath, JSON.stringify(unifiedCacheData), 'utf-8'); + + // Nettoyer les anciens fichiers de cache séparés après migration réussie + await cleanupOldCacheFiles(safeAnimeName, animeCacheDir); + } catch (e) { + } + } else if (Object.keys(existingAnimeCache).length === 0) { + // Si pas de cache unifié existant, migrer les anciens fichiers séparés + await migrateOldCacheFiles(safeAnimeName, animeCacheDir); + } + } + })(); + + } catch (error) { + console.error('Erreur /anime/search/:query:', error); + return res.status(500).json({ error: 'Erreur serveur' }); + } +}); + +// Supprime le cache d'un anime (recherche + cache unifié) +app.delete('/anime/search/:query/cache', async (req, res) => { + try { + const { query } = req.params; + const cacheKey = generateCacheKey(query); + const animeCacheDir = ANIME_SAMA_CACHE_DIR; + + let deletedFiles = []; + let errors = []; + + // 1. Supprimer le fichier de cache de recherche + try { + const searchCacheFile = path.join(animeCacheDir, `${cacheKey}.json`); + await fsp.unlink(searchCacheFile); + deletedFiles.push(`search cache: ${cacheKey}.json`); + } catch (err) { + if (err.code !== 'ENOENT') { + errors.push(`Erreur suppression cache de recherche: ${err.message}`); + } + } + + // 2. Supprimer le cache unifié de l'anime (basé sur le nom) + try { + // Lire le cache de recherche pour obtenir le nom exact de l'anime + // Sinon, on utilise directement la query décodée + const decodedQuery = decodeURIComponent(query); + const safeAnimeName = decodedQuery.replace(/[^a-zA-Z0-9\s\-_]/g, '').trim(); + const animeFile = path.join(animeCacheDir, `${safeAnimeName}.json`); + + try { + await fsp.unlink(animeFile); + deletedFiles.push(`unified cache: ${safeAnimeName}.json`); + } catch (err) { + if (err.code !== 'ENOENT') { + errors.push(`Erreur suppression cache unifié: ${err.message}`); + } + } + + // 3. Supprimer également les anciens fichiers de cache séparés (si existants) + const allCacheFiles = await fsp.readdir(animeCacheDir).catch(() => []); + const oldSeasonFiles = allCacheFiles.filter(f => + f.startsWith(safeAnimeName + '_') && f.endsWith('.json') + ); + + for (const oldFile of oldSeasonFiles) { + try { + await fsp.unlink(path.join(animeCacheDir, oldFile)); + deletedFiles.push(`old season cache: ${oldFile}`); + } catch (err) { + errors.push(`Erreur suppression ancien cache ${oldFile}: ${err.message}`); + } + } + } catch (err) { + errors.push(`Erreur lors de la recherche des fichiers: ${err.message}`); + } + + // Réponse + if (deletedFiles.length > 0) { + return res.status(200).json({ + success: true, + message: `Cache anime "${decodeURIComponent(query)}" supprimé.`, + deletedFiles, + errors: errors.length > 0 ? errors : undefined + }); + } else { + return res.status(404).json({ + success: false, + error: 'Aucun cache trouvé pour cet anime.', + errors: errors.length > 0 ? errors : undefined + }); + } + } catch (err) { + console.error('Erreur suppression cache anime:', err); + return res.status(500).json({ success: false, error: 'Erreur serveur.' }); + } +}); + +// Fonction pour obtenir les détails d'un contenu depuis l'ID TMDB +async function getTMDBDetails(id, type) { + try { + // Récupérer d'abord les données sans langue pour avoir le titre international + let response = await axios.get(`${TMDB_API_URL}/${type}/${id}`, { + params: { + api_key: TMDB_API_KEY, + language: 'fr-FR' + } + }); + + if (!response.data) { + return null; + } + + // Essayer ensuite de récupérer les données en français pour l'overview + let frenchResponse = null; + try { + frenchResponse = await axios.get(`${TMDB_API_URL}/${type}/${id}`, { + params: { + api_key: TMDB_API_KEY, + language: 'fr-FR' + } + }); + } catch (error) { + // Si la requête française échoue, on continue avec les données internationales + console.log(`Impossible de récupérer les données françaises pour ${id}, utilisation des données internationales`); + } + + // Formater les données selon le type + let details = { + id: response.data.id, + title: type === 'movie' ? response.data.title : response.data.name, // Titre international + original_title: type === 'movie' ? response.data.original_title : response.data.original_name, + release_date: type === 'movie' ? response.data.release_date : response.data.first_air_date, + poster_path: response.data.poster_path, + backdrop_path: response.data.backdrop_path, + overview: frenchResponse?.data?.overview || response.data.overview, // Overview français si disponible, sinon international + vote_average: response.data.vote_average + }; + // Ne plus sauvegarder en cache + // await saveToCache(CACHE_DIR.TMDB, details); + return details; + } catch (error) { + console.error(`Erreur lors de la récupération des détails TMDB pour ${id} (${type}):`, error); + return null; + } +} + +// Fonction pour normaliser les caractères spéciaux pour les requêtes Coflix +function normalizeCoflixQuery(query) { + if (!query) return query; + + // Dictionnaire des caractères à remplacer + const replacements = { + 'à': 'a', 'á': 'a', 'â': 'a', 'ã': 'a', 'ä': 'a', 'å': 'a', + 'è': 'e', 'é': 'e', 'ê': 'e', 'ë': 'e', + 'ì': 'i', 'í': 'i', 'î': 'i', 'ï': 'i', + 'ò': 'o', 'ó': 'o', 'ô': 'o', 'õ': 'o', 'ö': 'o', + 'ù': 'u', 'ú': 'u', 'û': 'u', 'ü': 'u', + 'ý': 'y', 'ÿ': 'y', + 'ñ': 'n', + 'ç': 'c', + 'œ': 'oe', 'æ': 'ae', + 'À': 'A', 'Á': 'A', 'Â': 'A', 'Ã': 'A', 'Ä': 'A', 'Å': 'A', + 'È': 'E', 'É': 'E', 'Ê': 'E', 'Ë': 'E', + 'Ì': 'I', 'Í': 'I', 'Î': 'I', 'Ï': 'I', + 'Ò': 'O', 'Ó': 'O', 'Ô': 'O', 'Õ': 'O', 'Ö': 'O', + 'Ù': 'U', 'Ú': 'U', 'Û': 'U', 'Ü': 'U', + 'Ý': 'Y', 'Ÿ': 'Y', + 'Ñ': 'N', + 'Ç': 'C', + 'Œ': 'OE', 'Æ': 'AE' + }; + + // Remplacer tous les caractères spéciaux + let normalized = query; + for (const [special, normal] of Object.entries(replacements)) { + normalized = normalized.split(special).join(normal); + } + + return normalized; +} + +// Fonction pour rechercher un contenu sur Coflix par titre +async function searchCoflixByTitle(title, mediaType, releaseYear) { + try { + // Normaliser le titre avant de faire la requête pour éviter les erreurs 400 + const normalizedTitle = normalizeCoflixQuery(title); + + const response = await axiosCoflixRequest({ method: 'get', url: `/suggest.php?query=${encodeURIComponent(normalizedTitle)}` }); + + // Vérifier que la réponse est un tableau + if (!Array.isArray(response.data)) { + console.error(`La réponse de l'API Coflix n'est pas un tableau: ${formatCoflixError(response.data)}`); + return []; + } + + // Mapper les résultats et calculer la similarité pour tous les types de média + const results = response.data.map(item => { + // Normaliser les titres pour calculer la similarité + const similarity = calculateTitleSimilarity(title, item.title); + + // Debug logging pour Alice + if (title.toLowerCase().includes('alice') || item.title.toLowerCase().includes('alice')) { + } + + // Extraire l'année de sortie + const resultYear = item.year ? parseInt(item.year) : null; + + return { + title: item.title, + url: item.url, + similarity: similarity, + year: resultYear, + id: item.ID, + excerpt: item.excerpt, + post_type: item.post_type, + rating: item.rating + }; + }); + + // Faire correspondre le type de média demandé avec les types de Coflix + let coflixTypes = []; + + if (mediaType === 'movie') { + coflixTypes = ['movies']; + } else if (mediaType === 'tv') { + // Pour la TV, on accepte séries et animes + coflixTypes = ['series', 'animes', 'doramas']; + } else if (mediaType === 'anime') { + coflixTypes = ['animes']; + } else { + // Si aucun type spécifié, accepter tous les types + coflixTypes = ['movies', 'series', 'animes', 'doramas']; + } + + // Filtrer d'abord par type de média + let filteredResults = mediaType + ? results.filter(item => coflixTypes.includes(item.post_type)) + : results; + + // filteredResults.map(r => `${r.title} (${r.post_type}) [${r.similarity}]`); // Original logging line + + // Sort filteredResults by similarity to easily pick the best one later. + filteredResults.sort((a, b) => b.similarity - a.similarity); + + if (releaseYear) { + const yearMatchedResults = filteredResults.filter(r => r.year === releaseYear); + + if (mediaType === 'movie') { + // For movies, strict year match. If yearMatchedResults is empty, filteredResults becomes empty. + // If not empty, take the best one (already sorted) if its similarity is good. + if (yearMatchedResults.length > 0 && yearMatchedResults[0].similarity >= 0.80) { + filteredResults = [yearMatchedResults[0]]; + } else { + filteredResults = []; + } + } else if (mediaType === 'tv') { // Covers 'series', 'animes', 'doramas' via coflixTypes + // For TV series, be strict about year matching to avoid wrong versions + if (yearMatchedResults.length > 0 && yearMatchedResults[0].similarity >= 0.70) { + // Use the best year match if similarity is decent + filteredResults = [yearMatchedResults[0]]; + } else { + // For TV series, do NOT use fallback to avoid wrong versions (like Shameless US 2011 instead of UK 2004) + filteredResults = []; // No fallback for TV series + } + } else { // For any other specific types (e.g. 'anime' if not covered by 'tv' explicitly above for some reason) + if (yearMatchedResults.length > 0 && yearMatchedResults[0].similarity >= 0.80) { + filteredResults = [yearMatchedResults[0]]; + } else { + filteredResults = []; + } + } + } else { // No releaseYear specified + // Use the best item from the type-filtered list if similarity is good. + if (filteredResults.length > 0 && filteredResults[0].similarity > 0.80) { + filteredResults = [filteredResults[0]]; + } else { + // If no release year, and best type-match is not good enough, or list is empty + filteredResults = []; + } + } + + // Return the filtered results + return filteredResults; + + } catch (error) { + // Affichage propre de l'erreur Coflix + console.error(`Erreur lors de la recherche sur Coflix pour ${title}: ${formatCoflixError(error)}`); + throw error; + } +} +// Fonction utilitaire pour calculer la similarité entre deux titres +function calculateTitleSimilarity(title1, title2) { + if (!title1 || !title2) return 0; + + const t1 = title1.toLowerCase(); + const t2 = title2.toLowerCase(); + + // Normaliser les titres (enlever les accents, etc.) + const normalize = (str) => str + .normalize("NFD") + .replace(/[\u0300-\u036f]/g, "") // remove diacritics + .replace(/[®™©]/g, "") // remove trademark-like symbols + .replace(/[^\p{L}\p{N}\s]/gu, " ") // replace other punctuation with space + .replace(/\s+/g, " ") + .trim(); + const norm1 = normalize(t1); + const norm2 = normalize(t2); + + // Exact match priorité absolue - Vérification stricte d'égalité + if (norm1 === norm2) { + return 1.0; + } + + // Vérification stricte pour les numéros de suite et sous-titres + // Extraire les numéros de suite (ex: "3", "2", etc.) + const extractNumbers = (str) => { + const numbers = str.match(/\b\d+\b/g); + return numbers ? numbers.map(n => parseInt(n)) : []; + }; + + const numbers1 = extractNumbers(norm1); + const numbers2 = extractNumbers(norm2); + + // Si un titre a un numéro et l'autre non, ou si les numéros sont différents, pénaliser fortement + if (numbers1.length > 0 || numbers2.length > 0) { + const hasCommonNumbers = numbers1.length > 0 && numbers2.length > 0 && + numbers1.some(n1 => numbers2.some(n2 => n1 === n2)); + + // Si un titre a un numéro et l'autre non, ou si les numéros sont différents + if (!hasCommonNumbers) { + return 0.2; // Forte pénalité pour numéros différents ou manquants + } + } + + // Vérifier les sous-titres (après ":" ou " - ") + const extractSubtitles = (str) => { + const parts = str.split(/[:|]/); + return parts.length > 1 ? parts[1].trim() : ""; + }; + + const subtitle1 = extractSubtitles(norm1); + const subtitle2 = extractSubtitles(norm2); + + // Si les titres ont des sous-titres différents, pénaliser + if (subtitle1 && subtitle2 && subtitle1 !== subtitle2) { + // Vérifier si les sous-titres sont similaires (même ville, même concept) + const subtitleWords1 = subtitle1.split(/\s+/).filter(w => w.length > 2); + const subtitleWords2 = subtitle2.split(/\s+/).filter(w => w.length > 2); + const commonSubtitleWords = subtitleWords1.filter(w1 => + subtitleWords2.some(w2 => w1.includes(w2) || w2.includes(w1)) + ); + + if (commonSubtitleWords.length === 0) { + return 0.3; // Pénalité pour sous-titres complètement différents + } + } + + // Vérification spéciale pour les titres avec des mots-clés de différenciation + // Si un titre contient des mots comme "londres", "paris", "new york" et l'autre non + const locationKeywords = ['londres', 'paris', 'new york', 'tokyo', 'berlin', 'rome', 'madrid', 'barcelone']; + const hasLocation1 = locationKeywords.some(keyword => norm1.includes(keyword)); + const hasLocation2 = locationKeywords.some(keyword => norm2.includes(keyword)); + + if (hasLocation1 !== hasLocation2) { + return 0.25; // Pénalité si un titre a une localisation et l'autre non + } + + // Gestion spéciale pour les titres courts (≤ 10 caractères) - À FAIRE EN PREMIER + if (norm1.length <= 10 || norm2.length <= 10) { + // Pour les titres courts, être plus strict avec l'inclusion pour éviter les faux positifs + if (norm2.includes(norm1) || norm1.includes(norm2)) { + const shorter = norm1.length <= norm2.length ? norm1 : norm2; + const longer = norm1.length <= norm2.length ? norm2 : norm1; + const lengthRatio = shorter.length / longer.length; + + // Être beaucoup plus strict pour éviter les correspondances comme "Alice" vs "Alice in Borderland" + if (lengthRatio >= 0.8) { + return 0.85; + } else if (lengthRatio >= 0.6) { + return 0.7; + } else if (lengthRatio >= 0.4) { + return 0.5; + } + // Pour les ratios très faibles (< 0.4), pénaliser fortement + return 0.2; + } + } + + // Boost si le titre recherché est un token de tête du résultat (ex: "f1" vs "f1 le film") + if (norm2.startsWith(norm1 + " ") || norm1.startsWith(norm2 + " ")) { + return 0.9; + } + + // Si les titres ne sont pas exactement identiques, on utilise une similarité inférieure à 1.0 + if (norm2.includes(norm1) || norm1.includes(norm2)) { + if (norm1.length < norm2.length && norm2.includes(norm1)) { + const lengthRatio = norm1.length / norm2.length; + // Être plus strict avec les correspondances partielles + if (lengthRatio >= 0.6) { + return 0.8 * lengthRatio; + } else if (lengthRatio >= 0.4) { + return 0.6 * lengthRatio; + } + return 0.3; // Pénalité forte pour les correspondances très partielles + } + // Si le titre trouvé est plus court et inclus dans la recherche + else if (norm2.length < norm1.length && norm1.includes(norm2)) { + const lengthRatio = norm2.length / norm1.length; + if (lengthRatio >= 0.6) { + return 0.75 * lengthRatio; + } else if (lengthRatio >= 0.4) { + return 0.55 * lengthRatio; + } + return 0.3; // Pénalité forte pour les correspondances très partielles + } + return 0.6; // Score réduit pour inclusion partielle générale + } + + // Diviser en mots et filtrer les mots courts (articles, etc.) + const filterShortWords = words => words.filter(w => w.length > 3); + const words1 = filterShortWords(norm1.split(/\s+/)); + const words2 = filterShortWords(norm2.split(/\s+/)); + + // Si pas de mots significatifs, utiliser les mots originaux + const finalWords1 = words1.length ? words1 : norm1.split(/\s+/); + const finalWords2 = words2.length ? words2 : norm2.split(/\s+/); + + // Calculer le pourcentage de mots correspondants avec un poids plus élevé pour l'ordre + let matches = 0; + let orderBonus = 0; + + finalWords1.forEach((word, index) => { + const matchIndex = finalWords2.findIndex(w => w.includes(word) || word.includes(w)); + if (matchIndex !== -1) { + matches++; + // Bonus si les mots sont dans un ordre similaire + if (Math.abs(index - matchIndex) < 2) { + orderBonus += 0.1; + } + } + }); + + const baseScore = matches / Math.max(finalWords1.length, finalWords2.length, 1); + return Math.min(baseScore + orderBonus, 0.95); // Maximum 0.95 pour les correspondances non exactes +} + +// Fonction pour filtrer les lecteurs emmmmbed.com et lecteur6.com des données +function filterEmmmmbedReaders(data) { + if (!data) return data; + + // Fonction récursive pour parcourir l'objet + function filterObject(obj) { + if (Array.isArray(obj)) { + return obj.map(item => filterObject(item)); + } else if (obj && typeof obj === 'object') { + const filtered = {}; + for (const [key, value] of Object.entries(obj)) { + if (key === 'player_links' && Array.isArray(value)) { + // Filtrer les lecteurs lecteur1.xtremestream.xyz + filtered[key] = value.filter(link => + !link.decoded_url || + !link.decoded_url.includes('lecteur1.xtremestream.xyz') + ); + } else { + filtered[key] = filterObject(value); + } + } + return filtered; + } + return obj; + } + + return filterObject(data); +} + +// Fonction pour extraire les données des films depuis Coflix +async function getMovieDataFromCoflix(url) { + let cachedData = null; + let hadCache = false; + try { + // Générer une clé de cache basée sur l'URL + const cacheKey = generateCacheKey({ url: url, type: 'movie' }); + + // Vérifier le cache sans expiration (stale-while-revalidate) + cachedData = await getFromCacheNoExpiration(CACHE_DIR.COFLIX, cacheKey); + hadCache = !!cachedData; // Mémoriser si on avait un cache + if (cachedData) { + // Ne pas utiliser le cache si player_links est vide — re-fetcher pour tenter d'obtenir les liens + if (!cachedData.player_links || cachedData.player_links.length === 0) { + console.log(`[COFLIX MOVIE] Cache ignoré (player_links vide) pour ${url} — re-fetch en cours`); + } else { + return cachedData; + } + } + + // Convertir l'URL complète en chemin relatif pour axiosCoflix + const relativePath = url.replace(/^https:\/\/coflix\.mov/, ''); + const proxiedUrl = `${url}`; + //console.log(`Récupération des données du film depuis ${proxiedUrl}`); + const response = await axiosCoflixRequest({ method: 'get', url: relativePath }); + const $ = cheerio.load(response.data); + + // Récupérer l'iframe + let iframe = $('main div div div article div:nth-child(2) div:nth-child(1) aside div div iframe'); + if (!iframe.length) { + iframe = $('article iframe'); + } + if (!iframe.length) { + iframe = $('iframe'); + } + + let iframeSrc = null; + let playerLinks = []; + + if (iframe.length > 0) { + iframeSrc = iframe.attr('src'); + + // Accéder à la page de l'iframe pour récupérer les liens des lecteurs + if (iframeSrc) { + try { + const iframePageResponse = await axiosLecteurVideoRequest({ method: 'get', url: iframeSrc }); + const iframePage$ = cheerio.load(iframePageResponse.data); + + // Extraire les liens des lecteurs + let playerItems = iframePage$('li[onclick*="showVideo"]'); + if (!playerItems.length) { + playerItems = iframePage$('div li[onclick]'); + } + + if (playerItems.length === 0) { + const bodyHtml = iframePage$('body').html() || ''; + console.warn(`[COFLIX MOVIE] ⚠️ Aucun playerItem — iframe: ${iframeSrc}, status: ${iframePageResponse.status}, taille: ${(iframePageResponse.data || '').length} chars, aperçu HTML: ${bodyHtml.substring(0, 500)}`); + } + + playerItems.each((i, element) => { + try { + const $element = iframePage$(element); + const onClickAttr = $element.attr('onclick') || ''; + + const base64Match = onClickAttr.match(/showVideo\(['"]([^'\"]+)['"]/); + + if (base64Match && base64Match[1]) { + const base64Url = base64Match[1]; + + let decodedUrl; + try { + decodedUrl = Buffer.from(base64Url, 'base64').toString('utf-8'); + } catch (decodeError) { + decodedUrl = null; + } + + const quality = $element.find('span').text().trim(); + + let language = 'Unknown'; + const info = $element.find('p').text().trim(); + if (info.toLowerCase().includes('french')) { + language = 'French'; + } else if (info.toLowerCase().includes('english')) { + language = 'English'; + } else if (info.toLowerCase().includes('vostfr')) { + language = 'VOSTFR'; + } + + playerLinks.push({ + // Supprimer le lien encodé en base64 + // base64_url: base64Url, + decoded_url: decodedUrl, // Garder le lien décodé + quality: quality, + language: language + }); + } + } catch (playerError) { + const errorCode = playerError.response?.status || playerError.code || 'unknown'; + console.error(`erreur: ${errorCode}`); + } + }); + } catch (iframePageError) { + const errorCode = iframePageError.response?.status || iframePageError.code || 'unknown'; + console.error(`[COFLIX MOVIE] ❌ Erreur requête iframe ${iframeSrc} — code: ${errorCode}, message: ${iframePageError.message}`); + } + } + } else { + console.log(`Aucun iframe trouvé pour l'URL ${url}`); + } + + const result = { + // Ne pas exposer l'URL de l'iframe si elle contient coflix + iframe_src: iframeSrc && !iframeSrc.includes('coflix') ? iframeSrc : null, + player_links: playerLinks + }; + + // Sauvegarder dans le cache + await saveToCache(CACHE_DIR.COFLIX, cacheKey, result); + + return result; + } catch (error) { + // En cas d'erreur HTTP/Axios (ex: 403), vérifier si on avait un cache + if (error && (error.isAxiosError || (error.response && error.response.status))) { + console.error(`Erreur lors de la récupération des données du film Coflix: ${formatCoflixError(error)}`); + // Si on avait un cache, retourner le cache au lieu de propager l'erreur + if (hadCache) { + console.log(`[COFLIX] Cache préservé malgré l'erreur pour ${url}`); + return cachedData; + } + throw error; + } + console.error(`Erreur lors de la récupération des données du film Coflix: ${formatCoflixError(error)}`); + // Pour les autres erreurs non HTTP, vérifier si on avait un cache + if (hadCache) { + console.log(`[COFLIX] Cache préservé malgré l'erreur pour ${url}`); + return cachedData; + } + // Si pas de cache, retourner une structure vide sans bloquer + return { iframe_src: null, player_links: [] }; + } +} +// Nouvelle fonction pour récupérer les épisodes via l'API Coflix +async function fetchCoflixSeriesEpisodes(postId, seasonNumber) { + try { + const apiUrl = `https://coflix.observer/wp-json/apiflix/v1/series/${postId}/${seasonNumber}`; + + const response = await axiosCoflixRequest({ method: 'get', url: `/wp-json/apiflix/v1/series/${postId}/${seasonNumber}` }); + if (response.data && Array.isArray(response.data.episodes)) { + return response.data; + } + return null; + } catch (error) { + // Affichage propre de l'erreur Coflix + console.error(`Erreur lors de la récupération des épisodes Coflix: ${formatCoflixError(error)}`); + return null; + } +} +// Fonction pour extraire les données des séries depuis Coflix +async function getTvDataFromCoflix(url, seasonNumber, episodeNumber) { + let cachedData = null; + let hadCache = false; + try { + // Générer une clé de cache basée sur l'URL, saison et épisode + const cacheKey = generateCacheKey({ url: url, season: seasonNumber, episode: episodeNumber, type: 'tv' }); + + // Vérifier le cache sans expiration (stale-while-revalidate) + cachedData = await getFromCacheNoExpiration(CACHE_DIR.COFLIX, cacheKey); + hadCache = !!cachedData; // Mémoriser si on avait un cache + if (cachedData) { + //console.log(`Données de la série Coflix récupérées depuis le cache pour ${url}`); + return cachedData; + } + + // Convertir l'URL complète en chemin relatif pour axiosCoflix + const relativePath = url.replace(/^https:\/\/coflix\.mov/, ''); + const proxiedUrl = `${url}`; + const response = await axiosCoflixRequest({ method: 'get', url: relativePath }); + const $ = cheerio.load(response.data); + + // Récupérer les saisons + const seasonItems = $('article section div aside div ul li'); + + if (!seasonItems.length) { + console.log(`[ERROR] Aucune saison trouvée pour ${url}`); + + // Essayer d'autres sélecteurs possibles pour diagnostiquer + const altSelectors = [ + 'ul li', + '.seasons li', + '.season-list li', + '[data-season]', + 'input[data-season]' + ]; + + for (const selector of altSelectors) { + const altItems = $(selector); + if (altItems.length > 0) { + } + } + + // Afficher un échantillon du HTML pour diagnostic + const bodyContent = $('body').html(); + if (bodyContent) { + const truncatedContent = bodyContent.substring(0, 500); + } + + return { + seasons: [], + current_episode: null + }; + } + + // Extraire les saisons + const seasons = []; + let targetSeason = null; + let postId = null; + + for (let i = 0; i < seasonItems.length; i++) { + const $seasonElement = $(seasonItems[i]); + const $label = $seasonElement.find('label'); + const $input = $label.find('input'); + + const sNumber = $input.attr('data-season'); + const seriesId = $input.attr('data-id'); + const currentPostId = $input.attr('post-id'); + const seasonName = $label.find('span').text().trim(); + + const season = { + season_number: parseInt(sNumber), + name: seasonName, + data_id: seriesId, + post_id: currentPostId, + episodes: [] + }; + + seasons.push(season); + + // Si c'est la saison recherchée, la marquer + if (parseInt(sNumber) === seasonNumber) { + targetSeason = season; + postId = currentPostId; + } + } + + // Extraire le slug de la série pour construire les URLs des épisodes + const slugMatch = url.match(/\/serie\/([^/]+)/); + const animeMatch = url.match(/\/animes\/([^/]+)/); + const seriesSlug = slugMatch ? slugMatch[1] : (animeMatch ? animeMatch[1] : ''); + + // Si une saison et un épisode spécifiques sont demandés + if (targetSeason && episodeNumber) { + // Tenter de récupérer les épisodes via l'API si on a un post_id + let episodeApiData = null; + let episodeUrl = null; + + if (postId) { + const apiData = await fetchCoflixSeriesEpisodes(postId, seasonNumber); + if (apiData && apiData.episodes) { + // Chercher l'épisode spécifique dans les données de l'API + const episode = apiData.episodes.find(ep => parseInt(ep.number) === parseInt(episodeNumber)); + if (episode && episode.links) { + // Convertir l'URL pour utiliser le proxy si c'est une URL coflix.observer + episodeUrl = episode.links.startsWith('https://coflix.observer') + ? `${episode.links}` + : episode.links; + // console.log(`URL d'épisode trouvée via l'API: ${episodeUrl}`); + } + } + } + + // Si l'URL n'a pas été trouvée via l'API, utiliser la méthode classique + if (!episodeUrl) { + // Pour tous les types de contenu (séries et animes), utiliser le format NxN + episodeUrl = `https://coflix.observer/episode/${seriesSlug}-${seasonNumber}x${episodeNumber}/`; + // console.log(`URL d'épisode construite manuellement: ${episodeUrl}`); + } + + try { + // console.log(`Récupération des données de l'épisode depuis ${episodeUrl}`); + // Utiliser directement makeCoflixRequest pour toutes les URLs + const episodePageResponse = await makeCoflixRequest(episodeUrl, { headers: coflixHeaders, timeout: 15000 }); + const episodePage$ = cheerio.load(episodePageResponse.data); + + // Extraire le titre de l'épisode + const episodeTitle = episodePage$('article header h1').text().trim(); + const episodePlayerLinks = []; + + // Trouver l'iframe dans la page de l'épisode + let episodeIframe = episodePage$('main div div div article div iframe'); + if (!episodeIframe.length) { + episodeIframe = episodePage$('article iframe'); + } + if (!episodeIframe.length) { + episodeIframe = episodePage$('iframe'); + } + + let episodeIframeSrc = null; + + if (episodeIframe.length > 0) { + episodeIframeSrc = episodeIframe.attr('src'); + // console.log(`Iframe trouvé pour l'épisode: ${episodeIframeSrc}`); + + // Accéder à la page de l'iframe pour l'épisode + if (episodeIframeSrc) { + try { + const iframePageResponse = await axiosLecteurVideoRequest({ method: 'get', url: episodeIframeSrc }); + const iframePage$ = cheerio.load(iframePageResponse.data); + + // Extraire les liens des lecteurs depuis la page de l'iframe + let playerItems = iframePage$('li[onclick*="showVideo"]'); + if (!playerItems.length) { + playerItems = iframePage$('div li[onclick]'); + } + + playerItems.each((i, element) => { + try { + const $element = iframePage$(element); + const onClickAttr = $element.attr('onclick') || ''; + + const base64Match = onClickAttr.match(/showVideo\(['"]([^'\"]+)['"]/); + + if (base64Match && base64Match[1]) { + const base64Url = base64Match[1]; + + let decodedUrl; + try { + decodedUrl = Buffer.from(base64Url, 'base64').toString('utf-8'); + } catch (decodeError) { + decodedUrl = null; + } + + const quality = $element.find('span').text().trim(); + + let language = 'Unknown'; + const info = $element.find('p').text().trim(); + if (info.toLowerCase().includes('french')) { + language = 'French'; + } else if (info.toLowerCase().includes('english')) { + language = 'English'; + } else if (info.toLowerCase().includes('vostfr')) { + language = 'VOSTFR'; + } + + episodePlayerLinks.push({ + // Supprimer le lien encodé en base64 + // base64_url: base64Url, + decoded_url: decodedUrl, // Garder le lien décodé + quality: quality, + language: language + }); + } + } catch (playerError) { + const errorCode = playerError.response?.status || playerError.code || 'unknown'; + console.error(`erreur: ${errorCode}`); + } + }); + } catch (iframePageError) { + const errorCode = iframePageError.response?.status || iframePageError.code || 'unknown'; + console.error(`erreur: ${errorCode}`); + } + } + } + + return { + seasons: seasons, + current_episode: { + season_number: seasonNumber, + episode_number: episodeNumber, + title: episodeTitle, + // Ne pas inclure l'URL de l'épisode + // url: episodeUrl, + // Ne pas exposer l'URL de l'iframe si elle contient coflix + iframe_src: episodeIframeSrc && !episodeIframeSrc.includes('coflix') ? episodeIframeSrc : null, + player_links: episodePlayerLinks + } + }; + } catch (episodeError) { + console.error(`Erreur lors de la récupération des données de l'épisode: ${formatCoflixError(episodeError)}`); + return { + seasons: seasons, + current_episode: null + }; + } + } + + const result = { + seasons: seasons, + current_episode: null + }; + + // Sauvegarder dans le cache + await saveToCache(CACHE_DIR.COFLIX, cacheKey, result); + + return result; + } catch (error) { + // En cas d'erreur HTTP/Axios (ex: 403), vérifier si on avait un cache + if (error && (error.isAxiosError || (error.response && error.response.status))) { + console.error(`Erreur lors de la récupération des données de la série Coflix: ${formatCoflixError(error)}`); + // Si on avait un cache, retourner le cache au lieu de propager l'erreur + if (hadCache) { + console.log(`[COFLIX] Cache préservé malgré l'erreur pour ${url}`); + return cachedData; + } + throw error; + } + console.error(`Erreur lors de la récupération des données de la série Coflix: ${formatCoflixError(error)}`); + // Pour les autres erreurs non HTTP, vérifier si on avait un cache + if (hadCache) { + console.log(`[COFLIX] Cache préservé malgré l'erreur pour ${url}`); + return cachedData; + } + // Si pas de cache, retourner une structure vide sans bloquer + return { seasons: [], current_episode: null }; + } +} + +// Route pour récupérer les liens à partir d'un ID TMDB +app.get('/api/tmdb/:type/:id', async (req, res) => { + const { id, type } = req.params; + + // Bloquer certains IDs TMDB spécifiques (comme demandé pour le movie 771) + if (type === 'movie' && id === '771') { + return res.status(404).json({ error: 'Not found' }); + } + const { season, episode } = req.query; + const cacheKey = generateCacheKey(`tmdb_links_${type}_${id}_${season || ''}_${episode || ''}`); + + try { + // 1. Vérifier le cache sans expiration (stale-while-revalidate) + const cachedData = await getFromCacheNoExpiration(CACHE_DIR.COFLIX, cacheKey); + const hadCache = !!cachedData; // Mémoriser si on avait un cache + let dataReturned = false; + if (cachedData) { + res.json(filterEmmmmbedReaders(cachedData)); // 2. Retourner les données en cache immédiatement (filtrées) + dataReturned = true; + + // Lancer la mise à jour en arrière-plan si nécessaire (vérifie 2 heures pour LecteurVideo) + (async () => { + try { + // Vérifier si le cache doit être mis à jour (2 heures pour LecteurVideo) + const shouldUpdate = await shouldUpdateCacheLecteurVideo(CACHE_DIR.COFLIX, cacheKey); + if (!shouldUpdate) { + return; // Ne pas mettre à jour le cache + } + + // Lancer la mise à jour + await updateCache(); + } catch (err) { + console.error("Erreur non gérée dans updateCache (TMDB):", err); + } + })(); + } + + // 3. Fonction pour récupérer les données fraîches et mettre à jour le cache + const updateCache = async () => { + try { + // Vérifier que le type est valide + if (type !== 'movie' && type !== 'tv') { + if (!dataReturned) { + res.status(400).json({ message: 'Type de média non valide' }); + } + return; + } + + // Pour les séries, vérifier que la saison et l'épisode sont fournis pour la mise à jour + if (type === 'tv' && (!season || !episode)) { + if (!dataReturned) { + res.status(400).json({ message: 'Paramètres de saison/épisode manquants' }); + } + return; + } + + // Récupérer les détails TMDB + const tmdbDetails = await getTMDBDetails(id, type); + if (!tmdbDetails) { + if (!dataReturned) { + res.status(404).json({ message: 'Contenu non trouvé sur TMDB' }); + } + return; + } + + // Extraire l'année de la date de sortie + const releaseYear = tmdbDetails.release_date ? parseInt(tmdbDetails.release_date.split('-')[0]) : null; + + // Rechercher sur Coflix avec le titre international d'abord + let coflixResults = await searchCoflixByTitle(tmdbDetails.title, type, releaseYear); + let bestResults = coflixResults; + + // Si aucun résultat trouvé avec le titre principal, essayer avec le titre original + if ((!coflixResults || !coflixResults.length || (coflixResults[0] && coflixResults[0].similarity < 0.8)) && tmdbDetails.original_title && tmdbDetails.original_title !== tmdbDetails.title) { + const originalResults = await searchCoflixByTitle(tmdbDetails.original_title, type, releaseYear); + + // Comparer les résultats et garder les meilleurs + if (originalResults && originalResults.length > 0) { + if (!bestResults || !bestResults.length) { + bestResults = originalResults; + } else { + // Garder le résultat avec la meilleure similarité + const bestSimilarity = Math.max( + bestResults[0]?.similarity || 0, + originalResults[0]?.similarity || 0 + ); + if (bestSimilarity === (originalResults[0]?.similarity || 0)) { + bestResults = originalResults; + } + } + } + } + + // Si toujours pas de bon résultat, essayer avec le titre français localisé + if ((!bestResults || !bestResults.length || (bestResults[0] && bestResults[0].similarity < 0.8))) { + try { + const frenchResponse = await axios.get(`${TMDB_API_URL}/${type}/${id}`, { + params: { + api_key: TMDB_API_KEY, + language: 'fr-FR' + } + }); + + if (frenchResponse.data) { + const frenchTitle = type === 'movie' ? frenchResponse.data.title : frenchResponse.data.name; + if (frenchTitle && frenchTitle !== tmdbDetails.title && frenchTitle !== tmdbDetails.original_title) { + const frenchResults = await searchCoflixByTitle(frenchTitle, type, releaseYear); + + // Comparer et garder les meilleurs + if (frenchResults && frenchResults.length > 0) { + if (!bestResults || !bestResults.length) { + bestResults = frenchResults; + } else { + const bestSimilarity = Math.max( + bestResults[0]?.similarity || 0, + frenchResults[0]?.similarity || 0 + ); + if (bestSimilarity === (frenchResults[0]?.similarity || 0)) { + bestResults = frenchResults; + } + } + } + } + } + } catch (error) { + console.log(`[TMDB API] ⚠️ Impossible de récupérer le titre français pour ${id}`); + } + } + + // Utiliser les meilleurs résultats trouvés + coflixResults = bestResults; + + // Gérer le cas où aucun résultat n'est trouvé sur Coflix OU si la meilleure correspondance n'est pas assez bonne + const similarityThreshold = 0.8; // Seuil de similarité minimum requis + + // Debug logging pour Alice + if (tmdbDetails.title.toLowerCase().includes('alice')) { + if (coflixResults && coflixResults.length > 0) { + } + } + + if (!coflixResults || !coflixResults.length || (coflixResults[0] && coflixResults[0].similarity < similarityThreshold)) { + if (!coflixResults || !coflixResults.length) { + } else { + } + + const unavailableResult = { + message: 'Contenu non disponible', + tmdb_id: id, + tmdb_details: tmdbDetails + }; + // Sauvegarder le statut "non disponible" dans le cache + await saveToCache(CACHE_DIR.COFLIX, cacheKey, unavailableResult); + if (!dataReturned) { + res.status(200).json(filterEmmmmbedReaders(unavailableResult)); // Retourner 200 OK avec le message (filtré) + } + return; // Arrêter le traitement pour cette mise à jour + } + + // Utiliser le premier résultat trouvé (maintenant garanti d'avoir une similarité suffisante) + const coflixUrl = coflixResults[0].url; + + let result = { + tmdb_details: tmdbDetails + }; + + // Récupérer les données spécifiques selon le type + if (type === 'movie') { + const movieData = await getMovieDataFromCoflix(coflixUrl); + result = { + ...result, + ...movieData + }; + } else if (type === 'tv') { + const seasonNum = parseInt(season); + const episodeNum = parseInt(episode); + const tvData = await getTvDataFromCoflix(coflixUrl, seasonNum, episodeNum); + result = { + ...result, + ...tvData + }; + } + + // 4. Vérifier si les résultats sont valides avant de sauvegarder + // Ne pas sauvegarder si on a des données vides ET qu'un cache existait déjà + const isEmptyResult = (type === 'movie' && (!result.player_links || result.player_links.length === 0)) || + (type === 'tv' && (!result.seasons || result.seasons.length === 0)); + + if (isEmptyResult) { + console.warn(`[TMDB ${type} ${id}] ⚠️ Aucun lien trouvé (player_links vide) — titre: ${tmdbDetails.title || tmdbDetails.original_title}, coflix URL: ${coflixResults[0]?.url || 'N/A'}`); + } + + if (!isEmptyResult || !dataReturned) { + // Sauvegarder en cache seulement si les résultats sont valides OU si aucun cache n'existait + await saveToCache(CACHE_DIR.COFLIX, cacheKey, result); + // console.log(`Cache mis à jour pour TMDB ${id} (${type})`); + } else { + } + + // Si les données n'avaient pas été retournées initialement (pas de cache), les retourner maintenant + if (!dataReturned) { + res.json(filterEmmmmbedReaders(result)); + } + + } catch (updateError) { + // Log only error message and code to avoid dumping large HTML or sensitive data + if (updateError && updateError.isAxiosError) { + // AxiosError: affiche code, message, et url de la requête + const url = updateError.config && updateError.config.url ? updateError.config.url : ''; + console.error( + `Erreur lors de la mise à jour du cache TMDB ${id} (${type}): [AxiosError] ${updateError.code || ''} ${updateError.message} ${url}` + ); + } else { + // Autre erreur: affiche juste le message ou la string + const msg = updateError && updateError.message + ? updateError.message + : (typeof updateError === 'string' + ? updateError + : JSON.stringify(updateError)); + console.error(`Erreur lors de la mise à jour du cache TMDB ${id} (${type}): ${msg}`); + } + // Si les données n'avaient pas été retournées et que la mise à jour échoue + if (!dataReturned) { + res.status(200).json({ + message: 'Contenu non disponible en raison d\'une erreur', + tmdb_id: id + }); + } + } + }; + + // Si pas de données en cache, faire la requête normale + if (!dataReturned) { + // Lancer la mise à jour du cache + await updateCache(); + } + + // Si les données du cache ont déjà été envoyées, la fonction se termine ici. + // Sinon, la réponse sera envoyée à la fin de updateCache. + + } catch (error) { + console.error(`Erreur lors de la récupération des liens TMDB ${id} (${type}):`, error); + // Ne renvoyer une erreur que si aucune donnée n'a encore été envoyée + if (!res.headersSent) { + res.status(200).json({ + message: 'Contenu non disponible en raison d\'une erreur', + tmdb_id: id + }); + } + } +}); + +// Create a cache directory for FrenchCloud data +const FRENCHCLOUD_CACHE_DIR = path.join(__dirname, 'cache', 'frenchcloud'); +(async () => { + try { + await fsp.access(FRENCHCLOUD_CACHE_DIR); + } catch { + await fsp.mkdir(FRENCHCLOUD_CACHE_DIR, { recursive: true }); + } +})(); +// Function to extract movie iframe from FrenchStream +async function getFrenchStreamMovie(imdbId) { + try { + const searchUrl = `https://fr.french-stream.sbs/xfsearch/${imdbId}`; + // console.log(`Searching for movie at ${searchUrl}`); + + const searchResponse = await makeRequestWithCorsFallback(searchUrl, { timeout: 5000, decompress: true }); + const $search = cheerio.load(searchResponse.data); + + // Find the movie link in search results + let movieLink = null; + $search('.short').each((index, element) => { + const $element = $search(element); + const link = $element.find('.short-poster').attr('href'); + // Assuming the first result is the correct one or add more logic if needed + if (link && !movieLink) { + movieLink = link; + } + }); + + if (!movieLink) { + return { error: 'Movie not found on FrenchStream' }; + } + + // console.log(`Found movie link: ${movieLink}`); + const movieResponse = await makeRequestWithCorsFallback(movieLink, { timeout: 5000, decompress: true }); + const $movie = cheerio.load(movieResponse.data); + + // Extract iframe src using the specified XPath logic + // XPath: /html/body/div[2]/div[1]/div/article/div[1]/div/div/div[1]/div/div/div/iframe + // Equivalent CSS selector: body > div:nth-child(2) > div:nth-child(1) > div > article > div:nth-child(1) > div > div > div:nth-child(1) > div > div > div > iframe + + // Trying a few selectors to be robust + let iframeSrc = $movie('body > div:nth-child(2) > div:nth-child(1) > div > article > div:nth-child(1) > div > div > div:nth-child(1) > div > div > div > iframe').attr('src'); + + if (!iframeSrc) { + // Fallback selectors + iframeSrc = $movie('iframe[src*="frenchcloud.cam"]').attr('src'); + } + + if (!iframeSrc) { + // Try finding it in the tabs content if the structure is slightly different + iframeSrc = $movie('.tabs-content iframe').attr('src'); + } + + if (!iframeSrc) { + return { error: 'Iframe not found on movie page' }; + } + + // Fetch the iframe content (FrenchCloud page) + const iframeResponse = await axios.get(iframeSrc, { + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', + 'Referer': 'https://fr.french-stream.sbs/' + }, + decompress: true + }); + + const $iframe = cheerio.load(iframeResponse.data); + const playerLinks = []; + + $iframe('._player-mirrors li').each((index, element) => { + const $element = $iframe(element); + const dataLink = $element.attr('data-link'); + const playerName = $element.text().trim(); + const isHD = $element.hasClass('fullhd'); + + // Skip links that contain frenchcloud.cam (often the embed itself) + if (!dataLink || dataLink.includes('frenchcloud.cam')) { + return; + } + + // Add protocol to links that start with // + let formattedLink = dataLink; + if (dataLink.startsWith('//')) { + formattedLink = 'https:' + dataLink; + } + + playerLinks.push({ + player: playerName, + link: formattedLink, + is_hd: isHD + }); + }); + + return { + iframe_src: iframeSrc, + player_links: playerLinks + }; + + } catch (error) { + return { error: `Failed to fetch movie data: ${error.message}` }; + } +} + +// --- Define the consolidated cache directory --- +const LINK_CACHE_DIR = path.join(__dirname, 'cache', 'links'); +(async () => { + try { + await fsp.access(LINK_CACHE_DIR); + } catch { + await fsp.mkdir(LINK_CACHE_DIR, { recursive: true }); + } +})(); +const CACHE_EXPIRATION_6H = 6 * 60 * 60 * 1000; // 6 hours in milliseconds + +// Route to get movie/show links using IMDB ID (Movies) or FrenchStream ID (TV) +app.get('/api/imdb/:type/:id', async (req, res) => { + const { id, type } = req.params; + // Return 404 for specific blocked IMDB ids + const blockedImdbIds = new Set([ + 'tt7069210', + 'tt0325980', + 'tt0383574', + 'tt0449088', + 'tt1298650', + 'tt1790809', + 'tt0099785' + ]); + if (blockedImdbIds.has(id)) { + return res.status(404).json({ error: 'Not found' }); + } + const cacheKey = type === 'movie' ? + generateCacheKey(`imdb_movie_${id}`) : + generateCacheKey(`frenchstream_${id}`); // Use consistent key logic + const cacheDir = LINK_CACHE_DIR; // Use consolidated cache dir + + try { + // 1. Check cache without expiration + const cachedData = await getFromCacheNoExpiration(cacheDir, cacheKey); + let dataReturned = false; + if (cachedData) { + // console.log(`Links/Data for ${type} ${id} retrieved from cache (stale-while-revalidate)`); + // Clean cached TV data if needed before returning + const dataToSend = type === 'tv' ? cleanTvCacheData(cachedData) : cachedData; + res.json(dataToSend); + dataReturned = true; + } + + // 3. Function to fetch fresh data and update cache + const updateCache = async () => { + try { + // console.log(`Mise à jour du cache en arrière-plan pour ${type} ${id}`); + + // Vérifier si le cache doit être mis à jour (pour TV uniquement, avec délai de 20 minutes) + if (type === 'tv') { + const shouldUpdate = await shouldUpdateCacheFrenchStream(cacheDir, cacheKey); + if (!shouldUpdate) { + // console.log(`Cache French-Stream ${cacheKey} modifié il y a moins de 20 minutes, pas de mise à jour en arrière-plan`); + return; // Ne pas mettre à jour le cache + } + } + + let responseData = {}; + + if (type === 'movie') { + // --- Handle Movies (using FrenchStream scraping) --- + const movieData = await getFrenchStreamMovie(id); + if (movieData.error) { + responseData = { message: 'Contenu non disponible', french_stream_id: id, details: movieData.error }; + } else { + responseData = { + ...movieData + }; + } + + } else if (type === 'tv') { + // --- Handle TV Series (using FrenchStream ID and FrenchStream logic) --- + const frenchStreamId = id; // ID is treated as FrenchStream ID for TV type + const seriesList = await getFrenchStreamSeries(frenchStreamId); + + if (!seriesList || (Array.isArray(seriesList) && seriesList.length === 0)) { + // Optional: Delete cache entry if source no longer exists? + // deleteFromCache(cacheDir, cacheKey); + responseData = { message: 'Contenu non disponible', french_stream_id: frenchStreamId }; // Simpler message instead of error + } else if (seriesList.error) { + // Check if it's a 404 error + if (seriesList.error.includes('404')) { + responseData = { message: 'Contenu non disponible', french_stream_id: frenchStreamId }; + } else { + responseData = { error: 'Failed to retrieve series list from FrenchStream', details: seriesList.error, french_stream_id: frenchStreamId }; + } + } else { + const MAX_SERIES = 10; + const seriesToProcess = seriesList.slice(0, MAX_SERIES); + + // Limiter la concurrence à 3 requêtes simultanées pour éviter de surcharger le serveur + await Promise.all(seriesToProcess.map(series => limitConcurrency3(async () => { + if (series.link) { + try { + const seriesDetails = await getFrenchStreamSeriesDetails(series.link, series.title); + if (!seriesDetails.error) { + series.seasons = seriesDetails.seasons; + series.release_date = seriesDetails.release_date; + series.summary = seriesDetails.summary; + series.tmdb_data = seriesDetails.tmdb_data; + const { baseName, partNumber } = extractSeriesInfo(series.title); + series.baseName = baseName; + series.partNumber = partNumber; + } else { + console.warn(`Could not fetch details for series: ${series.title} (${series.link}), Error: ${seriesDetails.error}`); + series.seasons = []; + } + } catch (detailsError) { + console.error(`Exception fetching details for ${series.title} (${series.link}):`, detailsError); + series.seasons = []; + } + } else { + series.seasons = []; + } + }))); + + // Group and Merge Series Parts + const seriesGroups = {}; + seriesToProcess.forEach(series => { + if (series.baseName) { + if (!seriesGroups[series.baseName]) { + seriesGroups[series.baseName] = []; + } + seriesGroups[series.baseName].push(series); + } + }); + + const mergedSeriesList = []; + for (const baseName in seriesGroups) { + const merged = mergeSeriesParts(seriesGroups[baseName]); + if (merged) { + mergedSeriesList.push(merged); + } + } + + // Clean the merged list for the final result + const cleanedSeries = cleanTvCacheData({ series: mergedSeriesList }); // Reuse cleaning function + + responseData = { + type: 'tv', + series: cleanedSeries.series // Use the cleaned list + }; + } + } else { + console.error(`Type invalide pour la mise à jour du cache: ${type}`); + return; // Should not happen due to initial check + } + + // 4. Save to cache (only if no error occurred during fetch) + if (!responseData.error) { + await saveToCache(cacheDir, cacheKey, responseData); + // console.log(`Cache mis à jour pour ${type} ${id}`); + } else { + } + + // If data was not returned initially, return it now + if (!dataReturned) { + if (responseData.error) { + // Determine appropriate status code based on error + const statusCode = responseData.error.includes('No series found') ? 404 : 500; + res.status(statusCode).json(responseData); // Return the error info + } else if (responseData.message === 'Contenu non disponible') { + // Return 200 status with message instead of error + res.status(200).json(responseData); + } else { + res.json(responseData); // Return the freshly fetched data + } + } + + } catch (updateError) { + console.error(`Erreur lors de la mise à jour du cache ${type} ${id}:`, updateError); + if (!dataReturned && !res.headersSent) { // Check headersSent again + // Check if the error includes a 404 + if (updateError.message && updateError.message.includes('404')) { + res.status(200).json({ message: 'Contenu non disponible', french_stream_id: id }); + } else { + res.status(500).json({ error: 'Erreur lors de la mise à jour du cache', details: updateError.message }); + } + } + } + }; + + // Run cache update in the background + updateCache().catch(err => console.error(`Erreur non gérée dans updateCache (${type} ${id}):`, err)); + + // If cached data was already sent, the function ends here. + // Otherwise, the response will be sent at the end of updateCache. + + } catch (error) { + console.error(`Erreur initiale dans /api/imdb/${type}/${id}:`, error); + if (!res.headersSent) { + // Check if the error includes a 404 + if (error.message && error.message.includes('404')) { + res.status(200).json({ message: 'Contenu non disponible', french_stream_id: id }); + } else { + res.status(500).json({ error: 'Erreur serveur interne lors du traitement initial', details: error.message }); + } + } + } +}); + +// Helper function to clean TV cache data before sending +const cleanTvCacheData = (cachedData) => { + if (!cachedData || !cachedData.series) { + return cachedData; // Return as is if structure is unexpected + } + return { + type: cachedData.type || 'tv', // ensure type is present + series: (cachedData.series || []).map(s => ({ + title: s.title || s.baseName, // Use baseName if available + audio_type: s.audio_type, + episode_count: s.episode_count, + release_date: s.release_date, + summary: s.summary, + tmdb_data: s.tmdb_data ? { + id: s.tmdb_data.id, + name: s.tmdb_data.name, + overview: s.tmdb_data.overview, + first_air_date: s.tmdb_data.first_air_date, + poster_path: s.tmdb_data.poster_path, + backdrop_path: s.tmdb_data.backdrop_path, + vote_average: s.tmdb_data.vote_average, + match_score: s.tmdb_data.match_score, + is_season_part: s.tmdb_data.is_season_part, // Include season part info + season_offset: s.tmdb_data.season_offset + } : null, + seasons: s.seasons || [] + })) + }; +}; +// ... (getFrenchStreamSeries function remains the same) ... +async function getFrenchStreamSeries(id) { + try { + const targetUrl = `https://fr.french-stream.sbs/xfsearch/${id}`; + + const response = await makeRequestWithCorsFallback(targetUrl, { + timeout: 5000, + decompress: true + }); + + const $ = cheerio.load(response.data); + + // Find all series in the search results + const seriesList = []; + $('.short').each(async (index, element) => { + try { + const $element = $(element); + const link = $element.find('.short-poster').attr('href'); + const title = $element.find('.short-title').text().trim(); + + // Skip items that don't have "saison" in their title + if (!title.toLowerCase().includes('saison')) { + return; + } + + const posterImg = $element.find('.short-poster img').attr('src'); + const poster = posterImg ? (posterImg.startsWith('/') ? 'https://fr.french-stream.sbs' + posterImg : posterImg) : null; + const audioType = $element.find('.film-verz a').text().trim(); + + // Extract episode count if available + let episodeCount = null; + const episodeElement = $element.find('.mli-eps i'); + if (episodeElement.length > 0) { + episodeCount = parseInt(episodeElement.text().trim()); + } + + seriesList.push({ + title, + link, + poster, + audio_type: audioType, + episode_count: episodeCount, + seasons: [] // Will be populated later for each series + }); + } catch (error) { + console.error(`Error parsing series element:`, error); + } + }); + + return seriesList; + } catch (error) { + return { error: `Erreur lors de la récupération des séries: ${error.message}` }; + } +} +// ... (getFrenchStreamSeriesDetails function remains the same) ... +async function getFrenchStreamSeriesDetails(seriesUrl, originalTitle) { + try { + // Convertir l'URL si elle utilise encore .gratis ou .legal + const targetUrl = seriesUrl.replace('french-stream.gratis', 'fr.french-stream.sbs').replace('french-stream.legal', 'fr.french-stream.sbs'); + + const response = await makeRequestWithCorsFallback(targetUrl, { + timeout: 5000, + decompress: true + }); + + const $ = cheerio.load(response.data); + + const seriesTitle = originalTitle; + + // Extract release date from <span class="release"> 2023 - </span> + let releaseDate = null; + + // Essayer plusieurs sélecteurs possibles pour la date de sortie + const releaseSelectors = [ + 'article div.fmain div.fleft div.poster span.release', + 'span.release', + 'article div.container div div span.release', + 'div.poster span.release', + '.release' + ]; + + // Essayer chaque sélecteur jusqu'à ce qu'on trouve la date + for (const selector of releaseSelectors) { + const releaseElement = $(selector); + if (releaseElement.length > 0) { + const releaseDateText = releaseElement.text().trim(); + // Extract year from text like "2023 - " + const yearMatch = releaseDateText.match(/(\d{4})/); + if (yearMatch) { + releaseDate = yearMatch[1]; + break; + } + } + } + + // Si toujours pas trouvé, chercher dans toute la page + if (!releaseDate) { + // Chercher tout texte contenant 4 chiffres qui pourrait être une année + const allText = $('body').text(); + const yearMatches = allText.match(/\b(19\d{2}|20\d{2})\b/g); + if (yearMatches && yearMatches.length > 0) { + // Prendre la première année trouvée dans la page + releaseDate = yearMatches[0]; + } + } + + // Extract summary from <p> inside #s-desc element + let summary = null; + + // Essayer différentes approches pour trouver le résumé + const summarySelectorApproaches = [ + // Approche 1: XPath complet converti en sélecteur CSS + () => { + const summaryElement = $('body > div:nth-child(2) > div > div > article > div:nth-child(3) > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > p:nth-child(2)'); + return summaryElement.length > 0 ? summaryElement.text().trim() : null; + }, + + // Approche 2: Recherche dans la zone principale du contenu + () => { + const mainContent = $('.finfo, .fcontent, .fdesc, #s-desc'); + if (mainContent.length > 0) { + const paragraphs = mainContent.find('p'); + // Récupérer le paragraphe le plus long (probablement le résumé) + let longestText = ""; + paragraphs.each((i, el) => { + const text = $(el).text().trim(); + if (text.length > longestText.length && + !text.includes("Résumé du film") && + !text.includes("streaming complet")) { + longestText = text; + } + }); + return longestText.length > 100 ? longestText : null; + } + return null; + }, + + // Approche 3: Recherche par mots-clés + () => { + // Mots-clés qui indiquent probablement un résumé + const summaryKeywords = ["histoire", "série", "saison", "épisode", "personnage", "aventure"]; + const paragraphs = $('p'); + let bestMatch = null; + let bestScore = 0; + + paragraphs.each((i, el) => { + const text = $(el).text().trim(); + if (text.length < 100) return; // Trop court pour être un résumé + + // Calculer un score basé sur les mots-clés présents + let score = 0; + const lowerText = text.toLowerCase(); + summaryKeywords.forEach(keyword => { + if (lowerText.includes(keyword)) score++; + }); + + // Bonus pour la longueur (résumés typiquement plus longs) + score += Math.min(text.length / 200, 3); + + // Malus pour les textes génériques + if (text.includes("streaming") || text.includes("vostfr") || + text.includes("gratuit") || text.includes("Résumé du film")) { + score -= 5; + } + + if (score > bestScore) { + bestScore = score; + bestMatch = text; + } + }); + + return bestScore > 2 ? bestMatch : null; + }, + + // Approche 4: Recherche directe du texte après les divs de métadonnées + () => { + // Trouver une div qui contient la date de sortie, puis chercher un paragraphe après + const releaseDiv = $('span.release').closest('div'); + if (releaseDiv.length > 0) { + // Chercher le premier paragraphe substantiel après cette div + let currentElement = releaseDiv; + let found = false; + + // Parcourir jusqu'à 10 éléments suivants + for (let i = 0; i < 10 && !found; i++) { + currentElement = currentElement.next(); + if (currentElement.length === 0) break; + + // Si c'est un paragraphe, vérifier son contenu + if (currentElement.is('p')) { + const text = currentElement.text().trim(); + if (text.length > 100 && + !text.includes("Résumé du film") && + !text.includes("streaming complet")) { + found = true; + return text; + } + } + + // Si c'est une div, chercher des paragraphes à l'intérieur + const innerP = currentElement.find('p'); + if (innerP.length > 0) { + const text = innerP.first().text().trim(); + if (text.length > 100 && + !text.includes("Résumé du film") && + !text.includes("streaming complet")) { + found = true; + return text; + } + } + } + } + return null; + } + ]; + + // Essayer chaque approche jusqu'à trouver un résumé + for (const approach of summarySelectorApproaches) { + try { + const result = approach(); + if (result) { + summary = result; + break; + } + } catch (error) { + console.error(`Erreur lors de l'extraction du résumé: ${error.message}`); + } + } + + // Dernière tentative: analyse du HTML brut + if (!summary) { + try { + const htmlContent = response.data; + + // Chercher le texte qui pourrait être un résumé après des marqueurs communs + const resumeMarkers = [ + '<div class="fdesc">', + '<div id="s-desc">', + '<h2>Synopsis</h2>', + '<h3>Synopsis</h3>', + 'Synopsis :' + ]; + + for (const marker of resumeMarkers) { + const markerIndex = htmlContent.indexOf(marker); + if (markerIndex !== -1) { + // Chercher le premier paragraphe substantiel après ce marqueur + const afterMarker = htmlContent.substring(markerIndex + marker.length); + const paragraphMatch = afterMarker.match(/<p[^>]*>([^<]{100,})<\/p>/); + + if (paragraphMatch && paragraphMatch[1]) { + summary = paragraphMatch[1].trim(); + break; + } + } + } + } catch (error) { + console.error(`Erreur lors de l'analyse du HTML brut: ${error.message}`); + } + } + + // Valider que le résumé n'est pas un texte par défaut + if (summary && ( + summary.includes("Résumé du film") || + summary.includes("streaming complet") || + summary.includes("vf et vostfr") || + summary.includes("vod gratuit sans limite") + )) { + summary = null; + } + + // Find series on TMDB using the extracted info + let tmdbData = null; + if (seriesTitle) { + // Pass the original title from FrenchStream; findTvSeriesOnTMDB will clean it + tmdbData = await findTvSeriesOnTMDB(seriesTitle, releaseDate, summary); + } + + // Find all seasons using the new structure + const seasons = []; + const seasonsContainer = $('.tab-content > .tab-pane'); // Updated selector + + seasonsContainer.each((seasonIndex, seasonElement) => { + try { + const $seasonElement = $(seasonElement); + const seasonId = $seasonElement.attr('id'); // e.g., season-1 + const seasonNumberMatch = seasonId ? seasonId.match(/\d+$/) : null; + const seasonNumber = seasonNumberMatch ? parseInt(seasonNumberMatch[0]) : seasonIndex + 1; // Fallback to index if ID parsing fails + const seasonTitle = `Saison ${seasonNumber}`; // Construct title + + const episodesMap = new Map(); // Use a map to group by episode number + + // Find all episodes in this season + const episodeElements = $seasonElement.find('ul li'); // Selector seems correct based on provided HTML + + episodeElements.each((episodeIndex, episodeElement) => { + try { + const $episodeElement = $(episodeElement); + const episodeLink = $episodeElement.find('a').first(); + + // Extract episode info + const episodeNumStr = episodeLink.text().trim(); + // Try to extract the base episode number if it contains non-digits (like '1 Special') + const episodeNumMatch = episodeNumStr.match(/^\d+/); + const episodeNum = episodeNumMatch ? episodeNumMatch[0] : episodeNumStr; // Use matched number or original string + + const episodeTitle = episodeLink.attr('data-title') || `Episode ${episodeNumStr}`; + const isVOSTFR = episodeTitle.includes('VOSTFR'); + const langKey = isVOSTFR ? 'vostfr' : 'vf'; + + // Get player links + const players = []; + $episodeElement.find('.mirrors a').each((playerIndex, playerElement) => { + const $playerElement = $(playerElement); + const playerName = $playerElement.text().trim(); + const playerLink = $playerElement.attr('data-link'); + + if (playerLink) { + players.push({ + name: playerName, + link: playerLink + }); + } + }); + + // Get or create the entry for this episode number + if (!episodesMap.has(episodeNum)) { + episodesMap.set(episodeNum, { + number: episodeNum, + versions: {} + }); + } + + // Add the current language version + episodesMap.get(episodeNum).versions[langKey] = { + title: episodeTitle, + players: players + }; + + } catch (error) { + console.error(`Error parsing episode element (Index ${episodeIndex}) in ${seriesUrl}:`, error.message); + } + }); + + // Convert map values to array and sort numerically by episode number + const episodes = Array.from(episodesMap.values()).sort((a, b) => { + const numA = parseInt(a.number); + const numB = parseInt(b.number); + if (isNaN(numA) || isNaN(numB)) return a.number.localeCompare(b.number); // Fallback for non-numeric eps + return numA - numB; + }); + + seasons.push({ + number: seasonNumber, + title: seasonTitle, + episodes: episodes // Use the structured episodes + }); + } catch (error) { + console.error(`Error parsing season element (ID ${seasonId || 'unknown'}) in ${seriesUrl}:`, error.message); // Improved error log + } + }); + + return { + title: seriesTitle, + release_date: releaseDate, + summary: summary, + tmdb_data: tmdbData, + seasons: seasons + }; + } catch (error) { + return { error: `Failed to fetch series details: ${error.message}` }; + } +} +// Helper function to extract base name and part number from series title +const extractSeriesInfo = (title) => { + let baseName = title; + let partNumber = 1; // Default to part 1 + let seasonInfo = {}; // Store season range if present + + // Match "Part X (Saison Y - Z)" + const partMatch = title.match(/\s*Part\s+(\d+)\s*\(Saison\s+(\d+)\s*-\s*(\d+)\)/i); + if (partMatch) { + partNumber = parseInt(partMatch[1]); + seasonInfo = { + part: partNumber, + start: parseInt(partMatch[2]), + end: parseInt(partMatch[3]) + }; + // Remove the Part info from the base name + baseName = baseName.replace(/\s*Part\s+\d+\s*\(Saison\s+\d+\s*-\s*\d+\)/i, ''); + } + + // Remove trailing "- Saison X" + baseName = baseName.replace(/\s*-\s*Saison\s+\d+$/i, ''); + + // Remove potential year in parenthesis if not already removed by part info + baseName = baseName.replace(/\s*\(\d{4}\)/, ''); + + return { baseName: baseName.trim(), partNumber, seasonInfo }; +}; + +// Helper function to merge series parts +const mergeSeriesParts = (parts) => { + if (!parts || parts.length === 0) { + return null; + } + if (parts.length === 1) { + return parts[0]; // Nothing to merge + } + + // Sort parts by partNumber (extracted during grouping) + parts.sort((a, b) => a.partNumber - b.partNumber); + + const mainPart = parts[0]; + const mergedSeasons = [...(mainPart.seasons || [])]; // Start with seasons from part 1 + + + // Track the maximum season number added so far + let maxSeasonNumberSoFar = 0; + if (mergedSeasons.length > 0) { + maxSeasonNumberSoFar = Math.max(...mergedSeasons.map(s => s.number)); + } + + for (let i = 1; i < parts.length; i++) { + const currentPart = parts[i]; + + // Calculate the adjustment based on the max season number from the *previous* merged parts + const adjustment = maxSeasonNumberSoFar; + + if (!currentPart.seasons || currentPart.seasons.length === 0) { + console.log(` Part ${currentPart.partNumber} has no seasons to merge.`); + continue; + } + + console.log(` Adjusting ${currentPart.seasons.length} season(s) for Part ${currentPart.partNumber}.`); + + let partMaxSeason = 0; // Track max season added *in this part* + currentPart.seasons.forEach(season => { + const originalSeasonNumber = season.number; + // The adjusted season number is the previous max + the original number from this part + const adjustedSeasonNumber = adjustment + originalSeasonNumber; + console.log(` Merging Season ${originalSeasonNumber} -> ${adjustedSeasonNumber}`); + + // Create a new season object to avoid modifying the original + const adjustedSeason = { + ...season, + number: adjustedSeasonNumber, + // Adjust title like "Saison X" + title: `Saison ${adjustedSeasonNumber}` + }; + mergedSeasons.push(adjustedSeason); + if (adjustedSeasonNumber > partMaxSeason) { + partMaxSeason = adjustedSeasonNumber; + } + }); + // Update the overall max season number + maxSeasonNumberSoFar = partMaxSeason; + } + + // Return the main part with merged seasons + // Ensure seasons are sorted correctly after merging + mergedSeasons.sort((a, b) => a.number - b.number); + + return { + ...mainPart, // Use metadata from the main part + seasons: mergedSeasons + }; +}; + +async function checkFrenchStreamVersion(imdbId) { + try { + const url = `https://fr.french-stream.sbs/xfsearch/${imdbId}`; + const response = await axiosFrenchStreamRequest({ method: 'get', url }); + const $ = cheerio.load(response.data); + + // Recherche de la version du film avec le XPath fourni + const versionElement = $('*[id="dle-content"] div div span:nth-child(2) a'); + const version = versionElement.text().trim(); + + return { + version: version || 'Unknown', + url: versionElement.attr('href') || null + }; + } catch (error) { + // console.error(`Erreur m3u8: ${error.response?.status || 'Erreur réseau'}`); + return { version: 'Unknown', url: null }; + } +} + +// Search endpoint that looks for both movies and TV series on TMDB +app.get('/search/:query', async (req, res) => { + try { + const { query } = req.params; + + // Get current date for release date filtering + const today = new Date(); + const formattedDate = today.toISOString().split('T')[0]; // Format: YYYY-MM-DD + + // Search for movies + const movieResponse = await axios.get(`${TMDB_API_URL}/search/movie`, { + params: { + api_key: TMDB_API_KEY, + query: query, + language: 'fr-FR', + page: 1, + include_adult: false, + sort_by: 'popularity.desc' + } + }); + + // Search for TV series + const tvResponse = await axios.get(`${TMDB_API_URL}/search/tv`, { + params: { + api_key: TMDB_API_KEY, + query: query, + language: 'fr-FR', + page: 1, + include_adult: false, + sort_by: 'popularity.desc' + } + }); + + // Process and filter movie results + const moviePromises = movieResponse.data.results.map(async movie => { + // Skip the hasPlayerLinks check and only filter based on TMDB metadata + if (movie.overview && movie.vote_average > 0 && movie.release_date && movie.release_date <= formattedDate) { + return { + id: movie.id, + title: movie.title, + original_title: movie.original_title, + type: 'movie', + release_date: movie.release_date, + poster_path: movie.poster_path ? `https://image.tmdb.org/t/p/w500${movie.poster_path}` : null, + backdrop_path: movie.backdrop_path ? `https://image.tmdb.org/t/p/original${movie.backdrop_path}` : null, + overview: movie.overview, + vote_average: movie.vote_average, + popularity: movie.popularity, + movix_url: `https://www.movix.blog/movie/${movie.id}` + }; + } + return null; // Exclude if no links or fails other filters + }); + // Function to check if a string uses primarily Latin characters + const isMainlyLatinCharacters = (str) => { + if (!str) return false; + // Check if at least 70% of characters are Latin + const latinChars = str.match(/[A-Za-z0-9\s\p{P}\p{S}]/gu) || []; + return latinChars.length / str.length >= 0.7; + }; + + // Sort movies by popularity after filtering and remove non-Latin titles + const finalMovies = (await Promise.all(moviePromises)) + .filter(Boolean) + .filter(movie => isMainlyLatinCharacters(movie.title) && isMainlyLatinCharacters(movie.original_title)) + .sort((a, b) => b.popularity - a.popularity); + + // Process and filter TV series results + const tvSeriesPromises = tvResponse.data.results.map(async seriesItem => { + // Skip the hasPlayerLinks check and only filter based on TMDB metadata + if (seriesItem.overview && seriesItem.vote_average > 0 && seriesItem.first_air_date && seriesItem.first_air_date <= formattedDate) { + return { + id: seriesItem.id, + title: seriesItem.name, + original_title: seriesItem.original_name, + type: 'tv', + release_date: seriesItem.first_air_date, + poster_path: seriesItem.poster_path ? `https://image.tmdb.org/t/p/w500${seriesItem.poster_path}` : null, + backdrop_path: seriesItem.backdrop_path ? `https://image.tmdb.org/t/p/original${seriesItem.backdrop_path}` : null, + overview: seriesItem.overview, + vote_average: seriesItem.vote_average, + popularity: seriesItem.popularity, + movix_url: `https://www.movix.blog/tv/${seriesItem.id}` + }; + } + return null; // Exclude if no links or fails other filters + }); + // Sort TV series by popularity after filtering and remove non-Latin titles + const finalTvSeries = (await Promise.all(tvSeriesPromises)) + .filter(Boolean) + .filter(series => isMainlyLatinCharacters(series.title) && isMainlyLatinCharacters(series.original_title)) + .sort((a, b) => b.popularity - a.popularity); + + // Structure the results + const structuredResults = { + movies: finalMovies, + tv: finalTvSeries + }; + + res.json(structuredResults); + } catch (error) { + console.error(`Erreur m3u8: ${error.response?.status || 'Erreur réseau'}`); + console.error(`Error searching TMDB for query "${req.params.query}":`, error.message); + if (error.response) { + console.error('TMDB API Response Error:', error.response.status, error.response.data); + } + res.status(500).json({ error: 'Failed to search TMDB', details: error.message }); + } +}); + +// User Data Configuration +const USER_DATA_DIR = path.join(__dirname, 'data'); +(async () => { + try { + await fsp.access(USER_DATA_DIR); + } catch { + await fsp.mkdir(USER_DATA_DIR, { recursive: true }); + } +})(); +// Create guests directory +const GUESTS_DIR = path.join(USER_DATA_DIR, 'guests'); +(async () => { + try { + await fsp.access(GUESTS_DIR); + } catch { + await fsp.mkdir(GUESTS_DIR, { recursive: true }); + } +})(); + +// Create users directory +const USERS_DIR = path.join(USER_DATA_DIR, 'users'); +(async () => { + try { + await fsp.access(USERS_DIR); + } catch { + await fsp.mkdir(USERS_DIR, { recursive: true }); + } +})(); + + +// Lecture directe sans cache pour les données utilisateur +async function readUserData(userType, userId) { + let filePath; + if (userType === 'guest') { + filePath = path.join(GUESTS_DIR, `guest-${userId}.json`); + } else if (userType === 'oauth') { + filePath = path.join(USERS_DIR, `${userId}.json`); + } else if (userType === 'bip39') { + filePath = path.join(USERS_DIR, `bip39-${userId}.json`); + } else { + return null; + } + + try { + // Lecture directe sans verrou pour la lecture (plus rapide) + const fileContent = await fsp.readFile(filePath, 'utf8'); + const data = JSON.parse(fileContent); + + // Sanitize data (avatars) on read + if (data.profiles && Array.isArray(data.profiles)) { + data.profiles.forEach(profile => { + if (profile.avatar && !profile.avatar.startsWith('/avatars/') && profile.avatar !== '') { + // Invalid avatar, fallback to default + profile.avatar = '/avatars/disney/disney_avatar_1.png'; + } + }); + } + + return data; + } catch (e) { + if (e.code === 'ENOENT') { + // Fichier n'existe pas, retourner objet vide + return {}; + } + console.error(`Erreur lors de la lecture des données utilisateur ${userType}:${userId}:`, e.message); + return {}; + } +} + +// Fonction d'écriture directe sans cache +async function writeUserData(userType, userId, data) { + let filePath; + if (userType === 'guest') { + filePath = path.join(GUESTS_DIR, `guest-${userId}.json`); + } else if (userType === 'oauth') { + filePath = path.join(USERS_DIR, `${userId}.json`); + } else if (userType === 'bip39') { + filePath = path.join(USERS_DIR, `bip39-${userId}.json`); + } else { + console.error(`Type d'utilisateur invalide: ${userType}`); + return false; + } + + try { + // Valider les données avant l'écriture + if (!data || typeof data !== 'object') { + throw new Error('Données invalides: les données doivent être un objet non-null'); + } + + // Utiliser l'écriture atomique sécurisée + const success = await safeWriteJsonFile(filePath, data); + if (!success) { + console.error(`Erreur de sauvegarde atomique pour ${userType}:${userId}`); + } + return success; + } catch (e) { + console.error(`Erreur de sauvegarde pour ${userType}:${userId}:`, e.message); + return false; + } +} + + +// === GESTION DU GRACEFUL SHUTDOWN === + +// Compteur d'opérations en cours +let activeOperations = 0; + +// Fonction pour marquer le début d'une opération +function startOperation() { + if (isShuttingDown) { + throw new Error('Server is shutting down'); + } + activeOperations++; +} + +// Fonction pour marquer la fin d'une opération +function endOperation() { + activeOperations--; + if (isShuttingDown && activeOperations === 0) { + console.log('All operations completed, server can shutdown safely'); + process.exit(0); + } +} + +// Fonction pour attendre que toutes les opérations se terminent +function waitForOperations() { + return new Promise((resolve) => { + if (activeOperations === 0) { + resolve(); + return; + } + + const checkInterval = setInterval(() => { + if (activeOperations === 0) { + clearInterval(checkInterval); + resolve(); + } + }, 100); + }); +} + +// Gestion des signaux de shutdown +process.on('SIGTERM', async () => { + console.log('SIGTERM received, starting graceful shutdown...'); + isShuttingDown = true; + await waitForOperations(); + process.exit(0); +}); + +process.on('SIGINT', async () => { + console.log('SIGINT received, starting graceful shutdown...'); + isShuttingDown = true; + await waitForOperations(); + process.exit(0); +}); + +process.on('SIGHUP', async () => { + console.log('SIGHUP received, starting graceful shutdown...'); + isShuttingDown = true; + await waitForOperations(); + process.exit(0); +}); + +// User data sync endpoints +// POST sync - requires JWT for oauth/bip39; guests sync is disabled +// Supports both legacy (without profileId) and new (with profileId) methods +app.post('/api/sync', async (req, res) => { + const startTime = Date.now(); + try { + // Vérifier si le serveur est en cours d'arrêt + if (isShuttingDown) { + return res.status(503).json({ error: 'Server is shutting down' }); + } + + // Marquer le début de l'opération + startOperation(); + + const { userType, userId, profileId, ops } = req.body; + + // Check for required parameters - profileId is optional for legacy support + if (!userType || !Array.isArray(ops)) { + return res.status(400).json({ error: 'Missing required parameters' }); + } + + // Determine if this is a legacy request (without profileId) + const isLegacyRequest = !profileId; + + // Reject guest sync requests + if (userType === 'guest') { + return res.status(403).json({ error: 'Guest sync is disabled' }); + } + + // For oauth/bip39 users, extract userId from JWT if not provided + let finalUserId = userId; + let authInfo = null; + + if (['oauth', 'bip39'].includes(userType)) { + const authStart = Date.now(); + authInfo = await getAuthIfValid(req); + if (!authInfo || authInfo.userType !== userType) { + return res.status(401).json({ error: 'Unauthorized' }); + } + + // Use userId from JWT if not provided in request body + if (!finalUserId) { + finalUserId = authInfo.userId; + } else if (authInfo.userId !== finalUserId) { + return res.status(401).json({ error: 'UserId mismatch' }); + } + } else if (!finalUserId) { + // For other user types, userId is still required + return res.status(400).json({ error: 'Missing userId' }); + } + + if (userType === 'vip') { + return res.status(200).json({ success: true, message: 'VIP users data is not persisted' }); + } + + // Note: updateSessionAccess est déjà appelé dans getAuthIfValid, pas besoin de le rappeler + + // Read current data from server - use legacy or profile method + let serverData; + const readStart = Date.now(); + if (isLegacyRequest) { + // Legacy method: read from user data directly + serverData = (await readUserData(userType, finalUserId)) || {}; + } else { + // New method: read from profile data + serverData = (await readProfileData(userType, finalUserId, profileId)) || {}; + } + + // Keys to ignore from persistence + const excluded = new Set(['session_id', 'guest_uuid', 'auth_token', 'access_token']); + + // Helper to safely parse JSON + const safeParse = (str, fallback) => { + try { return JSON.parse(str); } catch { return fallback; } + }; + + // Apply each operation sequentially + for (const op of ops) { + if (!op || !op.key || excluded.has(op.key)) continue; + const key = op.key; + const currentRaw = serverData[key]; + + switch (op.op) { + case 'set': { + if (typeof op.value === 'string') { + serverData[key] = op.value; + } + break; + } + case 'remove': { + delete serverData[key]; + break; + } + case 'arrayAdd': { + const value = op.value; + const arr = safeParse(currentRaw, []); + if (Array.isArray(arr)) { + let next = arr.slice(); + const exists = (item) => { + if (value && typeof value === 'object' && 'id' in value) { + return item && typeof item === 'object' && item.id === value.id; + } + return JSON.stringify(item) === JSON.stringify(value); + }; + if (!next.some(exists)) next.push(value); + serverData[key] = JSON.stringify(next); + } + break; + } + case 'arrayRemove': { + const arr = safeParse(currentRaw, []); + const value = op.value; + if (Array.isArray(arr)) { + const next = arr.filter(item => { + if (value && typeof value === 'object' && 'id' in value) { + return !(item && typeof item === 'object' && item.id === value.id); + } + return JSON.stringify(item) !== JSON.stringify(value); + }); + serverData[key] = JSON.stringify(next); + } + break; + } + case 'arrayClear': { + serverData[key] = '[]'; + break; + } + case 'objPatch': { + const obj = safeParse(currentRaw, {}); + const sets = (op.delta && op.delta.set) || {}; + const removes = (op.delta && op.delta.remove) || []; + if (typeof obj === 'object' && obj) { + for (const [k, v] of Object.entries(sets)) { + // Generic nested array merge support when value contains __arrayPatch + if ( + v && + typeof v === 'object' && + v.__arrayPatch + ) { + const patch = v.__arrayPatch; + const currentArrRaw = Array.isArray(obj[k]) ? obj[k] : (() => { try { return JSON.parse(obj[k]); } catch (e) { return []; } })(); + const currentArr = Array.isArray(currentArrRaw) ? currentArrRaw : []; + + const byId = new Map(); + currentArr.forEach((it) => { + if (it && typeof it === 'object' && it.id) { + byId.set(it.id, it); + } + }); + + // Apply patch operations + if (patch.add) { + patch.add.forEach((item) => { + if (item && typeof item === 'object' && item.id) { + byId.set(item.id, item); + } + }); + } + if (patch.update) { + patch.update.forEach((item) => { + if (item && typeof item === 'object' && item.id) { + byId.set(item.id, item); + } + }); + } + if (patch.remove) { + patch.remove.forEach((item) => { + if (item && typeof item === 'object' && item.id) { + byId.delete(item.id); + } + }); + } + if (patch.removeIds) { + patch.removeIds.forEach((id) => { + byId.delete(id); + }); + } + + obj[k] = Array.from(byId.values()); + } else { + obj[k] = v; + } + } + removes.forEach((k) => delete obj[k]); + serverData[key] = JSON.stringify(obj); + } + break; + } + } + } + + // Save data back to server + const writeStart = Date.now(); + let writeSuccess; + if (isLegacyRequest) { + writeSuccess = await writeUserData(userType, finalUserId, serverData); + } else { + writeSuccess = await writeProfileData(userType, finalUserId, profileId, serverData); + } + + if (!writeSuccess) { + console.error(`[SYNC] Échec de l'écriture pour ${userType}:${finalUserId}${profileId ? ':' + profileId : ''}`); + await logSyncErrorToDiscord('Échec de l\'écriture des données', { userType, userId: finalUserId, profileId, payload: req.body }); + return res.status(500).json({ success: false, error: 'Failed to save data' }); + } + + res.status(200).json({ success: true }); + } catch (error) { + console.error('Erreur de sauvegarde:', error); + const { userType, userId, profileId } = req.body || {}; + await logSyncErrorToDiscord('Exception lors de la synchronisation', { userType, userId, profileId, error: error.message, payload: req.body }); + res.status(500).json({ error: 'Failed to sync data' }); + } finally { + // Marquer la fin de l'opération + endOperation(); + } +}); + +// GET sync - requires JWT for oauth/bip39; guests sync is disabled +// Supports both legacy (without profileId) and new (with profileId) methods +app.get('/api/sync/:userType/:userId/:profileId?', async (req, res) => { + try { + // Vérifier si le serveur est en cours d'arrêt + if (isShuttingDown) { + return res.status(503).json({ error: 'Server is shutting down' }); + } + + // Marquer le début de l'opération + startOperation(); + + const { userType, userId, profileId } = req.params; + + // Reject guest sync requests + if (userType === 'guest') { + return res.status(403).json({ error: 'Guest sync is disabled' }); + } + + // Enforce JWT for oauth/bip39 + if (['oauth', 'bip39'].includes(userType)) { + const auth = await getAuthIfValid(req); + if (!auth || auth.userType !== userType || auth.userId !== userId) { + return res.status(401).json({ error: 'Unauthorized' }); + } + } + + if (!userType || !userId) { + return res.status(400).json({ error: 'Missing required parameters' }); + } + + // Determine if this is a legacy request (without profileId) + const isLegacyRequest = !profileId; + if (userType === 'vip') { + return res.status(200).json({ success: true, data: {} }); + } + + // Read data using appropriate method + let data; + if (isLegacyRequest) { + // Legacy method: read from user data directly + data = await readUserData(userType, userId); + } else { + // New method: read from profile data + data = await readProfileData(userType, userId, profileId); + } + + // Ensure timestamp is a number before sending to client + if (data && data.lastUpdated) { + if (typeof data.lastUpdated === 'string') { + data.lastUpdated = new Date(data.lastUpdated).getTime(); + } + } else if (data) { + data.lastUpdated = 0; + } + + res.status(200).json({ success: true, data: data || {} }); + } catch (error) { + console.error('Erreur de lecture:', error); + res.status(500).json({ error: 'Failed to retrieve data' }); + } finally { + // Marquer la fin de l'opération + endOperation(); + } +}); + +// Generate UUID for guest users +app.get('/api/guest/uuid', (req, res) => { + const uuid = uuidv4(); + res.status(200).json({ uuid }); +}); + +// Profile Management Endpoints + +// Helper function to read profile data - lecture directe sans cache +async function readProfileData(userType, userId, profileId) { + const profileDir = path.join(USERS_DIR, 'profiles', userType, userId); + const profilePath = path.join(profileDir, `${profileId}.json`); + + try { + // Lecture directe sans verrou pour la lecture (plus rapide) + const fileContent = await fsp.readFile(profilePath, 'utf8'); + const data = JSON.parse(fileContent); + return data; + } catch (e) { + if (e.code === 'ENOENT') { + // Fichier n'existe pas, retourner objet vide + return {}; + } + console.error(`Erreur lors de la lecture des données de profil ${userType}:${userId}:${profileId}:`, e.message); + return {}; + } +} + +// Helper function to write profile data - écriture directe sans cache +async function writeProfileData(userType, userId, profileId, data) { + const profileDir = path.join(USERS_DIR, 'profiles', userType, userId); + const profilePath = path.join(profileDir, `${profileId}.json`); + + try { + // Valider les données avant l'écriture + if (!data || typeof data !== 'object') { + throw new Error('Données de profil invalides: les données doivent être un objet non-null'); + } + + // Utiliser l'écriture atomique sécurisée (crée le répertoire automatiquement) + const success = await safeWriteJsonFile(profilePath, data); + if (!success) { + console.error(`Erreur de sauvegarde atomique pour le profil ${profileId}`); + } + return success; + } catch (e) { + console.error('Error writing profile data:', e); + return false; + } +} + +// GET /api/profiles - Get all profiles for authenticated user +app.get('/api/profiles', async (req, res) => { + try { + const auth = await getAuthIfValid(req); + if (!auth || !['oauth', 'bip39'].includes(auth.userType)) { + return res.status(401).json({ error: 'Unauthorized' }); + } + + const userData = await readUserData(auth.userType, auth.userId); + const profiles = userData.profiles || []; + + res.status(200).json({ success: true, profiles }); + } catch (error) { + console.error('Error getting profiles:', error); + res.status(500).json({ error: 'Failed to get profiles' }); + } +}); + +// POST /api/profiles - Create new profile (max 5 per user) +app.post('/api/profiles', async (req, res) => { + try { + const auth = await getAuthIfValid(req); + if (!auth || !['oauth', 'bip39'].includes(auth.userType)) { + return res.status(401).json({ error: 'Unauthorized' }); + } + + const { name, avatar } = req.body; + if (!name || !avatar) { + return res.status(400).json({ error: 'Name and avatar are required' }); + } + + // Validate avatar format (must be a local path starting with /avatars/) + if (avatar && !avatar.startsWith('/avatars/') && avatar !== '') { + return res.status(400).json({ error: 'Invalid avatar URL. Must be a local path starting with /avatars/' }); + } + + const userData = await readUserData(auth.userType, auth.userId); + const profiles = userData.profiles || []; + + // Check if user already has 5 profiles + if (profiles.length >= 5) { + return res.status(400).json({ error: 'Maximum 5 profiles allowed' }); + } + + // Generate new profile ID + const profileId = uuidv4(); + const newProfile = { + id: profileId, + name: name.trim(), + avatar, + createdAt: new Date().toISOString(), + isDefault: profiles.length === 0 // First profile is default + }; + + // Add profile to user data + userData.profiles = [...profiles, newProfile]; + userData.lastUpdated = Date.now(); + + const success = await writeUserData(auth.userType, auth.userId, userData); + if (!success) { + return res.status(500).json({ error: 'Failed to create profile' }); + } + + res.status(200).json({ success: true, profile: newProfile }); + } catch (error) { + console.error('Error creating profile:', error); + res.status(500).json({ error: 'Failed to create profile' }); + } +}); + +// PUT /api/profiles/:profileId - Update profile (name, avatar) +app.put('/api/profiles/:profileId', async (req, res) => { + try { + const auth = await getAuthIfValid(req); + if (!auth || !['oauth', 'bip39'].includes(auth.userType)) { + return res.status(401).json({ error: 'Unauthorized' }); + } + + const { profileId } = req.params; + const { name, avatar } = req.body; + + if (!name && !avatar) { + return res.status(400).json({ error: 'Name or avatar is required' }); + } + + // Validate avatar format if provided + if (avatar && !avatar.startsWith('/avatars/') && avatar !== '') { + return res.status(400).json({ error: 'Invalid avatar URL. Must be a local path starting with /avatars/' }); + } + + const userData = await readUserData(auth.userType, auth.userId); + const profiles = userData.profiles || []; + + const profileIndex = profiles.findIndex(p => p.id === profileId); + if (profileIndex === -1) { + return res.status(404).json({ error: 'Profile not found' }); + } + + // Update profile + if (name) profiles[profileIndex].name = name.trim(); + if (avatar) profiles[profileIndex].avatar = avatar; + + userData.profiles = profiles; + userData.lastUpdated = Date.now(); + + const success = await writeUserData(auth.userType, auth.userId, userData); + if (!success) { + return res.status(500).json({ error: 'Failed to update profile' }); + } + + res.status(200).json({ success: true, profile: profiles[profileIndex] }); + } catch (error) { + console.error('Error updating profile:', error); + res.status(500).json({ error: 'Failed to update profile' }); + } +}); + +// DELETE /api/profiles/:profileId - Delete profile (except last one) +app.delete('/api/profiles/:profileId', async (req, res) => { + try { + const auth = await getAuthIfValid(req); + if (!auth || !['oauth', 'bip39'].includes(auth.userType)) { + return res.status(401).json({ error: 'Unauthorized' }); + } + + const { profileId } = req.params; + + const userData = await readUserData(auth.userType, auth.userId); + const profiles = userData.profiles || []; + + // If this is the last profile, we'll allow deletion and create a new default profile + const isLastProfile = profiles.length <= 1; + + const profileIndex = profiles.findIndex(p => p.id === profileId); + if (profileIndex === -1) { + return res.status(404).json({ error: 'Profile not found' }); + } + + // Check if deleted profile was default BEFORE removing it + const wasDefault = profiles[profileIndex]?.isDefault; + + // Remove profile from user data + profiles.splice(profileIndex, 1); + + // If this was the last profile, create a new default profile + if (isLastProfile) { + // Get user's account info for new default profile + let defaultName = 'Profil'; + let defaultAvatar = '/avatars/disney/disney_avatar_1.png'; + + if (auth.userType === 'bip39' && userData.auth) { + try { + const authData = JSON.parse(userData.auth); + if (authData.userProfile) { + defaultName = authData.userProfile.username || 'Profil'; + defaultAvatar = authData.userProfile.avatar || defaultAvatar; + } + } catch (e) { + console.log('Could not parse auth data for new default profile'); + } + } + + // Create new default profile + const newProfileId = uuidv4(); + const newDefaultProfile = { + id: newProfileId, + name: defaultName, + avatar: defaultAvatar, + createdAt: new Date().toISOString(), + isDefault: true + }; + + profiles.push(newDefaultProfile); + } else if (wasDefault && profiles.length > 0) { + // If deleted profile was default and there are remaining profiles, make first remaining profile default + profiles[0].isDefault = true; + } + + userData.profiles = profiles; + userData.lastUpdated = Date.now(); + + const success = await writeUserData(auth.userType, auth.userId, userData); + if (!success) { + return res.status(500).json({ error: 'Failed to delete profile' }); + } + + // Delete profile data file + const profileDir = path.join(USERS_DIR, 'profiles', auth.userType, auth.userId); + const profilePath = path.join(profileDir, `${profileId}.json`); + try { + await fsp.unlink(profilePath); + } catch (e) { + // Ignore if file doesn't exist + } + + res.status(200).json({ + success: true, + newDefaultProfile: isLastProfile ? profiles[profiles.length - 1] : null + }); + } catch (error) { + console.error('Error deleting profile:', error); + res.status(500).json({ error: 'Failed to delete profile' }); + } +}); +// GET /api/profiles/:profileId/data - Get profile-specific data +app.get('/api/profiles/:profileId/data', async (req, res) => { + try { + // Vérifier si le serveur est en cours d'arrêt + if (isShuttingDown) { + return res.status(503).json({ error: 'Server is shutting down' }); + } + + // Marquer le début de l'opération + startOperation(); + + const auth = await getAuthIfValid(req); + if (!auth || !['oauth', 'bip39'].includes(auth.userType)) { + return res.status(401).json({ error: 'Unauthorized' }); + } + + const { profileId } = req.params; + + // Verify profile exists + const userData = await readUserData(auth.userType, auth.userId); + const profiles = userData.profiles || []; + const profile = profiles.find(p => p.id === profileId); + + if (!profile) { + return res.status(404).json({ error: 'Profile not found' }); + } + + // Read profile data + const profileData = await readProfileData(auth.userType, auth.userId, profileId); + + res.status(200).json({ success: true, data: profileData }); + } catch (error) { + console.error('Error getting profile data:', error); + res.status(500).json({ error: 'Failed to get profile data' }); + } finally { + // Marquer la fin de l'opération + endOperation(); + } +}); + +// POST /api/profiles/migrate - Migrate existing user data to default profile +app.post('/api/profiles/migrate', async (req, res) => { + try { + const auth = await getAuthIfValid(req); + if (!auth || !['oauth', 'bip39'].includes(auth.userType)) { + return res.status(401).json({ error: 'Unauthorized' }); + } + + const { userData } = req.body; + + // Check if user already has profiles + const existingUserData = await readUserData(auth.userType, auth.userId); + if (existingUserData.profiles && existingUserData.profiles.length > 0) { + return res.status(400).json({ error: 'User already has profiles' }); + } + + // Get user's account info for default profile + let defaultName = 'Profil'; + let defaultAvatar = '/avatars/disney/disney_avatar_1.png'; + + if (auth.userType === 'bip39' && existingUserData.auth) { + try { + const authData = JSON.parse(existingUserData.auth); + if (authData.userProfile) { + defaultName = authData.userProfile.username || 'Profil'; + defaultAvatar = authData.userProfile.avatar || defaultAvatar; + } + } catch (e) { + console.log('Could not parse auth data for default profile'); + } + } else if (auth.userType === 'oauth') { + // For Discord/Google users, we'll use generic defaults + defaultName = 'Profil'; + } + + // Create default profile + const profileId = uuidv4(); + const defaultProfile = { + id: profileId, + name: defaultName, + avatar: defaultAvatar, + createdAt: new Date().toISOString(), + isDefault: true + }; + + // Keys to exclude from migration + const excludedKeys = new Set([ + 'auth_token', 'session_id', 'guest_uuid', 'access_token', + 'discord_token', 'google_token', 'auth', 'discord_auth', + 'google_auth', 'bip39_auth', 'discord_user', 'google_user', + 'episodeAlertsLastCheck', 'lastUpdated', 'sessions' + ]); + + // Migrate user data to profile + const profileData = {}; + if (userData && typeof userData === 'object') { + Object.entries(userData).forEach(([key, value]) => { + if (!excludedKeys.has(key) && typeof value === 'string') { + profileData[key] = value; + } + }); + } + + // Save profile data + const profileSuccess = await writeProfileData(auth.userType, auth.userId, profileId, profileData); + if (!profileSuccess) { + return res.status(500).json({ error: 'Failed to save profile data' }); + } + + // Update user data with profiles list + existingUserData.profiles = [defaultProfile]; + existingUserData.lastUpdated = Date.now(); + + const userSuccess = await writeUserData(auth.userType, auth.userId, existingUserData); + if (!userSuccess) { + return res.status(500).json({ error: 'Failed to save user data' }); + } + + res.status(200).json({ success: true, profile: defaultProfile }); + } catch (error) { + console.error('Error migrating profile:', error); + res.status(500).json({ error: 'Failed to migrate profile' }); + } +}); + +// BIP39 Authentication Routes + +// Generate a new 12-word mnemonic phrase in French +app.get('/api/auth/bip39/generate', (req, res) => { + try { + const mnemonic = bip39.generateMnemonic(128); // 128 bits = 12 words + res.status(200).json({ + success: true, + mnemonic: mnemonic + }); + } catch (error) { + console.error('Error generating mnemonic:', error); + res.status(500).json({ + success: false, + error: 'Erreur lors de la génération de la phrase secrète' + }); + } +}); + +// Create account with BIP39 mnemonic (returns JWT) +app.post('/api/auth/bip39/create', async (req, res) => { + try { + const { mnemonic, username, avatar } = req.body; + + if (!mnemonic || !username) { + return res.status(400).json({ success: false, error: 'Phrase secrète et nom d\'utilisateur requis' }); + } + + // Normalize mnemonic: lowercase, trim, and collapse multiple spaces to single space + const normalizedMnemonic = mnemonic.normalize('NFKD').toLowerCase().trim().replace(/\s+/g, ' '); + + // Validate mnemonic + if (!bip39.validateMnemonic(normalizedMnemonic)) { + return res.status(400).json({ success: false, error: 'Phrase secrète invalide' }); + } + + // Generate user ID from normalized mnemonic hash + const userId = crypto.createHash('sha256').update(normalizedMnemonic).digest('hex').substring(0, 16); + + // Create user profile + const userProfile = { + id: userId, + username: username.trim(), + avatar: avatar || 'https://as2.ftcdn.net/v2/jpg/05/89/93/27/1000_F_589932782_vQAEAZhHnq1QCGu5ikwrYaQD0Mmurm0N.webp', + provider: 'bip39', + createdAt: new Date().toISOString() + }; + + // Create session for BIP39 user + const sessionId = await createUserSession('bip39', userId, req); + const token = issueJwt('bip39', userId, sessionId); + + // Save user profile in user data + let userData = await readUserData('bip39', userId) || {}; + userData.auth = JSON.stringify({ + userProfile, + provider: 'bip39' + }); + userData.bip39_auth = 'true'; + userData.lastUpdated = Date.now(); + await writeUserData('bip39', userId, userData); + + res.status(200).json({ + success: true, + userProfile, + sessionId, + token, + message: 'Compte créé avec succès' + }); + } catch (error) { + console.error('Error creating BIP39 account:', error); + res.status(500).json({ success: false, error: 'Erreur lors de la création du compte' }); + } +}); + +// Login with BIP39 mnemonic (returns JWT) +app.post('/api/auth/bip39/login', async (req, res) => { + try { + const { mnemonic } = req.body; + + if (!mnemonic) { + return res.status(400).json({ success: false, error: 'Phrase secrète requise' }); + } + + // Normalize mnemonic: NFKD (standard BIP39), lowercase, trim, and collapse multiple spaces to single space + const normalizedMnemonic = mnemonic.normalize('NFKD').toLowerCase().trim().replace(/\s+/g, ' '); + + // Validate mnemonic + if (!bip39.validateMnemonic(normalizedMnemonic)) { + return res.status(400).json({ success: false, error: 'Phrase secrète invalide' }); + } + + // Generate user ID from normalized mnemonic hash + const userId = crypto.createHash('sha256').update(normalizedMnemonic).digest('hex').substring(0, 16); + + // Try to get existing user profile from stored data + let userProfile = null; + let userData = await readUserData('bip39', userId) || {}; + + try { + if (userData && userData.auth) { + const authData = JSON.parse(userData.auth); + if (authData && authData.userProfile) { + userProfile = authData.userProfile; + } + } + } catch (error) { + console.log('No existing user profile found, will create default'); + } + + // If no existing profile found, create a default one and save it + if (!userProfile) { + userProfile = { + id: userId, + username: `Utilisateur-${userId.substring(0, 8)}`, + avatar: 'https://as2.ftcdn.net/v2/jpg/05/89/93/27/1000_F_589932782_vQAEAZhHnq1QCGu5ikwrYaQD0Mmurm0N.webp', + provider: 'bip39', + createdAt: new Date().toISOString() + }; + + // Save the default profile to user data + userData.auth = JSON.stringify({ + userProfile, + provider: 'bip39' + }); + userData.bip39_auth = 'true'; + userData.lastUpdated = Date.now(); + await writeUserData('bip39', userId, userData); + } + + // Create session for BIP39 user + const sessionId = await createUserSession('bip39', userId, req); + const token = issueJwt('bip39', userId, sessionId); + + res.status(200).json({ + success: true, + userId, + sessionId, + token, + userProfile, + message: 'Connexion réussie' + }); + } catch (error) { + console.error('Error logging in with BIP39:', error); + res.status(500).json({ success: false, error: 'Erreur lors de la connexion' }); + } +}); + +// Discord authentication: verify access_token and issue JWT +app.post('/api/auth/discord/verify', async (req, res) => { + try { + const { access_token } = req.body || {}; + if (!access_token) { + return res.status(400).json({ success: false, error: 'access_token requis' }); + } + // Verify with Discord API + const resp = await axios.get('https://discord.com/api/users/@me', { + headers: { Authorization: `Bearer ${access_token}` } + }); + const user = resp.data; + if (!user || !user.id) { + return res.status(401).json({ success: false, error: 'Token Discord invalide' }); + } + const userId = String(user.id); + const sessionId = await createUserSession('oauth', userId, req); + const token = issueJwt('oauth', userId, sessionId); + return res.status(200).json({ success: true, sessionId, token, user }); + } catch (error) { + console.error('Discord verify error:', error.response?.status || error.message); + return res.status(401).json({ success: false, error: 'Échec de vérification Discord' }); + } +}); + +// Google authentication: verify access_token and issue JWT +app.post('/api/auth/google/verify', async (req, res) => { + try { + const { access_token } = req.body || {}; + if (!access_token) { + return res.status(400).json({ success: false, error: 'access_token requis' }); + } + // Verify with Google API + const resp = await axios.get('https://www.googleapis.com/oauth2/v3/userinfo', { + headers: { Authorization: `Bearer ${access_token}` } + }); + const data = resp.data; + if (!data || !data.sub) { + return res.status(401).json({ success: false, error: 'Token Google invalide' }); + } + const userId = String(data.sub); + const sessionId = await createUserSession('oauth', userId, req); + const token = issueJwt('oauth', userId, sessionId); + return res.status(200).json({ success: true, sessionId, token, user: data }); + } catch (error) { + console.error('Google verify error:', error.response?.status || error.message); + return res.status(401).json({ success: false, error: 'Échec de vérification Google' }); + } +}); + +// Session Management Routes + +// Utility function to generate device fingerprint +const generateDeviceFingerprint = (userAgent, ip) => { + const crypto = require('crypto'); + const fingerprint = crypto.createHash('sha256') + .update(`${userAgent}-${ip || 'unknown'}-${Date.now()}`) + .digest('hex') + .substring(0, 32); + return fingerprint; +}; + +// Utility function to encrypt device info +const encryptDeviceInfo = (deviceInfo) => { + const crypto = require('crypto'); + const algorithm = 'aes-256-cbc'; + const key = crypto.scryptSync('movix-session-key', 'salt', 32); + const iv = crypto.randomBytes(16); + + const cipher = crypto.createCipheriv(algorithm, key, iv); + let encrypted = cipher.update(deviceInfo, 'utf8', 'base64'); + encrypted += cipher.final('base64'); + + return `${iv.toString('base64')}.${encrypted}`; +}; + + + +// Create a new session for a user (MySQL) +const createUserSession = async (userType, userId, req) => { + try { + if (!pool) { + console.error('MySQL pool not ready for session creation'); + return null; + } + + const userAgent = req.headers['user-agent'] || 'Unknown'; + const ip = req.ip || req.connection.remoteAddress || 'Unknown'; + + // Generate session ID + const sessionId = uuidv4(); + + // Create encrypted device fingerprint + const deviceInfo = generateDeviceFingerprint(userAgent, ip); + const encryptedDevice = encryptDeviceInfo(deviceInfo); + + // Insert session into MySQL + await pool.execute( + 'INSERT INTO user_sessions (id, user_id, user_type, device, user_agent) VALUES (?, ?, ?, ?, ?)', + [sessionId, userId, userType, encryptedDevice, userAgent] + ); + + console.log(`[SESSION] Created new session ${sessionId} for ${userType}:${userId}`); + return sessionId; + } catch (error) { + console.error('Error creating user session:', error); + return null; + } +}; + +// Update session access time (MySQL) +const updateSessionAccess = async (userType, userId, sessionId) => { + try { + if (!pool) { + return false; + } + + // Fire-and-forget: ne pas bloquer le flux principal + pool.execute( + 'UPDATE user_sessions SET accessed_at = NOW() WHERE id = ? AND user_id = ? AND user_type = ?', + [sessionId, userId, userType] + ).catch(err => console.error('Error updating session access:', err)); + + return true; + } catch (error) { + console.error('Error updating session access:', error); + return false; + } +}; + +// Get user sessions - JWT required (MySQL) +app.get('/api/sessions', async (req, res) => { + try { + const auth = await getAuthIfValid(req); + if (!auth) { + return res.status(401).json({ success: false, error: 'Unauthorized' }); + } + const { userType, userId } = auth; + + // Only allow sessions for oauth, bip39 users + if (!['oauth', 'bip39'].includes(userType)) { + return res.status(400).json({ success: false, error: 'Type d\'utilisateur non supporté pour les sessions' }); + } + + if (!pool) { + return res.status(503).json({ success: false, error: 'Service temporairement indisponible' }); + } + + // Get sessions from MySQL + const [rows] = await pool.execute( + 'SELECT id, device, user_agent as userAgent, created_at as createdAt, accessed_at as accessedAt FROM user_sessions WHERE user_id = ? AND user_type = ? ORDER BY accessed_at DESC', + [userId, userType] + ); + + const sessions = rows.map(row => ({ + id: row.id, + userId: userId, + device: row.device, + userAgent: row.userAgent, + createdAt: row.createdAt ? new Date(row.createdAt).toISOString() : null, + accessedAt: row.accessedAt ? new Date(row.accessedAt).toISOString() : null + })); + + res.status(200).json({ success: true, data: { count: sessions.length, items: sessions } }); + } catch (error) { + console.error('Error getting sessions:', error); + res.status(500).json({ success: false, error: 'Erreur lors de la récupération des sessions' }); + } +}); + +// Delete a specific session - JWT required; user can only delete own session (MySQL) +app.post('/api/sessions/delete', async (req, res) => { + try { + const auth = await getAuthIfValid(req); + if (!auth) { + return res.status(401).json({ success: false, error: 'Unauthorized' }); + } + const { userType, userId } = auth; + const { sessionId } = req.body; + + if (!sessionId) { + return res.status(400).json({ success: false, error: 'ID de session requis' }); + } + + if (!['oauth', 'bip39'].includes(userType)) { + return res.status(400).json({ success: false, error: 'Type d\'utilisateur non supporté pour les sessions' }); + } + + if (!pool) { + return res.status(503).json({ success: false, error: 'Service temporairement indisponible' }); + } + + // Delete session from MySQL + const [result] = await pool.execute( + 'DELETE FROM user_sessions WHERE id = ? AND user_id = ? AND user_type = ?', + [sessionId, userId, userType] + ); + + if (result.affectedRows === 0) { + return res.status(404).json({ success: false, error: 'Session non trouvée' }); + } + + res.status(200).json({ success: true, message: 'Session supprimée avec succès' }); + } catch (error) { + console.error('Error deleting session:', error); + res.status(500).json({ success: false, error: 'Erreur lors de la suppression de la session' }); + } +}); + +// Route pour proxy HTML brut (remplace l'ancienne route /proxy) +app.get(/^\/proxy\/(.*)/, async (req, res) => { + try { + // Extract the target URL after /proxy/ + let targetUrl = req.url.slice(7); // Remove '/proxy/' + + // Decode the URL recursively if it's encoded (handles double/triple encoding) + try { + let decoded = targetUrl; + let previousDecoded = ''; + // Keep decoding until the URL doesn't change anymore (handles multiple encodings) + while (decoded !== previousDecoded) { + previousDecoded = decoded; + try { + decoded = decodeURIComponent(decoded); + } catch (e) { + // If decoding fails, break the loop + break; + } + } + targetUrl = decoded; + } catch (decodeError) { + // If decoding fails, use the original URL + console.warn('Failed to decode URL:', targetUrl, decodeError.message); + } + + // Fix recursive proxying issue - remove any localhost/proxy/ patterns + const localhostProxyPattern = /localhost(:\d+)?\/proxy\//i; + if (localhostProxyPattern.test(targetUrl)) { + console.log(`Detected recursive proxy request in: ${targetUrl}`); + targetUrl = targetUrl.replace(localhostProxyPattern, ''); + console.log(`Corrected to: ${targetUrl}`); + } + + // Check if the URL starts with http(s)://, if not, prepend https:// + if (!targetUrl.startsWith('http://') && !targetUrl.startsWith('https://')) { + targetUrl = 'https://' + targetUrl; + } + + // === TVDIRECT SPECIAL HANDLING === + if (targetUrl.includes('tvdirect.ddns')) { + try { + const cacheKey = crypto.createHash('md5').update(targetUrl).digest('hex'); + // Ensure directory exists + await fsp.mkdir(CACHE_DIR.TVDIRECT, { recursive: true }); + const cacheFile = path.join(CACHE_DIR.TVDIRECT, `${cacheKey}.json`); + + // Helper to fetch external resource + const fetchTvDirect = async () => { + console.log(`[TVDIRECT] Fetching ${targetUrl}`); + const resp = await axios.get(targetUrl, { + headers: { + 'User-Agent': 'stremio', + 'Accept': '*/*' + }, + responseType: 'text', + timeout: 15000 + }); + return { + data: resp.data, + headers: resp.headers, + timestamp: Date.now() + }; + }; + + // Try to read from cache + let cachedEntry = null; + try { + const fileContent = await fsp.readFile(cacheFile, 'utf8'); + cachedEntry = JSON.parse(fileContent); + } catch (e) { /* No cache or invalid */ } + + const CACHE_TTL = 24 * 60 * 60 * 1000; // 24 hours + const now = Date.now(); + + if (cachedEntry && cachedEntry.data) { + // Serve cached response + if (cachedEntry.headers && cachedEntry.headers['content-type']) { + res.setHeader('Content-Type', cachedEntry.headers['content-type']); + } + res.setHeader('Access-Control-Allow-Origin', '*'); + res.send(cachedEntry.data); + + // Check if stale for background update + if (now - cachedEntry.timestamp > CACHE_TTL) { + console.log(`[TVDIRECT] Cache stale for ${targetUrl}, updating in background...`); + // Background update (no await) + fetchTvDirect().then(async (newData) => { + await safeWriteJsonFile(cacheFile, newData); + console.log(`[TVDIRECT] Background update success for ${targetUrl}`); + }).catch(err => console.error(`[TVDIRECT] Background update failed: ${err.message}`)); + } + return; // Exit route + } + + // No cache, fetch synchronously + const newData = await fetchTvDirect(); + await safeWriteJsonFile(cacheFile, newData); + + if (newData.headers && newData.headers['content-type']) { + res.setHeader('Content-Type', newData.headers['content-type']); + } + res.setHeader('Access-Control-Allow-Origin', '*'); + res.send(newData.data); + return; // Exit route + } catch (error) { + console.error(`[TVDIRECT] Error handling request:`, error); + return res.status(502).json({ error: 'TVDirect proxy failed', details: error.message }); + } + } + + // Préparer les headers à forwarder + let refererOrigin; + let targetHost; + try { + const urlObj = new URL(targetUrl); + refererOrigin = urlObj.origin; + targetHost = urlObj.host; + } catch (urlError) { + // Si l'URL est invalide, utiliser une valeur par défaut + console.warn('Invalid URL for referer:', targetUrl, urlError.message); + refererOrigin = 'https://vmwesa.online'; + targetHost = 'vmwesa.online'; + } + + // Headers spécifiques pour vmwesa/vidmoly et certains CDN (ex: getromes.space) + const isVmwesa = /vmwesa\.online|vidmoly|getromes\.space/i.test(targetUrl); + + // Headers spécifiques pour dropcdn + const isDropcdn = /dropcdn/i.test(targetUrl); + + // Headers spécifiques pour serversicuro + const isServersicuro = /serversicuro/i.test(targetUrl); + + // Headers spécifiques pour coflix + const isCoflix = /coflix\.(bet|si|boo|io)/i.test(targetUrl); + + const headers = isCoflix ? { + 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8', + 'Accept-Language': 'fr-FR,fr;q=0.7', + 'Cache-Control': 'no-cache', + 'Pragma': 'no-cache', + 'Priority': 'u=0, i', + 'Referer': 'https://coflix.observer/', + 'Sec-CH-UA': '"Brave";v="141", "Not?A_Brand";v="8", "Chromium";v="141"', + 'Sec-CH-UA-Mobile': '?0', + 'Sec-CH-UA-Platform': '"Windows"', + 'Sec-Fetch-Dest': 'iframe', + 'Sec-Fetch-Mode': 'navigate', + 'Sec-Fetch-Site': 'cross-site', + 'Sec-Fetch-Storage-Access': 'none', + 'Sec-GPC': '1', + 'Upgrade-Insecure-Requests': '1', + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36' + } : isVmwesa ? { + 'Accept': 'application/vnd.apple.mpegurl,application/x-mpegURL,*/*', + 'Accept-Encoding': 'gzip, deflate, br, zstd', + 'Accept-Language': 'fr-FR,fr;q=0.8', + 'Connection': 'keep-alive', + 'Host': targetHost, + 'Origin': 'https://vidmoly.net', + 'Referer': 'https://vidmoly.net/', + 'Sec-CH-UA': '"Not;A=Brand";v="99", "Brave";v="139", "Chromium";v="139"', + 'Sec-CH-UA-Mobile': '?0', + 'Sec-CH-UA-Platform': '"Windows"', + 'Sec-Fetch-Dest': 'empty', + 'Sec-Fetch-Mode': 'cors', + 'Sec-Fetch-Site': 'cross-site', + 'Sec-GPC': '1', + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36' + } : isDropcdn ? { + 'Accept': '*/*', + 'Accept-Encoding': 'gzip, deflate, br, zstd', + 'Accept-Language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7', + 'Connection': 'keep-alive', + 'Host': targetHost, + 'Origin': 'https://dropload.tv', + 'Referer': 'https://dropload.tv/', + 'Sec-CH-UA': '"Not;A=Brand";v="99", "Brave";v="139", "Chromium";v="139"', + 'Sec-CH-UA-Mobile': '?0', + 'Sec-CH-UA-Platform': '"Windows"', + 'Sec-Fetch-Dest': 'empty', + 'Sec-Fetch-Mode': 'cors', + 'Sec-Fetch-Site': 'cross-site', + 'Sec-GPC': '1', + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36' + } : isServersicuro ? { + 'Accept': '*/*', + 'Accept-Encoding': 'gzip, deflate, br, zstd', + 'Accept-Language': 'fr-FR,fr;q=0.8', + 'Connection': 'keep-alive', + 'Host': targetHost, + 'Origin': 'https://supervideo.cc', + 'Referer': 'https://supervideo.cc/', + 'Sec-CH-UA': '"Not;A=Brand";v="99", "Brave";v="139", "Chromium";v="139"', + 'Sec-CH-UA-Mobile': '?0', + 'Sec-CH-UA-Platform': '"Windows"', + 'Sec-Fetch-Dest': 'empty', + 'Sec-Fetch-Mode': 'cors', + 'Sec-Fetch-Site': 'cross-site', + 'Sec-GPC': '1', + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36' + } : { + 'User-Agent': req.headers['user-agent'] || 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', + 'Referer': refererOrigin, + 'Accept': req.headers['accept'] || '*/*', + 'Accept-Encoding': req.headers['accept-encoding'] || 'gzip, deflate, br', + 'Connection': 'keep-alive', + }; + // Forward Range header if present (important for video streaming) + if (req.headers['range']) { + headers['Range'] = req.headers['range']; + } + + // Détecter si c'est un .m3u8 (playlist HLS) + const isM3U8 = targetUrl.toLowerCase().includes('.m3u8') || (req.headers.accept && req.headers.accept.includes('application/vnd.apple.mpegurl')); + + // Faire la requête distante avec l'agent de streaming pour le proxy + const response = await axios({ + method: 'get', + url: targetUrl, + responseType: isM3U8 ? 'text' : 'stream', + headers, + timeout: 30000, + maxRedirects: 5, + validateStatus: status => true, // On gère nous-même les codes d'erreur + decompress: true // Disable automatic decompression for better performance + }); + + // Copier les headers utiles + Object.entries(response.headers).forEach(([key, value]) => { + // Éviter certains headers problématiques + if (!['transfer-encoding', 'connection', 'content-encoding'].includes(key.toLowerCase())) { + res.setHeader(key, value); + } + }); + + // CORS headers + res.setHeader('Access-Control-Allow-Origin', '*'); + res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS', 'DELETE'); + res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Range'); + + // Si c'est un .m3u8, retourner le contenu original sans modification + if (isM3U8 && typeof response.data === 'string') { + const contentType = response.headers['content-type'] || ''; + const bodyText = response.data; + + // Retourner le contenu M3U8 original sans modification + if (contentType) res.setHeader('content-type', contentType); + res.status(response.status).send(bodyText); + return; + } + + // Gestion du code de retour (206 pour Range, sinon code d'origine) + res.status(response.status); + + // Détecter si c'est un flux vidéo (.m3u8, .ts) pour appliquer le throttle approprié + const isVideoStream = targetUrl.toLowerCase().includes('.m3u8') || + targetUrl.toLowerCase().includes('.ts') || + (req.headers.accept && req.headers.accept.includes('application/vnd.apple.mpegurl')); + + if (isVideoStream) { + response.data.pipe(res); + } else { + response.data.pipe(res); + } + } catch (error) { + console.error('Proxy error:', error.message); + if (error.response) { + res.status(error.response.status).json({ + error: `Target server responded with ${error.response.status}`, + message: error.message + }); + } else if (error.request) { + res.status(504).json({ + error: 'Gateway Timeout', + message: 'No response received from target server' + }); + } else { + res.status(500).json({ + error: 'Internal Server Error', + message: error.message + }); + } + } +}); + +app.get('/api/darkino/download-premium/:id', async (req, res) => { + try { + const { id } = req.params; + // Effectuer la requête POST sans payload, juste les cookies + const response = await axiosDarkinoRequest({ method: 'post', url: `/api/v1/download-premium/${id}` }); + res.status(response.status).json(response.data); + } catch (error) { + console.error('Erreur lors de la requête download-premium:', error.response?.status || error.message); + if (error.response) { + res.status(error.response.status).json({ error: error.response.data || 'Erreur lors de la requête download-premium' }); + } else { + res.status(500).json({ error: 'Erreur lors de la requête download-premium' }); + } + } +}); + +// Fonction utilitaire pour paginer intelligemment sur l'API Darkibox +async function findDarkiboxEntriesForEpisode({ titleId, seasonId, episodeId, perPage = 100, maxPages = 10 }) { + // Rafraîchir les cookies avant de commencer la pagination + try { + await refreshDarkinoSessionIfNeeded(); + } catch (e) { + console.warn('Erreur lors du rafraîchissement des cookies Darkino:', e.message); + } + let page = 1; + let foundEntries = []; + let shouldContinue = true; + while (shouldContinue && page <= maxPages) { + const url = `/api/v1/liens?perPage=${perPage}&page=${page}&title_id=${titleId}&loader=linksdl&season=${seasonId}&filters=&paginate=preferLengthAware`; + try { + // Utiliser la nouvelle fonction de requête + const resp = await axiosDarkinoRequest({ + method: 'get', + url: url, + headers: darkiHeaders + }); + const data = resp.data?.pagination?.data || []; + // Cherche les entrées correspondant à l'épisode + const matching = data.filter(entry => + entry.host && entry.host.id_host === 2 && entry.host.name === 'darkibox' && + (entry.episode_id == episodeId || entry.episode == episodeId || entry.episode_number == episodeId) + ); + if (matching.length > 0) { + foundEntries = matching; + break; + } + // Pagination intelligente : + const nextPage = resp.data?.pagination?.next_page; + if (!nextPage) { + shouldContinue = false; + } else { + page = nextPage; + } + } catch (error) { + console.error(`[DARKIBOX] Erreur lors de la recherche des liens (page ${page}):`, error.message); + shouldContinue = false; + } + } + return foundEntries; +} + +// Variable pour suivre le dernier appel à la page d'accueil de Darkino +let lastDarkinoHomeRequest = 0; +const DARKINO_SESSION_REFRESH_INTERVAL = 10 * 60 * 1000; // 10 minutes en millisecondes + +// Fonction pour rafraîchir la session Darkino seulement si nécessaire +const refreshDarkinoSessionIfNeeded = async () => { + const now = Date.now(); + if (now - lastDarkinoHomeRequest > DARKINO_SESSION_REFRESH_INTERVAL) { + try { + // Utiliser la nouvelle fonction de requête + await axiosDarkinoRequest({ method: 'get', url: '/' }); + lastDarkinoHomeRequest = now; + console.log('[DARKINO] Session refreshed'); + } catch (error) { + // Ne pas logger les erreurs 500/403 pour DARKINO session refresh + if (!error.response || (error.response.status !== 500 && error.response.status !== 403)) { + console.error('[DARKINO] Failed to refresh session:', error.message); + } + } + } +}; +app.get('/api/titles/:id/download', async (req, res) => { + if (DARKINO_MAINTENANCE) { + return res.status(200).json({ error: 'Service Darkino temporairement indisponible (maintenance)' }); + } + try { + const { id } = req.params; + + // Generate cache key + const cacheKey = generateCacheKey(`titles_download_${id}`); + + // Check if results are in cache + const cachedData = await getFromCacheNoExpiration(DARKINOS_CACHE_DIR, cacheKey); + const M3U8_CACHE_EXPIRY = 8 * 60 * 60 * 1000; // 8 hours in milliseconds + + let dataReturned = false; + if (cachedData && cachedData.sources !== undefined) { + // console.log(`[API/TITLES/DOWNLOAD] Found cached data for ${id}`); + + const now = Date.now(); + const needM3u8Refresh = !cachedData.m3u8Timestamp || (now - cachedData.m3u8Timestamp > M3U8_CACHE_EXPIRY); + let sourcesWithM3u8 = cachedData.sourcesWithM3u8 || []; + + if (needM3u8Refresh) { + // console.log(`[API/TITLES/DOWNLOAD] Refreshing M3U8 URLs for ${id}`); + sourcesWithM3u8 = await Promise.all( + cachedData.sources.map(async (source) => { + const m3u8Result = await extractM3u8Url(source.src); + if (m3u8Result) { + return { + ...source, + m3u8: m3u8Result.url, + quality: m3u8Result.quality || source.quality + }; + } + return { ...source, m3u8: null }; + }) + ); + // Mise à jour du cache avec les URLs m3u8 rafraîchies + await saveToCache(DARKINOS_CACHE_DIR, cacheKey, { + sources: cachedData.sources, + sourcesWithM3u8: sourcesWithM3u8, + m3u8Timestamp: now + }); + } + + // Déduplication des sources par m3u8 + const seenM3u8 = new Set(); + const seenSrc = new Set(); + const dedupedSources = []; + for (const source of sourcesWithM3u8) { + const key = source.m3u8 || source.src; + if (!key) continue; + if (!seenM3u8.has(key)) { + seenM3u8.add(key); + dedupedSources.push(source); + } + } + // Déduplication supplémentaire sur src (pour éviter les doublons d'URL) + const finalSources = []; + for (const source of dedupedSources) { + if (!seenSrc.has(source.src)) { + seenSrc.add(source.src); + finalSources.push(source); + } + } + // Filtrer les sources avec m3u8: null avant de retourner + const filteredSources = finalSources.filter(source => source.m3u8 !== null); + // Retourner les sources dédupliquées et filtrées + res.status(200).json({ sources: filteredSources }); + dataReturned = true; + (async () => { + try { + // Vérifier si le cache doit être mis à jour + const shouldUpdate = await shouldUpdateCache(DARKINOS_CACHE_DIR, cacheKey); + if (!shouldUpdate) { + return; // Ne pas mettre à jour le cache + } + + await refreshDarkinoSessionIfNeeded(); + const response = await axiosDarkinoRequest({ method: 'get', url: `/api/v1/titles/${id}/download` }); + let freshSources = response.data.alternative_videos || []; + if (response.data.video) { + freshSources.unshift(response.data.video); + } + if (freshSources.length > 0) { + const basicSources = freshSources.map(source => ({ + src: source.src, + language: source.language, + quality: source.quality, + sub: source.sub + })); + const currentCacheData = await getFromCacheNoExpiration(DARKINOS_CACHE_DIR, cacheKey) || {}; + if (JSON.stringify(basicSources) !== JSON.stringify(currentCacheData.sources)) { + await saveToCache(DARKINOS_CACHE_DIR, cacheKey, { sources: basicSources }); + } + } + } catch (refreshError) { + } + })(); + return; + } + // Si pas de cache valide, comportement normal (requête Darkino) + const maxRetries = 3; + let retryCount = 0; + let response; + let success = false; + await refreshDarkinoSessionIfNeeded(); + while (!success && retryCount < maxRetries) { + try { + response = await axiosDarkinoRequest({ method: 'get', url: `/api/v1/titles/${id}/download` }); + success = true; + } catch (error) { + if (error.response?.data?.message === "Il y a eu un problème. Veuillez réessayer plus tard.") { + throw error; + } + + // Arrêter immédiatement sur les erreurs 500/403 + if (error.response && (error.response.status === 500 || error.response.status === 403)) { + throw error; + } + + retryCount++; + if (retryCount >= maxRetries) { + throw error; + } + if (!error.response) { + const delay = Math.min(2000 * Math.pow(1.5, retryCount), 5000) + (Math.random() * 500); + await new Promise(resolve => setTimeout(resolve, delay)); + } else { + throw error; + } + } + } + // ... existing code ... + + } catch (error) { + console.error(`Erreur lors de la récupération des liens de téléchargement:`, error); + res.status(500).json({ error: 'Erreur lors de la récupération des liens de téléchargement' }); + } +}); + +// Supprime le cache d'un film +app.delete('/api/films/download/:id/cache', async (req, res) => { + try { + const { id } = req.params; + const cacheKey = generateCacheKey(`films_download_${id}`); + const cacheFile = path.join(DARKINOS_CACHE_DIR, `${cacheKey}.json`); + await fsp.unlink(cacheFile); + return res.status(200).json({ success: true, message: `Cache film ${id} supprimé.` }); + } catch (err) { + if (err.code === 'ENOENT') { + return res.status(404).json({ success: false, error: 'Cache introuvable.' }); + } + console.error('Erreur suppression cache film :', err); + return res.status(500).json({ success: false, error: 'Erreur serveur.' }); + } +}); + +// Supprime le cache d'un épisode de série +app.delete('/api/series/download/:titleId/season/:seasonId/episode/:episodeId/cache', async (req, res) => { + try { + const { titleId, seasonId, episodeId } = req.params; + const cacheKey = generateCacheKey(`series_download_${titleId}_${seasonId}_${episodeId}`); + const cacheFile = path.join(DARKINOS_CACHE_DIR, `${cacheKey}.json`); + await fsp.unlink(cacheFile); + return res.status(200).json({ success: true, message: `Cache épisode ${titleId}/${seasonId}/${episodeId} supprimé.` }); + } catch (err) { + if (err.code === 'ENOENT') { + return res.status(404).json({ success: false, error: 'Cache introuvable.' }); + } + console.error('Erreur suppression cache épisode :', err); + return res.status(500).json({ success: false, error: 'Erreur serveur.' }); + } +}); + + + + + +// Liste des proxies SOCKS5 (avec authentification) +const parseJsonArrayEnv = (envName, fallback = []) => { + const rawValue = process.env[envName]; + if (!rawValue) return fallback; + try { + const parsed = JSON.parse(rawValue); + return Array.isArray(parsed) ? parsed : fallback; + } catch { + return fallback; + } +}; + +const PROXIES = parseJsonArrayEnv('SOCKS5_PROXIES', []); + + + +// Liste des proxies HTTP spécifiques pour Darkino/Darkiworld +const DARKINO_HTTP_PROXIES = [ + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px023004.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px023005.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px016007.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px016008.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px022505.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px022507.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px016501.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px016006.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px051005.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px052001.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px051003.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px043005.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px090404.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px043006.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px043004.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px410701.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px015601.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px200401.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px032004.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px014004.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px490701.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px032002.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px013601.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px580801.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px210404.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px591701.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px591801.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px711001.pointtoserver.com:10780', + 'http://purevpn0s7397024:6CU9ZvexLGTqpB@px510201.pointtoserver.com:10780' +]; + +// Convertir les proxies HTTP en objets pour Darkino +const DARKINO_PROXIES = DARKINO_HTTP_PROXIES.map(proxyStr => { + // Parser l'URL HTTP: http://user:pass@host:port + if (proxyStr.includes('://')) { + // Format: http://user:pass@host:port + const match = proxyStr.match(/^(\w+):\/\/(?:([^:]+):([^@]+)@)?([^:]+):(\d+)$/); + if (match) { + return { + host: match[4], + port: parseInt(match[5]), + auth: match[2] && match[3] ? `${match[2]}:${match[3]}` : undefined, + type: match[1] + }; + } + } + // Format HTTP simple: host:port + const [host, port] = proxyStr.split(':'); + return { host, port: parseInt(port), type: 'http' }; +}); + +// Fonction utilitaire pour choisir aléatoirement un proxy (toujours utiliser un proxy) +function pickRandomProxyOrNone() { + // Sélectionner toujours un proxy aléatoire parmi la liste + const idx = Math.floor(Math.random() * PROXIES.length); + return PROXIES[idx]; +} + +// Fonction utilitaire pour créer un agent proxy SOCKS5 (avec cache) +function getProxyAgent(proxy) { + if (!proxy) return null; + const auth = proxy.auth ? `${proxy.auth}@` : ''; + const cacheKey = `${proxy.host}:${proxy.port}:${auth}`; + + // Vérifier le cache d'abord + if (proxyAgentCache.has(cacheKey)) { + return proxyAgentCache.get(cacheKey); + } + + const proxyUrl = `socks5h://${auth}${proxy.host}:${proxy.port}`; + // Utilisation de SocksProxyAgent pour les proxies SOCKS5 + const agent = new SocksProxyAgent(proxyUrl); + + // Mettre en cache l'agent + proxyAgentCache.set(cacheKey, agent); + return agent; +} + +// Fonction utilitaire pour créer un agent proxy (pour Darkino) - avec cache +function getDarkinoHttpProxyAgent(proxy) { + if (!proxy) return null; + const auth = proxy.auth ? `${proxy.auth}@` : ''; + const cacheKey = `${proxy.type}:${proxy.host}:${proxy.port}:${auth}`; + + // Vérifier le cache d'abord + if (darkinoProxyAgentCache.has(cacheKey)) { + return darkinoProxyAgentCache.get(cacheKey); + } + + let agents; + if (proxy.type === 'socks5h' || proxy.type === 'socks5') { + // Utilisation de SocksProxyAgent pour les proxies SOCKS5 + const proxyUrl = `${proxy.type}://${auth}${proxy.host}:${proxy.port}`; + const agent = new SocksProxyAgent(proxyUrl); + agents = { + httpAgent: agent, + httpsAgent: agent + }; + } else { + // Utilisation de HttpProxyAgent et HttpsProxyAgent pour les proxies HTTP + // IMPORTANT: Inclure l'authentification dans l'URL du proxy + const proxyUrl = `http://${auth}${proxy.host}:${proxy.port}`; + agents = { + httpAgent: new HttpProxyAgent(proxyUrl), + httpsAgent: new HttpsProxyAgent(proxyUrl) + }; + } + + // Mettre en cache les agents + darkinoProxyAgentCache.set(cacheKey, agents); + return agents; +} + +// Fonction utilitaire pour générer le referer dynamiquement +function generateDarkiReferer(url) { + const baseUrl = 'https://darkiworld2026.com'; + + if (url.includes('/season/') && url.includes('/episode/') && url.includes('/download')) { + // Pour les épisodes de séries: /titles/{titleId}/season/{seasonId}/episode/{episodeId}/download + const match = url.match(/\/titles\/(\d+)\/season\/(\d+)\/episode\/(\d+)\/download/); + if (match) { + const [, titleId, seasonId, episodeId] = match; + return `${baseUrl}/titles/${titleId}/season/${seasonId}/episode/${episodeId}/download?filters=W3sia2V5IjoiaWRfaG9zdCIsInZhbHVlIjoyLCJpc0luYWN0aXZlIjpmYWxzZSwidmFsdWVLZXkiOjJ9XQ%3D%3D`; + } + } else if (url.includes('/titles/') && url.includes('/download')) { + // Pour les films: /titles/{id}/download + const match = url.match(/\/titles\/(\d+)\/download/); + if (match) { + const [, titleId] = match; + return `${baseUrl}/titles/${titleId}/download`; + } + } else if (url.includes('/search/')) { + // Pour la recherche + return `${baseUrl}/search`; + } + + // Par défaut, utiliser l'URL de base + return baseUrl; +} +// Fonction utilitaire pour requêtes Darkino avec proxies (SOCKS5h) +async function axiosDarkinoRequest(config) { + // Vérifier si on est en cooldown après une erreur 403 + if (Date.now() < darkino403CooldownUntil) { + const remainingMs = darkino403CooldownUntil - Date.now(); + const remainingMin = Math.ceil(remainingMs / 60000); + const error = new Error(`Darkino en cooldown (403 Cloudflare). Réessayez dans ${remainingMin} minute(s).`); + error.isDarkinoCooldown = true; + error.response = { status: 403 }; + throw error; + } + + const requestUrl = `https://darkiworld2026.com${config.url}`; + + // Générer le referer dynamiquement selon l'URL + const dynamicReferer = generateDarkiReferer(config.url); + + // Headers pour les requêtes Darkino + const darkinoRequestHeaders = { + ...darkiHeaders, + 'referer': dynamicReferer, + ...config.headers, + }; + + if (!ENABLE_DARKINO_PROXY) { + // Si le proxy est désactivé, faire la requête directe + try { + const response = await axios({ + ...config, + url: requestUrl, + headers: darkinoRequestHeaders, + timeout: 15000, + withCredentials: false, + decompress: true + }); + + const setCookieHeader = response.headers['set-cookie']; + if (setCookieHeader) { + await Promise.all(setCookieHeader.map(cookie => cookieJar.setCookie(cookie, 'https://darkiworld2026.com'))); + } + return response; + } catch (error) { + if (error.response && error.response.headers['set-cookie']) { + const setCookieHeader = error.response.headers['set-cookie']; + await Promise.all(setCookieHeader.map(cookie => cookieJar.setCookie(cookie, 'https://darkiworld2026.com'))); + } + // En cas d'erreur 403, activer le cooldown + if (error.response?.status === 403) { + darkino403CooldownUntil = Date.now() + DARKINO_403_COOLDOWN_MS; + console.log(`[DARKINO] Erreur 403 détectée (direct) - Cooldown activé pour 5 minutes`); + } + throw error; + } + } + + // Utiliser les proxies HTTP spécifiques de Darkino avec rotation aléatoire + const darkinoProxies = [...DARKINO_PROXIES]; // Copie pour pouvoir mélanger + + // Mélanger aléatoirement les proxies + for (let i = darkinoProxies.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [darkinoProxies[i], darkinoProxies[j]] = [darkinoProxies[j], darkinoProxies[i]]; + } + + let lastError = null; + const maxRetries = 1; // Une seule tentative + + for (let i = 0; i < maxRetries; i++) { + const proxy = darkinoProxies[i]; + const agents = getDarkinoHttpProxyAgent(proxy); + + try { + const response = await axios({ + ...config, + method: config.method || 'get', + url: requestUrl, + headers: darkinoRequestHeaders, + timeout: 20000, + withCredentials: false, + decompress: true, + httpAgent: agents.httpAgent, + httpsAgent: agents.httpsAgent, + proxy: false + }); + + // Mettre à jour le cookieJar avec la réponse + const setCookieHeader = response.headers['set-cookie']; + if (setCookieHeader) { + await Promise.all(setCookieHeader.map(cookie => cookieJar.setCookie(cookie, 'https://darkiworld2026.com'))); + } + return response; + } catch (error) { + lastError = error; + const statusCode = error.response?.status; + + // Mettre à jour les cookies même en cas d'erreur si le header est présent + if (error.response && error.response.headers['set-cookie']) { + const setCookieHeader = error.response.headers['set-cookie']; + await Promise.all(setCookieHeader.map(cookie => cookieJar.setCookie(cookie, 'https://darkiworld2026.com'))); + } + + // En cas d'erreur 429 (Too Many Requests), essayer avec le prochain proxy si disponible + if (statusCode === 429) { + continue; + } + + // En cas d'erreur 403 (Cloudflare challenge), activer le cooldown de 5 minutes + if (statusCode === 403) { + darkino403CooldownUntil = Date.now() + DARKINO_403_COOLDOWN_MS; + throw error; + } + + // Pour les autres erreurs (400, 500, etc.), arrêter immédiatement + if (statusCode && statusCode !== 429) { + throw error; + } + } + } + + // Si on arrive ici, tous les proxies ont échoué + throw lastError || new Error('Tous les proxies Darkino ont échoué'); +} + +// Fonction utilitaire pour requêtes Coflix avec proxies Cloudflare Workers +async function axiosCoflixRequest(config) { + // Détection robuste du domaine cible (coflix.observer, coflix.si, coflix.cc, coflix.boo). Si URL relative, on considère que c'est Coflix. + const targetUrl = config.url || ''; + const isAbsolute = /^https?:\/\//i.test(targetUrl); + const isCoflixDomain = isAbsolute ? /(coflix\.(observer|bz|fi|si|boo|io|foo))/i.test(targetUrl) : true; + + try { + if (!ENABLE_COFLIX_PROXY || !isCoflixDomain) { + return await axiosCoflix({ ...config }); + } + + // Utiliser makeCoflixRequest avec les proxies Cloudflare Workers + const absoluteUrl = isAbsolute + ? targetUrl + : `${COFLIX_BASE_URL}${targetUrl.startsWith('/') ? '' : '/'}${targetUrl}`; + + return await makeCoflixRequest(absoluteUrl, { + headers: { ...coflixHeaders, ...(config.headers || {}) }, + timeout: config.timeout || 7000, + decompress: true, + responseType: config.responseType + }); + } catch (error) { + // Logger les erreurs 403 + if (error.response?.status === 403) { + console.log(`[Coflix] Erreur 403 Forbidden dans axiosCoflixRequest`); + console.log(`[Coflix] URL: ${targetUrl}`); + } + throw error; + } +} + +// Fonction utilitaire pour requêtes French-Stream (SPA) via CORS fallback +async function axiosFrenchStreamRequest(config) { + const targetUrl = config.url || ''; + const isAbsolute = /^https?:\/\//i.test(targetUrl); + const baseMatches = config.baseURL && /french-?stream/i.test(config.baseURL); + const isFrenchStream = /french-?stream/i.test(targetUrl) || baseMatches; + + if (!ENABLE_FRENCH_STREAM_PROXY || !isFrenchStream) { + return axios({ ...config }); + } + + const absoluteUrl = isAbsolute + ? targetUrl + : (config.baseURL ? `${config.baseURL.replace(/\/$/, '')}/${targetUrl.replace(/^\//, '')}` : targetUrl); + + return makeRequestWithCorsFallback(absoluteUrl, { + headers: { ...(config.headers || {}) }, + timeout: config.timeout || 5000, + decompress: true, + responseType: config.responseType + }); +} + +// Fonction utilitaire pour requêtes LecteurVideo avec proxies Wiflix +async function axiosLecteurVideoRequest(config) { + const urlStr = config.url || ''; + const isLecteur = /lecteurvideo|lecteur-video|lecteur/i.test(urlStr) || (config.baseURL && /lecteurvideo|lecteur-video|lecteur/i.test(config.baseURL)); + + if (!ENABLE_LECTEURVIDEO_PROXY || !isLecteur) { + return axios({ ...config }); + } + + try { + // Construire l'URL absolue si nécessaire + let absoluteUrl = config.url; + if (config.baseURL && !config.url.startsWith('http')) { + // Nettoyer les URLs avant la concaténation pour éviter les espaces + const cleanBaseURL = config.baseURL.trim(); + const cleanUrl = config.url.trim(); + absoluteUrl = cleanBaseURL + cleanUrl; + } + + // Utiliser makeLecteurVideoRequest avec les proxies Wiflix + return await makeLecteurVideoRequest(absoluteUrl, { + timeout: config.timeout || 5000, + headers: config.headers, + decompress: config.decompress !== false, + responseType: config.responseType, + responseEncoding: config.responseEncoding + }); + } catch (error) { + throw error; + } +} + +// Fonction utilitaire pour requêtes FStream avec proxy (sans retry) +async function axiosFStreamRequest(config) { + const urlStr = config.url || ''; + const isFStream = urlStr.includes(FSTREAM_BASE_URL.replace('https://', '').replace('http://', '')) || + (config.baseURL && config.baseURL.includes(FSTREAM_BASE_URL.replace('https://', '').replace('http://', ''))); + + if (!ENABLE_FSTREAM_PROXY || !isFStream) { + // S'assurer que la session est valide et attacher le cookie automatiquement + await ensureFStreamSession(); + const existingHeaders = config.headers || {}; + const cookieHeader = Object.entries(fstreamCookies) + .filter(([, v]) => v !== '' && v != null) + .map(([k, v]) => `${k}=${v}`) + .join('; '); + const response = await axiosFStream({ + ...config, + timeout: 8000, + headers: { + ...existingHeaders, + 'Cookie': existingHeaders['Cookie'] || cookieHeader + } + }); + // Incrémenter le compteur après une requête réussie + fstreamRequestCounter++; + return response; + } + + // Utiliser un seul proxy aléatoire sans retry + const shuffledProxies = [...PROXIES].sort(() => Math.random() - 0.5); + const proxy = shuffledProxies[0]; // Prendre seulement le premier proxy + + try { + const agent = getProxyAgent(proxy); + // S'assurer que la session est valide et attacher le cookie automatiquement + await ensureFStreamSession(); + const existingHeaders = config.headers || {}; + const cookieHeader = Object.entries(fstreamCookies) + .filter(([, v]) => v !== '' && v != null) + .map(([k, v]) => `${k}=${v}`) + .join('; '); + const response = await axiosFStream({ + ...config, + timeout: 6000, // Timeout strict de 6 secondes + decompress: true, + httpAgent: agent, + httpsAgent: agent, + proxy: false + , + headers: { + ...existingHeaders, + 'Cookie': existingHeaders['Cookie'] || cookieHeader + } + }); + // Incrémenter le compteur après une requête réussie + fstreamRequestCounter++; + return response; + } catch (error) { + // Pas de retry, jeter directement l'erreur + throw error; + } +} + +// Fonction utilitaire pour requêtes AnimeSama avec proxy +async function axiosAnimeSamaRequest(config) { + let urlStr = config.url || ''; + + // Nettoyage automatique des URLs supprimé comme demandé: + // On utilise désormais directement l'URL fournie (qui doit être correcte via ANIME_SAMA_URL) + + const isAnimeSama = urlStr.includes('anime-sama.si') || urlStr.includes('anime-sama.fr') || + (config.baseURL && (config.baseURL.includes('anime-sama.si') || config.baseURL.includes('anime-sama.fr'))); + + if (!ENABLE_ANIME_PROXY || !isAnimeSama) { + return axiosAnimeSama({ ...config, timeout: 30000 }); + } + + // Filtrer les proxies disponibles (non en cooldown) + const availableProxies = getAvailableProxies(CLOUDFLARE_WORKERS_PROXIES); + + // Construire l'URL complète + let absoluteUrl = urlStr; + if (config.baseURL && !urlStr.startsWith('http')) { + absoluteUrl = config.baseURL + urlStr; + } else if (!urlStr.startsWith('http') && !absoluteUrl.startsWith('http')) { + // Si l'URL n'est pas complète et qu'on n'a pas de baseURL, utiliser ANIME_SAMA_URL + absoluteUrl = ANIME_SAMA_URL + (urlStr.startsWith('/') ? urlStr.substring(1) : urlStr); + } + + // Headers pour les requêtes Anime-Sama via proxy + const animeSamaHeaders = { + 'Accept-Language': 'fr-FR,fr;q=0.6', + 'Cache-Control': 'no-cache', + 'Pragma': 'no-cache', + 'Priority': 'u=0, i', + 'Sec-CH-UA': '"Chromium";v="142", "Brave";v="142", "Not_A Brand";v="99"', + 'Sec-CH-UA-Mobile': '?0', + 'Sec-CH-UA-Platform': '"Windows"', + 'Sec-Fetch-Dest': 'document', + 'Sec-Fetch-Mode': 'navigate', + 'Sec-Fetch-Site': 'none', + 'Sec-Fetch-User': '?1', + 'Sec-GPC': '1', + 'Upgrade-Insecure-Requests': '1', + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36' + }; + + // Supprimer les headers liés à l'IP d'origine pour éviter de les transmettre + const headersToRemove = ['X-Forwarded-For', 'X-Real-IP', 'X-Client-IP', 'CF-Connecting-IP', 'True-Client-IP', 'X-Original-Forwarded-For']; + const cleanHeaders = { ...animeSamaHeaders }; + + // Si config.headers existe, le nettoyer aussi + if (config.headers) { + const configHeaders = { ...config.headers }; + headersToRemove.forEach(header => { + delete configHeaders[header]; + delete configHeaders[header.toLowerCase()]; + }); + Object.assign(cleanHeaders, configHeaders); + } + + // Choisir un proxy SOCKS5h aléatoire + const socks5Proxy = pickRandomProxyOrNone(); + const proxyAgent = socks5Proxy ? getProxyAgent(socks5Proxy) : null; + + let lastError = null; + + // Essayer chaque proxy Cloudflare jusqu'à ce qu'un fonctionne + for (let i = 0; i < availableProxies.length; i++) { + const cloudflareProxy = availableProxies[i]; + const proxiedUrl = `${cloudflareProxy}${absoluteUrl}`; + + try { + const response = await axiosAnimeSama({ + ...config, + url: proxiedUrl, + headers: cleanHeaders, + timeout: 30000, + decompress: true, + ...(proxyAgent ? { httpAgent: proxyAgent, httpsAgent: proxyAgent, proxy: false } : {}) + }); + + // Succès : marquer le proxy comme sain + markProxyAsHealthy(cloudflareProxy); + return response; + } catch (error) { + lastError = error; + const statusCode = error.response?.status; + const errorCode = statusCode || error.code || 'unknown'; + + // En cas d'erreur 429 (Too Many Requests), marquer le proxy et essayer le suivant + if (statusCode === 429) { + markProxyAsErrored(cloudflareProxy, 429); + continue; + } + + // En cas d'erreur 5xx, marquer le proxy et essayer le suivant + if (statusCode >= 500 && statusCode < 600) { + markProxyAsErrored(cloudflareProxy, statusCode); + continue; + } + + // En cas de timeout, marquer le proxy et essayer le suivant + if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') { + markProxyAsErrored(cloudflareProxy, errorCode); + continue; + } + + // Pour les autres erreurs, throw immédiatement sans essayer d'autres proxies + throw error; + } + } + + // Si on arrive ici, tous les proxies ont échoué + if (lastError) { + throw lastError; + } + + // Fallback si aucune erreur n'a été capturée (ne devrait jamais arriver) + throw new Error('Erreur inconnue lors de la requête Anime Sama'); +} + + +// === UTILITY: Fusion des streaming_links par langue === +function mergeStreamingLinks(oldLinks, newLinks) { + // oldLinks et newLinks sont des tableaux d'objets { language, players } + const merged = {}; + + // D'abord, copier les anciens liens + (oldLinks || []).forEach(l => { + merged[l.language] = Array.isArray(l.players) ? [...l.players] : []; + }); + + // Ensuite, remplacer par les nouveaux liens si disponibles + (newLinks || []).forEach(l => { + if (l.players && l.players.length > 0) { + // Si on a de nouveaux lecteurs, on remplace complètement les anciens + merged[l.language] = Array.isArray(l.players) ? [...l.players] : []; + } + }); + + // Retourne sous forme d'array d'objets + return Object.entries(merged).map(([language, players]) => ({ language, players })); +} + +// === UTILITY: Migration des anciens fichiers de cache séparés vers le cache unifié === +async function migrateOldCacheFiles(safeAnimeName, animeCacheDir) { + try { + const allCacheFiles = await fsp.readdir(animeCacheDir).catch(() => []); + const oldSeasonFiles = allCacheFiles.filter(f => f.startsWith(safeAnimeName + '_') && f.endsWith('.json')); + + if (oldSeasonFiles.length === 0) return; + + + const migratedSeasons = {}; + + for (const seasonFile of oldSeasonFiles) { + try { + const seasonContent = await fsp.readFile(path.join(animeCacheDir, seasonFile), 'utf-8'); + const seasonCache = JSON.parse(seasonContent); + const seasonName = seasonFile.replace(safeAnimeName + '_', '').replace('.json', ''); + + migratedSeasons[seasonName] = { + timestamp: seasonCache.timestamp || Date.now(), + episodes: seasonCache.episodes || [] + }; + } catch (e) { + } + } + + if (Object.keys(migratedSeasons).length > 0) { + const unifiedCacheData = { + timestamp: Date.now(), + seasons: migratedSeasons + }; + + const animeCachePath = path.join(animeCacheDir, `${safeAnimeName}.json`); + await writeFileAtomic(animeCachePath, JSON.stringify(unifiedCacheData), 'utf-8'); + + // Nettoyer les anciens fichiers après migration réussie + await cleanupOldCacheFiles(safeAnimeName, animeCacheDir); + } + } catch (e) { + } +} + +// === UTILITY: Nettoyage des anciens fichiers de cache séparés === +async function cleanupOldCacheFiles(safeAnimeName, animeCacheDir) { + try { + const allCacheFiles = await fsp.readdir(animeCacheDir).catch(() => []); + const oldSeasonFiles = allCacheFiles.filter(f => f.startsWith(safeAnimeName + '_') && f.endsWith('.json')); + + for (const oldFile of oldSeasonFiles) { + try { + await fsp.unlink(path.join(animeCacheDir, oldFile)); + } catch (e) { + } + } + } catch (e) { + } +} + +// Fonction pour supprimer les lecteurs fsvid des réponses FStream +function removeFsvidPlayers(data, isVip = false) { + // Log de débogage + + // Si pas de données, retourner tel quel + if (!data) { + return data; + } + + // Si l'utilisateur est VIP, ne pas filtrer les lecteurs fsvid + if (isVip) { + return data; + } + + // Par défaut, toujours filtrer les lecteurs fsvid (même si remove_fsvid est false) + + // Pour les films : filtrer players.organized + if (data.players && typeof data.players === 'object') { + const filteredPlayers = {}; + let totalPlayers = 0; + + Object.keys(data.players).forEach(playerType => { + if (Array.isArray(data.players[playerType])) { + // Filtrer les lecteurs dont l'URL contient "fsvid" + const filteredPlayerList = data.players[playerType].filter(player => { + return !player.url || !player.url.includes('fsvid'); + }); + + if (filteredPlayerList.length > 0) { + filteredPlayers[playerType] = filteredPlayerList; + totalPlayers += filteredPlayerList.length; + } + } else { + // Si ce n'est pas un array, garder tel quel + filteredPlayers[playerType] = data.players[playerType]; + } + }); + + return { + ...data, + players: filteredPlayers, + total: totalPlayers, + metadata: { + ...data.metadata, + fsvidFiltered: true + } + }; + } + + // Pour les séries : filtrer episodes + if (data.episodes && typeof data.episodes === 'object') { + const filteredEpisodes = {}; + let totalPlayers = 0; + + Object.keys(data.episodes).forEach(episodeKey => { + const episode = data.episodes[episodeKey]; + if (episode && typeof episode === 'object') { + const filteredEpisode = { ...episode }; + + // Vérifier si l'épisode a une structure "languages" + if (episode.languages && typeof episode.languages === 'object') { + const filteredLanguages = {}; + + Object.keys(episode.languages).forEach(languageKey => { + const languagePlayers = episode.languages[languageKey]; + + if (Array.isArray(languagePlayers)) { + // Filtrer les lecteurs dont l'URL contient "fsvid" + const filteredPlayerList = languagePlayers.filter(player => { + return !player.url || !player.url.includes('fsvid'); + }); + + if (filteredPlayerList.length > 0) { + filteredLanguages[languageKey] = filteredPlayerList; + totalPlayers += filteredPlayerList.length; + } + } else { + // Si ce n'est pas un array, garder tel quel + filteredLanguages[languageKey] = languagePlayers; + } + }); + + filteredEpisode.languages = filteredLanguages; + } else { + // Structure ancienne sans "languages" - filtrer directement + Object.keys(episode).forEach(playerType => { + if (Array.isArray(episode[playerType])) { + // Filtrer les lecteurs dont l'URL contient "fsvid" + const filteredPlayerList = episode[playerType].filter(player => { + return !player.url || !player.url.includes('fsvid'); + }); + + if (filteredPlayerList.length > 0) { + filteredEpisode[playerType] = filteredPlayerList; + totalPlayers += filteredPlayerList.length; + } + } + }); + } + + // Garder l'épisode seulement s'il a encore des lecteurs + if (episode.languages ? Object.keys(filteredEpisode.languages).length > 0 : Object.keys(filteredEpisode).some(key => Array.isArray(filteredEpisode[key]) && filteredEpisode[key].length > 0)) { + filteredEpisodes[episodeKey] = filteredEpisode; + } + } + }); + + return { + ...data, + episodes: filteredEpisodes, + total: totalPlayers, + metadata: { + ...data.metadata, + fsvidFiltered: true + } + }; + } + + return data; +} + +/* === ROUTE FSTREAM === */ + +const FSTREAM_BASE_URL = 'https://french-stream.one/'; +const FSTREAM_SEARCH_URL = `${FSTREAM_BASE_URL}/engine/ajax/search.php`; + +// Configuration des cookies FStream (PHPSESSID sera récupéré dynamiquement via login) +const fstreamCookies = { + 'PHPSESSID': '', + 'dle_user_id': '', + 'dle_password': '', + 'dle_skin': 'VFV25', + 'dle_newpm': '0', + '__cf_logged_in': '1', + 'CF_VERIFIED_DEVICE_ae9bb95a6761c08a92f916b7ed7d2c4a985eb220591d1410240412c516f37b0c': '1756239054' +}; + +// Compteur de requêtes pour le système de session FStream (1 login pour 5 requêtes) +let fstreamRequestCounter = 0; +const MAX_REQUESTS_PER_SESSION = 5; + +// Configuration axios pour FStream +const axiosFStream = axios.create({ + baseURL: FSTREAM_BASE_URL, + timeout: 6000, + headers: { + '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', + 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8', + 'Accept-Language': 'fr-FR,fr;q=0.9,en;q=0.8', + 'Accept-Encoding': 'gzip, deflate, br', + 'DNT': '1', + 'Connection': 'keep-alive', + 'Upgrade-Insecure-Requests': '1', + 'Sec-Fetch-Dest': 'document', + 'Sec-Fetch-Mode': 'navigate', + 'Sec-Fetch-Site': 'same-origin', + 'Sec-Fetch-User': '?1', + 'Sec-GPC': '1', + 'Pragma': 'no-cache', + 'Cache-Control': 'no-cache', + 'sec-ch-ua': '"Not(A:Brand";v="8", "Chromium";v="144", "Brave";v="144"', + 'sec-ch-ua-mobile': '?0', + 'sec-ch-ua-platform': '"Windows"', + 'Referer': 'https://french-stream.one/' + }, + decompress: true +}); + +// === Authentification FStream (login pour récupérer le PHPSESSID) === +const FSTREAM_LOGIN_NAME = 'Waltortue1234'; +const FSTREAM_LOGIN_PASSWORD = 'Grenoble38@'; + +let fstreamLoginPromise = null; + +function extractCookieValue(cookies, name) { + if (!cookies || !Array.isArray(cookies)) return null; + const target = cookies.find(c => typeof c === 'string' && c.startsWith(`${name}=`)); + if (!target) return null; + const semi = target.indexOf(';'); + const pair = semi !== -1 ? target.slice(0, semi) : target; + const idx = pair.indexOf('='); + return idx !== -1 ? pair.slice(idx + 1) : null; +} + +async function loginToFStream() { + // Empêcher les connexions concurrentes + if (fstreamLoginPromise) return fstreamLoginPromise; + fstreamLoginPromise = (async () => { + try { + const formData = new URLSearchParams(); + formData.append('login_name', FSTREAM_LOGIN_NAME); + formData.append('login_password', FSTREAM_LOGIN_PASSWORD); + formData.append('login', 'submit'); + + const response = await axiosFStream({ + method: 'post', + url: '/', + data: formData, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Origin': FSTREAM_BASE_URL, + 'Referer': FSTREAM_BASE_URL + }, + // Important: pas de proxy ni d'entêtes Cookie pour le login initial + proxy: false + }); + + const setCookie = response.headers && (response.headers['set-cookie'] || response.headers['Set-Cookie']); + const phpsessid = extractCookieValue(setCookie, 'PHPSESSID'); + const dleUserId = extractCookieValue(setCookie, 'dle_user_id'); + const dlePassword = extractCookieValue(setCookie, 'dle_password'); + const dleNewpm = extractCookieValue(setCookie, 'dle_newpm'); + + if (phpsessid) { + fstreamCookies['PHPSESSID'] = phpsessid; + } else { + throw new Error('PHPSESSID non présent dans set-cookie'); + } + if (dleUserId) fstreamCookies['dle_user_id'] = dleUserId; + if (dlePassword) fstreamCookies['dle_password'] = dlePassword; + if (dleNewpm) fstreamCookies['dle_newpm'] = dleNewpm; + console.log('[FSTREAM LOGIN] ✅ Connexion réussie, cookies récupérés'); + + // Changer le skin vers VFV25 via POST (nécessaire pour obtenir le bon HTML) + try { + const skinCookieHeader = Object.entries(fstreamCookies) + .filter(([, v]) => v !== '' && v != null) + .map(([k, v]) => `${k}=${v}`) + .join('; '); + + const skinFormData = new URLSearchParams(); + skinFormData.append('skin_name', 'VFV25'); + skinFormData.append('action_skin_change', 'yes'); + + await axiosFStream({ + method: 'post', + url: '/', + data: skinFormData, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Origin': FSTREAM_BASE_URL, + 'Referer': FSTREAM_BASE_URL + '/', + 'Cookie': skinCookieHeader + }, + proxy: false + }); + + fstreamCookies['dle_skin'] = 'VFV25'; + console.log('[FSTREAM LOGIN] ✅ Skin changé vers VFV25'); + } catch (skinError) { + console.warn('[FSTREAM LOGIN] ⚠️ Erreur changement de skin:', skinError.message); + } + + return true; + } finally { + // Réinitialiser la promesse pour permettre de relancer en cas d'erreur future + fstreamLoginPromise = null; + } + })(); + return fstreamLoginPromise; +} + +async function ensureFStreamSession() { + // Vérifier si on a besoin d'un nouveau login (pas de PHPSESSID ou compteur dépassé) + if (!fstreamCookies['PHPSESSID'] || fstreamRequestCounter >= MAX_REQUESTS_PER_SESSION) { + await loginToFStream(); + // Réinitialiser le compteur après un nouveau login + fstreamRequestCounter = 0; + } +} + +// Fonction pour récupérer les détails TMDB +async function getFStreamTMDBDetails(id, type) { + try { + // Exécuter les requêtes en parallèle pour réduire la latence + const [response, noLangResponse] = await Promise.all([ + axios.get(`${TMDB_API_URL}/${type}/${id}`, { + params: { + api_key: TMDB_API_KEY, + language: "fr-FR" + } + }).catch(err => { + console.error(`Erreur TMDB main (fr-FR) pour ${id}:`, err.message); + return null; + }), + + axios.get(`${TMDB_API_URL}/${type}/${id}`, { + params: { + api_key: TMDB_API_KEY + } + }).catch(err => { + // console.log(`Impossible de récupérer les données sans langue pour ${id}`); + return null; + }) + ]); + + if (!response || !response.data) { + return null; + } + + // Le 3ème appel était redondant (c'était exactement le même que le premier) -> Supprimé + + return { + id: response.data.id, + title: type === 'movie' ? response.data.title : response.data.name, + original_title: type === 'movie' ? response.data.original_title : response.data.original_name, + name_no_lang: noLangResponse?.data ? (type === 'movie' ? noLangResponse.data.title : noLangResponse.data.name) : null, + release_date: type === 'movie' ? response.data.release_date : response.data.first_air_date, + overview: response.data.overview // On a déjà récupéré la version FR dans response + }; + } catch (error) { + console.error(`Erreur lors de la récupération des détails TMDB pour ${id} (${type}):`, error); + return null; + } +} + +// Fonction pour rechercher sur FStream +async function searchFStream(query, page = 1) { + try { + const formData = new URLSearchParams(); + formData.append('query', query); + formData.append('page', page.toString()); + + const response = await axiosFStreamRequest({ + method: 'post', + url: FSTREAM_SEARCH_URL, + data: formData, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + } + }); + + if (response.status !== 200) { + throw new Error(`Erreur HTTP: ${response.status}`); + } + + return response.data; + } catch (error) { + // Gérer les erreurs spécifiques qui ne doivent pas être mises en cache + if (error.response) { + const status = error.response.status; + if (status === 429 || status === 403 || status === 503 || status === 502) { + // Relancer l'erreur pour qu'elle soit gérée par le cache + throw error; + } + } + + console.error(`Erreur lors de la recherche FStream: ${error.message}`); + throw error; + } +} + +// Fonction pour scraper les films récents depuis la page FStream +async function scrapeFStreamRecentMovies() { + try { + const response = await axiosFStreamRequest({ + method: 'get', + url: 'https://french-stream.one/films/', + timeout: 10000 + }); + + if (response.status !== 200) { + throw new Error(`Erreur HTTP: ${response.status}`); + } + + if (!response.data || typeof response.data !== 'string') { + throw new Error('La réponse n\'est pas du HTML valide'); + } + + const $ = cheerio.load(response.data); + const movies = []; + + // Sélecteur précis pour les films dans l'élément dle-content + // Sur la page /films/, tous les .short dans #dle-content sont des films + const dleContent = $('#dle-content'); + let filmElements; + + if (dleContent.length > 0) { + // Essayer d'abord .short.film (classes séparées) + filmElements = dleContent.find('.short.film'); + + // Si rien trouvé, essayer div.short.film + if (filmElements.length === 0) { + filmElements = dleContent.find('div.short.film'); + } + + // Si toujours rien, essayer avec attribut class contenant "short" et "film" + if (filmElements.length === 0) { + filmElements = dleContent.find('div[class*="short"][class*="film"]'); + } + + // Si toujours rien, utiliser tous les .short (sur /films/, ce sont tous des films) + if (filmElements.length === 0) { + const shortInDle = dleContent.find('.short'); + if (shortInDle.length > 0) { + filmElements = shortInDle; + } + } + } else { + // Fallback: chercher directement dans tout le document + filmElements = $('.short.film'); + + if (filmElements.length === 0) { + filmElements = $('div.short.film'); + } + + if (filmElements.length === 0) { + filmElements = $('div[class*="short"][class*="film"]'); + } + + if (filmElements.length === 0) { + const allShorts = $('.short'); + if (allShorts.length > 0) { + filmElements = allShorts; + } + } + } + + filmElements.each((index, element) => { + try { + const $el = $(element); + + // Extraire le titre depuis .short-title + const titleElement = $el.find('.short-title'); + if (titleElement.length === 0) return; + + const title = titleElement.text().trim(); + if (!title) return; + + // Extraire le lien depuis a.short-poster + const linkElement = $el.find('a.short-poster'); + if (linkElement.length === 0) return; + + const href = linkElement.attr('href'); + if (!href) return; + + // Construire l'URL complète + const fullLink = href.startsWith('http') + ? href + : href.startsWith('/') + ? `https://french-stream.one${href}` + : `https://french-stream.one/${href}`; + + // Extraire l'ID du film depuis le lien (ex: /films/15123288-good-fortune.html -> 15123288) + let movieId = null; + const idMatch = href.match(/(\d+)/); + if (idMatch) { + movieId = idMatch[1]; + } + + // Extraire le trailer ID si disponible (dans span#trailer-{id}) + // Les IDs sont uniques dans le document, donc on peut chercher directement + let trailerId = null; + if (movieId) { + // Chercher d'abord dans l'élément et ses descendants + let trailerElement = $el.find(`span#trailer-${movieId}`); + // Si non trouvé, chercher dans tout le document (les IDs sont uniques) + if (trailerElement.length === 0) { + trailerElement = $(`span#trailer-${movieId}`); + } + if (trailerElement.length > 0) { + trailerId = trailerElement.text().trim(); + } + } + + // Extraire la description si disponible (dans span#desc-{id}) + let description = null; + if (movieId) { + // Chercher d'abord dans l'élément et ses descendants + let descElement = $el.find(`span#desc-${movieId}`); + // Si non trouvé, chercher dans tout le document (les IDs sont uniques) + if (descElement.length === 0) { + descElement = $(`span#desc-${movieId}`); + } + if (descElement.length > 0) { + description = descElement.text().trim(); + } + } + + // Extraire la qualité et version + const quality = $el.find('.film-quality a').text().trim() || null; + const version = $el.find('.film-version a').text().trim() || null; + + // Extraire l'image pour obtenir l'URL du poster + const imgElement = $el.find('img'); + let posterUrl = null; + if (imgElement.length > 0) { + posterUrl = imgElement.attr('src'); + if (posterUrl && !posterUrl.startsWith('http')) { + posterUrl = posterUrl.startsWith('/') + ? `https://french-stream.one${posterUrl}` + : `https://french-stream.one/${posterUrl}`; + } + } + + // Extraire la note si disponible + const ratingElement = $el.find('.vote-score'); + let rating = null; + if (ratingElement.length > 0) { + const ratingText = ratingElement.text().trim(); + const ratingMatch = ratingText.match(/(\d+\.?\d*)/); + if (ratingMatch) { + rating = parseFloat(ratingMatch[1]); + } + } + + movies.push({ + title: title, + link: fullLink, + id: movieId, + trailerId: trailerId, + description: description, + quality: quality, + version: version, + posterUrl: posterUrl, + rating: rating, + source: 'fstream_recent' + }); + + } catch (error) { + console.error(`[FSTREAM RECENT] Erreur lors du parsing d'un film: ${error.message}`); + } + }); + + return movies; + + } catch (error) { + console.error(`[FSTREAM RECENT] Erreur lors du scraping: ${error.message}`); + return []; + } +} + +// Fonction pour scraper les séries récentes depuis la page FStream +async function scrapeFStreamRecentSeries() { + try { + const response = await axiosFStreamRequest({ + method: 'get', + url: 'https://french-stream.one/s-tv/', + timeout: 10000 + }); + + if (response.status !== 200) { + throw new Error(`Erreur HTTP: ${response.status}`); + } + + const $ = cheerio.load(response.data); + const series = []; + + // Sélecteur pour les séries dans l'élément dle-content + const seriesElements = $('#dle-content .short.serie'); + + seriesElements.each((index, element) => { + try { + const $el = $(element); + + // Extraire le titre + const titleElement = $el.find('.short-title'); + if (titleElement.length === 0) return; + + const title = titleElement.text().trim(); + if (!title) return; + + // Extraire le lien + const linkElement = $el.find('a.short-poster'); + if (linkElement.length === 0) return; + + const href = linkElement.attr('href'); + if (!href) return; + + const fullLink = href.startsWith('http') ? href : `https://french-stream.one${href}`; + + // Extraire l'ID de la série depuis le lien + let seriesId = null; + const idMatch = href.match(/(\d+)/); + if (idMatch) { + seriesId = idMatch[1]; + } + + // Extraire l'image pour obtenir l'ID TMDB si possible + const imgElement = $el.find('img'); + let tmdbId = null; + if (imgElement.length > 0) { + const imgSrc = imgElement.attr('src'); + if (imgSrc && imgSrc.includes('tmdb.org')) { + const tmdbMatch = imgSrc.match(/\/t\/p\/w\d+\/([^\/]+)\.jpg/); + if (tmdbMatch) { + // L'ID TMDB est dans le nom du fichier, mais on ne peut pas l'extraire directement + // On garde juste l'info qu'il y a une image TMDB + } + } + } + + series.push({ + title: title, + link: fullLink, + id: seriesId, + tmdbId: tmdbId, + source: 'fstream_recent_series' + }); + + } catch (error) { + console.error(`[FSTREAM RECENT SERIES] Erreur lors du parsing d'une série: ${error.message}`); + } + }); + + return series; + + } catch (error) { + console.error(`[FSTREAM RECENT SERIES] Erreur lors du scraping: ${error.message}`); + return []; + } +} + +// Fonction pour rechercher un film dans les films récents +async function findMovieInRecentFStream(tmdbTitle, tmdbYear) { + try { + const recentMovies = await scrapeFStreamRecentMovies(); + + if (recentMovies.length === 0) { + return null; + } + + // Fonction pour extraire et retirer l'année d'un titre + const extractYear = (title) => { + const yearMatch = title.match(/\((\d{4})\)/); + return yearMatch ? yearMatch[1] : null; + }; + + const removeYear = (title) => { + return title.replace(/\s*\((\d{4})\)\s*$/, '').trim(); + }; + + // Normaliser le titre pour la comparaison (sans l'année) + const normalizeTitle = (str) => { + if (!str) return ''; + // Retirer l'année avant normalisation + let cleaned = removeYear(str); + return cleaned + .toLowerCase() + .normalize('NFD') + .replace(/[\u0300-\u036f]/g, '') + .replace(/[^\w\s]/g, '') + .replace(/\s+/g, ' ') + .trim(); + }; + + // Extraire l'année du titre TMDB si elle n'est pas fournie + let yearToMatch = tmdbYear; + if (!yearToMatch) { + yearToMatch = extractYear(tmdbTitle); + } + + // Titre TMDB sans l'année + const tmdbTitleWithoutYear = removeYear(tmdbTitle); + const normalizedTmdbTitle = normalizeTitle(tmdbTitleWithoutYear); + + let bestMatch = null; + let bestSimilarity = 0; + + // Chercher une correspondance exacte ou très proche + for (const movie of recentMovies) { + const normalizedMovieTitle = normalizeTitle(movie.title); + + // Correspondance exacte (sans année) + if (normalizedMovieTitle === normalizedTmdbTitle) { + return movie; + } + + // Utiliser calculateTitleSimilarity pour une comparaison plus intelligente + const similarity = calculateTitleSimilarity(normalizedTmdbTitle, normalizedMovieTitle); + + // Si la similarité est élevée, garder le meilleur match + if (similarity > bestSimilarity) { + bestSimilarity = similarity; + bestMatch = movie; + } + } + + // Si on a un bon match (seuil réduit à 0.7 pour être plus permissif) + if (bestMatch && bestSimilarity >= 0.7) { + return bestMatch; + } + + // Si pas de match mais qu'on a un titre très similaire, essayer quand même + // (cas où le titre est presque identique mais avec une petite différence) + if (bestMatch && bestSimilarity >= 0.6 && normalizedTmdbTitle.length > 3) { + // Vérifier si le titre recherché contient le titre trouvé ou vice versa + const tmdbWords = normalizedTmdbTitle.split(/\s+/).filter(w => w.length > 2); + const movieWords = normalizeTitle(bestMatch.title).split(/\s+/).filter(w => w.length > 2); + + // Si tous les mots significatifs du titre TMDB sont dans le titre FStream ou vice versa + const allWordsMatch = tmdbWords.length > 0 && ( + tmdbWords.every(word => movieWords.some(mw => mw.includes(word) || word.includes(mw))) || + movieWords.every(word => tmdbWords.some(tw => tw.includes(word) || word.includes(tw))) + ); + + if (allWordsMatch) { + return bestMatch; + } + } + + return null; + + } catch (error) { + console.error(`[FSTREAM RECENT] Erreur lors de la recherche: ${error.message}`); + return null; + } +} + +// Fonction pour rechercher une série dans les séries récentes +async function findSeriesInRecentFStream(tmdbTitle, tmdbYear) { + try { + const recentSeries = await scrapeFStreamRecentSeries(); + + if (recentSeries.length === 0) { + return null; + } + + // Normaliser le titre pour la comparaison + const normalizeTitle = (str) => (str || '') + .toLowerCase() + .normalize('NFD') + .replace(/[\u0300-\u036f]/g, '') + .replace(/[^\w\s]/g, '') + .replace(/\s+/g, ' ') + .trim(); + + const normalizedTmdbTitle = normalizeTitle(tmdbTitle); + + // Chercher une correspondance exacte ou très proche + for (const series of recentSeries) { + const normalizedSeriesTitle = normalizeTitle(series.title); + + // Correspondance exacte + if (normalizedSeriesTitle === normalizedTmdbTitle) { + return series; + } + + // Correspondance partielle (au moins 80% de similarité) + const similarity = calculateTitleSimilarity(normalizedTmdbTitle, normalizedSeriesTitle); + if (similarity > 0.8) { + return series; + } + } + + return null; + + } catch (error) { + console.error(`[FSTREAM RECENT SERIES] Erreur lors de la recherche: ${error.message}`); + return null; + } +} + +// Fonction pour rechercher sur FStream AVEC proxy (pour éviter les rate limits) +async function searchFStreamDirect(query, page = 1) { + try { + const formData = new URLSearchParams(); + formData.append('query', query); + formData.append('page', page.toString()); + + const response = await axiosFStreamRequest({ + method: 'post', + url: FSTREAM_SEARCH_URL, + data: formData, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + } + }); + + if (response.status !== 200) { + throw new Error(`Erreur HTTP: ${response.status}`); + } + + return response.data; + } catch (error) { + // Gérer les erreurs spécifiques qui ne doivent pas être mises en cache + if (error.response) { + const status = error.response.status; + if (status === 429 || status === 403 || status === 503 || status === 502) { + // Relancer l'erreur pour qu'elle soit gérée par le cache + throw error; + } + } + + throw error; + } +} + +async function fetchFStreamSeasonSearchResults(tmdbId, serieTitle) { + try { + const formData = new URLSearchParams(); + formData.append('serie_tag', `s-${tmdbId}`); + + const response = await axiosFStreamRequest({ + method: 'post', + url: `${FSTREAM_BASE_URL}/engine/ajax/get_seasons.php`, + data: formData, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', + 'X-Requested-With': 'XMLHttpRequest' + }, + timeout: 6000 + }); + + let seasonsData = response.data; + if (typeof seasonsData === 'string') { + const trimmed = seasonsData.trim(); + if (!trimmed) { + return []; + } + try { + seasonsData = JSON.parse(trimmed); + } catch (parseError) { + console.error(`[FSTREAM TV] Impossible de parser les saisons pour ${tmdbId}: ${parseError.message}`); + return []; + } + } + + if (!Array.isArray(seasonsData)) { + return []; + } + + const normalizedSerieTitle = serieTitle || ''; + + return seasonsData + .map((season) => { + if (!season) return null; + + const rawTitle = season.title || ''; + const altName = season.alt_name || ''; + const seasonMatch = rawTitle.match(/Saison\s+(\d+)/i) || altName.match(/saison-(\d+)/i); + if (!seasonMatch) { + return null; + } + + const seasonNumber = parseInt(seasonMatch[1], 10); + if (Number.isNaN(seasonNumber)) { + return null; + } + + const rawYear = season.serie_anne; + const year = rawYear && /^\d{4}$/.test(String(rawYear)) ? parseInt(rawYear, 10) : null; + + const fullUrl = (season.full_url || '').replace(/\\/g, '/'); + if (!fullUrl) { + return null; + } + const normalizedLink = fullUrl.startsWith('http') + ? fullUrl + : `${FSTREAM_BASE_URL}${fullUrl.startsWith('/') ? '' : '/'}${fullUrl}`; + + const baseTitle = rawTitle || `Saison ${seasonNumber}`; + const combinedTitle = normalizedSerieTitle ? `${normalizedSerieTitle} - ${baseTitle}` : baseTitle; + + return { + title: combinedTitle, + originalTitle: rawTitle || combinedTitle, + link: normalizedLink, + seasonNumber, + year + }; + }) + .filter(Boolean); + } catch (error) { + console.error(`[FSTREAM TV] Erreur lors de la récupération des saisons pour ${tmdbId}: ${error.message}`); + return []; + } +} +// Fonction pour extraire les lecteurs vidéo depuis une page FStream +async function extractFStreamPlayers(htmlContent, isSeries = false) { + try { + const $ = cheerio.load(htmlContent); + let players = []; + + if (isSeries) { + // Pour les séries, utiliser la nouvelle fonction spécialisée + return await extractFStreamSeriesPlayers(htmlContent); + } else { + // Pour les films + + // Nouvelle méthode: Extraction via #film-data + const filmData = $('#film-data'); + if (filmData.length > 0) { + const providers = ['premium', 'vidzy', 'uqload', 'dood', 'voe', 'filmoon', 'netu']; + + providers.forEach(provider => { + // Vérifier chaque version + const versions = { + 'vostfr': 'VOSTFR', + 'vff': 'VFF', + 'vfq': 'VFQ', + '': 'Default' + }; + + Object.entries(versions).forEach(([suffix, label]) => { + const attr = `data-${provider}${suffix}`; + const value = filmData.attr(attr); + + if (value && value.trim() !== '') { + let url = value; + // Pour netu, la valeur est un ID (pas une URL), construire l'URL embed + if (provider === 'netu' && !value.startsWith('http')) { + url = `https://www.fembed.com/v/${value}`; + } + + if (url.startsWith('http')) { + players.push({ + url: url, + type: 'embed', + quality: 'HD', + player: provider, + version: label + }); + } + } + }); + }); + } + + // Ancienne méthode: extraire depuis le script JavaScript + // Ne s'exécute que si on n'a pas encore trouvé de lecteurs (ou pour compléter) + if (players.length === 0) { + const scriptContent = $('script').text(); + + // Chercher l'objet playerUrls dans le script + const playerUrlsMatch = scriptContent.match(/var\s+playerUrls\s*=\s*({[\s\S]*?});/); + + if (playerUrlsMatch && playerUrlsMatch[1]) { + try { + // Essayer de parser l'objet JavaScript + const playerUrlsStr = playerUrlsMatch[1]; + + // Extraire toutes les versions de tous les lecteurs + const playerPattern = /"([^"]+)":\s*{([^}]+)}/g; + let playerMatch; + + while ((playerMatch = playerPattern.exec(playerUrlsStr)) !== null) { + const playerName = playerMatch[1]; + const versionsStr = playerMatch[2]; + + // Extraire toutes les versions pour ce lecteur + const versionPattern = /"([^"]+)":\s*"([^"]*)"/g; + let versionMatch; + + while ((versionMatch = versionPattern.exec(versionsStr)) !== null) { + const version = versionMatch[1]; + const url = versionMatch[2]; + + // Ne pas ajouter les URLs vides + if (url && url.trim() !== '') { + players.push({ + url: url, + type: 'embed', + quality: 'HD', + player: playerName, + version: version + }); + } + } + } + + // Si on n'a pas trouvé avec le pattern complexe, essayer un pattern plus simple + if (players.length === 0) { + const urlPattern = /"([^"]+)":\s*"([^"]+)"/g; + while ((match = urlPattern.exec(playerUrlsStr)) !== null) { + const key = match[1]; + const url = match[2]; + + // Filtrer les clés qui ressemblent à des URLs + if (url && url.includes('http') && !key.includes('Default') && !key.includes('VFQ') && !key.includes('VFF') && !key.includes('VOSTFR')) { + players.push({ + url: url, + type: 'embed', + quality: 'HD', + player: key + }); + } + } + } + + } catch (parseError) { + console.error('Erreur lors du parsing de playerUrls:', parseError.message); + } + } + + // Fallback: chercher des URLs directement dans le script + if (players.length === 0) { + const urlPattern = /https?:\/\/[^\s"']+/g; + const urls = scriptContent.match(urlPattern); + if (urls) { + urls.forEach(url => { + if (url.includes('embed') || url.includes('player')) { + players.push({ + url: url, + type: 'embed', + quality: 'HD' + }); + } + }); + } + } + } + + // Fallback final: chercher des iframes ou liens embed + if (players.length === 0) { + $('iframe[src], a[href*="embed"], a[href*="player"]').each((_, element) => { + const $el = $(element); + const src = $el.attr('src') || $el.attr('href'); + if (src && !src.includes('episodes-suivant')) { + players.push({ + url: src.startsWith('http') ? src : `${FSTREAM_BASE_URL}${src}`, + type: 'embed', + quality: 'HD' + }); + } + }); + } + } + + // Dédupliquer les URLs et organiser par langue + const uniquePlayers = []; + const seenUrls = new Set(); + + players.forEach(player => { + if (!seenUrls.has(player.url)) { + seenUrls.add(player.url); + uniquePlayers.push(player); + } + }); + + // Organiser les lecteurs par langue/version + const organizedPlayers = { + VFQ: [], // Version Française Qualité + VFF: [], // Version Française Film + VOSTFR: [], // Version Originale Sous-Titrée Français + Default: [] // Version par défaut + }; + + uniquePlayers.forEach(player => { + // Si la version est connue et existe dans notre structure, on l'utilise + // Sinon on met dans Default + const version = (player.version && organizedPlayers[player.version]) ? player.version : 'Default'; + + organizedPlayers[version].push({ + url: player.url, + type: player.type, + quality: player.quality, + player: player.player || 'Lecteur' + }); + }); + + // Retourner la structure organisée + return { + organized: organizedPlayers, + total: uniquePlayers.length + }; + } catch (error) { + console.error(`Erreur lors de l'extraction des lecteurs FStream: ${error.message}`); + // Retourner un objet vide mais structuré pour éviter les erreurs + return { + organized: { VFQ: [], VFF: [], VOSTFR: [], Default: [] }, + total: 0 + }; + } +} + +// Nouvelle fonction spécialisée pour extraire les lecteurs des séries +async function extractFStreamSeriesPlayers(htmlContent) { + try { + const $ = cheerio.load(htmlContent); + const episodes = {}; + + // Extraire la date de sortie depuis le XPath spécifié + let fstreamReleaseDate = null; + + // Essayer plusieurs sélecteurs pour trouver l'élément de date + const selectors = [ + 'html body div:nth-child(2) div div:nth-child(2) article div:nth-child(2) div:nth-child(1) div:nth-child(1) div:nth-child(1) span:nth-child(2)', + 'span.release', + 'div[class*="release"] span', + 'article div span[class*="release"]', + 'div[class*="info"] span[class*="release"]', + 'div[class*="meta"] span[class*="release"]' + ]; + + for (const selector of selectors) { + const releaseSpan = $(selector); + if (releaseSpan.length > 0) { + const releaseText = releaseSpan.text().trim(); + + // Extraire l'année du texte "2023 - " ou similaire + const yearMatch = releaseText.match(/(\d{4})/); + if (yearMatch) { + fstreamReleaseDate = yearMatch[1]; + break; + } + } + } + + // Si aucun sélecteur spécifique ne fonctionne, chercher dans tout le contenu + if (!fstreamReleaseDate) { + const allText = $.text(); + const yearMatches = allText.match(/(\d{4})\s*-\s*/g); + if (yearMatches && yearMatches.length > 0) { + // Prendre la première année trouvée qui semble être une date de sortie + const firstYear = yearMatches[0].match(/(\d{4})/)[1]; + if (parseInt(firstYear) >= 1900 && parseInt(firstYear) <= new Date().getFullYear() + 2) { + fstreamReleaseDate = firstYear; + } + } + } + + // ============ NOUVELLE MÉTHODE (24/12/2025): Parsing via IDs HTML ============ + let foundEpisodesData = false; + + try { + const versionMap = { + '#episodes-vf-data': 'VF', + '#episodes-vostfr-data': 'VOSTFR', + '#episodes-vo-data': 'VOENG' + }; + + for (const [selector, langKey] of Object.entries(versionMap)) { + const container = $(selector); + if (container.length > 0) { + container.children('div').each((_, element) => { + const $el = $(element); + const epNumStr = $el.attr('data-ep'); + + if (!epNumStr) return; + + const epNum = parseInt(epNumStr); + if (isNaN(epNum) || epNum === 0) return; + + // Mappage des attributs aux noms de lecteurs + const attributes = { + 'data-premium': 'FSvid', + 'data-vidzy': 'Vidzy', + 'data-uqload': 'Uqload', + 'data-netu': 'Netu', + 'data-voe': 'Voe' + }; + + const playersToAdd = []; + + Object.entries(attributes).forEach(([attr, playerName]) => { + const url = $el.attr(attr); + if (url && url.startsWith('http')) { + playersToAdd.push({ + url: url, + type: 'embed', + quality: 'HD', + player: playerName + }); + } + }); + + // Si des lecteurs ont été trouvés, on les ajoute + if (playersToAdd.length > 0) { + // Initialiser l'épisode si nécessaire + if (!episodes[epNum]) { + episodes[epNum] = { + number: epNum, + title: `Episode ${epNum}`, + languages: { + VF: [], + VOSTFR: [], + VOENG: [], + Default: [] + } + }; + } + + // Ajouter les lecteurs trouvés + playersToAdd.forEach(player => { + // Vérifier si le lien existe déjà pour éviter les doublons + const exists = episodes[epNum].languages[langKey].some(p => p.url === player.url); + if (!exists) { + episodes[epNum].languages[langKey].push(player); + } + }); + } + }); + + // Si on a trouvé des épisodes via cette méthodes, on peut considérer qu'on a des données + if (Object.keys(episodes).length > 0) { + foundEpisodesData = true; + } + } + } + + if (foundEpisodesData) { + console.log(`[FStream] ✅ Données trouvées via les IDs HTML (#episodes-*-data) : ${Object.keys(episodes).length} épisodes`); + } + } catch (newMethodError) { + console.error(`[FStream] Erreur nouvelle méthode extraction: ${newMethodError.message}`); + } + + // ============ ANCIENNE MÉTHODE: Parser episodesData depuis le script (Fallback) ============ + // Chercher le script contenant episodesData + // (Ne s'exécutera que si foundEpisodesData est false si on ajoute une condition, mais ici on laisse tourner pour compléter potentiellement) + + $('script').each((_, scriptEl) => { + const scriptContent = $(scriptEl).html() || ''; + + // Chercher var episodesData = {...} + const episodesDataMatch = scriptContent.match(/var\s+episodesData\s*=\s*(\{[\s\S]*?\});(?:\s*var|\s*\n\s*var|\s*\n\s*\n)/); + + if (episodesDataMatch && episodesDataMatch[1]) { + try { + // Nettoyer le JSON (remplacer les trailing commas, etc.) + let jsonStr = episodesDataMatch[1]; + + // Parser manuellement car ce n'est pas du JSON valide + // Extraire VF + const vfMatch = jsonStr.match(/vf:\s*\{([\s\S]*?)\},\s*(?:vostfr|vo):/); + const vostfrMatch = jsonStr.match(/vostfr:\s*\{([\s\S]*?)\},\s*vo:/); + const voMatch = jsonStr.match(/vo:\s*\{([\s\S]*?)\}\s*\}/); + + // Fonction pour parser les épisodes d'une langue + const parseLanguageEpisodes = (langContent, langKey) => { + if (!langContent) return; + + // Extraire chaque épisode: numéro: {player1:"url1", player2:"url2"} + const episodePattern = /(\d+):\s*\{([^}]+)\}/g; + let epMatch; + + while ((epMatch = episodePattern.exec(langContent)) !== null) { + const epNum = parseInt(epMatch[1]); + const playersContent = epMatch[2]; + + // Créer l'entrée d'épisode si elle n'existe pas + if (!episodes[epNum]) { + episodes[epNum] = { + number: epNum, + title: `Episode ${epNum}`, + languages: { + VF: [], + VOSTFR: [], + VOENG: [], + Default: [] + } + }; + } + + // Extraire chaque player: nom:"url" + const playerPattern = /(\w+):"([^"]+)"/g; + let playerMatch; + + while ((playerMatch = playerPattern.exec(playersContent)) !== null) { + const playerName = playerMatch[1]; + const playerUrl = playerMatch[2]; + + // Ignorer les URLs invalides + if (!playerUrl || playerUrl.includes('[') || playerUrl.includes('xfvalue_')) { + continue; + } + + // Déterminer le nom du player pour l'affichage + let displayName = playerName.toUpperCase(); + if (playerName === 'vidzy') displayName = 'Vidzy'; + else if (playerName === 'uqload') displayName = 'Uqload'; + else if (playerName === 'netu') displayName = 'Netu'; + else if (playerName === 'voe') displayName = 'Voe'; + else if (playerName === 'premium') displayName = 'Premium'; + + const player = { + url: playerUrl, + type: 'embed', + quality: 'HD', + player: displayName + }; + + // Ajouter au bon langKey + const targetLang = langKey === 'vo' ? 'VOENG' : (langKey === 'vostfr' ? 'VOSTFR' : 'VF'); + + // Éviter les doublons + const exists = episodes[epNum].languages[targetLang].some(p => p.url === playerUrl); + if (!exists) { + episodes[epNum].languages[targetLang].push(player); + } + } + } + }; + + // Parser chaque langue + if (vfMatch && vfMatch[1]) { + parseLanguageEpisodes(vfMatch[1], 'vf'); + } + if (vostfrMatch && vostfrMatch[1]) { + parseLanguageEpisodes(vostfrMatch[1], 'vostfr'); + } + if (voMatch && voMatch[1]) { + parseLanguageEpisodes(voMatch[1], 'vo'); + } + + foundEpisodesData = Object.keys(episodes).length > 0; + if (foundEpisodesData) { + console.log(`[FStream] ✅ Parsed episodesData: ${Object.keys(episodes).length} episodes found`); + } + + } catch (parseError) { + console.error('[FStream] Erreur parsing episodesData:', parseError.message); + } + } + }); + + // ============ MÉTHODE LEGACY: Chercher dans le HTML si episodesData non trouvé ============ + if (!foundEpisodesData) { + console.log('[FStream] episodesData non trouvé, utilisation de la méthode legacy...'); + + // Chercher tous les divs fullsfeature (épisodes) - inclure tous les IDs, pas seulement "episode" + $('div.fullsfeature').each((_, element) => { + const $episode = $(element); + const episodeId = $episode.attr('id'); + + // Extraire le titre de l'épisode + const titleSpan = $episode.find('.selink span').first(); + const episodeTitle = titleSpan.text().trim(); + + // Vérifier que c'est un vrai épisode avec un titre valide + if (!episodeTitle || episodeTitle.trim() === '') { + return; + } + + // Déterminer la langue/version basée sur le titre + let language = 'Default'; + if (episodeTitle.toLowerCase().includes('vostfr')) { + language = 'VOSTFR'; + } else if (episodeTitle.toLowerCase().includes('vf')) { + language = 'VFF'; + } + + // Extraire le numéro d'épisode + const episodeMatch = episodeTitle.match(/épisode\s+(\d+)/i); + const episodeNumber = episodeMatch ? parseInt(episodeMatch[1]) : 1; + + // Extraire les lecteurs de cet épisode + const episodePlayers = []; + $episode.find('ul.btnss a.fsctab').each((_, linkElement) => { + const $link = $(linkElement); + const href = $link.attr('href'); + const playerName = $link.text().trim(); + + if (href && href.startsWith('http') && !href.includes('episodes-suivant')) { + episodePlayers.push({ + url: href, + type: 'embed', + quality: 'HD', + player: playerName + }); + } + }); + + // Ajouter l'épisode à la structure seulement s'il a des lecteurs + if (episodePlayers.length > 0) { + if (!episodes[episodeNumber]) { + episodes[episodeNumber] = { + number: episodeNumber, + title: episodeTitle, + languages: { + VF: [], + VOSTFR: [], + VOENG: [], + Default: [] + } + }; + } + + // Ajouter les lecteurs à la langue appropriée + const langKey = language === 'VOSTFR' ? 'VOSTFR' : 'VF'; + episodes[episodeNumber].languages[langKey] = episodePlayers; + } + }); + + // Chercher aussi les épisodes VOENG dans div.elink + $('div.elink a.fstab').each((_, linkElement) => { + const $link = $(linkElement); + const href = $link.attr('href'); + const linkText = $link.text().trim(); + const dataEpisodeId = $link.attr('data-episode-id'); + + // Vérifier que c'est un lien valide + if (!href || !href.startsWith('http') || linkText.trim() === '') { + return; + } + + // Extraire le numéro d'épisode du texte + const episodeMatch = linkText.match(/episode\s+(\d+)/i); + if (!episodeMatch) { + return; + } + + const episodeNumber = parseInt(episodeMatch[1]); + + // Déterminer la langue/version + let language = 'Default'; + const lowerText = linkText.toLowerCase(); + if (lowerText.includes('vosteng') || lowerText.includes('voeng')) { + language = 'VOENG'; + } else if (lowerText.includes('vostfr')) { + language = 'VOSTFR'; + } else if (lowerText.includes('vf')) { + language = 'VFF'; + } + + // Déterminer le nom du player depuis l'URL + let playerName = 'Unknown'; + if (href.includes('fsvid.lol')) { + playerName = 'FSvid'; + } else if (href.includes('vidzy.org')) { + playerName = 'Vidzy'; + } else if (href.includes('uqload')) { + playerName = 'Uqload'; + } else if (href.includes('voe.sx')) { + playerName = 'Voe'; + } + + // Créer l'objet player + const player = { + url: href, + type: 'embed', + quality: 'HD', + player: playerName + }; + + // Ajouter l'épisode à la structure + if (!episodes[episodeNumber]) { + episodes[episodeNumber] = { + number: episodeNumber, + title: linkText, + languages: { + VF: [], + VOSTFR: [], + VOENG: [], + Default: [] + } + }; + } + + // Ajouter le lecteur à la langue appropriée + const langKey = language === 'VOENG' ? 'VOENG' : (language === 'VOSTFR' ? 'VOSTFR' : 'VF'); + + // Vérifier que le player n'existe pas déjà (éviter les doublons) + const existingPlayer = episodes[episodeNumber].languages[langKey].find(p => p.url === href); + if (!existingPlayer) { + episodes[episodeNumber].languages[langKey].push(player); + } + }); + } + + // Organiser par langue pour la compatibilité avec l'API + const organizedPlayers = { + VF: [], + VOSTFR: [], + VOENG: [], + Default: [] + }; + + // Compter le total de lecteurs + let totalPlayers = 0; + + // Organiser les lecteurs par langue + Object.values(episodes).forEach(episode => { + Object.entries(episode.languages).forEach(([lang, players]) => { + if (players.length > 0) { + organizedPlayers[lang].push(...players); + totalPlayers += players.length; + } + }); + }); + + // Retourner la structure organisée + return { + organized: organizedPlayers, + episodes: episodes, + total: totalPlayers, + fstreamReleaseDate: fstreamReleaseDate + }; + } catch (error) { + console.error(`Erreur lors de l'extraction des lecteurs série FStream: ${error.message}`); + // Retourner un objet vide mais structuré pour éviter les erreurs + return { + organized: { VF: [], VOSTFR: [], VOENG: [], Default: [] }, + episodes: {}, + total: 0, + fstreamReleaseDate: null + }; + } +} +// Fonction pour filtrer les résultats de recherche FStream +function filterFStreamResults(results, originalTitle, releaseYear) { + try { + const $ = cheerio.load(results); + const filteredResults = []; + + // Chercher les éléments de recherche selon la structure réelle + $('div.search-item').each((_, element) => { + const $el = $(element); + const titleElement = $el.find('.search-title'); + const title = titleElement.text().trim(); + + // Extraire le lien depuis l'attribut onclick + const onclickAttr = $el.attr('onclick'); + let link = null; + if (onclickAttr) { + // Supporter les attributs avec quotes simples ou doubles + const linkMatch = onclickAttr.match(/location\.href=['"]([^'\"]+)['"]/); + if (linkMatch) { + link = linkMatch[1]; + } + } + + if (!title || !link) return; + + // Nettoyer le titre + let cleanTitle = title; + let seasonNumber = null; + let year = null; + + // Extraire l'année si présente + const yearMatch = title.match(/\((\d{4})\)/); + if (yearMatch) { + year = parseInt(yearMatch[1]); + cleanTitle = title.replace(/\s*\(\d{4}\)/, '').trim(); + } + + // Extraire le numéro de saison si présent + const seasonMatch = cleanTitle.match(/Saison\s+(\d+)/i); + if (seasonMatch) { + seasonNumber = parseInt(seasonMatch[1]); + cleanTitle = cleanTitle.replace(/\s*-\s*Saison\s+\d+$/i, '').trim(); + } else { + // Fallback: chercher "Saison X" dans le titre original + const originalSeasonMatch = title.match(/Saison\s+(\d+)/i); + if (originalSeasonMatch) { + seasonNumber = parseInt(originalSeasonMatch[1]); + } + } + + // Normaliser les titres (accents, ponctuation, espaces) pour comparaisons robustes + const normalize = (str) => + (str || '') + .toLowerCase() + .normalize('NFD') + .replace(/[\u0300-\u036f]/g, '') // accents + .replace(/['’`´]/g, '') // apostrophes + .replace(/[^a-z0-9\s-]/g, '') // autres ponctuations + .replace(/\s+-\s+/g, ' ') // espaces autour de tirets + .replace(/\s+/g, ' ') // espaces multiples + .trim(); + + const normalizedOriginal = normalize(originalTitle); + const normalizedClean = normalize(cleanTitle); + + // Correspondance avec préférence au titre exact, sinon recouvrement de tokens + const tokenize = (str) => (str || '') + .split(' ') + .filter(Boolean); + + const originalTokens = new Set(tokenize(normalizedOriginal)); + const cleanTokens = new Set(tokenize(normalizedClean)); + + let intersectionSize = 0; + for (const token of cleanTokens) { + if (originalTokens.has(token)) intersectionSize += 1; + } + + // Utiliser la taille du plus GRAND ensemble pour éviter que 1 mot ne valide des titres longs + const largerSetSize = Math.max(1, Math.max(originalTokens.size, cleanTokens.size)); + const overlapScore = intersectionSize / largerSetSize; // plus strict pour titres d'une seule unité + + // Exiger l'année quand elle est disponible des deux côtés, sinon utiliser seulement le score de recouvrement + const hasBothYears = Boolean(releaseYear && year); + const yearMatches = hasBothYears ? parseInt(releaseYear) === year : true; + + const exactTitleMatch = normalizedClean === normalizedOriginal; + const threshold = 0.7; // seuil pour correspondances partielles proches + // N'autoriser les correspondances partielles que si le titre n'est pas beaucoup plus long + const partialLengthOk = cleanTokens.size <= originalTokens.size + 1; + // Cas important: le titre trouvé est un sous-ensemble exact du titre recherché (ex: sans sous-titre) + // Exiger que le sous-ensemble couvre au moins 50% des tokens originaux pour éviter les faux positifs + // (ex: "Sauvage" ne doit pas matcher "L'instinct sauvage") + const subsetCoverage = cleanTokens.size / Math.max(1, originalTokens.size); + const resultIsSubsetOfOriginal = Array.from(cleanTokens).every(t => originalTokens.has(t)) && subsetCoverage >= 0.5; + const shouldInclude = yearMatches && ( + exactTitleMatch || + resultIsSubsetOfOriginal || + (overlapScore >= threshold && partialLengthOk) + ); + + if (shouldInclude) { + filteredResults.push({ + title: cleanTitle, + originalTitle: title, + link: link.startsWith('http') ? link : `${FSTREAM_BASE_URL}${link}`, + seasonNumber, + year + }); + } + }); + + // Pas de tri nécessaire ici + + return filteredResults; + } catch (error) { + console.error(`Erreur lors du filtrage des résultats FStream: ${error.message}`); + return []; + } +} +// Route pour les films FStream +app.get('/api/fstream/movie/:id', async (req, res) => { + const { id } = req.params; + + // Définir cacheKey en dehors du try pour qu'il soit disponible dans le catch + const cacheKey = generateFStreamCacheKey('movie', id); + + try { + // Vérifier le cache d'abord + const cachedData = await getFStreamFromCache(cacheKey); + if (cachedData) { + if (!cachedData.success) { + } + // Retourner les données du cache immédiatement + res.status(200).json(cachedData); + + // Mettre à jour le cache en arrière-plan avec déduplication + setImmediate(async () => { + try { + await getOrCreateFStreamRequest(`${cacheKey}_background`, async () => { + // Récupérer les détails TMDB + const tmdbDetails = await getFStreamTMDBDetails(id, 'movie'); + if (!tmdbDetails) { + return; + } + + const searchQuery = tmdbDetails.title; + + // Rechercher sur FStream (sans proxy) + let searchResults = await searchFStreamDirect(searchQuery); + + // Filtrer les résultats + let filteredResults = filterFStreamResults(searchResults, tmdbDetails.title, tmdbDetails.release_date?.split('-')[0]); + + + + // Si aucun résultat, TOUJOURS vérifier dans les films récents + // (pas seulement si le film est strictement récent, car la liste FStream peut contenir des films variés) + if (filteredResults.length === 0) { + try { + const recentMovie = await findMovieInRecentFStream(tmdbDetails.title, tmdbDetails.release_date?.split('-')[0]); + + if (recentMovie) { + + // Récupérer la page du contenu depuis le film récent + const contentResponse = await axiosFStreamRequest({ + method: 'get', + url: recentMovie.link + }); + + if (contentResponse.status === 200) { + // Extraire les lecteurs vidéo + const players = await extractFStreamPlayers(contentResponse.data, false); + + if (players.total > 0) { + // Formater la réponse avec le film récent + const response = { + success: true, + source: 'FStream', + type: 'movie', + tmdb: tmdbDetails, + search: { + query: tmdbDetails.title, + results: 1, + bestMatch: { + title: recentMovie.title, + originalTitle: `${recentMovie.title} (${tmdbDetails.release_date?.split('-')[0]})`, + link: recentMovie.link, + seasonNumber: null, + year: parseInt(tmdbDetails.release_date?.split('-')[0]) + } + }, + players: players.organized, + total: players.total, + metadata: { + extractedAt: new Date().toISOString(), + backgroundUpdate: true, + foundInRecent: true + } + }; + + // Sauvegarder en cache + await saveFStreamToCache(cacheKey, response); + return; + } + } + } + } catch (recentError) { + console.error(`[FSTREAM BACKGROUND] Erreur lors de la recherche dans les récents: ${recentError.message}`); + } + + // Créer un résultat d'erreur pour le cache + const errorResult = { + success: false, + error: 'Aucun résultat trouvé', + message: `Aucun contenu trouvé pour "${tmdbDetails.title}" sur FStream`, + search: { + query: tmdbDetails.title, + results: 0, + checkedRecent: true + }, + timestamp: new Date().toISOString() + }; + + // Sauvegarder l'erreur en cache + await saveFStreamToCache(cacheKey, errorResult); + return; + } + + // Filtrer par année si disponible - OBLIGATOIRE pour les films + let bestResult = null; + const tmdbYear = tmdbDetails.release_date?.split('-')[0]; + + if (tmdbYear) { + // Chercher UNIQUEMENT les résultats avec correspondance d'année exacte + const yearMatches = filteredResults.filter(result => result.year === parseInt(tmdbYear)); + + if (yearMatches.length > 0) { + // Prendre le premier résultat avec la bonne année (correspondance exacte uniquement) + bestResult = yearMatches[0]; + } else { + // TOUJOURS vérifier dans les films récents quand il n'y a pas de correspondance d'année + try { + const recentMovie = await findMovieInRecentFStream(tmdbDetails.title, tmdbDetails.release_date?.split('-')[0]); + + if (recentMovie) { + + // Récupérer la page du contenu depuis le film récent + const contentResponse = await axiosFStreamRequest({ + method: 'get', + url: recentMovie.link + }); + + if (contentResponse.status === 200) { + // Extraire les lecteurs vidéo + const players = await extractFStreamPlayers(contentResponse.data, false); + + if (players.total > 0) { + // Formater la réponse avec le film récent + const response = { + success: true, + source: 'FStream', + type: 'movie', + tmdb: tmdbDetails, + search: { + query: tmdbDetails.title, + results: 1, + bestMatch: { + title: recentMovie.title, + originalTitle: `${recentMovie.title} (${tmdbDetails.release_date?.split('-')[0]})`, + link: recentMovie.link, + seasonNumber: null, + year: parseInt(tmdbDetails.release_date?.split('-')[0]) + } + }, + players: players.organized, + total: players.total, + metadata: { + extractedAt: new Date().toISOString(), + backgroundUpdate: true, + foundInRecent: true + } + }; + + // Sauvegarder en cache + await saveFStreamToCache(cacheKey, response); + return; + } + } + } + } catch (recentError) { + console.error(`[FSTREAM BACKGROUND] Erreur lors de la recherche dans les récents: ${recentError.message}`); + } + + // Créer un résultat d'erreur pour le cache + const errorResult = { + success: false, + error: 'Aucune correspondance d\'année', + message: `Aucun contenu trouvé avec l'année ${tmdbYear} pour "${tmdbDetails.title}" sur FStream`, + search: { + query: tmdbDetails.title, + results: filteredResults.length, + year: tmdbYear, + checkedRecent: true + }, + timestamp: new Date().toISOString() + }; + + // Sauvegarder l'erreur en cache + await saveFStreamToCache(cacheKey, errorResult); + return; + } + } else { + // Si pas d'année TMDB, prendre le premier résultat (cas rare) + bestResult = filteredResults[0]; + } + + // Vérification de sécurité + if (!bestResult) { + + // Créer un résultat d'erreur pour le cache + const errorResult = { + success: false, + error: 'Aucun résultat valide', + message: `Aucun résultat valide trouvé pour "${tmdbDetails.title}" sur FStream`, + search: { + query: tmdbDetails.title, + results: filteredResults.length + }, + timestamp: new Date().toISOString() + }; + + // Sauvegarder l'erreur en cache + await saveFStreamToCache(cacheKey, errorResult); + return; + } + + // Récupérer la page du contenu + const contentResponse = await axiosFStreamRequest({ + method: 'get', + url: bestResult.link + }); + + if (contentResponse.status !== 200) { + return; + } + + // Extraire les lecteurs vidéo + const players = await extractFStreamPlayers(contentResponse.data, false); + + if (players.total === 0) { + return; + } + + // Formater la réponse + const response = { + success: true, + source: 'FStream', + type: 'movie', + tmdb: tmdbDetails, + search: { + query: searchQuery, + results: filteredResults.length, + bestMatch: bestResult + }, + players: players.organized, + total: players.total, + metadata: { + extractedAt: new Date().toISOString(), + backgroundUpdate: true + } + }; + + // Sauvegarder en cache + await saveFStreamToCache(cacheKey, response); + return response; + }); + } catch (error) { + } + }); + + return; + } + + // Pas de cache, faire la requête avec déduplication + const result = await getOrCreateFStreamRequest(cacheKey, async () => { + // Récupérer les détails TMDB + const tmdbDetails = await getFStreamTMDBDetails(id, 'movie'); + if (!tmdbDetails) { + throw new Error('Contenu TMDB non trouvé'); + } + + const searchQuery = tmdbDetails.title; + + // Rechercher sur FStream (sans proxy) + let searchResults = await searchFStreamDirect(searchQuery); + + // Filtrer les résultats + let filteredResults = filterFStreamResults(searchResults, tmdbDetails.title, tmdbDetails.release_date?.split('-')[0]); + + // Filtrer par année si disponible - OBLIGATOIRE pour les films + let bestResult = null; + const tmdbYear = tmdbDetails.release_date?.split('-')[0]; + + if (tmdbYear) { + // Chercher UNIQUEMENT les résultats avec correspondance d'année exacte + const yearMatches = filteredResults.filter(result => result.year === parseInt(tmdbYear)); + + if (yearMatches.length > 0) { + // Prendre le premier résultat avec la bonne année (correspondance exacte uniquement) + bestResult = yearMatches[0]; + } else { + // Vérifier dans les films récents quand il n'y a pas de correspondance d'année + const recentMovie = await findMovieInRecentFStream(tmdbDetails.title, tmdbYear); + + if (recentMovie) { + bestResult = { + title: recentMovie.title, + originalTitle: `${recentMovie.title} (${tmdbYear})`, + link: recentMovie.link, + seasonNumber: null, + year: parseInt(tmdbYear) + }; + } else { + throw new Error(`Aucun résultat trouvé avec l'année ${tmdbYear} sur FStream`); + } + } + } else { + // Si pas d'année TMDB, prendre le premier résultat (cas rare) + if (filteredResults.length > 0) { + bestResult = filteredResults[0]; + } + } + + // Si toujours aucun résultat, vérifier dans les films récents + if (filteredResults.length === 0 && !bestResult) { + const recentMovie = await findMovieInRecentFStream(tmdbDetails.title, tmdbYear); + + if (recentMovie) { + bestResult = { + title: recentMovie.title, + originalTitle: `${recentMovie.title}${tmdbYear ? ` (${tmdbYear})` : ''}`, + link: recentMovie.link, + seasonNumber: null, + year: tmdbYear ? parseInt(tmdbYear) : null + }; + } else { + throw new Error('Aucun résultat trouvé sur FStream'); + } + } + + // Vérification de sécurité + if (!bestResult) { + throw new Error('Aucun résultat valide trouvé sur FStream'); + } + + // Récupérer la page du contenu + const contentResponse = await axiosFStreamRequest({ + method: 'get', + url: bestResult.link + }); + + if (contentResponse.status !== 200) { + throw new Error(`Erreur lors de la récupération de la page: ${contentResponse.status}`); + } + + // Extraire les lecteurs vidéo (films uniquement) + const players = await extractFStreamPlayers(contentResponse.data, false); + + if (players.total === 0) { + return res.status(404).json({ + error: 'Aucun lecteur vidéo trouvé', + searchQuery, + bestResult: bestResult.title + }); + } + + // Formater la réponse + const response = { + success: true, + source: 'FStream', + type: 'movie', + tmdb: tmdbDetails, + search: { + query: searchQuery, + results: filteredResults.length, + bestMatch: bestResult + }, + players: players.organized, + total: players.total, + metadata: { + extractedAt: new Date().toISOString() + } + }; + + return response; + }); + + // Sauvegarder en cache seulement si pas d'erreur + await saveFStreamToCache(cacheKey, result); + + res.status(200).json(result); + + } catch (error) { + console.error(`[FSTREAM MOVIE] Erreur: ${error.message}`); + + // Ne pas mettre à jour le cache en cas d'erreur + // Créer un résultat d'erreur pour le cache + const errorResult = { + success: false, + error: 'Erreur lors de la récupération des sources FStream', + message: error.message, + timestamp: new Date().toISOString() + }; + + // Sauvegarder l'erreur en cache (non-résultat) + await saveFStreamToCache(cacheKey, errorResult); + + res.status(500).json(errorResult); + } +}); + +// Route de test pour les films récents FStream +app.get('/api/fstream/test/recent', async (req, res) => { + try { + const recentMovies = await scrapeFStreamRecentMovies(); + res.status(200).json({ + success: true, + count: recentMovies.length, + movies: recentMovies.slice(0, 10), // Limiter à 10 pour la lisibilité + timestamp: new Date().toISOString() + }); + } catch (error) { + res.status(500).json({ + success: false, + error: error.message, + timestamp: new Date().toISOString() + }); + } +}); + +// Route de test pour les séries récentes FStream +app.get('/api/fstream/test/recent-series', async (req, res) => { + try { + const recentSeries = await scrapeFStreamRecentSeries(); + res.status(200).json({ + success: true, + count: recentSeries.length, + series: recentSeries.slice(0, 10), // Limiter à 10 pour la lisibilité + timestamp: new Date().toISOString() + }); + } catch (error) { + res.status(500).json({ + success: false, + error: error.message, + timestamp: new Date().toISOString() + }); + } +}); + +// Route de debug pour voir les requêtes FStream en cours +app.get('/api/fstream/debug/ongoing', async (req, res) => { + try { + const ongoingKeys = Array.from(ongoingFStreamRequests.keys()); + res.status(200).json({ + success: true, + ongoingRequests: ongoingKeys.length, + keys: ongoingKeys, + timestamp: new Date().toISOString() + }); + } catch (error) { + res.status(500).json({ + success: false, + error: error.message + }); + } +}); + +// Route pour supprimer le cache FStream d'un film +app.get('/api/fstream/movie/:id/clear-cache', async (req, res) => { + const { id } = req.params; + const cacheKey = generateFStreamCacheKey('movie', id); + const cacheFilePath = path.join(CACHE_DIR.FSTREAM, `${cacheKey}.json`); + + try { + // Supprimer le cache fichier + await fsp.unlink(cacheFilePath); + // Supprimer le cache Redis + try { await redis.del(`fstream:${cacheKey}`); } catch {} + console.log(`[FSTREAM Cache] Cache cleared for movie ${id}`); + res.json({ success: true, message: `Cache cleared for movie ${id}` }); + } catch (error) { + if (error.code === 'ENOENT') { + // Fichier pas trouvé, tenter quand même de supprimer le cache Redis + try { await redis.del(`fstream:${cacheKey}`); } catch {} + res.status(404).json({ error: `No cache found for movie ${id}` }); + } else { + console.error(`[FSTREAM Cache] Error clearing cache for movie ${id}:`, error.message); + res.status(500).json({ error: 'Failed to clear cache' }); + } + } +}); + +// Route pour supprimer le cache FStream d'une série +app.get('/api/fstream/tv/:id/season/:season/clear-cache', async (req, res) => { + const { id, season } = req.params; + const { episode } = req.query; + const cacheKey = generateFStreamCacheKey('tv', id, season, episode || null); + const cacheFilePath = path.join(CACHE_DIR.FSTREAM, `${cacheKey}.json`); + + try { + await fsp.unlink(cacheFilePath); + try { await redis.del(`fstream:${cacheKey}`); } catch {} + console.log(`[FSTREAM Cache] Cache cleared for tv ${id} S${season}${episode ? ' E' + episode : ''}`); + res.json({ success: true, message: `Cache cleared for tv ${id} season ${season}${episode ? ' episode ' + episode : ''}` }); + } catch (error) { + if (error.code === 'ENOENT') { + try { await redis.del(`fstream:${cacheKey}`); } catch {} + res.status(404).json({ error: `No cache found for tv ${id} season ${season}` }); + } else { + console.error(`[FSTREAM Cache] Error clearing cache for tv ${id}:`, error.message); + res.status(500).json({ error: 'Failed to clear cache' }); + } + } +}); + +// Route pour les séries FStream +app.get('/api/fstream/tv/:id/season/:season', async (req, res) => { + const { id, season } = req.params; + const { episode } = req.query; // numéro d'épisode optionnel + + // Log de débogage + + // Définir cacheKey en dehors du try pour qu'il soit disponible dans le catch + const cacheKey = generateFStreamCacheKey('tv', id, season, episode); + + try { + // Vérifier le cache d'abord + const cachedData = await getFStreamFromCache(cacheKey); + if (cachedData) { + // Retourner les données du cache immédiatement + res.status(200).json(cachedData); + + // Mettre à jour le cache en arrière-plan avec déduplication + setImmediate(async () => { + try { + await getOrCreateFStreamRequest(`${cacheKey}_background`, async () => { + // Récupérer les détails TMDB + const tmdbDetails = await getFStreamTMDBDetails(id, 'tv'); + if (!tmdbDetails) { + return; + } + + let searchQuery; + if (id === '259909') { + searchQuery = 'Dexter : Résurrection - Saison 1'; + } else { + searchQuery = `${tmdbDetails.title} - Saison ${season}`; + } + + // Rechercher sur FStream (sans proxy) + let searchResults = await searchFStreamDirect(searchQuery); + + // Filtrer les résultats + let filteredResults = filterFStreamResults(searchResults, tmdbDetails.title, tmdbDetails.release_date?.split('-')[0]); + + // Si aucun résultat, essayer avec l'année + if (filteredResults.length === 0) { + // Dernier recours précoce : requête directe des saisons via l'endpoint ajax + const directSeasonsEarly = await fetchFStreamSeasonSearchResults(id, tmdbDetails.title); + if (directSeasonsEarly.length > 0) { + filteredResults = directSeasonsEarly; + } + + // Essayer une recherche de fallback avec l'année + if (tmdbDetails.release_date) { + const year = tmdbDetails.release_date.split('-')[0]; + const fallbackQuery = `${tmdbDetails.title} (${year}) - Saison ${season}`; + + try { + let fallbackSearchResults = await searchFStreamDirect(fallbackQuery); + + let fallbackFilteredResults = filterFStreamResults(fallbackSearchResults, tmdbDetails.title, year); + + if (fallbackFilteredResults.length > 0) { + filteredResults = fallbackFilteredResults; + } + } catch (fallbackError) { + console.log(`[FSTREAM TV BACKGROUND] ⚠️ Erreur lors de la recherche de fallback avec année: ${fallbackError.message}`); + } + } + + // Si toujours aucun résultat, essayer avec le nom sans paramètre de langue + if (filteredResults.length === 0 && tmdbDetails.name_no_lang && tmdbDetails.name_no_lang !== tmdbDetails.title) { + const noLangFallbackQuery = `${tmdbDetails.name_no_lang} - Saison ${season}`; + + try { + let noLangSearchResults = await searchFStreamDirect(noLangFallbackQuery); + + let noLangFilteredResults = filterFStreamResults(noLangSearchResults, tmdbDetails.name_no_lang, tmdbDetails.release_date?.split('-')[0]); + + if (noLangFilteredResults.length > 0) { + filteredResults = noLangFilteredResults; + console.log(`[FSTREAM TV BACKGROUND] ✅ Fallback avec nom sans langue réussi: "${noLangFallbackQuery}"`); + } + } catch (noLangFallbackError) { + console.log(`[FSTREAM TV BACKGROUND] ⚠️ Erreur lors de la recherche de fallback avec nom sans langue: ${noLangFallbackError.message}`); + } + } + + // Si toujours aucun résultat après tous les fallbacks + if (filteredResults.length === 0) { + // Dernier recours : requête directe des saisons via l'endpoint ajax (seconde tentative) + const directSeasons = await fetchFStreamSeasonSearchResults(id, tmdbDetails.title); + if (directSeasons.length > 0) { + filteredResults = directSeasons; + } + + // Si toujours aucun résultat, vérifier si la série est récente (moins de 2 jours) + if (filteredResults.length === 0) { + const releaseDate = tmdbDetails.release_date; + let shouldCheckRecent = false; + + if (releaseDate) { + const releaseDateTime = new Date(releaseDate); + const now = new Date(); + const diffInDays = (now - releaseDateTime) / (1000 * 60 * 60 * 24); + + if (diffInDays <= 2) { + shouldCheckRecent = true; + console.log(`[FSTREAM TV BACKGROUND] Série récente détectée (${diffInDays.toFixed(1)} jours), recherche dans les séries récentes...`); + } + } + + // Si la série est récente, chercher dans les séries récentes + if (shouldCheckRecent) { + try { + const recentSeries = await findSeriesInRecentFStream(tmdbDetails.title, tmdbDetails.release_date?.split('-')[0]); + + if (recentSeries) { + console.log(`[FSTREAM TV BACKGROUND] ✅ Série trouvée dans les récents: "${recentSeries.title}"`); + + // Récupérer la page du contenu depuis la série récente + const contentResponse = await axiosFStreamRequest({ + method: 'get', + url: recentSeries.link + }); + + if (contentResponse.status === 200) { + // Extraire les lecteurs vidéo + const players = await extractFStreamPlayers(contentResponse.data, true); + + if (players.total > 0) { + // Formater la réponse avec la série récente + const response = { + success: true, + source: 'FStream', + type: 'tv', + tmdb: tmdbDetails, + search: { + query: `${tmdbDetails.title} - Saison ${season}`, + results: 1, + bestMatch: { + title: recentSeries.title, + originalTitle: `${recentSeries.title} (${tmdbDetails.release_date?.split('-')[0]})`, + link: recentSeries.link, + seasonNumber: parseInt(season), + year: parseInt(tmdbDetails.release_date?.split('-')[0]) + } + }, + episodes: players.episodes, + total: players.total, + metadata: { + season: parseInt(season), + episode: episode ? parseInt(episode) : null, + extractedAt: new Date().toISOString(), + backgroundUpdate: true, + foundInRecent: true + } + }; + + // Sauvegarder en cache + await saveFStreamToCache(cacheKey, response); + return; + } + } + } + } catch (recentError) { + console.error(`[FSTREAM TV BACKGROUND] Erreur lors de la recherche dans les récents: ${recentError.message}`); + } + } + + // Créer un résultat d'erreur pour le cache + const errorResult = { + success: false, + error: 'Aucun résultat trouvé', + message: `Aucun contenu trouvé pour "${tmdbDetails.title} - Saison ${season}" sur FStream`, + search: { + query: `${tmdbDetails.title} - Saison ${season}`, + fallbackQuery: tmdbDetails.release_date ? `${tmdbDetails.title} (${tmdbDetails.release_date.split('-')[0]}) - Saison ${season}` : null, + noLangFallbackQuery: tmdbDetails.name_no_lang && tmdbDetails.name_no_lang !== tmdbDetails.title ? `${tmdbDetails.name_no_lang} - Saison ${season}` : null, + results: 0, + checkedRecent: shouldCheckRecent + }, + timestamp: new Date().toISOString() + }; + + // Sauvegarder l'erreur en cache + await saveFStreamToCache(cacheKey, errorResult); + return; + } + } + } + + // Filtrer par saison demandée + const requestedSeason = parseInt(season); + + // Chercher une correspondance exacte de saison + const seasonMatch = filteredResults.find(result => { + if (result.seasonNumber) { + return result.seasonNumber === requestedSeason; + } + return false; + }); + + if (seasonMatch) { + } else { + console.log(`[FSTREAM TV BACKGROUND] ⚠️ Aucune correspondance exacte de saison trouvée`); + } + + // Si aucune correspondance exacte, chercher dans le titre original + let bestResult = seasonMatch; + if (!bestResult) { + const titleSeasonMatch = filteredResults.find(result => { + if (result.originalTitle) { + const seasonInTitle = result.originalTitle.match(/Saison\s+(\d+)/i); + if (seasonInTitle) { + return parseInt(seasonInTitle[1]) === requestedSeason; + } + } + return false; + }); + bestResult = titleSeasonMatch; + if (titleSeasonMatch) { + } + } + + // Si toujours aucune correspondance, créer un résultat d'erreur pour le cache + if (!bestResult) { + // Filtrer seulement les saisons de la série demandée + const availableSeasons = filteredResults + .filter(r => r.seasonNumber && r.title.toLowerCase().includes(tmdbDetails.title.toLowerCase().split(/[:\-]/)[0].trim().toLowerCase())) + .map(r => r.seasonNumber) + .filter((season, index, arr) => arr.indexOf(season) === index) // Supprimer les doublons + .sort((a, b) => a - b); + + const seasonText = availableSeasons.length > 0 + ? `Saisons disponibles pour "${tmdbDetails.title}": ${availableSeasons.join(', ')}` + : `Aucune saison trouvée pour "${tmdbDetails.title}"`; + + + // Créer un résultat d'erreur pour le cache + const errorResult = { + success: false, + error: 'Erreur lors de la récupération des sources FStream', + message: `Saison ${requestedSeason} non trouvée. ${seasonText}`, + timestamp: new Date().toISOString() + }; + + // Sauvegarder l'erreur en cache + await saveFStreamToCache(cacheKey, errorResult); + return errorResult; + } + + // Récupérer la page du contenu + const contentResponse = await axiosFStreamRequest({ + method: 'get', + url: bestResult.link, + headers: { + 'Cookie': Object.entries(fstreamCookies) + .map(([key, value]) => `${key}=${value}`) + .join('; ') + } + }); + + if (contentResponse.status !== 200) { + return; + } + + // Extraire les lecteurs vidéo (séries) + const players = await extractFStreamPlayers(contentResponse.data, true); + + if (players.total === 0) { + return; + } + + // Valider la date de sortie + let isAvailable = true; + if (tmdbDetails.release_date) { + const tmdbYear = tmdbDetails.release_date.split('-')[0]; + + if (players.fstreamReleaseDate) { + const fstreamYear = players.fstreamReleaseDate; + if (fstreamYear !== tmdbYear) { + isAvailable = false; + } else { + } + } else { + // Si aucune date n'est trouvée sur FStream, marquer comme non disponible par sécurité + isAvailable = false; + } + } + + // Formater la réponse + const response = { + success: isAvailable, + source: 'FStream', + type: 'tv', + tmdb: tmdbDetails, + search: { + query: searchQuery, + results: filteredResults.length, + bestMatch: bestResult + }, + episodes: isAvailable ? players.episodes : {}, + total: isAvailable ? players.total : 0, + metadata: { + season: parseInt(season), + episode: episode ? parseInt(episode) : null, + extractedAt: new Date().toISOString(), + backgroundUpdate: true, + fstreamReleaseDate: players.fstreamReleaseDate, + dateValidation: { + fstreamYear: players.fstreamReleaseDate, + tmdbYear: tmdbDetails.release_date?.split('-')[0], + isAvailable: isAvailable + } + } + }; + + // Sauvegarder en cache + await saveFStreamToCache(cacheKey, response); + return response; + }); + } catch (error) { + } + }); + + return; + } + + // Pas de cache, faire la requête avec déduplication + const result = await getOrCreateFStreamRequest(cacheKey, async () => { + // Récupérer les détails TMDB + const tmdbDetails = await getFStreamTMDBDetails(id, 'tv'); + if (!tmdbDetails) { + throw new Error('Contenu TMDB non trouvé'); + } + + let searchQuery; + if (id === '259909') { + searchQuery = 'Dexter : Résurrection - Saison 1'; + } else { + searchQuery = `${tmdbDetails.title} - Saison ${season}`; + } + + // Rechercher sur FStream (sans proxy) + let searchResults = await searchFStreamDirect(searchQuery); + + // Filtrer les résultats + let filteredResults = filterFStreamResults(searchResults, tmdbDetails.title, tmdbDetails.release_date?.split('-')[0]); + + // Si aucun résultat, essayer avec l'année + if (filteredResults.length === 0) { + // Dernier recours précoce : requête directe des saisons via l'endpoint ajax + const directSeasonsEarly = await fetchFStreamSeasonSearchResults(id, tmdbDetails.title); + if (directSeasonsEarly.length > 0) { + filteredResults = directSeasonsEarly; + console.log(`[FSTREAM TV] ✅ Requête directe des saisons réussie (ajax - précoce)`); + } + + // Essayer une recherche de fallback avec l'année + if (tmdbDetails.release_date) { + const year = tmdbDetails.release_date.split('-')[0]; + const fallbackQuery = `${tmdbDetails.title} (${year}) - Saison ${season}`; + + try { + let fallbackSearchResults = await searchFStreamDirect(fallbackQuery); + + let fallbackFilteredResults = filterFStreamResults(fallbackSearchResults, tmdbDetails.title, year); + + if (fallbackFilteredResults.length > 0) { + filteredResults = fallbackFilteredResults; + } + } catch (fallbackError) { + console.log(`[FSTREAM TV] ⚠️ Erreur lors de la recherche de fallback avec année: ${fallbackError.message}`); + } + } + + // Si toujours aucun résultat, essayer avec le nom sans paramètre de langue + if (filteredResults.length === 0 && tmdbDetails.name_no_lang && tmdbDetails.name_no_lang !== tmdbDetails.title) { + const noLangFallbackQuery = `${tmdbDetails.name_no_lang} - Saison ${season}`; + + try { + let noLangSearchResults = await searchFStreamDirect(noLangFallbackQuery); + + let noLangFilteredResults = filterFStreamResults(noLangSearchResults, tmdbDetails.name_no_lang, tmdbDetails.release_date?.split('-')[0]); + + if (noLangFilteredResults.length > 0) { + filteredResults = noLangFilteredResults; + console.log(`[FSTREAM TV] ✅ Fallback avec nom sans langue réussi: "${noLangFallbackQuery}"`); + } + } catch (noLangFallbackError) { + console.log(`[FSTREAM TV] ⚠️ Erreur lors de la recherche de fallback avec nom sans langue: ${noLangFallbackError.message}`); + } + } + + // Si toujours aucun résultat après tous les fallbacks + if (filteredResults.length === 0) { + // Dernier recours : requête directe des saisons via l'endpoint ajax (seconde tentative) + const directSeasons = await fetchFStreamSeasonSearchResults(id, tmdbDetails.title); + if (directSeasons.length > 0) { + filteredResults = directSeasons; + console.log(`[FSTREAM TV] ✅ Requête directe des saisons réussie (ajax)`); + } + } + + if (filteredResults.length === 0) { + throw new Error('Aucun résultat trouvé sur FStream'); + } + } + + // Filtrer par saison demandée + const requestedSeason = parseInt(season); + + // Chercher une correspondance exacte de saison + const seasonMatch = filteredResults.find(result => { + if (result.seasonNumber) { + return result.seasonNumber === requestedSeason; + } + return false; + }); + + // Si aucune correspondance exacte, chercher dans le titre original + let bestResult = seasonMatch; + if (!bestResult) { + const titleSeasonMatch = filteredResults.find(result => { + if (result.originalTitle) { + const seasonInTitle = result.originalTitle.match(/Saison\s+(\d+)/i); + if (seasonInTitle) { + return parseInt(seasonInTitle[1]) === requestedSeason; + } + } + return false; + }); + bestResult = titleSeasonMatch; + } + + // Si toujours aucune correspondance, retourner une erreur plutôt que le premier résultat + if (!bestResult) { + // Filtrer seulement les saisons de la série demandée + const availableSeasons = filteredResults + .filter(r => r.seasonNumber && r.title.toLowerCase().includes(tmdbDetails.title.toLowerCase().split(/[:\-]/)[0].trim().toLowerCase())) + .map(r => r.seasonNumber) + .filter((season, index, arr) => arr.indexOf(season) === index) // Supprimer les doublons + .sort((a, b) => a - b); + + const seasonText = availableSeasons.length > 0 + ? `Saisons disponibles pour "${tmdbDetails.title}": ${availableSeasons.join(', ')}` + : `Aucune saison trouvée pour "${tmdbDetails.title}"`; + + throw new Error(`Saison ${requestedSeason} non trouvée. ${seasonText}`); + } + + // Get content page + const contentResponse = await axiosFStreamRequest({ + method: 'get', + url: bestResult.link + }); + + if (contentResponse.status !== 200) { + throw new Error(`Erreur HTTP: ${contentResponse.status}`); + } + + // Extraire les lecteurs vidéo (séries) + const players = await extractFStreamPlayers(contentResponse.data, true); + + if (players.total === 0) { + throw new Error('Aucun lecteur vidéo trouvé'); + } + + // Valider la date de sortie + let isAvailable = true; + if (tmdbDetails.release_date) { + const tmdbYear = tmdbDetails.release_date.split('-')[0]; + + if (players.fstreamReleaseDate) { + const fstreamYear = players.fstreamReleaseDate; + if (fstreamYear !== tmdbYear) { + isAvailable = false; + } else { + } + } else { + // Si aucune date n'est trouvée sur FStream, marquer comme non disponible par sécurité + isAvailable = false; + } + } + + // Formater la réponse + return { + success: isAvailable, + source: 'FStream', + type: 'tv', + tmdb: tmdbDetails, + search: { + query: searchQuery, + results: filteredResults.length, + bestMatch: bestResult + }, + episodes: isAvailable ? players.episodes : {}, + total: isAvailable ? players.total : 0, + metadata: { + season: parseInt(season), + episode: episode ? parseInt(episode) : null, + extractedAt: new Date().toISOString(), + fstreamReleaseDate: players.fstreamReleaseDate, + dateValidation: { + fstreamYear: players.fstreamReleaseDate, + tmdbYear: tmdbDetails.release_date?.split('-')[0], + isAvailable: isAvailable + } + } + }; + }); + + // Sauvegarder en cache seulement si pas d'erreur + await saveFStreamToCache(cacheKey, result); + + res.status(200).json(result); + + } catch (error) { + console.error(`[FSTREAM TV] Erreur: ${error.message}`); + + // Ne pas mettre à jour le cache en cas d'erreur + // Créer un résultat d'erreur pour le cache + const errorResult = { + success: false, + error: 'Erreur lors de la récupération des sources FStream', + message: error.message, + timestamp: new Date().toISOString() + }; + + // Sauvegarder l'erreur en cache (non-résultat) + await saveFStreamToCache(cacheKey, errorResult); + + res.status(500).json(errorResult); + } +}); + +// Route pour supprimer tout le cache Coflix d'une série entière (toutes saisons/épisodes) +app.get('/api/tmdb/cache/series/:id', async (req, res) => { + const { id } = req.params; + const cacheDir = CACHE_DIR.COFLIX; + + try { + await fsp.mkdir(cacheDir, { recursive: true }); + const files = await fsp.readdir(cacheDir); + + let removed = 0; + const removedFiles = []; + + for (const file of files) { + if (!file.endsWith('.json')) continue; + const fullPath = path.join(cacheDir, file); + + try { + const content = await fsp.readFile(fullPath, 'utf-8'); + const data = JSON.parse(content); + + // Vérifier si c'est un cache pour cette série TMDB + const isSameId = data && String(data.tmdb_id) === String(id); + const isTvSeries = data && data.tmdb_details && (typeof data.tmdb_details.title === 'string' || typeof data.tmdb_details.original_title === 'string'); + + if (isSameId && isTvSeries) { + await fsp.unlink(fullPath); + removed++; + removedFiles.push(file); + } + } catch (parseError) { + // Ignorer les fichiers corrompus + continue; + } + } + + console.log(`Cache Coflix supprimé pour la série TMDB ${id}: ${removed} fichiers`); + res.json({ + message: `Cache Coflix supprimé pour la série TMDB ${id}`, + removed_files: removed, + files: removedFiles + }); + + } catch (error) { + console.error(`Erreur lors de la suppression du cache Coflix pour la série ${id}: ${error.message}`); + res.status(500).json({ + error: 'Erreur lors de la suppression du cache Coflix', + message: error.message + }); + } +}); + +// Route pour supprimer le cache Coflix d'un contenu TMDB spécifique +// Exemples : +// DELETE /api/tmdb/cache/movie/136797 → supprime le cache du film +// DELETE /api/tmdb/cache/tv/12345?season=1&episode=3 → supprime un épisode précis +// DELETE /api/tmdb/cache/tv/12345 → supprime TOUS les épisodes de la série +app.delete('/api/tmdb/cache/:type/:id', async (req, res) => { + const { id, type } = req.params; + const { season, episode } = req.query; + + try { + let removedFiles = 0; + let removedRedisKeys = 0; + + // Si c'est une série sans season/episode, supprimer tous les fichiers de cache liés + if (type === 'tv' && !season && !episode) { + // Parcourir le dossier de cache pour trouver tous les fichiers liés à cet ID + const files = await fsp.readdir(CACHE_DIR.COFLIX); + for (const file of files) { + if (!file.endsWith('.json')) continue; + const fullPath = path.join(CACHE_DIR.COFLIX, file); + try { + const content = await fsp.readFile(fullPath, 'utf-8'); + const data = JSON.parse(content); + if (data && String(data.tmdb_id) === String(id)) { + await fsp.unlink(fullPath); + removedFiles++; + // Supprimer aussi le cache Redis (L1) correspondant + const memKey = `${CACHE_DIR.COFLIX}:${file.replace('.json', '')}`; + try { await redis.del(memKey); removedRedisKeys++; } catch {} + } + } catch { continue; } + } + } else { + // Suppression d'un cache spécifique (film ou épisode précis) + const cacheKey = generateCacheKey(`tmdb_links_${type}_${id}_${season || ''}_${episode || ''}`); + const cacheFile = path.join(CACHE_DIR.COFLIX, `${cacheKey}.json`); + const memKey = `${CACHE_DIR.COFLIX}:${cacheKey}`; + + // Supprimer le cache fichier (L2) + try { + await fsp.unlink(cacheFile); + removedFiles++; + } catch (e) { + if (e.code !== 'ENOENT') throw e; + } + + // Supprimer le cache Redis (L1) + try { await redis.del(memKey); removedRedisKeys++; } catch {} + } + + console.log(`Cache supprimé pour TMDB ${type} ${id} (${removedFiles} fichier(s), ${removedRedisKeys} clé(s) Redis)`); + res.json({ + message: `Cache supprimé pour TMDB ${type} ${id}`, + removed_files: removedFiles, + removed_redis_keys: removedRedisKeys + }); + } catch (error) { + console.error(`Erreur lors de la suppression du cache: ${error.message}`); + res.status(500).json({ error: 'Erreur lors de la suppression du cache' }); + } +}); + +// Supprimer tout le cache SenpaiStream d'une série (toutes saisons/épisodes) +app.get('/api/SenpaiStream/tv/cache/:tmdbId', async (req, res) => { + const { tmdbId } = req.params; + const cacheDir = path.join(__dirname, 'cache', 'SenpaiStream'); + + try { + await fsp.mkdir(cacheDir, { recursive: true }); + const files = await fsp.readdir(cacheDir); + + let removed = 0; + for (const file of files) { + if (!file.endsWith('.json')) continue; + const fullPath = path.join(cacheDir, file); + try { + const content = await fsp.readFile(fullPath, 'utf-8'); + const data = JSON.parse(content); + // Cible les caches TV pour cette série: + // - cas normal: season & episode présents + // - cas not-found: pas de season/episode mais tmdb_details contient name/original_name (spécifique TV) + const isSameId = data && String(data.tmdb_id) === String(tmdbId); + const isTvByFields = data && data.tmdb_details && (typeof data.tmdb_details.name === 'string' || typeof data.tmdb_details.original_name === 'string'); + const hasEpisodeFields = typeof data?.season !== 'undefined' && typeof data?.episode !== 'undefined'; + if (isSameId && (hasEpisodeFields || isTvByFields)) { + await fsp.unlink(fullPath); + removed++; + } + } catch (err) { + // Ignorer fichiers illisibles/corrompus + continue; + } + } + + return res.json({ + success: true, + tmdb_id: tmdbId, + removed, + cache_dir: cacheDir, + timestamp: new Date().toISOString() + }); + } catch (error) { + console.error(`[SenpaiStream TV CACHE CLEAR] Erreur: ${error.message}`); + return res.status(500).json({ + success: false, + error: 'Erreur lors de la suppression du cache SenpaiStream TV', + message: error.message, + tmdb_id: tmdbId, + timestamp: new Date().toISOString() + }); + } +}); + +// ==================== WIFLIX ROUTES ==================== + +// Fonctions utilitaires pour Wiflix +const normalizeString = (str) => { + if (!str) return ''; + return str + .toLowerCase() + .normalize('NFD') + .replace(/[\u0300-\u036f]/g, '') // Supprimer les accents + .replace(/[^\w\s]/g, ' ') // Remplacer la ponctuation par des espaces + .replace(/\s+/g, ' ') // Normaliser les espaces + .trim(); +}; + +const getLevenshteinSimilarity = (str1, str2) => { + const s1 = normalizeString(str1); + const s2 = normalizeString(str2); + + if (s1 === s2) return 1; + if (s1.length === 0 || s2.length === 0) return 0; + + const matrix = []; + for (let i = 0; i <= s2.length; i++) { + matrix[i] = [i]; + } + for (let j = 0; j <= s1.length; j++) { + matrix[0][j] = j; + } + + for (let i = 1; i <= s2.length; i++) { + for (let j = 1; j <= s1.length; j++) { + if (s2.charAt(i - 1) === s1.charAt(j - 1)) { + matrix[i][j] = matrix[i - 1][j - 1]; + } else { + matrix[i][j] = Math.min( + matrix[i - 1][j - 1] + 1, + matrix[i][j - 1] + 1, + matrix[i - 1][j] + 1 + ); + } + } + } + + const maxLength = Math.max(s1.length, s2.length); + return maxLength === 0 ? 1 : (maxLength - matrix[s2.length][s1.length]) / maxLength; +}; + +// Fonction pour rechercher un film sur Wiflix +async function searchWiflixMovie(title, baseUrl = 'https://flemmix.irish') { + // Endpoint AJAX de recherche + const searchUrl = `${baseUrl}/engine/ajax/search.php`; + try { + const response = await axiosWiflixRequest({ + url: searchUrl, + method: 'POST', + data: new URLSearchParams({ + query: title + }), + headers: { + 'accept-language': 'fr-FR,fr;q=0.5', + 'cache-control': 'no-cache', + 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', + 'origin': 'https://flemmix.irish', + 'pragma': 'no-cache', + 'priority': 'u=1, i', + 'referer': 'https://flemmix.irish/', + 'sec-ch-ua': '"Chromium";v="142", "Brave";v="142", "Not_A Brand";v="99"', + 'sec-ch-ua-arch': '"x86"', + 'sec-ch-ua-bitness': '"64"', + 'sec-ch-ua-full-version-list': '"Chromium";v="142.0.0.0", "Brave";v="142.0.0.0", "Not_A Brand";v="99.0.0.0"', + 'sec-ch-ua-mobile': '?0', + 'sec-ch-ua-model': '""', + 'sec-ch-ua-platform': '"Windows"', + 'sec-ch-ua-platform-version': '"19.0.0"', + 'sec-fetch-dest': 'empty', + 'sec-fetch-mode': 'cors', + 'sec-fetch-site': 'same-origin', + 'sec-gpc': '1', + 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36', + 'x-requested-with': 'XMLHttpRequest' + } + }); + + + const $ = cheerio.load(response.data); + + // La réponse AJAX contient directement des éléments <a> avec les résultats + // Format: <a href="url"><span class="searchheading">Titre</span><span></span></a> + const searchResults = $('a'); + + if (searchResults.length === 0) { + return null; + } + + let bestMatch = null; + let bestSimilarity = 0; + + searchResults.each((index, element) => { + const $result = $(element); + const href = $result.attr('href'); + + // Ignorer les liens de "Recherche Avancée" et autres liens internes + if (!href || href.includes('do=search') || href.includes('mode=advanced')) { + return; + } + + // Le titre est dans le span.searchheading + const $titleSpan = $result.find('span.searchheading'); + if (!$titleSpan.length) return; + + const resultTitle = $titleSpan.text().trim(); + const resultTitleLower = resultTitle.toLowerCase(); + + // Déterminer si c'est une série ou un film en regardant l'URL et le titre + const isSeries = href.includes('/serie-') || resultTitleLower.includes('saison'); + const searchIsSeries = title.toLowerCase().includes('saison'); + + // Filtrer les films si on cherche une série et vice-versa + if (searchIsSeries && !isSeries) { + return; + } + if (!searchIsSeries && isSeries) { + return; + } + + // Pour les séries, vérifier la correspondance de saison + if (searchIsSeries) { + const searchSeasonMatch = title.match(/saison\s+(\d+)/i); + if (searchSeasonMatch) { + const searchSeason = parseInt(searchSeasonMatch[1]); + const resultSeasonMatch = resultTitle.match(/saison\s+(\d+)/i); + + if (resultSeasonMatch) { + const resultSeason = parseInt(resultSeasonMatch[1]); + if (searchSeason !== resultSeason) { + return; // Mauvaise saison + } + } else { + return; // On cherche une saison mais le résultat n'en a pas + } + } + } + + // Calculer la similarité en utilisant le titre nettoyé (sans "saison X") + const cleanSearchTitle = title.toLowerCase().replace(/\s+saison\s+\d+/g, '').trim(); + const cleanResultTitle = resultTitle.toLowerCase().replace(/\s+saison\s+\d+/g, '').trim(); + + let similarity = 0; + if (cleanResultTitle === cleanSearchTitle) { + similarity = 1.0; + } else if (typeof getLevenshteinSimilarity === 'function') { + similarity = getLevenshteinSimilarity(cleanResultTitle, cleanSearchTitle); + } else { + // Fallback simple + similarity = cleanResultTitle.includes(cleanSearchTitle) || cleanSearchTitle.includes(cleanResultTitle) ? 0.9 : 0; + } + + // Construire l'URL complète si nécessaire + let fullUrl = href; + if (fullUrl && !fullUrl.startsWith('http')) { + fullUrl = fullUrl.startsWith('/') ? `${baseUrl}${fullUrl}` : `${baseUrl}/${fullUrl}`; + } + + if (similarity >= 0.85 && similarity > bestSimilarity) { + bestSimilarity = similarity; + bestMatch = fullUrl ? encodeURI(fullUrl) : fullUrl; + } + }); + + return bestMatch; + } catch (error) { + const urlUsed = error.wiflixUrl || searchUrl; + const proxyUsed = error.wiflixProxy || (ENABLE_WIFLIX_PROXY ? 'Aucun proxy (désactivé)' : 'Direct (sans proxy)'); + const proxiedUrl = error.wiflixProxiedUrl || urlUsed; + + return null; + } +} + +// Fonction pour extraire la date de sortie depuis une page Wiflix +function extractWiflixReleaseDate($) { + try { + // Pour les films et séries, chercher dans /html/body/div[1]/div/div/div/div/div/article/div[1]/div[2]/ul/li[2]/div[2] + // Équivalent CSS: body > div:first-child > div > div > div > div > div > article > div:first-child > div:nth-child(2) > ul > li:nth-child(2) > div:nth-child(2) + const releaseDateElement = $('body > div:first-child > div > div > div > div > div > article > div:first-child > div:nth-child(2) > ul > li:nth-child(2) > div:nth-child(2)'); + + if (releaseDateElement.length > 0) { + const dateText = releaseDateElement.text().trim(); + // Extraire l'année (4 chiffres consécutifs) + const yearMatch = dateText.match(/(\d{4})/); + if (yearMatch) { + return parseInt(yearMatch[1]); + } + } + + // Fallback: chercher d'autres sélecteurs possibles pour la date + const fallbackSelectors = [ + 'div.mov-desc', + '.mov-desc', + 'li:contains("Année") + li', + 'li:contains("Date") + li' + ]; + + for (const selector of fallbackSelectors) { + const element = $(selector); + if (element.length > 0) { + const text = element.text().trim(); + const yearMatch = text.match(/(\d{4})/); + if (yearMatch) { + return parseInt(yearMatch[1]); + } + } + } + + return null; + } catch (error) { + console.error('[WIFLIX] Erreur lors de l\'extraction de la date:', error); + return null; + } +} + +// Fonction pour extraire les lecteurs vidéo d'une page Wiflix +async function extractWiflixPlayers(pageUrl) { + try { + const response = await axiosWiflixRequest({ + url: pageUrl, + method: 'GET' + }); + + const $ = cheerio.load(response.data); + const players = []; + + // Extraire la date de sortie + const releaseYear = extractWiflixReleaseDate($); + + + // Vérifier si c'est une série (avec divs d'épisodes) ou un film + const episodeDivs = $('div[class*="ep"][class*="vf"], div[class*="ep"][class*="vs"]'); + + if (episodeDivs.length > 0) { + // C'est une série - traiter les divs d'épisodes + episodeDivs.each((index, element) => { + const $episodeDiv = $(element); + const episodeClass = $episodeDiv.attr('class'); + + // Extraire le numéro d'épisode et le type (vf/vs) + const episodeMatch = episodeClass.match(/ep(\d+)(vf|vs)/); + if (episodeMatch) { + const episodeNumber = parseInt(episodeMatch[1]); + const type = episodeMatch[2] === 'vf' ? 'VF' : 'VOSTFR'; + + // Chercher les liens dans ce div d'épisode + $episodeDiv.find('a[onclick]').each((linkIndex, linkElement) => { + const $link = $(linkElement); + const onclick = $link.attr('onclick'); + const $span = $link.find('span.clichost'); + + if (onclick && $span.length) { + const match = onclick.match(/loadVideo\('(.+?)'\)/); + if (match && match[1]) { + const url = match[1]; + const name = $span.text().trim(); + + // Traitement spécial pour certains lecteurs + let processedUrl = url; + if (url.includes('tipfly.xyz')) { + // Extraire l'ID depuis l'URL tipfly et le convertir en oneupload + const tipflyMatch = url.match(/tipfly\.xyz\/em-?\d+-(.+)/); + if (tipflyMatch && tipflyMatch[1]) { + processedUrl = `https://oneupload.net/embed-${tipflyMatch[1]}.html`; + } + } else if (name.toLowerCase() === 'voe' || url.includes('jilliandescribecompany.com')) { + processedUrl = url.replace(/^https?:\/\/[^/]+/, 'https://voe.sx'); + } + + // Extraire le nom du domaine pour le nom du lecteur + const domainMatch = processedUrl.match(/https?:\/\/(?:www\.)?([^\/]+)/); + const domainName = domainMatch ? domainMatch[1] : name; + + players.push({ + name: domainName, + url: processedUrl, + episode: episodeNumber, + type: type + }); + + } + } + }); + } + }); + } else { + // C'est un film - chercher directement dans les liens tabs-sel + const filmLinks = $('.tabs-sel a[onclick]'); + + filmLinks.each((index, element) => { + const $link = $(element); + const onclick = $link.attr('onclick'); + const $span = $link.find('span'); + + if (onclick && $span.length) { + const match = onclick.match(/loadVideo\('(.+?)'\)/); + if (match && match[1]) { + const url = match[1]; + const name = $span.text().trim(); + + // Déterminer le type (VF ou VOSTFR) basé sur le nom + let type = 'VF'; + if (name.toLowerCase().includes('vostfr')) { + type = 'VOSTFR'; + } + + // Traitement spécial pour certains lecteurs + let processedUrl = url; + if (url.includes('tipfly.xyz')) { + // Extraire l'ID depuis l'URL tipfly et le convertir en oneupload + const tipflyMatch = url.match(/tipfly\.xyz\/em-?\d+-(.+)/); + if (tipflyMatch && tipflyMatch[1]) { + processedUrl = `https://oneupload.net/embed-${tipflyMatch[1]}.html`; + } + } else if (name.toLowerCase() === 'voe' || url.includes('jilliandescribecompany.com')) { + processedUrl = url.replace(/^https?:\/\/[^/]+/, 'https://voe.sx'); + } + + // Extraire le nom du domaine pour le nom du lecteur + const domainMatch = processedUrl.match(/https?:\/\/(?:www\.)?([^\/]+)/); + const domainName = domainMatch ? domainMatch[1] : name; + + players.push({ + name: domainName, + url: processedUrl, + episode: 1, // Films n'ont qu'un seul "épisode" + type: type + }); + + } + } + }); + } + + return { + players: players, + releaseYear: releaseYear + }; + } catch (error) { + return { + players: [], + releaseYear: null + }; + } +} + +// Fonction pour classer les lecteurs par langue +function categorizeWiflixPlayers(players) { + const vf = []; + const vostfr = []; + + players.forEach(player => { + if (player.type === 'VOSTFR') { + vostfr.push(player); + } else { + vf.push(player); + } + }); + + return { vf, vostfr }; +} +// Fonction pour faire des requêtes vers Wiflix +async function axiosWiflixRequest(config) { + const urlStr = config.url || ''; + const isWiflix = urlStr.includes('https://flemmix.irish') || urlStr.includes('flemmix') || + (config.baseURL && (config.baseURL.includes('https://flemmix.irish') || config.baseURL.includes('flemmix'))); + + + if (!ENABLE_WIFLIX_PROXY || !isWiflix) { + const defaultConfig = { + timeout: 15000, + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', + 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', + 'Accept-Language': 'fr-FR,fr;q=0.9,en;q=0.8', + 'Accept-Encoding': 'gzip, deflate, br', + 'DNT': '1', + 'Connection': 'keep-alive', + 'Upgrade-Insecure-Requests': '1' + } + }; + + const finalConfig = { ...defaultConfig, ...config }; + + try { + const response = await axios(finalConfig); + return response; + } catch (error) { + // Ajouter des informations sur l'URL utilisée à l'erreur + error.wiflixUrl = config.url || urlStr; + error.wiflixProxy = 'Direct (sans proxy)'; + error.wiflixProxiedUrl = config.url || urlStr; + console.error(`[WIFLIX REQUEST] Erreur: ${error.message}`); + throw error; + } + } + + // Construire l'URL complète + let absoluteUrl = urlStr; + if (config.baseURL && !urlStr.startsWith('http')) { + absoluteUrl = config.baseURL + urlStr; + } else if (!urlStr.startsWith('http')) { + absoluteUrl = 'https://flemmix.irish' + (urlStr.startsWith('/') ? urlStr : '/' + urlStr); + } + + // Filtrer les proxies disponibles (non en cooldown) + const availableProxies = getAvailableProxies(CLOUDFLARE_WORKERS_PROXIES); + + const defaultHeaders = { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', + 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', + 'Accept-Language': 'fr-FR,fr;q=0.9,en;q=0.8', + 'Accept-Encoding': 'gzip, deflate, br', + 'DNT': '1', + 'Connection': 'keep-alive', + 'Upgrade-Insecure-Requests': '1', + ...(config.headers || {}) + }; + + let lastError = null; + + // Essayer avec les proxies Cloudflare disponibles + for (let i = 0; i < availableProxies.length; i++) { + const cloudflareProxy = availableProxies[i]; + const proxiedUrl = buildProxiedUrl(cloudflareProxy, absoluteUrl); + + try { + // Extraire url et headers de config pour éviter les conflits + const { url: _, headers: __, ...restConfig } = config; + const response = await axios({ + url: proxiedUrl, + method: restConfig.method || 'GET', + headers: defaultHeaders, + timeout: restConfig.timeout || 15000, + decompress: true, + responseType: restConfig.responseType || 'text', + ...restConfig + }); + + // Succès : marquer le proxy comme sain + markProxyAsHealthy(cloudflareProxy); + return response; + } catch (error) { + const statusCode = error.response?.status; + const errorCode = statusCode || error.code || 'unknown'; + + // Ajouter des informations sur l'URL et le proxy utilisé à l'erreur + error.wiflixUrl = absoluteUrl; + error.wiflixProxy = cloudflareProxy; + error.wiflixProxiedUrl = proxiedUrl; + lastError = error; + + // En cas d'erreur 429 (Too Many Requests), marquer le proxy et essayer le suivant + if (statusCode === 429) { + markProxyAsErrored(cloudflareProxy, 429); + continue; + } + + // En cas d'erreur 5xx, marquer le proxy et essayer le suivant + if (statusCode >= 500 && statusCode < 600) { + markProxyAsErrored(cloudflareProxy, statusCode); + continue; + } + + // En cas de timeout, marquer le proxy et essayer le suivant + if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') { + markProxyAsErrored(cloudflareProxy, errorCode); + continue; + } + + // Pour les autres erreurs, throw immédiatement sans essayer d'autres proxies + throw error; + } + } + + // Si on arrive ici, tous les proxies ont échoué + if (lastError) throw lastError; + throw new Error('Erreur inconnue lors de la requête Wiflix'); +} + +// Fonction pour récupérer les données d'un film Wiflix +async function fetchWiflixMovieData(tmdbId, cachedData = null) { + try { + // Récupérer les détails TMDB + const frenchDetails = await axios.get(`${TMDB_API_URL}/movie/${tmdbId}`, { + params: { + api_key: TMDB_API_KEY, + language: 'fr-FR' + } + }); + + const originalDetails = await axios.get(`${TMDB_API_URL}/movie/${tmdbId}`, { + params: { + api_key: TMDB_API_KEY, + language: 'fr-FR' + } + }); + + if (!frenchDetails.data || !originalDetails.data) { + // Si on avait un cache, le retourner au lieu de l'erreur + if (cachedData) { + console.log(`[WIFLIX] Cache préservé malgré l'erreur TMDB pour movie ${tmdbId}`); + return cachedData; + } + return { + success: false, + error: 'Film non trouvé sur TMDB', + tmdb_id: tmdbId + }; + } + + const tmdbData = frenchDetails.data; + const originalData = originalDetails.data; + + // Titres à essayer dans l'ordre + const titlesToTry = [ + tmdbData.title, // Titre français + originalData.original_title, // Titre original + originalData.title // Titre international + ].filter(Boolean).filter((title, index, arr) => arr.indexOf(title) === index); + + let movieUrl = null; + + // Essayer chaque titre + for (const title of titlesToTry) { + movieUrl = await searchWiflixMovie(title); + if (movieUrl) { + break; + } + } + + if (!movieUrl) { + return { + success: false, + error: 'Film non trouvé sur Wiflix', + tmdb_id: tmdbId, + titles_tried: titlesToTry + }; + } + + // Extraire les lecteurs vidéo et la date de sortie + const extractionResult = await extractWiflixPlayers(movieUrl); + const players = extractionResult.players; + const wiflixReleaseYear = extractionResult.releaseYear; + + if (players.length === 0) { + return { + success: false, + error: 'Aucun lecteur vidéo trouvé', + tmdb_id: tmdbId, + wiflix_url: movieUrl + }; + } + + // Vérifier la correspondance des dates de sortie + if (wiflixReleaseYear) { + const tmdbReleaseYear = tmdbData.release_date ? new Date(tmdbData.release_date).getFullYear() : null; + + if (tmdbReleaseYear && wiflixReleaseYear !== tmdbReleaseYear) { + console.log(`[WIFLIX MOVIE] Date mismatch: TMDB ${tmdbReleaseYear} vs Wiflix ${wiflixReleaseYear} pour ${tmdbData.title}`); + return { + success: false, + error: 'Film non disponible sur Wiflix (date de sortie différente)', + tmdb_id: tmdbId, + wiflix_url: movieUrl, + tmdb_release_year: tmdbReleaseYear, + wiflix_release_year: wiflixReleaseYear + }; + } + } + + // Classer les lecteurs par langue + const categorizedPlayers = categorizeWiflixPlayers(players); + + return { + success: true, + tmdb_id: tmdbId, + title: tmdbData.title, + original_title: originalData.original_title, + wiflix_url: movieUrl, + players: { + vf: categorizedPlayers.vf, + vostfr: categorizedPlayers.vostfr + }, + cache_timestamp: new Date().toISOString() + }; + } catch (error) { + console.error(`[WIFLIX MOVIE] Erreur dans fetchWiflixMovieData: ${error.message}`); + // Si on avait un cache, le retourner au lieu de l'erreur + if (cachedData) { + console.log(`[WIFLIX] Cache préservé malgré l'erreur pour movie ${tmdbId}`); + return cachedData; + } + // Sinon retourner une erreur + return { + success: false, + error: 'Erreur lors de la récupération des données Wiflix', + message: error.message, + tmdb_id: tmdbId + }; + } +} + +// Route pour les films Wiflix +app.get('/api/wiflix/movie/:tmdbId', async (req, res) => { + const { tmdbId } = req.params; + const cacheKey = generateCacheKey(`wiflix_movie_${tmdbId}`); + const cacheDir = path.join(__dirname, 'cache', 'wiflix'); + + try { + // Créer le dossier de cache s'il n'existe pas + await fsp.mkdir(cacheDir, { recursive: true }); + + // Check if results are in cache without expiration (stale-while-revalidate) + const cachedData = await getFromCacheNoExpiration(cacheDir, cacheKey); + let dataReturned = false; + + if (cachedData) { + // console.log(`Film Wiflix pour TMDB ID "${tmdbId}" récupéré du cache`); + res.status(200).json(cachedData); // Return cached data immediately + dataReturned = true; + + // Vérifier si le cache a été mis à jour récemment (moins de 12 heures) + const RECENT_UPDATE_THRESHOLD = 12 * 60 * 60 * 1000; // 12 heures en millisecondes + const cachePath = path.join(cacheDir, `${cacheKey}.json`); + let shouldSkipUpdate = false; + + try { + const stats = await fsp.stat(cachePath); + const timeSinceLastUpdate = Date.now() - stats.mtime.getTime(); + if (timeSinceLastUpdate < RECENT_UPDATE_THRESHOLD) { + shouldSkipUpdate = true; + } + } catch (e) { + // Fichier n'existe pas, continuer normalement + } + + // Update cache in background only if not recently updated + if (!shouldSkipUpdate) { + updateWiflixCache(cacheDir, cacheKey, 'movie', tmdbId); + } + } + + // Si pas de données en cache, faire la requête normale + if (!dataReturned) { + const result = await fetchWiflixMovieData(tmdbId, null); + + // Sauvegarder en cache seulement si le résultat est valide + // Ne pas mettre à jour le cache avec des erreurs + if (result.success) { + await saveToCache(cacheDir, cacheKey, result); + } else { + // Si échec et pas de cache, sauvegarder quand même pour éviter de refaire la requête + await saveToCache(cacheDir, cacheKey, result); + } + + if (!result.success) { + return res.status(404).json(result); + } + + res.json(result); + } + + } catch (error) { + console.error(`[WIFLIX MOVIE] Erreur: ${error.message}`); + res.status(500).json({ + success: false, + error: 'Erreur lors de la récupération des données Wiflix', + message: error.message, + tmdb_id: tmdbId + }); + } +}); + +// Fonction pour récupérer les données Wiflix d'une série TV +async function fetchWiflixTvData(tmdbId, season, cachedData = null) { + try { + // Récupérer les détails TMDB de la série + const frenchDetails = await axios.get(`${TMDB_API_URL}/tv/${tmdbId}`, { + params: { + api_key: TMDB_API_KEY, + language: 'fr-FR' + } + }); + + const originalDetails = await axios.get(`${TMDB_API_URL}/tv/${tmdbId}`, { + params: { + api_key: TMDB_API_KEY, + language: 'fr-FR' + } + }); + + // Récupérer les détails de la saison spécifique + const seasonDetails = await axios.get(`${TMDB_API_URL}/tv/${tmdbId}/season/${season}`, { + params: { + api_key: TMDB_API_KEY, + language: 'fr-FR' + } + }); + + if (!frenchDetails.data || !originalDetails.data || !seasonDetails.data) { + // Si on avait un cache, le retourner au lieu de l'erreur + if (cachedData) { + console.log(`[WIFLIX] Cache préservé malgré l'erreur TMDB pour tv ${tmdbId} saison ${season}`); + return cachedData; + } + return { + success: false, + error: 'Série ou saison non trouvée sur TMDB', + tmdb_id: tmdbId, + season: season + }; + } + + const tmdbData = frenchDetails.data; + const originalData = originalDetails.data; + const seasonData = seasonDetails.data; + + // Titres à essayer dans l'ordre + const titlesToTry = [ + tmdbData.name, // Nom français + originalData.original_name, // Nom original + originalData.name // Nom international + ].filter(Boolean).filter((title, index, arr) => arr.indexOf(title) === index); + + let seriesUrl = null; + + // Essayer chaque titre + for (const title of titlesToTry) { + seriesUrl = await searchWiflixMovie(`${title} saison ${season}`); + if (seriesUrl) { + break; + } + } + + if (!seriesUrl) { + return { + success: false, + error: 'Série non trouvée sur Wiflix', + tmdb_id: tmdbId, + season: season, + titles_tried: titlesToTry + }; + } + + // Extraire les lecteurs vidéo et la date de sortie + const extractionResult = await extractWiflixPlayers(seriesUrl); + const players = extractionResult.players; + const wiflixReleaseYear = extractionResult.releaseYear; + + if (players.length === 0) { + return { + success: false, + error: 'Aucun lecteur vidéo trouvé', + tmdb_id: tmdbId, + season: season, + wiflix_url: seriesUrl + }; + } + + // Vérifier la correspondance des dates de sortie avec la saison spécifique + if (wiflixReleaseYear) { + // Utiliser la date de sortie de la saison spécifique au lieu de la série entière + const tmdbReleaseYear = seasonData.air_date ? new Date(seasonData.air_date).getFullYear() : null; + + if (tmdbReleaseYear && wiflixReleaseYear !== tmdbReleaseYear) { + console.log(`[WIFLIX TV] Date mismatch: TMDB Season ${season} (${tmdbReleaseYear}) vs Wiflix ${wiflixReleaseYear} pour ${tmdbData.name}`); + return { + success: false, + error: 'Série non disponible sur Wiflix (date de sortie différente)', + tmdb_id: tmdbId, + season: season, + wiflix_url: seriesUrl, + tmdb_release_year: tmdbReleaseYear, + wiflix_release_year: wiflixReleaseYear + }; + } + } + + // Organiser les lecteurs par épisode et par langue + const episodes = {}; + + players.forEach(player => { + const episodeNum = player.episode; + if (!episodes[episodeNum]) { + episodes[episodeNum] = { + vf: [], + vostfr: [] + }; + } + + if (player.type === 'VOSTFR') { + episodes[episodeNum].vostfr.push(player); + } else { + episodes[episodeNum].vf.push(player); + } + }); + + return { + success: true, + tmdb_id: tmdbId, + title: tmdbData.name, + original_title: originalData.original_name, + season: parseInt(season), + wiflix_url: seriesUrl, + episodes: episodes, + cache_timestamp: new Date().toISOString() + }; + + } catch (error) { + console.error(`[WIFLIX TV] Erreur: ${error.message}`); + // Si on avait un cache, le retourner au lieu de l'erreur + if (cachedData) { + console.log(`[WIFLIX] Cache préservé malgré l'erreur pour tv ${tmdbId} saison ${season}`); + return cachedData; + } + return { + success: false, + error: 'Erreur lors de la récupération des données Wiflix', + message: error.message, + tmdb_id: tmdbId, + season: season + }; + } +} + +// Route pour les séries Wiflix +app.get('/api/wiflix/tv/:tmdbId/:season', async (req, res) => { + const { tmdbId, season } = req.params; + const cacheKey = generateCacheKey(`wiflix_tv_${tmdbId}_${season}`); + const cacheDir = path.join(__dirname, 'cache', 'wiflix'); + + try { + // Créer le dossier de cache s'il n'existe pas + await fsp.mkdir(cacheDir, { recursive: true }); + + // Vérifier le cache sans expiration (stale-while-revalidate) + const cachedData = await getFromCacheNoExpiration(cacheDir, cacheKey); + let dataReturned = false; + + if (cachedData) { + // Retourner immédiatement les données en cache + res.json(cachedData); + dataReturned = true; + + // Vérifier si le cache a été mis à jour récemment (moins de 12 heures) + const RECENT_UPDATE_THRESHOLD = 12 * 60 * 60 * 1000; // 12 heures en millisecondes + const cachePath = path.join(cacheDir, `${cacheKey}.json`); + let shouldSkipUpdate = false; + + try { + const stats = await fsp.stat(cachePath); + const timeSinceLastUpdate = Date.now() - stats.mtime.getTime(); + if (timeSinceLastUpdate < RECENT_UPDATE_THRESHOLD) { + shouldSkipUpdate = true; + } + } catch (e) { + // Fichier n'existe pas, continuer normalement + } + + // Lancer la mise à jour en arrière-plan seulement si pas récemment mis à jour + if (!shouldSkipUpdate) { + updateWiflixCache(cacheDir, cacheKey, 'tv', tmdbId, season); + } + } + + // Si pas de données en cache, faire la requête normale + if (!dataReturned) { + const result = await fetchWiflixTvData(tmdbId, season, null); + + // Sauvegarder en cache seulement si le résultat est valide + // Ne pas mettre à jour le cache avec des erreurs + if (result.success) { + await saveToCache(cacheDir, cacheKey, result); + } else { + // Si échec et pas de cache, sauvegarder quand même pour éviter de refaire la requête + await saveToCache(cacheDir, cacheKey, result); + } + + if (!result.success) { + return res.status(404).json(result); + } + + res.json(result); + } + + } catch (error) { + console.error(`[WIFLIX TV] Erreur: ${error.message}`); + res.status(500).json({ + success: false, + error: 'Erreur lors de la récupération des données Wiflix', + message: error.message, + tmdb_id: tmdbId, + season: season + }); + } +}); + + +// ==================================================================== +// === ADMIN ROUTES - GESTION DES LIENS DE STREAMING ET CLÉS VIP === +// ==================================================================== + +// === ROUTES PUBLIQUES (sans authentification) === + +/** + * GET /api/streaming-links/:type/:id + * Récupérer les liens de streaming pour un film ou une série + * Params: type (movie/tv), id (TMDB ID) + * Query: season (optionnel pour les séries), episode (optionnel pour les séries) + */ +app.get('/api/links/:type/:id', async (req, res) => { + try { + const { type, id } = req.params; + const { season, episode } = req.query; + + // Validation + if (!['movie', 'tv'].includes(type)) { + return res.status(400).json({ success: false, error: 'Type invalide. Utilisez "movie" ou "tv"' }); + } + + let query, params; + + if (type === 'movie') { + query = 'SELECT id, links FROM films WHERE id = ?'; + params = [id]; + } else { + // Pour les séries + if (!season || !episode) { + // Retourner tous les épisodes de la série + query = 'SELECT id, series_id, season_number, episode_number, links FROM series WHERE series_id = ? ORDER BY season_number, episode_number'; + params = [id]; + } else { + // Retourner un épisode spécifique + query = 'SELECT id, series_id, season_number, episode_number, links FROM series WHERE series_id = ? AND season_number = ? AND episode_number = ?'; + params = [id, parseInt(season), parseInt(episode)]; + } + } + + const [rows] = await pool.execute(query, params); + + if (rows.length === 0) { + return res.status(404).json({ + success: false, + error: 'Aucun lien trouvé', + type, + id, + ...(season && { season }), + ...(episode && { episode }) + }); + } + + // Parser les liens JSON + const result = rows.map(row => ({ + ...row, + links: typeof row.links === 'string' ? JSON.parse(row.links) : row.links + })); + + res.json({ + success: true, + type, + data: type === 'movie' ? result[0] : result + }); + + } catch (error) { + console.error('❌ Error fetching streaming links:', error); + res.status(500).json({ + success: false, + error: 'Erreur lors de la récupération des liens', + message: error.message + }); + } +}); + +/** + * POST /api/verify-access-code + * Vérifier un code d'accès VIP (utilisé lors de la saisie initiale du code) + * Body: { code: string } + */ +app.post('/api/verify-access-code', async (req, res) => { + try { + const { code } = req.body; + + if (!code) { + return res.status(400).json({ + success: false, + error: 'Code d\'accès requis' + }); + } + + // Utiliser le module centralisé checkVip + const vipStatus = await verifyAccessKey(code); + + if (!vipStatus.vip) { + if (vipStatus.reason === 'key_expired') { + return res.status(410).json({ + success: false, + error: 'Code d\'accès expiré' + }); + } + if (vipStatus.reason === 'key_inactive') { + return res.status(403).json({ + success: false, + error: 'Code d\'accès désactivé' + }); + } + return res.status(404).json({ + success: false, + error: 'Code d\'accès invalide ou expiré' + }); + } + + return res.json({ + success: true, + message: 'Code d\'accès valide', + data: { + key: code, + duration: vipStatus.duration, + expiresAt: vipStatus.expiresAt + } + }); + + } catch (error) { + console.error('❌ Error verifying access code:', error); + return res.status(500).json({ + success: false, + error: 'Erreur lors de la vérification du code d\'accès' + }); + } +}); + +/** + * GET /api/check-vip + * Vérification côté serveur du statut VIP via le header x-access-key. + * Appelé périodiquement par le frontend pour s'assurer que la clé est toujours valide. + * Si la clé n'est plus valide, le frontend doit révoquer le statut VIP local. + */ +app.get('/api/check-vip', async (req, res) => { + try { + const accessKey = req.headers['x-access-key']; + + if (!accessKey) { + return res.json({ vip: false, reason: 'no_key' }); + } + + const vipStatus = await verifyAccessKey(accessKey); + + return res.json({ + vip: vipStatus.vip, + expiresAt: vipStatus.expiresAt || null, + duration: vipStatus.duration || null, + reason: vipStatus.reason || null + }); + + } catch (error) { + console.error('❌ Error checking VIP status:', error); + return res.status(500).json({ vip: false, error: 'Erreur interne' }); + } +}); + +// === ROUTES ADMIN (avec authentification) === + +/** + * POST /api/admin/links + * Ajouter ou mettre à jour des liens de streaming + * Body: { type: 'movie'|'tv', id: string, links: array, season?: number, episode?: number } + */ +app.post('/api/admin/links', isUploaderOrAdmin, async (req, res) => { + try { + const { type, id, links, season, episode } = req.body; + + // Validation + if (!type || !id || !links || !Array.isArray(links)) { + return res.status(400).json({ + success: false, + error: 'Paramètres invalides. Required: type, id, links (array)' + }); + } + + if (!['movie', 'tv'].includes(type)) { + return res.status(400).json({ success: false, error: 'Type invalide. Utilisez "movie" ou "tv"' }); + } + + if (type === 'tv' && (season === undefined || season === null || episode === undefined || episode === null)) { + return res.status(400).json({ + success: false, + error: 'Pour les séries, season et episode sont requis' + }); + } + + if (type === 'movie') { + // Récupérer les liens existants + const [existing] = await pool.execute( + 'SELECT links FROM films WHERE id = ?', + [id] + ); + + let finalLinks = links; + if (existing.length > 0 && existing[0].links) { + // Parse existing links + const existingLinks = typeof existing[0].links === 'string' + ? JSON.parse(existing[0].links) + : existing[0].links; + + // Merge with new links, avoiding duplicates + const existingUrls = new Set(existingLinks.map(link => + typeof link === 'string' ? link : link.url || JSON.stringify(link) + )); + + const newLinksToAdd = links.filter(link => { + const url = typeof link === 'string' ? link : link.url || JSON.stringify(link); + return !existingUrls.has(url); + }); + + finalLinks = [...existingLinks, ...newLinksToAdd]; + } + + const linksJson = JSON.stringify(finalLinks); + + // Insérer ou mettre à jour le film + await pool.execute( + 'INSERT INTO films (id, links) VALUES (?, ?) ON DUPLICATE KEY UPDATE links = VALUES(links), updated_at = CURRENT_TIMESTAMP', + [id, linksJson] + ); + + res.json({ + success: true, + message: 'Liens de film ajoutés/mis à jour avec succès', + type: 'movie', + id, + linksCount: finalLinks.length + }); + + } else { + // Insérer ou mettre à jour l'épisode de série + // Vérifier si l'épisode existe déjà + const [existing] = await pool.execute( + 'SELECT id, links FROM series WHERE series_id = ? AND season_number = ? AND episode_number = ?', + [id, season, episode] + ); + + let finalLinks = links; + if (existing.length > 0 && existing[0].links) { + // Parse existing links + const existingLinks = typeof existing[0].links === 'string' + ? JSON.parse(existing[0].links) + : existing[0].links; + + // Merge with new links, avoiding duplicates + const existingUrls = new Set(existingLinks.map(link => + typeof link === 'string' ? link : link.url || JSON.stringify(link) + )); + + const newLinksToAdd = links.filter(link => { + const url = typeof link === 'string' ? link : link.url || JSON.stringify(link); + return !existingUrls.has(url); + }); + + finalLinks = [...existingLinks, ...newLinksToAdd]; + } + + const linksJson = JSON.stringify(finalLinks); + + if (existing.length > 0) { + // Mise à jour + await pool.execute( + 'UPDATE series SET links = ? WHERE series_id = ? AND season_number = ? AND episode_number = ?', + [linksJson, id, season, episode] + ); + } else { + // Insertion + await pool.execute( + 'INSERT INTO series (series_id, season_number, episode_number, links) VALUES (?, ?, ?, ?)', + [id, season, episode, linksJson] + ); + } + + res.json({ + success: true, + message: 'Liens d\'épisode ajoutés/mis à jour avec succès', + type: 'tv', + id, + season, + episode, + linksCount: finalLinks.length + }); + } + + } catch (error) { + console.error('❌ Error adding streaming links:', error); + res.status(500).json({ + success: false, + error: 'Erreur lors de l\'ajout des liens', + message: error.message + }); + } +}); +/** + * DELETE /api/admin/streaming-links + * Supprimer des liens de streaming + * Body: { type: 'movie'|'tv', id: string, season?: number, episode?: number } + */ +app.delete('/api/admin/links', isUploaderOrAdmin, async (req, res) => { + try { + const { type, id, season, episode } = req.body; + + // Validation + if (!type || !id) { + return res.status(400).json({ + success: false, + error: 'Paramètres invalides. Required: type, id' + }); + } + + if (!['movie', 'tv'].includes(type)) { + return res.status(400).json({ success: false, error: 'Type invalide. Utilisez "movie" ou "tv"' }); + } + + if (type === 'movie') { + const [result] = await pool.execute('DELETE FROM films WHERE id = ?', [id]); + + if (result.affectedRows === 0) { + return res.status(404).json({ success: false, error: 'Film non trouvé' }); + } + + res.json({ + success: true, + message: 'Film supprimé avec succès', + type: 'movie', + id + }); + + } else { + // Pour les séries + let query, params; + + if (season && episode) { + // Supprimer un épisode spécifique + query = 'DELETE FROM series WHERE series_id = ? AND season_number = ? AND episode_number = ?'; + params = [id, season, episode]; + } else if (season) { + // Supprimer toute une saison + query = 'DELETE FROM series WHERE series_id = ? AND season_number = ?'; + params = [id, season]; + } else { + // Supprimer toute la série + query = 'DELETE FROM series WHERE series_id = ?'; + params = [id]; + } + + const [result] = await pool.execute(query, params); + + if (result.affectedRows === 0) { + return res.status(404).json({ success: false, error: 'Aucune donnée trouvée à supprimer' }); + } + + res.json({ + success: true, + message: `${result.affectedRows} épisode(s) supprimé(s) avec succès`, + type: 'tv', + id, + ...(season && { season }), + ...(episode && { episode }), + deletedCount: result.affectedRows + }); + } + + } catch (error) { + console.error('❌ Error deleting streaming links:', error); + res.status(500).json({ + success: false, + error: 'Erreur lors de la suppression des liens', + message: error.message + }); + } +}); + +/** + * PUT /api/admin/streaming-links + * Modifier des liens de streaming (remplacer complètement) + * Body: { type: 'movie'|'tv', id: string, links: array, season?: number, episode?: number } + */ +app.put('/api/admin/links', isUploaderOrAdmin, async (req, res) => { + try { + const { type, id, links, season, episode } = req.body; + + // Validation + if (!type || !id || !links || !Array.isArray(links)) { + return res.status(400).json({ + success: false, + error: 'Paramètres invalides. Required: type, id, links (array)' + }); + } + + if (!['movie', 'tv'].includes(type)) { + return res.status(400).json({ success: false, error: 'Type invalide. Utilisez "movie" ou "tv"' }); + } + + if (type === 'tv' && (season === undefined || season === null || episode === undefined || episode === null)) { + return res.status(400).json({ + success: false, + error: 'Pour les séries, season et episode sont requis' + }); + } + + const linksJson = JSON.stringify(links); + + if (type === 'movie') { + const [result] = await pool.execute( + 'UPDATE films SET links = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', + [linksJson, id] + ); + + if (result.affectedRows === 0) { + return res.status(404).json({ success: false, error: 'Film non trouvé' }); + } + + res.json({ + success: true, + message: 'Liens de film modifiés avec succès', + type: 'movie', + id, + linksCount: links.length + }); + + } else { + const [result] = await pool.execute( + 'UPDATE series SET links = ? WHERE series_id = ? AND season_number = ? AND episode_number = ?', + [linksJson, id, season, episode] + ); + + if (result.affectedRows === 0) { + return res.status(404).json({ success: false, error: 'Épisode non trouvé' }); + } + + res.json({ + success: true, + message: 'Liens d\'épisode modifiés avec succès', + type: 'tv', + id, + season, + episode, + linksCount: links.length + }); + } + + } catch (error) { + console.error('❌ Error updating streaming links:', error); + res.status(500).json({ + success: false, + error: 'Erreur lors de la modification des liens', + message: error.message + }); + } +}); + +// === ROUTES ADMIN - GESTION DES CLÉS VIP === + +/** + * GET /api/admin/check + * Vérifier les droits d'administration (admin ou uploader) + */ +app.get('/api/admin/check', isUploaderOrAdmin, async (req, res) => { + try { + res.json({ + success: true, + message: 'Droits d\'administration confirmés', + admin: { + userId: req.admin.userId, + userType: req.admin.userType, + adminId: req.admin.adminId, + role: req.admin.role // Inclure le rôle dans la réponse + } + }); + } catch (error) { + console.error('❌ Admin check error:', error); + res.status(500).json({ success: false, error: 'Erreur lors de la vérification admin' }); + } +}); + +/** + * GET /api/admin/vip-keys + * Récupérer toutes les clés VIP + * Query: active (optionnel, true/false), used (optionnel, true/false) + */ +app.get('/api/admin/vip-keys', isAdmin, async (req, res) => { + try { + const { active, used } = req.query; + + let query = 'SELECT * FROM access_keys'; + const conditions = []; + const params = []; + + if (active !== undefined) { + conditions.push('active = ?'); + params.push(active === 'true' ? 1 : 0); + } + + if (used !== undefined) { + conditions.push('used = ?'); + params.push(used === 'true' ? 1 : 0); + } + + if (conditions.length > 0) { + query += ' WHERE ' + conditions.join(' AND '); + } + + query += ' ORDER BY created_at DESC'; + + const [rows] = await pool.execute(query, params); + + res.json({ + success: true, + keys: rows, + count: rows.length + }); + + } catch (error) { + console.error('❌ Error fetching VIP keys:', error); + res.status(500).json({ + success: false, + error: 'Erreur lors de la récupération des clés VIP', + message: error.message + }); + } +}); + +/** + * POST /api/admin/vip-keys + * Ajouter une nouvelle clé VIP + * Body: { key: string, duree_validite?: string, expires_at?: string } + */ +app.post('/api/admin/vip-keys', isAdmin, async (req, res) => { + try { + const { key, duree_validite, expires_at } = req.body; + + // Validation + if (!key || key.trim().length === 0) { + return res.status(400).json({ + success: false, + error: 'La clé est requise et ne peut pas être vide' + }); + } + + if (key.length > 255) { + return res.status(400).json({ + success: false, + error: 'La clé ne peut pas dépasser 255 caractères' + }); + } + + // Vérifier si la clé existe déjà + const [existing] = await pool.execute( + 'SELECT key_value FROM access_keys WHERE key_value = ?', + [key] + ); + + if (existing.length > 0) { + return res.status(409).json({ + success: false, + error: 'Cette clé existe déjà' + }); + } + + // Calculer la date d'expiration si duree_validite est fournie + let expiresAtValue = expires_at; + + if (duree_validite && !expires_at) { + const now = new Date(); + const match = duree_validite.match(/(\d+)\s*(min|minute|minutes|h|hour|hours|heure|heures|d|day|days|jour|jours|m|month|months|mois|y|year|years|an|ans)/i); + + if (match) { + const duration = parseInt(match[1]); + const unit = match[2].toLowerCase(); + + if (unit.startsWith('min')) { + now.setMinutes(now.getMinutes() + duration); + } else if (unit.startsWith('h')) { + now.setHours(now.getHours() + duration); + } else if (unit.startsWith('d') || unit.startsWith('j')) { + now.setDate(now.getDate() + duration); + } else if (unit.startsWith('m')) { + now.setMonth(now.getMonth() + duration); + } else if (unit.startsWith('y') || unit.startsWith('an')) { + now.setFullYear(now.getFullYear() + duration); + } + + expiresAtValue = now.toISOString().slice(0, 19).replace('T', ' '); + } + } + + // Insérer la nouvelle clé + await pool.execute( + 'INSERT INTO access_keys (key_value, active, used, duree_validite, expires_at, created_at) VALUES (?, 1, 0, ?, ?, NOW())', + [key, duree_validite || null, expiresAtValue || null] + ); + + // Invalider le cache VIP pour cette clé + invalidateVipCache(key); + + res.status(201).json({ + success: true, + message: 'Clé VIP créée avec succès', + key: { + key_value: key, + duree_validite: duree_validite || null, + expires_at: expiresAtValue || null, + active: true, + used: false + } + }); + + } catch (error) { + console.error('❌ Error adding VIP key:', error); + res.status(500).json({ + success: false, + error: 'Erreur lors de l\'ajout de la clé VIP', + message: error.message + }); + } +}); + +/** + * PUT /api/admin/vip-keys/:key + * Modifier une clé VIP (expiration, durée, statut) + * Body: { duree_validite?: string, expires_at?: string, active?: boolean, used?: boolean } + */ +app.put('/api/admin/vip-keys/:key', isAdmin, async (req, res) => { + try { + const { key } = req.params; + const { duree_validite, expires_at, active, used } = req.body; + + // Vérifier si la clé existe + const [existing] = await pool.execute( + 'SELECT * FROM access_keys WHERE key_value = ?', + [key] + ); + + if (existing.length === 0) { + return res.status(404).json({ + success: false, + error: 'Clé VIP non trouvée' + }); + } + + // Construire la requête de mise à jour dynamiquement + const updates = []; + const params = []; + + if (duree_validite !== undefined) { + updates.push('duree_validite = ?'); + params.push(duree_validite || null); + + // Si duree_validite est fournie, calculer la nouvelle date d'expiration + if (duree_validite && expires_at === undefined) { + const now = new Date(); + const match = duree_validite.match(/(\d+)\s*(min|minute|minutes|h|hour|hours|heure|heures|d|day|days|jour|jours|m|month|months|mois|y|year|years|an|ans)/i); + + if (match) { + const duration = parseInt(match[1]); + const unit = match[2].toLowerCase(); + + if (unit.startsWith('min')) { + now.setMinutes(now.getMinutes() + duration); + } else if (unit.startsWith('h')) { + now.setHours(now.getHours() + duration); + } else if (unit.startsWith('d') || unit.startsWith('j')) { + now.setDate(now.getDate() + duration); + } else if (unit.startsWith('m')) { + now.setMonth(now.getMonth() + duration); + } else if (unit.startsWith('y') || unit.startsWith('an')) { + now.setFullYear(now.getFullYear() + duration); + } + + updates.push('expires_at = ?'); + params.push(now.toISOString().slice(0, 19).replace('T', ' ')); + } + } + } + + if (expires_at !== undefined) { + updates.push('expires_at = ?'); + params.push(expires_at || null); + } + + if (active !== undefined) { + updates.push('active = ?'); + params.push(active ? 1 : 0); + } + + if (used !== undefined) { + updates.push('used = ?'); + params.push(used ? 1 : 0); + } + + if (updates.length === 0) { + return res.status(400).json({ + success: false, + error: 'Aucune modification fournie' + }); + } + + params.push(key); + + await pool.execute( + `UPDATE access_keys SET ${updates.join(', ')}, updated_at = CURRENT_TIMESTAMP WHERE key_value = ?`, + params + ); + + // Invalider le cache VIP pour cette clé + invalidateVipCache(key); + + // Récupérer la clé mise à jour + const [updated] = await pool.execute( + 'SELECT * FROM access_keys WHERE key_value = ?', + [key] + ); + + res.json({ + success: true, + message: 'Clé VIP modifiée avec succès', + key: updated[0] + }); + + } catch (error) { + console.error('❌ Error updating VIP key:', error); + res.status(500).json({ + success: false, + error: 'Erreur lors de la modification de la clé VIP', + message: error.message + }); + } +}); + +/** + * DELETE /api/admin/vip-keys/:key + * Supprimer une clé VIP + */ +// Route pour supprimer un fichier de cache d'anime spécifique +app.get('/api/anime/cache/:cacheFile', async (req, res) => { + try { + const { cacheFile } = req.params; + + // Vérifier que le nom du fichier est valide (sécurité) + if (!cacheFile || !cacheFile.endsWith('.json')) { + return res.status(400).json({ + error: 'Nom de fichier invalide. Le fichier doit se terminer par .json' + }); + } + + // Construire le chemin complet du fichier de cache + const cacheFilePath = path.join(ANIME_SAMA_CACHE_DIR, cacheFile); + + // Vérifier que le fichier existe + try { + await fsp.access(cacheFilePath); + } catch (error) { + if (error.code === 'ENOENT') { + return res.status(404).json({ + error: 'Fichier de cache non trouvé', + cacheFile: cacheFile + }); + } + throw error; + } + + // Supprimer le fichier + await fsp.unlink(cacheFilePath); + + console.log(`[ANIME-CACHE] Fichier de cache supprimé: ${cacheFile}`); + + res.json({ + success: true, + message: 'Fichier de cache supprimé avec succès', + cacheFile: cacheFile + }); + + } catch (error) { + console.error('Erreur lors de la suppression du cache anime:', error); + res.status(500).json({ + error: 'Erreur lors de la suppression du fichier de cache', + details: error.message + }); + } +}); + +app.delete('/api/admin/vip-keys/:key', isAdmin, async (req, res) => { + try { + const { key } = req.params; + + const [result] = await pool.execute( + 'DELETE FROM access_keys WHERE key_value = ?', + [key] + ); + + if (result.affectedRows === 0) { + return res.status(404).json({ + success: false, + error: 'Clé VIP non trouvée' + }); + } + + // Invalider le cache VIP pour cette clé + invalidateVipCache(key); + + res.json({ + success: true, + message: 'Clé VIP supprimée avec succès', + key + }); + + } catch (error) { + console.error('❌ Error deleting VIP key:', error); + res.status(500).json({ + success: false, + error: 'Erreur lors de la suppression de la clé VIP', + message: error.message + }); + } +}); + +// === ROUTE POUR TOUS LES LIENS DARKIWORLD ENHANCEMENT === + +/** + * GET /api/darkiworld/enhancement/:type/:id + * Récupérer tous les liens d'amélioration DarkiWorld pour un film ou un épisode + * Params: type (movie/tv), id (TMDB ID) + * Query: season (optionnel pour les séries), episode (optionnel pour les séries) + */ +app.get('/api/darkiworld/download/:type/:id', async (req, res) => { + try { + const { type, id } = req.params; + const { season, episode } = req.query; + + // Validation + if (!['movie', 'tv'].includes(type)) { + return res.status(400).json({ + success: false, + error: 'Type invalide. Utilisez "movie" ou "tv"' + }); + } + + if (type === 'tv' && (!season || !episode)) { + return res.status(400).json({ + success: false, + error: 'Pour les séries, les paramètres season et episode sont requis' + }); + } + + // Generate cache key + const cacheKey = generateCacheKey(`darkiworld_download_${type}_${id}${type === 'tv' ? `_${season}_${episode}` : ''}`); + + // Check if results are in cache without expiration (stale-while-revalidate) + const cachedData = await getFromCacheNoExpiration(DOWNLOAD_CACHE_DIR, cacheKey); + let dataReturned = false; + + if (cachedData) { + // console.log(`Résultats de téléchargement pour ${type}/${id} récupérés du cache`); + res.status(200).json(cachedData); // Return cached data immediately + dataReturned = true; + } + + // Vérifier si l'utilisateur a accès premium (optionnel) + const auth = await getAuthIfValid(req); + const darkiworld_premium = auth && auth.userType === 'premium'; + + let allEnhancementLinks = []; + + if (type === 'movie') { + // Pour les films + try { + // 1. Récupérer tous les liens pour le film (pas seulement darkibox) + const liensResp = await axiosDarkinoRequest({ + method: 'get', + url: `/api/v1/liens?perPage=100&title_id=${id}&loader=linksdl&season=1&filters=&paginate=preferLengthAware` + }); + + const allEntries = liensResp.data?.pagination?.data || []; + + // Traiter directement les entrées sans faire de requête de décodage + const enhancementSources = allEntries.map(entry => { + if (!entry) return null; + + const hostInfo = entry.host; + let embedUrl = null; + let provider = hostInfo?.name || 'unknown'; + + // Traitement spécial pour darkibox + if (provider === 'darkibox') { + // Pour darkibox, construire l'URL d'embed avec l'ID + embedUrl = `https://darkibox.com/embed-${entry.id}.html`; + } else { + // Pour les autres providers, utiliser le lien direct s'il existe + embedUrl = entry.lien || `https://darkibox.com/embed-${entry.id}.html`; + } + + return { + id: entry.id, + language: (entry?.langues_compact && entry.langues_compact.length > 0) + ? entry.langues_compact.map(l => l.name).join(', ') + : undefined, + quality: entry?.qual?.qual, + sub: (entry?.subs_compact && entry.subs_compact.length > 0) + ? entry.subs_compact.map(s => s.name).join(', ') + : undefined, + provider: provider, + host_id: hostInfo?.id_host, + host_name: hostInfo?.name, + size: entry?.taille, + upload_date: entry?.created_at, + host_icon: hostInfo?.icon, + view: entry?.view + }; + }); + + allEnhancementLinks = enhancementSources.filter(Boolean); + } catch (err) { + console.error('[ENHANCEMENT] Erreur lors de la récupération des liens pour le film:', err.message); + } + + } else { + // Pour les séries (épisodes) + try { + // 1. Paginer intelligemment pour trouver l'épisode + const allEntries = await findAllEntriesForEpisode({ + titleId: id, + seasonId: parseInt(season), + episodeId: parseInt(episode), + perPage: 100, + maxPages: 10 + }); + + // Traiter directement les entrées sans faire de requête de décodage + const enhancementSources = allEntries.map(entry => { + if (!entry) return null; + + const hostInfo = entry.host; + let embedUrl = null; + let provider = hostInfo?.name || 'unknown'; + + // Traitement spécial pour darkibox + if (provider === 'darkibox') { + // Pour darkibox, construire l'URL d'embed avec l'ID + embedUrl = `https://darkibox.com/embed-${entry.id}.html`; + } else { + // Pour les autres providers, utiliser le lien direct s'il existe + embedUrl = entry.lien || `https://darkibox.com/embed-${entry.id}.html`; + } + + return { + id: entry.id, + language: (entry?.langues_compact && entry.langues_compact.length > 0) + ? entry.langues_compact.map(l => l.name).join(', ') + : undefined, + quality: entry?.qual?.qual, + sub: (entry?.subs_compact && entry.subs_compact.length > 0) + ? entry.subs_compact.map(s => s.name).join(', ') + : undefined, + provider: provider, + host_id: hostInfo?.id_host, + host_name: hostInfo?.name, + size: entry?.taille, + upload_date: entry?.created_at, + episode_id: entry?.episode_id, + episode_number: entry?.episode_number, + host_icon: hostInfo?.icon, + view: entry?.view, + saison: entry?.saison, + episode: entry?.episode, + full_saison: entry?.full_saison + }; + }); + + allEnhancementLinks = enhancementSources.filter(Boolean); + } catch (err) { + console.error('[ENHANCEMENT] Erreur lors de la récupération des liens pour l\'épisode:', err.message); + } + } + + const responseData = { + success: true, + all: allEnhancementLinks + }; + + // Si on n'a pas encore retourné de données, retourner maintenant + if (!dataReturned) { + res.json(responseData); + } + + // Background update du cache + (async () => { + try { + // Vérifier si le cache doit être mis à jour + const shouldUpdate = await shouldUpdateCache(DOWNLOAD_CACHE_DIR, cacheKey); + if (!shouldUpdate) { + return; // Ne pas mettre à jour le cache + } + + // Si on a des données, sauvegarder dans le cache + if (allEnhancementLinks && allEnhancementLinks.length > 0) { + await saveToCache(DOWNLOAD_CACHE_DIR, cacheKey, responseData); + } + } catch (cacheError) { + // Silent fail on cache save + } + })(); + + } catch (error) { + console.error('❌ Error fetching DarkiWorld enhancement links:', error); + + // Si Darkino retourne 500, ne pas créer/mettre à jour le cache et renvoyer le cache existant si présent + if (error.response && error.response.status >= 500) { + try { + const fallbackCache = await getFromCacheNoExpiration(DOWNLOAD_CACHE_DIR, cacheKey); + if (fallbackCache) { + return res.status(200).json(fallbackCache); + } + } catch (_) { } + } + + if (!res.headersSent) { + res.status(500).json({ + success: false, + error: 'Erreur lors de la récupération des liens d\'amélioration DarkiWorld', + message: error.message + }); + } + } +}); + +// Fonction utilitaire pour récupérer toutes les entrées d'un épisode (pas seulement darkibox) +async function findAllEntriesForEpisode({ titleId, seasonId, episodeId, perPage = 100, maxPages = 10 }) { + // Rafraîchir les cookies avant de commencer la pagination + try { + await refreshDarkinoSessionIfNeeded(); + } catch (e) { + console.warn('Erreur lors du rafraîchissement des cookies Darkino:', e.message); + } + + let page = 1; + let foundEntries = []; + let shouldContinue = true; + + while (shouldContinue && page <= maxPages) { + const url = `/api/v1/liens?perPage=${perPage}&page=${page}&title_id=${titleId}&loader=linksdl&season=${seasonId}&filters=&paginate=preferLengthAware`; + try { + const resp = await axiosDarkinoRequest({ + method: 'get', + url: url, + headers: darkiHeaders + }); + + const data = resp.data?.pagination?.data || []; + + // Chercher toutes les entrées correspondant à l'épisode ET les liens de saison complète + const matching = data.filter(entry => + entry.host && + ( + // Liens d'épisode spécifique + (entry.episode_id == episodeId || entry.episode == episodeId || entry.episode_number == episodeId) || + // Liens de saison complète (full_saison = 1) + entry.full_saison == 1 + ) + ); + + if (matching.length > 0) { + foundEntries = [...foundEntries, ...matching]; + } + + // Pagination intelligente + const nextPage = resp.data?.pagination?.next_page; + if (!nextPage) { + shouldContinue = false; + } else { + page = nextPage; + } + } catch (error) { + console.error(`[ENHANCEMENT] Erreur lors de la recherche des liens (page ${page}):`, error.message); + shouldContinue = false; + } + } + + return foundEntries; +} +/** + * GET /api/darkiworld/decode/:id + * Extraire le lien décodé (m3u8) pour un ID de lien DarkiWorld + * Params: id (ID du lien DarkiWorld) + */ +app.get('/api/darkiworld/decode/:id', async (req, res) => { + try { + const { id } = req.params; + + if (!id) { + return res.status(400).json({ + success: false, + error: 'ID du lien requis' + }); + } + + // Generate cache key + const cacheKey = generateCacheKey(`darkiworld_decode_${id}`); + + // Check if results are in cache without expiration (stale-while-revalidate) + const cachedData = await getFromCacheNoExpiration(DOWNLOAD_CACHE_DIR, cacheKey); + let dataReturned = false; + let shouldDoBackgroundUpdate = false; + + if (cachedData) { + // Vérifier si le lien en cache est un lien d'embed invalide + const embedUrl = cachedData.embed_url || ''; + const isInvalidEmbedLink = /\/embed-\d+\.html$/i.test(embedUrl); + + if (isInvalidEmbedLink) { + // Le cache contient un lien d'embed invalide, réessayer d'obtenir le bon lien + console.warn(`[DECODE] Cache contient un lien d'embed invalide pour ${id}: ${embedUrl}`); + // Ne pas retourner le cache, continuer pour refetch + } else { + // Cache valide, le retourner immédiatement + res.status(200).json(cachedData); + dataReturned = true; + + // Vérifier si on doit faire un background update (fichier modifié il y a plus de 24h) + shouldDoBackgroundUpdate = await shouldUpdateCache24h(DOWNLOAD_CACHE_DIR, cacheKey); + + // Si pas besoin de background update, on s'arrête là + if (!shouldDoBackgroundUpdate) { + return; + } + // Sinon on continue pour faire le fetch en arrière-plan + } + } + + + + // Si pas de cache valide + // Si en maintenance + if (DARKINO_MAINTENANCE) { + if (!dataReturned) { + return res.status(200).json({ error: 'Service Darkino temporairement indisponible (maintenance)' }); + } + return; // Si on a déjà retourné des données, on arrête juste le traitement (pas de background update) + } + + // Fonction pour récupérer les données fraîches + const fetchFreshData = async () => { + let linkInfo = null; + let embedUrl = null; + let provider = 'unknown'; + let retryCount = 0; + const maxRetries = 2; + + while (retryCount < maxRetries) { + try { + const linkResp = await axiosDarkinoRequest({ + method: 'post', + url: `/api/v1/liens/${id}/download` + }); + + linkInfo = linkResp.data; + provider = linkInfo?.host?.name || 'unknown'; + + if (provider === 'darkibox') { + embedUrl = `https://darkibox.com/embed-${id}.html`; + } else { + embedUrl = linkInfo?.lien || `https://darkibox.com/embed-${id}.html`; + } + + const isInvalidEmbedLink = /\/embed-\d+\.html$/i.test(embedUrl); + + if (isInvalidEmbedLink && retryCount < maxRetries - 1) { + retryCount++; + await new Promise(resolve => setTimeout(resolve, 1000)); + continue; + } else if (isInvalidEmbedLink) { + throw new Error('Lien d\'embed invalide'); + } + + break; + } catch (err) { + if (retryCount < maxRetries - 1) { + retryCount++; + await new Promise(resolve => setTimeout(resolve, 1000)); + continue; + } + throw err; + } + } + + return { + success: true, + id: id, + provider: provider, + embed_url: embedUrl, + metadata: linkInfo ? { + language: (linkInfo?.langues_compact && linkInfo.langues_compact.length > 0) + ? linkInfo.langues_compact.map(l => l.name).join(', ') + : undefined, + quality: linkInfo?.qual?.qual, + sub: (linkInfo?.subs_compact && linkInfo.subs_compact.length > 0) + ? linkInfo.subs_compact.map(s => s.name).join(', ') + : undefined, + size: linkInfo?.size, + upload_date: linkInfo?.created_at + } : null + }; + }; + + // Si on fait un background update (données déjà retournées au client) + if (dataReturned && shouldDoBackgroundUpdate) { + // Background update du cache + (async () => { + try { + const freshData = await fetchFreshData(); + if (freshData && freshData.embed_url) { + await saveToCache(DOWNLOAD_CACHE_DIR, cacheKey, freshData); + } + } catch (bgError) { + // Silent fail on background update + } + })(); + return; + } + + // Si on n'a pas encore retourné de données, faire le fetch normal + try { + const responseData = await fetchFreshData(); + + // Retourner les données + res.json(responseData); + + // Mise à jour du cache + if (responseData.embed_url) { + try { + await saveToCache(DOWNLOAD_CACHE_DIR, cacheKey, responseData); + } catch (cacheError) { + // Silent fail on cache save + } + } + } catch (fetchError) { + return res.status(404).json({ + success: false, + error: 'Lien non trouvé ou inaccessible', + id: id + }); + } + + } catch (error) { + if (res.headersSent) { + console.error('❌ Error decoding DarkiWorld link (headers already sent):', error.message); + return; + } + console.error('❌ Error decoding DarkiWorld link:', error); + + // Si Darkino retourne 500, ne pas créer/mettre à jour le cache et renvoyer le cache existant si présent + if (error.response && error.response.status >= 500) { + try { + const fallbackCache = await getFromCacheNoExpiration(DOWNLOAD_CACHE_DIR, cacheKey); + if (fallbackCache) { + return res.status(200).json(fallbackCache); + } + } catch (_) { } + } + + if (!res.headersSent) { + res.status(500).json({ + success: false, + error: 'Erreur lors du décodage du lien DarkiWorld', + message: error.message + }); + } + } +}); + +/** + * GET /api/darkiworld/seasons/:titleId + * Récupérer les saisons d'une série depuis DarkiWorld + * Params: titleId (ID DarkiWorld de la série) + * Query: page (optionnel, défaut: 1), perPage (optionnel, défaut: 8) + */ +app.get('/api/darkiworld/seasons/:titleId', async (req, res) => { + let dataReturned = false; + try { + const { titleId } = req.params; + const { page = 1, perPage = 8 } = req.query; + + if (!titleId) { + return res.status(400).json({ + success: false, + error: 'ID de la série requis' + }); + } + + // Generate cache key + const cacheKey = generateCacheKey(`darkiworld_seasons_${titleId}_${page}_${perPage}`); + + // Check if results are in cache without expiration (stale-while-revalidate) + const cachedData = await getFromCacheNoExpiration(DOWNLOAD_CACHE_DIR, cacheKey); + + if (cachedData) { + // console.log(`Saisons pour ${titleId} récupérées du cache`); + res.status(200).json(cachedData); // Return cached data immediately + dataReturned = true; + } + + // Récupérer les saisons depuis DarkiWorld + const seasonsResponse = await axiosDarkinoRequest({ + method: 'get', + url: `/api/v1/titles/${titleId}/seasons?perPage=${perPage}&query=&page=${page}` + }); + + const responseData = { + success: true, + ...seasonsResponse.data + }; + + // Si on n'a pas encore retourné de données, retourner maintenant + if (!dataReturned) { + res.json(responseData); + } + + // Background update du cache + (async () => { + try { + // Vérifier si le cache doit être mis à jour + const shouldUpdate = await shouldUpdateCache(DOWNLOAD_CACHE_DIR, cacheKey); + if (!shouldUpdate) { + return; // Ne pas mettre à jour le cache + } + + // Si on a des données, sauvegarder dans le cache + if (seasonsResponse.data && seasonsResponse.data.pagination) { + await saveToCache(DOWNLOAD_CACHE_DIR, cacheKey, responseData); + } + } catch (cacheError) { + // Silent fail on cache save + } + })(); + + } catch (error) { + + // Si Darkino retourne 500, ne pas créer/mettre à jour le cache et renvoyer le cache existant si présent + if (error.response && error.response.status >= 500) { + // Si on a déjà retourné des données (cache), on ne fait RIEN + if (dataReturned) return; + + try { + const fallbackCache = await getFromCacheNoExpiration(DOWNLOAD_CACHE_DIR, cacheKey); + if (fallbackCache) { + return res.status(200).json(fallbackCache); + } + } catch (_) { } + } + + if (!res.headersSent) { + res.status(500).json({ + success: false, + error: 'Erreur lors de la récupération des saisons DarkiWorld', + message: error.message + }); + } + } +}); + +/** + * GET /api/darkiworld/episodes/:titleId/:seasonNumber + * Récupérer les épisodes d'une saison depuis DarkiWorld + * Params: titleId (ID DarkiWorld de la série), seasonNumber (numéro de la saison: 0, 1, 2, etc.) + * Query: page (optionnel, défaut: 1), perPage (optionnel, défaut: 30) + */ +app.get('/api/darkiworld/episodes/:titleId/:seasonNumber', async (req, res) => { + let dataReturned = false; + try { + const { titleId, seasonNumber } = req.params; + const { page = 1, perPage = 30 } = req.query; + + if (!titleId || seasonNumber === undefined) { + return res.status(400).json({ + success: false, + error: 'ID de la série et numéro de saison requis' + }); + } + + // Generate cache key + const cacheKey = generateCacheKey(`darkiworld_episodes_${titleId}_${seasonNumber}_${page}_${perPage}`); + + // Check if results are in cache without expiration (stale-while-revalidate) + const cachedData = await getFromCacheNoExpiration(DOWNLOAD_CACHE_DIR, cacheKey); + + if (cachedData) { + // console.log(`Épisodes pour ${titleId}/${seasonNumber} récupérés du cache`); + res.status(200).json(cachedData); // Return cached data immediately + dataReturned = true; + } + + // Récupérer les épisodes depuis DarkiWorld + const episodesResponse = await axiosDarkinoRequest({ + method: 'get', + url: `/api/v1/titles/${titleId}/seasons/${seasonNumber}/episodes?perPage=${perPage}&excludeDescription=true&query=&orderBy=episode_number&orderDir=asc&page=${page}` + }); + + const responseData = { + success: true, + ...episodesResponse.data + }; + + // Si on n'a pas encore retourné de données, retourner maintenant + if (!dataReturned) { + res.json(responseData); + } + + // Background update du cache + (async () => { + try { + // Vérifier si le cache doit être mis à jour + const shouldUpdate = await shouldUpdateCache(DOWNLOAD_CACHE_DIR, cacheKey); + if (!shouldUpdate) { + return; // Ne pas mettre à jour le cache + } + + // Si on a des données, sauvegarder dans le cache + if (episodesResponse.data && episodesResponse.data.pagination) { + await saveToCache(DOWNLOAD_CACHE_DIR, cacheKey, responseData); + } + } catch (cacheError) { + // Silent fail on cache save + } + })(); + + } catch (error) { + + // Si Darkino retourne 500, ne pas créer/mettre à jour le cache et renvoyer le cache existant si présent + if (error.response && error.response.status >= 500) { + // Si on a déjà retourné des données (cache), on ne fait RIEN + if (dataReturned) return; + + try { + const fallbackCache = await getFromCacheNoExpiration(DOWNLOAD_CACHE_DIR, cacheKey); + if (fallbackCache) { + return res.status(200).json(fallbackCache); + } + } catch (_) { } + } + + if (!res.headersSent) { + res.status(500).json({ + success: false, + error: 'Erreur lors de la récupération des épisodes DarkiWorld', + message: error.message + }); + } + } +}); + + +// === VOIRDRAMA CONFIGURATION === +const VOIRDRAMA_BASE_URL = 'https://voirdrama.org'; + +async function fetchDramaTvData(tmdbId, season, episode) { + try { + // 1. Get Series Name from TMDB + const tmdbResponse = await axios.get(`${TMDB_API_URL}/tv/${tmdbId}`, { + params: { + api_key: TMDB_API_KEY, + language: 'fr-FR', + append_to_response: 'credits' + } + }); + + const showName = tmdbResponse.data.name; + const firstAirDate = tmdbResponse.data.first_air_date; // Format: YYYY-MM-DD + + // 2. Construct Search Query + // Si c'est saison 1, tu prends le nom direct, si c'est saison 2, 3 etc, tu mets ex : Culinary Class Wars 2 + let searchQuery = showName; + if (parseInt(season) > 1) { + searchQuery += ` ${season}`; + } + + // 3. Search on Voirdrama + const formData = new URLSearchParams(); + formData.append('action', 'ajaxsearchpro_search'); + formData.append('aspp', searchQuery); + formData.append('asid', '7'); + formData.append('asp_inst_id', '7_1'); + formData.append('options', 'aspf[vf__1]=vf&asp_gen[]=excerpt&asp_gen[]=content&asp_gen[]=title&filters_initial=1&filters_changed=0&qtranslate_lang=0¤t_page_id=510'); + + // Proxy handling for search - Utiliser proxy SOCKS5h comme demandé + const proxy = pickRandomProxyOrNone(); + const agent = proxy ? getProxyAgent(proxy) : null; + + const axiosConfig = { + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', + 'Referer': VOIRDRAMA_BASE_URL + }, + proxy: false + }; + + if (agent) { + axiosConfig.httpAgent = agent; + axiosConfig.httpsAgent = agent; + } + + const searchResponse = await axios.post(`${VOIRDRAMA_BASE_URL}/wp-admin/admin-ajax.php`, formData, axiosConfig); + + // 4. Parse Search Result + const rawData = searchResponse.data; + // Extract HTML part between markers + // ___ASPSTART_HTML___ ... ___ASPEND_HTML___ + const htmlMatch = rawData.match(/___ASPSTART_HTML___([\s\S]*?)___ASPEND_HTML___/); + + if (!htmlMatch) { + console.log('[VOIRDRAMA] Structure de réponse de recherche invalide ou pas de résultats HTML'); + return { success: false, error: 'Film/Série non trouvé sur Voirdrama' }; + } + + const $ = cheerio.load(htmlMatch[1]); + + let bestLink = null; + let fallbackLink = $('div.asp_content h3 a.asp_res_url').first().attr('href'); + + if (!firstAirDate) { + bestLink = fallbackLink; + } else { + // Month map for parsing "Dec 12, 2025" + const monthsMap = { + 'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', 'May': '05', 'Jun': '06', + 'Jul': '07', 'Aug': '08', 'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12' + }; + + // Try to find a date match + const candidates = []; + $('div.item').each((i, el) => { + const link = $(el).find('a.asp_res_url').attr('href'); + const dateText = $(el).find('.summary-content').text().trim(); + + if (link) { + candidates.push({ link, dateText }); + } + }); + + for (const candidate of candidates) { + const { link, dateText } = candidate; + let matched = false; + + // 1. Try to check date from search result if present + if (dateText) { + const parts = dateText.split(/[\s,]+/); + if (parts.length >= 3) { + const mStr = parts[0].substring(0, 3); + const dStr = parts[1]; + const yStr = parts[2]; + const month = monthsMap[mStr]; + + if (month && dStr && yStr) { + const day = dStr.padStart(2, '0'); + const formattedDate = `${yStr}-${month}-${day}`; + if (formattedDate === firstAirDate) { + bestLink = link; + matched = true; + } + } + } + } + + if (matched) break; + + // 2. If no match yet (or no dateText), fetch the page to check the date + if (!bestLink) { + try { + // Determine proxy usage for this request + const pageConfig = { + headers: { + 'User-Agent': axiosConfig.headers['User-Agent'] + }, + proxy: false + }; + if (agent) { + pageConfig.httpAgent = agent; + pageConfig.httpsAgent = agent; + } + + const pageResponse = await axios.get(link, pageConfig); + const $page = cheerio.load(pageResponse.data); + + let pageDateFound = false; + + $page('.summary-content').each((_, el) => { + const txt = $(el).text().trim(); + // Try parsing this text + const parts = txt.split(/[\s,]+/); + if (parts.length >= 3) { + const mStr = parts[0].substring(0, 3); + const dStr = parts[1]; + const yStr = parts[2]; + const month = monthsMap[mStr]; + if (month && dStr && yStr) { + const day = dStr.padStart(2, '0'); + const fDate = `${yStr}-${month}-${day}`; + if (fDate === firstAirDate) { + pageDateFound = true; + return false; + } + } + } + }); + + if (pageDateFound) { + bestLink = link; + break; + } + + } catch (err) { + // Check next candidate + } + } + } + } + + // Fallback if no specific date match found + if (!bestLink) { + return { success: false, error: 'Série non trouvée sur Voirdrama (Aucune date correspondante)' }; + } + + // 5. Construct Episode URL + // Format: https://voirdrama.org/drama/slug/ -> https://voirdrama.org/drama/slug/slug-episode-vostfr/ + // Remove trailing slash if present + const cleanLink = bestLink.replace(/\/$/, ''); + const slug = cleanLink.split('/').pop(); + + const paddedEpisode = episode.toString().padStart(2, '0'); + // Note: User example had slug repeated: /slug/slug-01-vostfr/ + const episodeUrl = `${cleanLink}/${slug}-${paddedEpisode}-vostfr/`; + + // 6. Fetch Episode Page + const episodeConfig = { + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', + }, + proxy: false + }; + + if (agent) { + episodeConfig.httpAgent = agent; + episodeConfig.httpsAgent = agent; + } + + const episodeResponse = await axios.get(episodeUrl, episodeConfig); + + // 7. Extract Sources + const episodeHtml = episodeResponse.data; + const sourcesMatch = episodeHtml.match(/var thisChapterSources = ({[\s\S]*?});/); + + if (!sourcesMatch) { + return { success: false, error: 'Sources non trouvées sur la page de l\'épisode' }; + } + + const sourcesJson = JSON.parse(sourcesMatch[1]); + const sources = []; + + for (const [key, value] of Object.entries(sourcesJson)) { + // 1. Clean Name + let name = key; + try { + name = JSON.parse(`"${key}"`); // Decode unicode if needed + } catch (e) { } + + // Remove "☰", "LECTEUR", numbers and extra spaces + name = name.replace(/[☰]/g, '').replace(/LECTEUR\s*\d+/i, '').trim(); + + // Map common abbreviated names if possible + if (name === 'VIDM') name = 'Vidmoly'; + if (name === 'RU') name = 'Ok.ru'; + if (name === 'VOE') name = 'Voe'; + if (name === 'UQLOAD') name = 'Uqload'; + if (name === 'UPSTREAM') name = 'Upstream'; + if (name === 'DOOD') name = 'Doodstream'; + + + // 2. Extract Link + let url = null; + + // Look for iframe src specifically to avoid script tags + const iframeMatch = value.match(/<iframe[^>]+src="([^"]+)"/i); + if (iframeMatch) { + url = iframeMatch[1]; + } else { + // Fallback: try to find http links that look like video embeds + const urlMatch = value.match(/https?:\/\/[^"\s']+/); + if (urlMatch) { + const candidate = urlMatch[0]; + // Exclude recaptcha, google api, and local admin-ajax + if (!candidate.includes('google.com/recaptcha') && !candidate.includes('admin-ajax.php')) { + url = candidate; + } + } + } + + // 3. Filter and Add + if (url) { + sources.push({ + name: name, + link: url, + // raw: value // Optional: keep raw for debug if needed, but user didn't ask for it + }); + } + } + + return { + success: true, + data: sources, + tmdbId: tmdbId, + season: season, + episode: episode + }; + + } catch (error) { + console.error('[VOIRDRAMA] Error:', error.message); + return { success: false, error: error.message }; + } +} + +// Route /api/drama/:type/:tmdbid +// Options: season (saison), episode (episode) +app.get('/api/drama/:type/:tmdbid', async (req, res) => { + const { type, tmdbid } = req.params; + const { season, episode } = req.query; + + if (type !== 'tv') { + return res.status(400).json({ + success: false, + error: 'Ce point de terminaison ne supporte que type=tv pour le moment avec saison/episode' + }); + } + + if (!season || !episode) { + return res.status(400).json({ + success: false, + error: 'Les paramètres ?season= et ?episode= sont requis.' + }); + } + + const cacheKey = generateCacheKey(`voirdrama_${tmdbid}_${season}_${episode}`); + const cacheDir = path.join(__dirname, 'cache', 'voirdrama'); + + try { + await fsp.mkdir(cacheDir, { recursive: true }); + + // Stale-while-revalidate: return cached data immediately + const cachedData = await getFromCacheNoExpiration(cacheDir, cacheKey); + let dataReturned = false; + + if (cachedData) { + // Return cached data immediately + if (!cachedData.success) { + res.status(404).json(cachedData); + } else { + res.json(cachedData); + } + dataReturned = true; + + // Background update if cache should be updated + const shouldUpdate = await shouldUpdateCache24h(cacheDir, cacheKey); + if (shouldUpdate) { + // Background update (non-blocking) + (async () => { + try { + const freshData = await fetchDramaTvData(tmdbid, season, episode); + await saveToCache(cacheDir, cacheKey, freshData); + } catch (bgError) { + console.error(`[VOIRDRAMA] Background update error:`, bgError.message); + } + })(); + } + return; + } + + // No cache - fetch fresh data + const result = await fetchDramaTvData(tmdbid, season, episode); + + // Save to cache (both success and error results) + await saveToCache(cacheDir, cacheKey, result); + + if (!result.success) { + return res.status(404).json(result); + } + + res.json(result); + + } catch (error) { + console.error('[API DRAMA] Error:', error); + res.status(500).json({ + success: false, + error: 'Erreur interne', + details: error.message + }); + } +}); + +// Helper function to extract poster ID from Purstream large_poster_path +// e.g., "https://www.themoviedb.org/t/p/w600_and_h900_bestv2/xEx4dHi2IrTB0vkVPccrGrMcZQW.jpg" +// returns "/xEx4dHi2IrTB0vkVPccrGrMcZQW.jpg" +const extractPosterPathFromPurstream = (largePosterPath) => { + if (!largePosterPath) return null; + const match = largePosterPath.match(/\/([a-zA-Z0-9]+\.jpg)$/); + return match ? `/${match[1]}` : null; +}; + +// Helper function to normalize date for comparison (YYYY-MM-DD or just YYYY) +const normalizeDate = (dateStr) => { + if (!dateStr) return null; + // Handle format like "2016-02-11 00:00:00" or "2016-02-11" + const match = dateStr.match(/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?/); + if (!match) return null; + return { + year: parseInt(match[1]), + month: match[2] ? parseInt(match[2]) : null, + day: match[3] ? parseInt(match[3]) : null, + yearStr: match[1] + }; +}; + +// Helper function to normalize title for comparison +const normalizeTitle = (title) => { + if (!title) return ''; + return title.toLowerCase() + .normalize('NFD').replace(/[\u0300-\u036f]/g, '') // Remove accents + .replace(/[^a-z0-9\s]/g, '') // Remove special chars + .replace(/\s+/g, ' ') // Normalize spaces + .trim(); +}; + +// ============================ +// === DRAGIV SOURCE (FILMS UNIQUEMENT) === +// ============================ + +const DRAGIV_BASE = 'https://kimpav.com'; +const DRAGIV_KEY = 'ph4p9rv4jpx7mg'; + +// Deduplication des requêtes Dragiv en cours +const ongoingDragivRequests = new Map(); + +const getOrCreateDragivRequest = async (cacheKey, requestFunction) => { + if (ongoingDragivRequests.has(cacheKey)) { + return ongoingDragivRequests.get(cacheKey); + } + const requestPromise = (async () => { + try { + return await requestFunction(); + } finally { + ongoingDragivRequests.delete(cacheKey); + } + })(); + ongoingDragivRequests.set(cacheKey, requestPromise); + return await requestPromise; +}; + +/** + * Récupère la liste des films depuis Dragiv + */ +async function fetchDragivHomeMovies() { + const homeUrl = `${DRAGIV_BASE}/${DRAGIV_KEY}/home/kimpav`; + + const response = await axios.get(homeUrl, { + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', + 'Referer': DRAGIV_BASE + }, + timeout: 15000 + }); + + const html = response.data; + const movieRegex = /href="(\/ph4p9rv4jpx7mg\/b\/kimpav\/\d+)"[^>]*>([^<]+)/g; + const matches = [...html.matchAll(movieRegex)]; + + const movies = []; + const seen = new Set(); + + for (const match of matches) { + const moviePath = match[1]; + const movieId = moviePath.split('/').pop(); + const title = match[2].trim(); + + if (!seen.has(movieId)) { + seen.add(movieId); + movies.push({ + id: movieId, + title: title, + url: `${DRAGIV_BASE}${moviePath}`, + path: moviePath + }); + } + } + + return movies; +} + +/** + * Récupère les sources d'un film Dragiv par son ID interne + */ +async function fetchDragivMovieData(movieId) { + const movieUrl = `${DRAGIV_BASE}/${DRAGIV_KEY}/b/kimpav/${movieId}`; + + const response = await axios.get(movieUrl, { + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', + 'Referer': `${DRAGIV_BASE}/${DRAGIV_KEY}/home/kimpav` + }, + timeout: 15000 + }); + + const html = response.data; + + const titleMatch = html.match(/<title>([^<]+)<\/title>/i); + const title = titleMatch ? titleMatch[1].replace(/^(Dragiv|Kimpav)\s*-\s*/i, '').trim() : 'Unknown'; + + const iframeMatch = html.match(/<iframe[^>]+src="(https:\/\/sharecloudy\.com\/[^"]+)"/i); + if (!iframeMatch) { + return { success: false, error: 'No iframe found', id: movieId, title }; + } + + const iframeUrl = iframeMatch[1]; + + const iframeResponse = await axios.get(iframeUrl, { + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', + 'Referer': movieUrl + }, + timeout: 15000 + }); + + const iframeHtml = iframeResponse.data; + + const m3u8Match = iframeHtml.match(/file:\s*"(https:\/\/[^"]+\.m3u8[^"]*)"/i); + if (!m3u8Match) { + return { success: false, error: 'No m3u8 found in iframe', id: movieId, title, iframeUrl }; + } + + const m3u8Url = m3u8Match[1]; + + // Extraire les qualités disponibles + const qualityRegex = /{\s*file:\s*"([^"]+\.m3u8[^"]*)"\s*,\s*label:\s*"([^"]+)"/g; + const qualityMatches = [...iframeHtml.matchAll(qualityRegex)]; + + const qualities = qualityMatches.length > 0 + ? qualityMatches.map(m => ({ url: m[1], quality: m[2] })) + : [{ url: m3u8Url, quality: 'HD' }]; + + return { + success: true, + id: movieId, + title, + movieUrl, + iframeUrl, + m3u8: m3u8Url, + qualities, + provider: 'sharecloudy.com', + referer: iframeUrl, + note: 'Le m3u8 nécessite le header Referer pour fonctionner' + }; +} + +/** + * Calcule un score de correspondance entre titres Dragiv + * Utilise Jaccard similarity sur les mots pour éviter les faux positifs + */ +function calculateDragivMatchScore(dragivTitle, searchTitle, tmdbTitle, tmdbOriginalTitle) { + const normalize = (str) => str.toLowerCase() + .replace(/[:\-–—'"]/g, ' ') + .replace(/[^\w\s\u00C0-\u024F]/g, '') + .replace(/\s+/g, ' ') + .trim(); + + const removeYear = (str) => str.replace(/\(?\d{4}\)?$/, '').trim(); + const sequelTokenRegex = /^(\d+|i|ii|iii|iv|v|vi|vii|viii|ix|x)$/i; + const getSequelTokens = (str) => { + if (!str) return new Set(); + return new Set( + str + .split(' ') + .map(token => token.trim().toLowerCase()) + .filter(token => sequelTokenRegex.test(token)) + ); + }; + const hasSequelMismatch = (candidateTitleOnly, referenceTitleOnly) => { + const candidateTokens = getSequelTokens(candidateTitleOnly); + const referenceTokens = getSequelTokens(referenceTitleOnly); + + if (candidateTokens.size === 0 && referenceTokens.size === 0) return false; + if (candidateTokens.size === 0 || referenceTokens.size === 0) return true; + + for (const token of candidateTokens) { + if (referenceTokens.has(token)) return false; + } + return true; + }; + + const dragivNorm = normalize(dragivTitle); + const searchNorm = normalize(searchTitle); + const tmdbNorm = normalize(tmdbTitle); + const tmdbOrigNorm = normalize(tmdbOriginalTitle || ''); + + const dragivTitleOnly = removeYear(dragivNorm); + const tmdbTitleOnly = removeYear(tmdbNorm); + const tmdbOrigTitleOnly = removeYear(tmdbOrigNorm); + + // Bloque les faux positifs de suites: ex. "Zootopie" vs "Zootopie 2" + const mismatchWithTmdb = hasSequelMismatch(dragivTitleOnly, tmdbTitleOnly); + const mismatchWithTmdbOriginal = tmdbOrigTitleOnly.length > 0 + ? hasSequelMismatch(dragivTitleOnly, tmdbOrigTitleOnly) + : true; + + if (mismatchWithTmdb && mismatchWithTmdbOriginal) return 0; + + // Match exact (titre complet ou sans année) + if (dragivNorm === searchNorm || dragivNorm === tmdbNorm) return 1.0; + if (tmdbOrigNorm.length > 0 && dragivNorm === tmdbOrigNorm) return 1.0; + if (dragivTitleOnly.length > 0 && tmdbTitleOnly.length > 0 && dragivTitleOnly === tmdbTitleOnly) return 1.0; + if (tmdbOrigTitleOnly.length > 0 && dragivTitleOnly === tmdbOrigTitleOnly) return 1.0; + + // Jaccard similarity sur les mots (plus robuste que substring includes) + const getWords = (str) => { + const words = str.split(' ').filter(w => w.length > 1); + return new Set(words); + }; + + const jaccard = (setA, setB) => { + if (setA.size === 0 || setB.size === 0) return 0; + let intersectionSize = 0; + for (const item of setA) { + if (setB.has(item)) intersectionSize++; + } + const unionSize = new Set([...setA, ...setB]).size; + return intersectionSize / unionSize; + }; + + const dragivWords = getWords(dragivTitleOnly); + const tmdbWords = getWords(tmdbTitleOnly); + const tmdbOrigWords = tmdbOrigTitleOnly.length > 0 ? getWords(tmdbOrigTitleOnly) : new Set(); + + let score = Math.max( + jaccard(dragivWords, tmdbWords), + tmdbOrigWords.size > 0 ? jaccard(dragivWords, tmdbOrigWords) : 0 + ); + + // Bonus année uniquement si le titre a déjà un bon score + if (score >= 0.5) { + const yearMatch = dragivTitle.match(/\((\d{4})\)/); + const searchYearMatch = searchTitle.match(/\((\d{4})\)/); + if (yearMatch && searchYearMatch && yearMatch[1] === searchYearMatch[1]) { + score = Math.min(score + 0.1, 1.0); + } + } + + return score; +} + +// === ROUTE : Chercher un film Dragiv par TMDB ID === +app.get('/api/dragiv/movie/:tmdbid', async (req, res) => { + const { tmdbid } = req.params; + const cacheKey = generateCacheKey(`dragiv_movie_${tmdbid}`); + + try { + // 1. Try cache + const cachedData = await getFromCacheNoExpiration(CACHE_DIR.DRAGIV, cacheKey); + if (cachedData) { + if (cachedData.notFound) { + res.status(404).json({ error: 'Movie not found on Dragiv (Cached)' }); + } else { + res.json(cachedData); + } + + // Background update si ancien (20 min) + const cacheFilePath = path.join(CACHE_DIR.DRAGIV, `${cacheKey}.json`); + try { + const stats = await fsp.stat(cacheFilePath); + const age = Date.now() - stats.mtime.getTime(); + if (age > 20 * 60 * 1000) { + updateDragivCache(cacheKey, tmdbid).catch(() => {}); + } + } catch (e) { /* ignore */ } + return; + } + + // 2. Fetch fresh avec deduplication + const data = await getOrCreateDragivRequest(cacheKey, () => fetchDragivByTmdbId(tmdbid)); + + if (!data || !data.success) { + const notFoundData = { notFound: true, tmdbId: tmdbid, timestamp: Date.now() }; + await fsp.writeFile(path.join(CACHE_DIR.DRAGIV, `${cacheKey}.json`), JSON.stringify(notFoundData), 'utf-8'); + return res.status(404).json({ error: 'Movie not found on Dragiv' }); + } + + await fsp.writeFile(path.join(CACHE_DIR.DRAGIV, `${cacheKey}.json`), JSON.stringify(data), 'utf-8'); + res.json(data); + + } catch (error) { + console.error('[DRAGIV API] Error:', error.message); + if (error.message && error.message.includes('not found')) { + return res.status(404).json({ error: error.message }); + } + res.status(500).json({ error: 'Internal Server Error' }); + } +}); + + + +// === ROUTE : Vider le cache Dragiv d'un film === +app.get('/api/dragiv/movie/:tmdbid/clear-cache', async (req, res) => { + const { tmdbid } = req.params; + const cacheKey = generateCacheKey(`dragiv_movie_${tmdbid}`); + const cacheFilePath = path.join(CACHE_DIR.DRAGIV, `${cacheKey}.json`); + + try { + await fsp.unlink(cacheFilePath); + console.log(`[DRAGIV Cache] Cache cleared for movie ${tmdbid}`); + res.json({ success: true, message: `Cache cleared for movie ${tmdbid}` }); + } catch (error) { + if (error.code === 'ENOENT') { + res.status(404).json({ error: `No cache found for movie ${tmdbid}` }); + } else { + console.error(`[DRAGIV Cache] Error clearing cache:`, error.message); + res.status(500).json({ error: 'Internal Server Error' }); + } + } +}); + +/** + * Cherche un film sur Dragiv à partir de son TMDB ID + */ +async function fetchDragivByTmdbId(tmdbId) { + try { + // 1. Récupérer les infos TMDB + const tmdbApiKey = process.env.TMDB_API_KEY || 'feb30ec8227ccefb4502124a5af8dffa'; + const tmdbUrl = `https://api.themoviedb.org/3/movie/${tmdbId}?api_key=${tmdbApiKey}&language=fr-FR`; + const tmdbResponse = await axios.get(tmdbUrl, { timeout: 10000 }); + const tmdbMovie = tmdbResponse.data; + + if (!tmdbMovie || !tmdbMovie.title) { + return { success: false, error: 'TMDB movie not found', tmdb_id: tmdbId }; + } + + const year = tmdbMovie.release_date ? tmdbMovie.release_date.split('-')[0] : null; + const searchTitle = year ? `${tmdbMovie.title} (${year})` : tmdbMovie.title; + + // 2. Récupérer la liste des films Dragiv + const allMovies = await fetchDragivHomeMovies(); + + // 3. Trouver le meilleur match + let bestMatch = null; + let bestScore = 0; + + for (const movie of allMovies) { + const score = calculateDragivMatchScore(movie.title, searchTitle, tmdbMovie.title, tmdbMovie.original_title); + if (score > bestScore) { + bestScore = score; + bestMatch = movie; + } + } + + // 4. Si trouvé avec un bon score, récupérer les sources (seuil strict pour éviter faux positifs) + if (bestMatch && bestScore >= 0.8) { + const movieData = await fetchDragivMovieData(bestMatch.id); + + // Vérification post-fetch : le titre de la page Dragiv doit aussi correspondre au film TMDB + if (movieData.success && movieData.title) { + const postFetchScore = calculateDragivMatchScore(movieData.title, searchTitle, tmdbMovie.title, tmdbMovie.original_title); + if (postFetchScore < 0.5) { + console.warn(`[DRAGIV] Post-fetch title mismatch: page="${movieData.title}" vs tmdb="${tmdbMovie.title}" (score=${postFetchScore})`); + return { + success: false, + error: 'Movie not found on Dragiv (post-fetch title mismatch)', + tmdb_id: parseInt(tmdbId), + searched_title: searchTitle, + best_match: { title: bestMatch.title, score: bestScore }, + page_title: movieData.title, + page_score: postFetchScore + }; + } + } + + if (movieData.success) { + return { + success: true, + tmdb_id: parseInt(tmdbId), + tmdb: { + id: tmdbMovie.id, + title: tmdbMovie.title, + original_title: tmdbMovie.original_title, + overview: tmdbMovie.overview, + release_date: tmdbMovie.release_date, + vote_average: tmdbMovie.vote_average, + poster_path: tmdbMovie.poster_path ? `https://image.tmdb.org/t/p/w500${tmdbMovie.poster_path}` : null, + backdrop_path: tmdbMovie.backdrop_path ? `https://image.tmdb.org/t/p/original${tmdbMovie.backdrop_path}` : null, + genres: tmdbMovie.genres || [], + runtime: tmdbMovie.runtime + }, + dragiv: { + id: movieData.id, + title: movieData.title, + movieUrl: movieData.movieUrl, + iframeUrl: movieData.iframeUrl, + m3u8: movieData.m3u8, + qualities: movieData.qualities, + provider: movieData.provider, + referer: movieData.referer + }, + match_score: bestScore, + source: 'dragiv' + }; + } + } + + // 5. Pas trouvé + return { + success: false, + error: 'Movie not found on Dragiv', + tmdb_id: parseInt(tmdbId), + searched_title: searchTitle, + best_match: bestMatch ? { title: bestMatch.title, score: bestScore } : null + }; + + } catch (error) { + console.error('[DRAGIV] fetchDragivByTmdbId error:', error.message); + return { success: false, error: error.message, tmdb_id: tmdbId }; + } +} + +/** + * Background update du cache Dragiv + */ +async function updateDragivCache(cacheKey, tmdbid) { + try { + const newData = await fetchDragivByTmdbId(tmdbid); + if (newData && newData.success) { + await fsp.writeFile(path.join(CACHE_DIR.DRAGIV, `${cacheKey}.json`), JSON.stringify(newData), 'utf-8'); + console.log(`[DRAGIV Cache] Updated background cache for movie ${tmdbid}`); + } + } catch (error) { + // Ne pas toucher au cache existant en cas d'erreur + } +} + +console.log('✅ DRAGIV source loaded (films only)'); + +// =========================================================================================== +// ===== FRANCE.TV (FTV) SOURCE — Recherche + épisodes d'une série/collection ===== +// =========================================================================================== + +const FTV_BASE = 'https://www.france.tv'; + +// --- FTV: Cache du next-action hash (TTL 30 min) --- +let ftvNextActionHash = null; +let ftvNextActionExpiry = 0; + +// Headers complets pour simuler un vrai navigateur Chrome sur france.tv +const FTV_BROWSER_HEADERS = { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36', + 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8', + 'Accept-Language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7', + 'Accept-Encoding': 'gzip, deflate, br, zstd', + 'Cache-Control': 'no-cache', + 'Pragma': 'no-cache', + 'Sec-Ch-Ua': '"Chromium";v="131", "Not_A Brand";v="24"', + 'Sec-Ch-Ua-Mobile': '?0', + 'Sec-Ch-Ua-Platform': '"Windows"', + 'Sec-Fetch-Dest': 'document', + 'Sec-Fetch-Mode': 'navigate', + 'Sec-Fetch-Site': 'none', + 'Sec-Fetch-User': '?1', + 'Upgrade-Insecure-Requests': '1', +}; + +/** + * Récupère dynamiquement le hash next-action depuis la page /recherche/ + * Ce hash change à chaque redéploiement de france.tv (Next.js Server Actions). + * + * Étapes : + * 1. GET https://www.france.tv/recherche/ + * 2. Trouver le <script src="/_next/static/chunks/app/recherche/page-XXXX.js"> + * 3. GET ce fichier JS + * 4. Extraire le hash de createServerReference("HASH", ...) + * + * Retente jusqu'à 3 fois en cas d'échec (connexion directe, sans proxy). + */ +async function getFtvNextActionHash() { + const now = Date.now(); + if (ftvNextActionHash && now < ftvNextActionExpiry) { + return ftvNextActionHash; + } + + const MAX_RETRIES = 3; + + for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) { + console.log(`[FTV] Fetching next-action hash (attempt ${attempt}/${MAX_RETRIES}, direct) ...`); + + try { + // Étape 1: Charger la page /recherche/ + const pageResponse = await axios.get(`${FTV_BASE}/recherche/`, { + headers: { ...FTV_BROWSER_HEADERS }, + proxy: false, + timeout: 15000, + maxRedirects: 5, + }); + + const html = pageResponse.data; + let hash = null; + + // Étape 2: Trouver le script chunk de la page recherche + // Pattern: <script src="/_next/static/chunks/app/recherche/page-XXXX.js" async=""> + const scriptMatch = html.match(/<script[^>]+src="(\/_next\/static\/chunks\/app\/recherche\/page-[^"]+\.js)"/); + + if (scriptMatch) { + const scriptUrl = `${FTV_BASE}${scriptMatch[1]}`; + console.log(`[FTV] Found recherche chunk: ${scriptUrl}`); + + // Étape 3: Télécharger le fichier JS + try { + const jsResponse = await axios.get(scriptUrl, { + headers: { + 'User-Agent': FTV_BROWSER_HEADERS['User-Agent'], + 'Accept': '*/*', + 'Accept-Language': 'fr-FR,fr;q=0.9', + 'Accept-Encoding': 'gzip, deflate, br, zstd', + 'Referer': `${FTV_BASE}/recherche/`, + 'Sec-Ch-Ua': FTV_BROWSER_HEADERS['Sec-Ch-Ua'], + 'Sec-Ch-Ua-Mobile': '?0', + 'Sec-Ch-Ua-Platform': '"Windows"', + 'Sec-Fetch-Dest': 'script', + 'Sec-Fetch-Mode': 'no-cors', + 'Sec-Fetch-Site': 'same-origin', + }, + proxy: false, + timeout: 15000, + }); + + const jsCode = jsResponse.data; + + // Étape 4: Extraire le hash de createServerReference("HASH", ...) + const serverRefMatch = jsCode.match(/createServerReference\)\s*\(\s*"([a-f0-9]{40,})"/); + if (serverRefMatch) { + hash = serverRefMatch[1]; + console.log(`[FTV] Found next-action hash via createServerReference: ${hash}`); + } + + // Fallback: chercher aussi le pattern searchAction + if (!hash) { + const searchActionMatch = jsCode.match(/"([a-f0-9]{40,})"[^]*?"searchAction"/); + if (searchActionMatch) { + hash = searchActionMatch[1]; + console.log(`[FTV] Found next-action hash via searchAction: ${hash}`); + } + } + } catch (jsErr) { + console.error(`[FTV] Error fetching JS chunk: ${jsErr.message}`); + } + } else { + console.warn('[FTV] Could not find recherche page chunk script tag'); + } + + // Fallback: chercher directement dans le HTML + if (!hash) { + const actionIdMatch = html.match(/\$ACTION_ID_([a-f0-9]{40,})/); + if (actionIdMatch) { + hash = actionIdMatch[1]; + console.log(`[FTV] Found next-action hash via $ACTION_ID_ fallback: ${hash}`); + } + } + + if (hash) { + ftvNextActionHash = hash; + ftvNextActionExpiry = now + 30 * 60 * 1000; // Cache 30 min + return hash; + } + + console.warn(`[FTV] Attempt ${attempt}: could not extract hash from page content`); + } catch (err) { + console.error(`[FTV] Attempt ${attempt} failed (direct): ${err.response?.status || err.message}`); + if (attempt < MAX_RETRIES) { + // Petit délai avant de retry avec un autre proxy + await new Promise(r => setTimeout(r, 500)); + } + } + } + + console.warn('[FTV] Could not extract next-action hash after all retries'); + return null; +} + +/** + * POST /api/ftv/search + * Body: { "query": "ninjago" } + * Recherche sur france.tv et renvoie les programmes (séries/collections) et vidéos individuelles. + */ +app.post('/api/ftv/search', async (req, res) => { + try { + const { query } = req.body; + if (!query || typeof query !== 'string' || !query.trim()) { + return res.status(400).json({ success: false, error: 'Le paramètre "query" est requis' }); + } + + const searchTerm = query.trim(); + + // Check cache (1h expiration for search) + const cacheKey = generateCacheKey(`ftv_search_${searchTerm.toLowerCase()}`); + const cached = await getFromCacheWithExpiration(CACHE_DIR.FTV, cacheKey, 1); + if (cached) { + console.log(`[FTV] Search cache hit for "${searchTerm}"`); + return res.json(cached); + } + + // Récupérer dynamiquement le hash next-action (change à chaque déploiement de france.tv) + const nextActionHash = await getFtvNextActionHash(); + if (!nextActionHash) { + return res.status(502).json({ success: false, error: 'Impossible de récupérer le hash de recherche France.tv. Le site a peut-être changé.' }); + } + + console.log(`[FTV] Using next-action hash: ${nextActionHash}`); + + const response = await axios.post(`${FTV_BASE}/recherche/`, [searchTerm], { + headers: { + 'accept': 'text/x-component', + 'accept-encoding': 'gzip, deflate, br, zstd', + 'accept-language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7', + 'cache-control': 'no-cache', + 'content-type': 'text/plain;charset=UTF-8', + 'next-action': nextActionHash, + 'next-router-state-tree': '%5B%22%22%2C%7B%22children%22%3A%5B%22recherche%22%2C%7B%22children%22%3A%5B%22__PAGE__%22%2C%7B%7D%2Cnull%2Cnull%5D%7D%2Cnull%2Cnull%5D%7D%2Cnull%2Cnull%2Ctrue%5D', + 'origin': FTV_BASE, + 'pragma': 'no-cache', + 'priority': 'u=1, i', + 'referer': `${FTV_BASE}/recherche/`, + 'sec-ch-ua': '"Chromium";v="131", "Not_A Brand";v="24"', + 'sec-ch-ua-mobile': '?0', + 'sec-ch-ua-platform': '"Windows"', + 'sec-fetch-dest': 'empty', + 'sec-fetch-mode': 'cors', + 'sec-fetch-site': 'same-origin', + 'user-agent': FTV_BROWSER_HEADERS['User-Agent'], + }, + proxy: false, + timeout: 15000, + validateStatus: () => true, + }); + + console.log(`[FTV] Search response status: ${response.status}`); + const text = typeof response.data === 'string' ? response.data : JSON.stringify(response.data); + console.log(`[FTV] Response text length: ${text.length}`); + + // Si 404, le hash a expiré entre-temps, forcer un refresh + if (response.status === 404) { + console.warn('[FTV] Got 404 — next-action hash is stale, invalidating cache...'); + ftvNextActionHash = null; + ftvNextActionExpiry = 0; + return res.json({ success: true, programs: [], videos: [], error_hint: 'Hash expiré, réessayez' }); + } + + // Parse RSC streaming format: lines like "1:{...json...}" + const lines = text.split('\n'); + let searchData = null; + for (const line of lines) { + if (line.trim()) console.log(`[FTV] RSC Line prefix: ${line.substring(0, 10)}...`); + // Chercher la ligne de données — peut commencer par 1:, 2:, etc. + const dataMatch = line.match(/^(\d+):\s*(\{.+)/); + if (dataMatch) { + console.log(`[FTV] Found data line starting with ${dataMatch[1]}: (length ${line.length})`); + try { + const parsed = JSON.parse(dataMatch[2]); + // Le résultat de recherche contient taxonomy et/ou video + if (parsed.taxonomy || parsed.video) { + searchData = parsed; + console.log(`[FTV] Parsed success. Taxonomy items: ${parsed.taxonomy ? parsed.taxonomy.length : 0}, Videos: ${parsed.video ? parsed.video.length : 0}`); + break; + } + } catch (e) { + console.error(`[FTV] JSON Parse error on line ${dataMatch[1]}:: ${e.message}`); + } + } + } + + if (!searchData) { + console.log('[FTV] No searchData found in RSC response lines.'); + // Log premiers 500 chars pour debug + console.log(`[FTV] Response preview: ${text.substring(0, 500)}`); + return res.json({ success: true, programs: [], videos: [] }); + } + + // Extract programs from taxonomy array + const programs = (searchData.taxonomy || []) + .filter(item => item.content && item.content.url) + .map(item => ({ + title: item.content.title || '', + description: item.content.description || '', + url: `${FTV_BASE}${item.content.url}`, + thumbnail: item.content.thumbnail?.x2 || item.content.thumbnail?.x1 || null, + type: item.content.type || 'program', // "program" or "collection" + channel: item.content.channel || null, + category: item.content.category?.label || null, + program_id: item.tracking?.program_id || null, + })); + + // Extract videos (individual episodes / films) + const videos = (searchData.video || []) + .filter(item => item.content && item.content.url) + .map(item => ({ + title: item.content.title || '', + titleLeading: item.content.titleLeading || '', + description: item.content.description || '', + url: `${FTV_BASE}${item.content.url}`, + thumbnail: item.content.thumbnail?.x2 || item.content.thumbnail?.x1 || null, + type: item.content.type || 'video', + channel: item.content.channel || null, + category: item.content.category?.label || null, + id: item.content.id || null, + season: item.content.title?.match(/^S(\d+)/)?.[1] || null, + episode: item.content.title?.match(/E(\d+)/)?.[1] || null, + csa: item.content.csa || null, + caption: item.content.caption || null, + })); + + console.log(`[FTV] Search results - Programs: ${programs.length}, Videos: ${videos.length}`); + const searchResult = { success: true, programs, videos }; + await saveToCache(CACHE_DIR.FTV, cacheKey, searchResult); + return res.json(searchResult); + + } catch (error) { + console.error('[FTV] Search error:', error.message); + return res.status(500).json({ success: false, error: error.message }); + } +}); + +/** + * GET /api/ftv/episodes?url=https://www.france.tv/france-3/lego-ninjago + * Récupère la page d'un programme et extrait tous les épisodes disponibles. + * Retourne la liste des épisodes avec leur URL d'extraction. + */ +app.get('/api/ftv/episodes', async (req, res) => { + try { + const { url } = req.query; + if (!url || !url.includes('france.tv')) { + return res.status(400).json({ success: false, error: 'URL france.tv requise' }); + } + + // Check cache (4h expiration for episodes) + const epCacheKey = generateCacheKey(`ftv_episodes_${url}`); + const epCached = await getFromCacheWithExpiration(CACHE_DIR.FTV, epCacheKey, 4); + if (epCached) { + console.log(`[FTV] Episodes cache hit for ${url}`); + return res.json(epCached); + } + + const response = await axios.get(url, { + headers: { ...FTV_BROWSER_HEADERS }, + proxy: false, + timeout: 15000, + }); + + const html = response.data; + const episodes = []; + const seen = new Set(); + + // Extract JSON data from self.__next_f.push() calls in the HTML + const scriptRegex = /self\.__next_f\.push\(\[1,"(.*?)"\]\)/gs; + let scriptMatch; + let fullJsonText = ''; + + while ((scriptMatch = scriptRegex.exec(html)) !== null) { + // Unescape the string content + let chunk = scriptMatch[1]; + try { + // The content is JSON-escaped (\\", \\n, \\u00xx, etc.) + chunk = JSON.parse(`"${chunk}"`); + } catch { /* use as-is */ } + fullJsonText += chunk; + } + + // Find video objects within the extracted text + // Pattern: objects with "url" containing france.tv path and "type":"video" + const videoPattern = /"content"\s*:\s*\{[^}]*"url"\s*:\s*"(\/[^"]+\.html)"[^}]*"type"\s*:\s*"video"/g; + let videoMatch; + + // More robust: find all JSON-like structures with video content + // Scan for content objects that have a url ending in .html and type=video + const contentBlockRegex = /\{"ariaLabel":\s*"[^"]*"[^]*?"content":\s*\{[^]*?"url":\s*"(\/[^"]+)"[^]*?"type":\s*"video"[^]*?\}[^]*?"variant":\s*"[^"]*"\}/g; + + // Simpler approach: find all url+title pairs from the JSON data + // Look for patterns like: "url":"/france-3/lego-ninjago/saison-17/7075787-les-disparus.html" + const urlTitleRegex = /"title"\s*:\s*"([^"]+)"[^]*?"titleLeading"\s*:\s*"([^"]*)"[^]*?"url"\s*:\s*"(\/[^"]+\.html)"|"url"\s*:\s*"(\/[^"]+\.html)"[^]*?"title"\s*:\s*"([^"]+)"/g; + + // Better: parse all the JSON chunks individually + // Each push contains partial RSC data; some contain full JSON arrays / objects + const allJsonChunks = []; + const jsonArrayRegex = /\[[\s\S]*?\{[\s\S]*?"content"[\s\S]*?"url"[\s\S]*?\}[\s\S]*?\]/g; + + // Actually, let's use a targeted regex to extract episode data + // from the full text blob. Each video entry looks like: + // "title":"S17 E11 - Les drainés","titleLeading":"Ninjago"..."url":"/france-3/lego-ninjago/saison-17/7452542-les-draines.html"..."type":"video" + + // Collect all .html URLs that are episode links + const episodeUrlRegex = /("url"\s*:\s*")(\/[^"]+\/(\d+)-[^"]+\.html)(")/g; + const titleRegex = /"title"\s*:\s*"([^"]+)"/g; + const titleLeadingRegex = /"titleLeading"\s*:\s*"([^"]+)"/g; + const descRegex = /"description"\s*:\s*"([^"]*(?:\\.[^"]*)*)"/g; + const thumbRegex1 = /"x2"\s*:\s*"(https:\/\/medias\.france\.tv\/[^"]+)"/g; + const idRegex = /"id"\s*:\s*(\d{4,})/g; + + // Most reliable: extract via Cheerio + script parsing + const $ = cheerio.load(html); + + // Gather ALL text from __next_f scripts + let allScriptData = ''; + $('script').each((_, el) => { + const raw = $(el).html() || ''; + if (raw.includes('__next_f')) { + const pushMatch = raw.match(/self\.__next_f\.push\(\[1,"(.*)"\]\)/s); + if (pushMatch) { + try { + allScriptData += JSON.parse(`"${pushMatch[1]}"`); + } catch { + allScriptData += pushMatch[1]; + } + } + } + }); + + // Now parse the concatenated text to find video objects + // Split by "variant" which marks the end of each card object + const cardChunks = allScriptData.split('"variant"'); + + for (const chunk of cardChunks) { + // Check if this chunk has a video-type content with a .html URL + if (!chunk.includes('"type":"video"') && !chunk.includes('"type": "video"')) continue; + + const urlMatch = chunk.match(/"url"\s*:\s*"(\/[^"]+\.html)"/); + if (!urlMatch) continue; + + const epUrl = urlMatch[1]; + if (seen.has(epUrl)) continue; + seen.add(epUrl); + + // Extract fields from this chunk + const titleMatch = chunk.match(/"title"\s*:\s*"([^"]+)"/); + const leadMatch = chunk.match(/"titleLeading"\s*:\s*"([^"]+)"/); + const descMatch = chunk.match(/"description"\s*:\s*"([^"]*(?:\\.[^"]*)*)"/); + const thumbMatch = chunk.match(/"x2"\s*:\s*"(https:\/\/medias\.france\.tv\/[^"]+)"/); + const idMatch = chunk.match(/"id"\s*:\s*(\d{4,})/); + const csaMatch = chunk.match(/"csa"\s*:\s*"([^"]+)"/); + + const title = titleMatch ? titleMatch[1] : ''; + const seasonMatch = title.match(/^S(\d+)/); + const episodeMatch = title.match(/E(\d+)/); + + let desc = descMatch ? descMatch[1] : ''; + try { desc = JSON.parse(`"${desc}"`); } catch { /* use as-is */ } + + episodes.push({ + title: title, + program: leadMatch ? leadMatch[1] : '', + description: desc, + url: `${FTV_BASE}${epUrl}`, + thumbnail: thumbMatch ? thumbMatch[1] : null, + id: idMatch ? parseInt(idMatch[1]) : null, + season: seasonMatch ? parseInt(seasonMatch[1]) : null, + episode: episodeMatch ? parseInt(episodeMatch[1]) : null, + csa: csaMatch ? csaMatch[1] : null, + }); + } + + // Sort by season then episode + episodes.sort((a, b) => { + if (a.season !== b.season) return (a.season || 0) - (b.season || 0); + return (a.episode || 0) - (b.episode || 0); + }); + + const episodesResult = { + success: true, + program_url: url, + total: episodes.length, + episodes, + }; + await saveToCache(CACHE_DIR.FTV, epCacheKey, episodesResult); + return res.json(episodesResult); + + } catch (error) { + console.error('[FTV] Episodes error:', error.message); + return res.status(500).json({ success: false, error: error.message }); + } +}); + +/** + * GET /api/ftv/info?url=https://www.france.tv/france-5/le-monde-de-jamy/... + * Récupère les informations d'une page film (player) ou série (programme). + * Détecte automatiquement le type de page et retourne les données structurées. + */ +app.get('/api/ftv/info', async (req, res) => { + try { + const { url } = req.query; + if (!url || !url.includes('france.tv')) { + return res.status(400).json({ success: false, error: 'URL france.tv requise' }); + } + + // Check cache (4h expiration for info) + const infoCacheKey = generateCacheKey(`ftv_info_${url}`); + const infoCached = await getFromCacheWithExpiration(CACHE_DIR.FTV, infoCacheKey, 4); + if (infoCached) { + console.log(`[FTV] Info cache hit for ${url}`); + return res.json(infoCached); + } + + const response = await axios.get(url, { + headers: { ...FTV_BROWSER_HEADERS }, + proxy: false, + timeout: 15000, + }); + + const html = response.data; + + // ---- Extract all RSC data from self.__next_f.push() calls ---- + const pushRegex = /self\.__next_f\.push\(\[1,\s*"((?:[^"\\]|\\.)*)"\]\)/g; + let allRscText = ''; + let pushMatch; + while ((pushMatch = pushRegex.exec(html)) !== null) { + let chunk = pushMatch[1]; + try { chunk = JSON.parse(`"${chunk}"`); } catch { /* use as-is */ } + allRscText += chunk; + } + + // ---- Detect page type ---- + const isPlayer = /"pageType"\s*:\s*"player"/.test(allRscText) || /data-template-id="player-replay"/.test(html); + const isProgramme = /"pageType"\s*:\s*"programme"/.test(allRscText) || /data-template-id="programme"/.test(html); + + if (isPlayer) { + // ===== FILM / VIDEO PAGE ===== + const result = { success: true, type: 'video' }; + + // Extract title - try JSON-LD VideoObject first + const ldJsonRegex = /<script[^>]*type="application\/ld\+json"[^>]*>([\s\S]*?)<\/script>/g; + let ldMatch; + while ((ldMatch = ldJsonRegex.exec(html)) !== null) { + try { + const ld = JSON.parse(ldMatch[1]); + if (ld['@type'] === 'VideoObject') { + result.title = ld.name || ''; + result.description = ld.description || ''; + result.thumbnail = (ld.thumbnailUrl && ld.thumbnailUrl[0]) || ''; + result.duration = ld.duration || ''; + result.director = ld.director ? (ld.director.name || ld.director) : ''; + result.uploadDate = ld.uploadDate || ''; + result.expires = ld.expires || ''; + break; + } + } catch { /* skip invalid JSON-LD */ } + } + + // Extract additional fields from RSC data + const csaMatch = allRscText.match(/"csaCode"\s*:\s*"([^"]+)"/); + result.csa = csaMatch ? csaMatch[1] : null; + + const channelMatch = allRscText.match(/"broadcastChannel"\s*:\s*"([^"]+)"/); + result.channel = channelMatch ? channelMatch[1] : null; + if (!result.channel) { + const ch2 = allRscText.match(/"channel"\s*:\s*"([^"]+)"/); + result.channel = ch2 ? ch2[1] : null; + } + + // Extract title from RSC if not from JSON-LD + if (!result.title) { + const titleMatch = allRscText.match(/"pageName"\s*:\s*"([^"]+)"/); + result.title = titleMatch ? titleMatch[1].replace(/_/g, ' ') : ''; + } + + // Extract description from RSC if not from JSON-LD + if (!result.description) { + const descMatch = allRscText.match(/"description"\s*:\s*"((?:[^"\\]|\\.)*)"/); + if (descMatch) { + try { result.description = JSON.parse(`"${descMatch[1]}"`); } + catch { result.description = descMatch[1]; } + } + } + + // Extract thumbnail from RSC if not from JSON-LD + if (!result.thumbnail) { + const thumbMatch = allRscText.match(/"vignette_16x9"[^}]*?"1800"\s*:\s*"([^"]+)"/); + result.thumbnail = thumbMatch ? thumbMatch[1] : null; + if (!result.thumbnail) { + const thumbAlt = allRscText.match(/https:\/\/medias\.france\.tv\/[^"]+\.jpg/); + result.thumbnail = thumbAlt ? thumbAlt[0] : null; + } + } + + // Extract duration in seconds from RSC if available + const durationSecMatch = allRscText.match(/"duration"\s*:\s*(\d{2,})/); + result.durationSeconds = durationSecMatch ? parseInt(durationSecMatch[1]) : null; + + // Extract program name + const progMatch = allRscText.match(/"programName"\s*:\s*"([^"]+)"/); + result.program = progMatch ? progMatch[1].replace(/_/g, ' ') : null; + + // Extract categories + const catMatch = allRscText.match(/"categories"\s*:\s*\["([^"]+)"\]/); + result.category = catMatch ? catMatch[1] : null; + + await saveToCache(CACHE_DIR.FTV, infoCacheKey, result); + return res.json(result); + } else if (isProgramme) { + // ===== SÉRIE / PROGRAMME PAGE ===== + const result = { success: true, type: 'programme' }; + + // Extract programme title from <title> tag or RSC + const titleTagMatch = html.match(/<title[^>]*>([^<]+)<\/title>/); + result.title = titleTagMatch ? titleTagMatch[1].replace(/ - (Regarder|France \d|France\.tv).*$/i, '').trim() : ''; + + // Extract description + const metaDescMatch = html.match(/<meta\s+name="description"\s+content="([^"]+)"/); + result.description = metaDescMatch ? metaDescMatch[1] : ''; + + // Try to get full description from RSC if meta one is truncated + if (result.description.endsWith('...') || result.description.endsWith('…') || result.description.length < 150) { + const rscDescMatch = allRscText.match(/"description"\s*:\s*"((?:[^"\\]|\\.)*)"/); + if (rscDescMatch) { + try { + const parsedDesc = JSON.parse(`"${rscDescMatch[1]}"`); + if (parsedDesc.length > result.description.length) { + result.description = parsedDesc; + } + } catch { + if (rscDescMatch[1].length > result.description.length) { + result.description = rscDescMatch[1]; + } + } + } + } + + // Extract thumbnail from og:image + const ogImageMatch = html.match(/<meta\s+property="og:image"\s+content="([^"]+)"/); + result.thumbnail = ogImageMatch ? ogImageMatch[1] : null; + + // Extract channel + const channelMatch = allRscText.match(/"channel"\s*:\s*"([^"]+)"/); + result.channel = channelMatch ? channelMatch[1] : null; + + // Extract program_id + const progIdMatch = allRscText.match(/"program_id"\s*:\s*"(\d+)"/); + result.programId = progIdMatch ? progIdMatch[1] : null; + + // Extract category + const catMatch = allRscText.match(/"category"\s*:\s*"([^"]+)"/); + result.category = catMatch ? catMatch[1] : null; + + // ---- Extract cast/crew from RSC text ---- + const directorMatch = allRscText.match(/Réalisé par\s*:\s*([^"\\]+)/); + result.director = directorMatch ? directorMatch[1].trim() : null; + + const castMatch = allRscText.match(/Avec\s*:\s*([^"\\]+)/); + result.cast = castMatch ? castMatch[1].trim() : null; + + // ---- Extract seasons and episodes ---- + const seasons = []; + const $ = cheerio.load(html); + + // Gather ALL text from __next_f scripts + let allScriptData = ''; + $('script').each((_, el) => { + const raw = $(el).html() || ''; + if (raw.includes('__next_f')) { + const pm = raw.match(/self\.__next_f\.push\(\[1,"(.*)"\]\)/s); + if (pm) { + try { allScriptData += JSON.parse(`"${pm[1]}"`); } + catch { allScriptData += pm[1]; } + } + } + }); + + // Find seasonsMap data - look for array of [seasonName, {contents, href}] + // The seasonsMap is encoded in RSC chunks as arrays of tuples + const seasonRegex = /\[\s*"(Saison\s+\d+)"[^]*?"contents"\s*:\s*\[([\s\S]*?)\]\s*,\s*"href"\s*:\s*"([^"]+)"\s*\}/g; + let seasonMatch; + + // More robust approach: split by "Saison" markers and extract episode blocks + const seasonSplits = allScriptData.split(/(?=\["Saison\s+\d+")/); + + for (const block of seasonSplits) { + const nameMatch = block.match(/^\["(Saison\s+\d+)"/); + if (!nameMatch) continue; + + const seasonName = nameMatch[1]; + const seasonNum = parseInt(seasonName.match(/\d+/)[0]); + const episodes = []; + const seen = new Set(); + + // Split by "variant" to find individual episode cards + const cardChunks = block.split('"variant"'); + + for (const chunk of cardChunks) { + if (!chunk.includes('"type":"video"')) continue; + + const urlMatch = chunk.match(/"url"\s*:\s*"(\/[^"]+\.html)"/); + if (!urlMatch) continue; + + const epUrl = urlMatch[1]; + if (seen.has(epUrl)) continue; + seen.add(epUrl); + + const titleMatch = chunk.match(/"title"\s*:\s*"([^"]+)"/); + const leadMatch = chunk.match(/"titleLeading"\s*:\s*"([^"]+)"/); + const descMatch = chunk.match(/"description"\s*:\s*"((?:[^"\\]|\\.)*)"/); + const thumbMatch = chunk.match(/"x2"\s*:\s*"(https:\/\/[^"]+)"/); + const idMatch = chunk.match(/"content_id"\s*:\s*(\d+)/); + if (!idMatch) { + var idMatch2 = chunk.match(/"id"\s*:\s*(\d{4,})/); + } + const csaMatch = chunk.match(/"csa"\s*:\s*"([^"]+)"/); + const durationMatch = chunk.match(/"duration"\s*:\s*"([^"]+)"/); + const vfIdMatch = chunk.match(/"video_factory_id"\s*:\s*"([0-9a-f-]{36})"/); + + const title = titleMatch ? titleMatch[1] : ''; + const epNumMatch = title.match(/E(\d+)/); + + let desc = descMatch ? descMatch[1] : ''; + try { desc = JSON.parse(`"${desc}"`); } catch { /* use as-is */ } + + episodes.push({ + title, + program: leadMatch ? leadMatch[1] : '', + description: desc, + url: `${FTV_BASE}${epUrl}`, + thumbnail: thumbMatch ? thumbMatch[1] : null, + contentId: (idMatch ? parseInt(idMatch[1]) : (idMatch2 ? parseInt(idMatch2[1]) : null)), + videoId: vfIdMatch ? vfIdMatch[1] : null, + season: seasonNum, + episode: epNumMatch ? parseInt(epNumMatch[1]) : null, + csa: csaMatch ? csaMatch[1] : null, + duration: durationMatch ? durationMatch[1] : null, + }); + } + + // Sort episodes by episode number + episodes.sort((a, b) => (a.episode || 0) - (b.episode || 0)); + + if (episodes.length > 0) { + seasons.push({ + name: seasonName, + number: seasonNum, + episodeCount: episodes.length, + episodes, + }); + } + } + + // If no seasons found with the split approach, try the card-based approach from /episodes + if (seasons.length === 0) { + const episodes = []; + const seen = new Set(); + const cardChunks = allScriptData.split('"variant"'); + + for (const chunk of cardChunks) { + if (!chunk.includes('"type":"video"')) continue; + const urlMatch = chunk.match(/"url"\s*:\s*"(\/[^"]+\.html)"/); + if (!urlMatch) continue; + const epUrl = urlMatch[1]; + if (seen.has(epUrl)) continue; + seen.add(epUrl); + + const titleMatch = chunk.match(/"title"\s*:\s*"([^"]+)"/); + const leadMatch = chunk.match(/"titleLeading"\s*:\s*"([^"]+)"/); + const descMatch = chunk.match(/"description"\s*:\s*"((?:[^"\\]|\\.)*)"/); + const thumbMatch = chunk.match(/"x2"\s*:\s*"(https:\/\/[^"]+)"/); + const idMatch = chunk.match(/"content_id"\s*:\s*(\d+)/) || chunk.match(/"id"\s*:\s*(\d{4,})/); + const vfIdMatch = chunk.match(/"video_factory_id"\s*:\s*"([0-9a-f-]{36})"/); + const durationMatch = chunk.match(/"duration"\s*:\s*"([^"]+)"/); + const csaMatch = chunk.match(/"csa"\s*:\s*"([^"]+)"/); + const title = titleMatch ? titleMatch[1] : ''; + + let desc = descMatch ? descMatch[1] : ''; + try { desc = JSON.parse(`"${desc}"`); } catch {} + + const seasonMatch = title.match(/S(\d+)/); + const epMatch = title.match(/E(\d+)/); + + episodes.push({ + title, + program: leadMatch ? leadMatch[1] : '', + description: desc, + url: `${FTV_BASE}${epUrl}`, + thumbnail: thumbMatch ? thumbMatch[1] : null, + contentId: idMatch ? parseInt(idMatch[1]) : null, + videoId: vfIdMatch ? vfIdMatch[1] : null, + season: seasonMatch ? parseInt(seasonMatch[1]) : null, + episode: epMatch ? parseInt(epMatch[1]) : null, + csa: csaMatch ? csaMatch[1] : null, + duration: durationMatch ? durationMatch[1] : null, + }); + } + + if (episodes.length > 0) { + // Group by season + const seasonMap = {}; + for (const ep of episodes) { + const sNum = ep.season || 1; + if (!seasonMap[sNum]) seasonMap[sNum] = []; + seasonMap[sNum].push(ep); + } + for (const [sNum, eps] of Object.entries(seasonMap)) { + eps.sort((a, b) => (a.episode || 0) - (b.episode || 0)); + seasons.push({ + name: `Saison ${sNum}`, + number: parseInt(sNum), + episodeCount: eps.length, + episodes: eps, + }); + } + seasons.sort((a, b) => a.number - b.number); + } + } + + result.seasons = seasons; + result.totalEpisodes = seasons.reduce((sum, s) => sum + s.episodeCount, 0); + + await saveToCache(CACHE_DIR.FTV, infoCacheKey, result); + return res.json(result); + + } else { + // Unknown page type + return res.json({ + success: false, + error: 'Type de page non reconnu (ni player ni programme)', + hint: 'Vérifiez que l\'URL pointe vers un film/vidéo ou une série sur france.tv', + }); + } + + } catch (error) { + console.error('[FTV] Info error:', error.message); + return res.status(500).json({ success: false, error: error.message }); + } +}); + +console.log('✅ FTV (france.tv) source loaded'); diff --git a/API/Mainapi/sharedListsRoutes.js b/API/Mainapi/sharedListsRoutes.js new file mode 100644 index 0000000..cf48622 --- /dev/null +++ b/API/Mainapi/sharedListsRoutes.js @@ -0,0 +1,866 @@ +const express = require('express'); +const router = express.Router(); +const fs = require('fs').promises; +const path = require('path'); +const crypto = require('crypto'); +const jwt = require('jsonwebtoken'); +const axios = require('axios'); +const { getPool } = require('./mysqlPool'); +const { verifyAccessKey } = require('./checkVip'); +const { verifyTurnstileFromRequest } = require('./utils/turnstile'); +// Réutiliser l'instance Redis partagée au lieu d'en créer une nouvelle (évite les fuites mémoire) +const { redis } = require('./config/redis'); + +// === JWT_SECRET === +const JWT_SECRET = process.env.JWT_SECRET; + +// === MySQL pool caché === +let _cachedPool = null; +function getCachedPool() { + if (!_cachedPool) _cachedPool = getPool(); + return _cachedPool; +} + +const SHARED_LIST_CACHE_TTL = 600; // 10 minutes +const USERS_DIR = path.join(__dirname, 'data', 'users'); + +// === OpenRouter API Configuration for content moderation (using Gemini 2.5 Flash Lite) === +const OPENROUTER_API_KEY = process.env.OPENROUTER_API_KEY; +const OPENROUTER_API_URL = 'https://openrouter.ai/api/v1/chat/completions'; +const OPENROUTER_MODEL = 'google/gemini-2.5-flash-lite'; +const FRONTEND_BASE_URL = process.env.FRONTEND_BASE_URL; + +// Fonction de modération des listes partagées avec OpenRouter/Gemini (exécutée en background) +async function moderateSharedListWithGemini(shareId, listName, items, username) { + try { + // Construire un résumé des items de la liste + const itemsSummary = (items || []).slice(0, 30).map(i => `${i.title || i.name || 'Sans titre'} (${i.type || 'inconnu'})`).join(', '); + + const prompt = `Tu es un modérateur de contenu. Analyse le nom de la liste, le pseudo de l'utilisateur, et le contenu de la liste partagée suivants et réponds UNIQUEMENT par un JSON valide. + +Pseudo de l'utilisateur: ${JSON.stringify(username)} +Nom de la liste: ${JSON.stringify(listName)} +Contenu de la liste (titres): ${JSON.stringify(itemsSummary)} + +Critères de modération (s'appliquent au pseudo, au nom de la liste ET au contenu): +1. INSULTES: Le nom de la liste ou le pseudo contient des insultes, injures, propos haineux ou dégradants +2. EROTIQUE: Le nom de la liste ou le pseudo contient du contenu érotique, sexuel ou inapproprié +3. PSEUDO_INAPPROPRIE: Le pseudo contient des insultes, contenu érotique, ou est inapproprié +4. NOM_LISTE_INAPPROPRIE: Le nom de la liste est vulgaire, offensant ou inapproprié +5. CONTENU_INAPPROPRIE: La liste semble être une compilation de contenu à caractère pornographique ou extrêmement violent + +Note: Les films et séries sont des contenus TMDB officiels, donc ils sont généralement acceptables. Ne flagge que si c'est CLAIREMENT inapproprié. + +Réponds UNIQUEMENT avec ce format JSON (sans markdown, sans backticks): +{"flagged": true/false, "reason": "INSULTES" ou "EROTIQUE" ou "PSEUDO_INAPPROPRIE" ou "NOM_LISTE_INAPPROPRIE" ou "CONTENU_INAPPROPRIE" ou null, "details": "explication courte"}`; + + const response = await axios.post( + OPENROUTER_API_URL, + { + model: OPENROUTER_MODEL, + messages: [{ role: 'user', content: prompt }], + max_tokens: 500, + temperature: 0.1 + }, + { + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${OPENROUTER_API_KEY}`, + 'HTTP-Referer': FRONTEND_BASE_URL, + 'X-Title': 'Movix Shared List Moderation' + }, + timeout: 15000 + } + ); + + const responseText = response.data?.choices?.[0]?.message?.content || ''; + + let moderationResult; + try { + const cleanedResponse = responseText.replace(/```json\n?|```\n?/g, '').trim(); + moderationResult = JSON.parse(cleanedResponse); + } catch (parseError) { + console.error('❌ Erreur parsing réponse OpenRouter (shared list):', parseError, 'Response:', responseText); + return { flagged: false }; + } + + if (moderationResult.flagged) { + console.log(`🚨 Liste partagée flaggée (ID: ${shareId}): ${moderationResult.reason} - ${moderationResult.details}`); + + // Marquer la liste comme modérée (retirer du catalogue) + await dbRun( + `UPDATE shared_lists SET is_public_in_catalog = 0, moderation_flagged = 1, moderation_reason = ?, moderation_details = ?, moderated_at = ? WHERE id = ?`, + [moderationResult.reason, moderationResult.details, Date.now(), shareId] + ); + + // Invalider le cache Redis + const row = await dbGet('SELECT share_code FROM shared_lists WHERE id = ?', [shareId]); + if (row) { + try { await redis.del(`sharedList:${row.share_code}`); } catch { /* ignore */ } + } + + console.log(`✅ Liste partagée ID ${shareId} retirée du catalogue pour modération`); + } + + return moderationResult; + } catch (error) { + console.error('❌ Erreur modération OpenRouter shared list (non bloquant):', error.message); + return { flagged: false }; + } +} + +// === Helper MySQL (même pattern que commentsRoutes.js) === +const dbRun = async (sql, params = []) => { + const pool = getCachedPool(); + const [result] = await pool.execute(sql, params); + return { + lastID: result.insertId || 0, + changes: result.affectedRows || 0 + }; +}; + +const dbGet = async (sql, params = []) => { + const pool = getCachedPool(); + const [rows] = await pool.execute(sql, params); + return rows.length > 0 ? rows[0] : null; +}; + +const dbAll = async (sql, params = []) => { + const pool = getCachedPool(); + const [rows] = await pool.execute(sql, params); + return rows; +}; + +// === Init table MySQL === +async function initSharedListsTable() { + try { + const pool = getCachedPool(); + await pool.execute(` + CREATE TABLE IF NOT EXISTS shared_lists ( + id INT AUTO_INCREMENT PRIMARY KEY, + user_id VARCHAR(255) NOT NULL, + user_type VARCHAR(50) NOT NULL, + profile_id VARCHAR(255) NOT NULL, + list_id VARCHAR(255) NOT NULL, + share_code VARCHAR(20) NOT NULL, + is_public_in_catalog TINYINT(1) NOT NULL DEFAULT 0, + moderation_flagged TINYINT(1) NOT NULL DEFAULT 0, + moderation_reason VARCHAR(255), + moderation_details TEXT, + moderated_at BIGINT, + created_at BIGINT NOT NULL, + updated_at BIGINT NOT NULL, + UNIQUE KEY uq_share_code (share_code), + UNIQUE KEY uq_user_list (user_id, user_type, profile_id, list_id), + INDEX idx_shared_lists_share_code (share_code), + INDEX idx_shared_lists_user_profile (user_id, user_type, profile_id), + INDEX idx_shared_lists_moderation (moderation_flagged, is_public_in_catalog) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci + `); + + console.log('✅ Table MySQL shared_lists initialisée'); + } catch (error) { + console.error('❌ Erreur initialisation table MySQL shared_lists:', error.message); + } +} + +// Init table au démarrage (async, non bloquant) +initSharedListsTable(); + +// === Auth middleware (comme commentsRoutes.js) === +const requireAuth = async (req, res, next) => { + const token = req.headers.authorization?.split(' ')[1]; + if (!token) { + return res.status(401).json({ error: 'Non authentifié' }); + } + + try { + const decoded = jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] }); + const { sub: userId, userType, sessionId } = decoded; + + if (!['oauth', 'bip39'].includes(userType) || !userId || !sessionId) { + return res.status(401).json({ error: 'Token invalide' }); + } + + // Vérifier la session en MySQL + const pool = getCachedPool(); + const [rows] = await pool.execute( + 'SELECT id FROM user_sessions WHERE id = ? AND user_id = ? AND user_type = ?', + [sessionId, userId, userType] + ); + + if (rows.length === 0) { + return res.status(401).json({ error: 'Session invalide ou expirée' }); + } + + req.user = { userId, userType, sessionId }; + next(); + } catch (error) { + return res.status(401).json({ error: 'Token invalide' }); + } +}; + +// === Admin middleware — vérifie que l'utilisateur est admin via la table admins MySQL === +const requireAdmin = async (req, res, next) => { + const token = req.headers.authorization?.split(' ')[1]; + if (!token) { + return res.status(401).json({ error: 'Non authentifié' }); + } + + try { + const decoded = jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] }); + const { sub: userId, userType, sessionId } = decoded; + + if (!['oauth', 'bip39'].includes(userType) || !userId || !sessionId) { + return res.status(401).json({ error: 'Token invalide' }); + } + + const pool = getCachedPool(); + + // Vérifier la session + const [sessionRows] = await pool.execute( + 'SELECT id FROM user_sessions WHERE id = ? AND user_id = ? AND user_type = ?', + [sessionId, userId, userType] + ); + if (sessionRows.length === 0) { + return res.status(401).json({ error: 'Session invalide ou expirée' }); + } + + // Vérifier le rôle admin + const [adminRows] = await pool.execute( + 'SELECT * FROM admins WHERE user_id = ? AND auth_type = ?', + [userId, userType === 'bip39' ? 'bip-39' : userType] + ); + if (adminRows.length === 0) { + return res.status(403).json({ error: 'Accès refusé - Droits admin requis' }); + } + + req.user = { userId, userType, sessionId }; + req.admin = { userId, userType, adminId: adminRows[0].id, role: adminRows[0].role || 'admin' }; + next(); + } catch (error) { + return res.status(401).json({ error: 'Token invalide' }); + } +}; + +// === Helper: vérifier que le profileId appartient bien à l'utilisateur === +async function verifyProfileOwnership(userId, userType, profileId) { + try { + const safeUserId = String(userId).replace(/[^a-zA-Z0-9_\-]/g, ''); + const safeProfileId = String(profileId).replace(/[^a-zA-Z0-9_\-]/g, ''); + + let userFilePath; + if (userType === 'bip39') { + userFilePath = path.join(USERS_DIR, `bip39-${safeUserId}.json`); + } else { + userFilePath = path.join(USERS_DIR, `${safeUserId}.json`); + } + + const userFile = await fs.readFile(userFilePath, 'utf8'); + const user = JSON.parse(userFile); + + if (user.profiles) { + return user.profiles.some(p => p.id === profileId); + } + return false; + } catch { + return false; + } +} + +// === Helper: récupérer les données utilisateur (username, avatar, isVip) depuis le profil === +async function getUserProfileData(userId, userType, profileId) { + try { + const safeUserId = String(userId).replace(/[^a-zA-Z0-9_\-]/g, ''); + const safeProfileId = String(profileId).replace(/[^a-zA-Z0-9_\-]/g, ''); + const safeUserType = ['oauth', 'bip39'].includes(userType) ? userType : 'oauth'; + + let userFilePath; + if (userType === 'bip39') { + userFilePath = path.join(USERS_DIR, `bip39-${safeUserId}.json`); + } else { + userFilePath = path.join(USERS_DIR, `${safeUserId}.json`); + } + + let username = 'Utilisateur'; + let avatar = '/avatars/disney/disney_avatar_1.png'; + let isVip = false; + + try { + const userFile = await fs.readFile(userFilePath, 'utf8'); + const user = JSON.parse(userFile); + + if (user.profiles) { + const profile = user.profiles.find(p => p.id === profileId); + if (profile) { + username = profile.name || 'Utilisateur'; + avatar = (profile.avatar && profile.avatar.startsWith('/avatars/')) ? profile.avatar : '/avatars/disney/disney_avatar_1.png'; + } + } + } catch { /* fichier utilisateur introuvable */ } + + // Vérifier le statut VIP en lisant l'access_code depuis les données du profil + try { + const profileDataPath = path.join(USERS_DIR, 'profiles', safeUserType, safeUserId, `${safeProfileId}.json`); + const profileData = JSON.parse(await fs.readFile(profileDataPath, 'utf8')); + const storedAccessCode = profileData.access_code || null; + if (storedAccessCode) { + const vipStatus = await verifyAccessKey(storedAccessCode); + isVip = vipStatus.vip; + } + } catch { /* pas de données de profil ou pas d'access_code */ } + + return { username, avatar, isVip }; + } catch { + return { username: 'Utilisateur', avatar: '/avatars/disney/disney_avatar_1.png', isVip: false }; + } +} + +// === Helper: récupérer la custom_lists depuis le fichier profil data === +async function getProfileCustomLists(userId, userType, profileId) { + try { + const safeUserId = String(userId).replace(/[^a-zA-Z0-9_\-]/g, ''); + const safeProfileId = String(profileId).replace(/[^a-zA-Z0-9_\-]/g, ''); + const safeUserType = ['oauth', 'bip39'].includes(userType) ? userType : 'oauth'; + + const profileDataPath = path.join(USERS_DIR, 'profiles', safeUserType, safeUserId, `${safeProfileId}.json`); + const profileData = JSON.parse(await fs.readFile(profileDataPath, 'utf8')); + + const customListsRaw = profileData.custom_lists; + if (!customListsRaw) return []; + + try { + return JSON.parse(customListsRaw); + } catch { + return []; + } + } catch { + return []; + } +} + +// === Helper: générer un code de partage unique === +function generateShareCode() { + return crypto.randomBytes(6).toString('base64url').slice(0, 10); +} + +// === Helper: construire le cache de la liste partagée et le mettre dans Redis === +async function buildAndCacheSharedList(shareCode, userId, userType, profileId, listId, isPublicInCatalog = false) { + try { + // Récupérer les données du profil (username, avatar) + const profileData = await getUserProfileData(userId, userType, profileId); + + // Récupérer les listes personnalisées du profil + const customLists = await getProfileCustomLists(userId, userType, profileId); + + // Trouver la liste spécifique + const list = customLists.find(l => String(l.id) === String(listId)); + if (!list) { + return null; + } + + const cachedData = { + shareCode, + username: profileData.username, + avatar: profileData.avatar, + isVip: profileData.isVip, + listName: list.name, + items: list.items || [], + itemCount: (list.items || []).length, + isPublicInCatalog: !!isPublicInCatalog, + cachedAt: Date.now() + }; + + // Mettre en cache dans Redis + try { + await redis.set( + `sharedList:${shareCode}`, + JSON.stringify(cachedData), + 'EX', + SHARED_LIST_CACHE_TTL + ); + } catch { /* Redis indisponible */ } + + return cachedData; + } catch (error) { + console.error('Erreur buildAndCacheSharedList:', error.message); + return null; + } +} + + +// ======================================== +// ROUTES +// ======================================== + +// POST /share — Partager une liste +router.post('/share', requireAuth, async (req, res) => { + try { + const { profileId, listId, publishToCatalog, turnstileToken } = req.body; + const { userId, userType } = req.user; + const isPublicInCatalog = !!publishToCatalog; + + // Vérification Turnstile (managed captcha) + const turnstileResult = await verifyTurnstileFromRequest(req, turnstileToken); + if (!turnstileResult.valid) return res.status(turnstileResult.status).json({ error: turnstileResult.error }); + + if (!profileId || !listId) { + return res.status(400).json({ error: 'profileId et listId requis' }); + } + + // Vérifier que le profil appartient bien à l'utilisateur + const isOwner = await verifyProfileOwnership(userId, userType, profileId); + if (!isOwner) { + return res.status(403).json({ error: 'Ce profil ne vous appartient pas' }); + } + + // Vérifier que la liste existe dans les données du profil + const customLists = await getProfileCustomLists(userId, userType, profileId); + const list = customLists.find(l => String(l.id) === String(listId)); + if (!list) { + return res.status(404).json({ error: 'Liste non trouvée' }); + } + + // Vérifier si la liste est déjà partagée + const existing = await dbGet( + 'SELECT share_code FROM shared_lists WHERE user_id = ? AND user_type = ? AND profile_id = ? AND list_id = ?', + [userId, userType, profileId, String(listId)] + ); + + if (existing) { + const now = Date.now(); + await dbRun( + 'UPDATE shared_lists SET is_public_in_catalog = ?, updated_at = ? WHERE user_id = ? AND user_type = ? AND profile_id = ? AND list_id = ?', + [isPublicInCatalog ? 1 : 0, now, userId, userType, profileId, String(listId)] + ); + + // Si on publie au catalogue, reset le flag de modération et lancer modération Gemini en background + if (isPublicInCatalog) { + await dbRun( + 'UPDATE shared_lists SET moderation_flagged = 0, moderation_reason = NULL, moderation_details = NULL, moderated_at = NULL WHERE user_id = ? AND user_type = ? AND profile_id = ? AND list_id = ?', + [userId, userType, profileId, String(listId)] + ); + const existingRecord = await dbGet( + 'SELECT id FROM shared_lists WHERE user_id = ? AND user_type = ? AND profile_id = ? AND list_id = ?', + [userId, userType, profileId, String(listId)] + ); + const profileData = await getUserProfileData(userId, userType, profileId); + moderateSharedListWithGemini(existingRecord.id, list.name, list.items || [], profileData.username) + .catch(err => console.error('Erreur modération Gemini liste (non bloquant):', err)); + } + + // Rafraîchir le cache et retourner le code existant + await buildAndCacheSharedList(existing.share_code, userId, userType, profileId, listId, isPublicInCatalog); + return res.json({ shareCode: existing.share_code, alreadyShared: true, isPublicInCatalog }); + } + + // Générer un code de partage unique + let shareCode; + let attempts = 0; + do { + shareCode = generateShareCode(); + const dup = await dbGet('SELECT id FROM shared_lists WHERE share_code = ?', [shareCode]); + if (!dup) break; + attempts++; + } while (attempts < 10); + + if (attempts >= 10) { + return res.status(500).json({ error: 'Impossible de générer un code unique' }); + } + + const now = Date.now(); + + // Insérer dans MySQL (seulement la référence, pas les données) + await dbRun( + 'INSERT INTO shared_lists (user_id, user_type, profile_id, list_id, share_code, is_public_in_catalog, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', + [userId, userType, profileId, String(listId), shareCode, isPublicInCatalog ? 1 : 0, now, now] + ); + + // Construire et mettre en cache la liste + await buildAndCacheSharedList(shareCode, userId, userType, profileId, listId, isPublicInCatalog); + + // Si publié au catalogue, lancer modération Gemini en background + if (isPublicInCatalog) { + const insertedRecord = await dbGet( + 'SELECT id FROM shared_lists WHERE share_code = ?', + [shareCode] + ); + const profileData = await getUserProfileData(userId, userType, profileId); + moderateSharedListWithGemini(insertedRecord.id, list.name, list.items || [], profileData.username) + .catch(err => console.error('Erreur modération Gemini liste (non bloquant):', err)); + } + + res.json({ shareCode, isPublicInCatalog }); + } catch (error) { + console.error('Erreur POST /share:', error.message); + res.status(500).json({ error: 'Erreur serveur' }); + } +}); + +// DELETE /share — Retirer le partage d'une liste +router.delete('/share', requireAuth, async (req, res) => { + try { + const { profileId, listId } = req.body; + const { userId, userType } = req.user; + + if (!profileId || !listId) { + return res.status(400).json({ error: 'profileId et listId requis' }); + } + + // Vérifier que le profil appartient bien à l'utilisateur + const isOwner = await verifyProfileOwnership(userId, userType, profileId); + if (!isOwner) { + return res.status(403).json({ error: 'Ce profil ne vous appartient pas' }); + } + + // Récupérer le share_code pour invalider le cache + const existing = await dbGet( + 'SELECT share_code FROM shared_lists WHERE user_id = ? AND user_type = ? AND profile_id = ? AND list_id = ?', + [userId, userType, profileId, String(listId)] + ); + + if (!existing) { + return res.status(404).json({ error: 'Partage non trouvé' }); + } + + // Supprimer de MySQL + await dbRun( + 'DELETE FROM shared_lists WHERE user_id = ? AND user_type = ? AND profile_id = ? AND list_id = ?', + [userId, userType, profileId, String(listId)] + ); + + // Invalider le cache Redis + try { + await redis.del(`sharedList:${existing.share_code}`); + } catch { /* Redis indisponible */ } + + res.json({ success: true }); + } catch (error) { + console.error('Erreur DELETE /share:', error.message); + res.status(500).json({ error: 'Erreur serveur' }); + } +}); + +// GET /share/status — Obtenir le status de partage pour les listes d'un profil +router.get('/share/status', requireAuth, async (req, res) => { + try { + const { profileId } = req.query; + const { userId, userType } = req.user; + + if (!profileId) { + return res.status(400).json({ error: 'profileId requis' }); + } + + const shared = await dbAll( + 'SELECT list_id, share_code, created_at, is_public_in_catalog FROM shared_lists WHERE user_id = ? AND user_type = ? AND profile_id = ?', + [userId, userType, profileId] + ); + + // Retourner un objet { listId: shareCode } + const statusMap = {}; + for (const row of shared) { + statusMap[row.list_id] = { + shareCode: row.share_code, + sharedAt: row.created_at, + isPublicInCatalog: !!row.is_public_in_catalog + }; + } + + res.json({ shared: statusMap }); + } catch (error) { + console.error('Erreur GET /share/status:', error.message); + res.status(500).json({ error: 'Erreur serveur' }); + } +}); + +// GET /list/:shareCode — Récupérer une liste partagée (route publique, pas besoin d'auth) +router.get('/list/:shareCode', async (req, res) => { + try { + const { shareCode } = req.params; + + if (!shareCode || shareCode.length > 20) { + return res.status(400).json({ error: 'Code de partage invalide' }); + } + + // Vérifier le cache Redis d'abord + try { + const cached = await redis.get(`sharedList:${shareCode}`); + if (cached) { + return res.json(JSON.parse(cached)); + } + } catch { /* Redis indisponible, on continue */ } + + // Pas de cache : chercher dans MySQL + const shareRecord = await dbGet( + 'SELECT user_id, user_type, profile_id, list_id, is_public_in_catalog FROM shared_lists WHERE share_code = ?', + [shareCode] + ); + + if (!shareRecord) { + return res.status(404).json({ error: 'Liste partagée non trouvée ou expirée' }); + } + + // Reconstruire et mettre en cache + const data = await buildAndCacheSharedList( + shareCode, + shareRecord.user_id, + shareRecord.user_type, + shareRecord.profile_id, + shareRecord.list_id, + !!shareRecord.is_public_in_catalog + ); + + if (!data) { + return res.status(404).json({ error: 'Liste non trouvée dans les données du profil' }); + } + + res.json(data); + } catch (error) { + console.error('Erreur GET /list/:shareCode:', error.message); + res.status(500).json({ error: 'Erreur serveur' }); + } +}); + +// GET /catalog — Récupérer les listes publiques du catalogue (route publique) +router.get('/catalog', async (req, res) => { + try { + const limitRaw = Number(req.query.limit); + const limit = Number.isFinite(limitRaw) ? Math.max(1, Math.min(100, limitRaw)) : 50; + + const rows = await dbAll( + 'SELECT share_code, user_id, user_type, profile_id, list_id, created_at, updated_at, is_public_in_catalog FROM shared_lists WHERE is_public_in_catalog = 1 AND moderation_flagged = 0 ORDER BY updated_at DESC LIMIT ?', + [limit] + ); + + const lists = (await Promise.all( + rows.map(async (row) => { + const data = await buildAndCacheSharedList( + row.share_code, + row.user_id, + row.user_type, + row.profile_id, + row.list_id, + true + ); + + if (!data) return null; + + return { + ...data, + sharedAt: row.created_at, + updatedAt: row.updated_at + }; + }) + )).filter(Boolean); + + res.json({ lists, total: lists.length }); + } catch (error) { + console.error('Erreur GET /catalog:', error.message); + res.status(500).json({ error: 'Erreur serveur' }); + } +}); + + +// ======================================== +// ADMIN ROUTES +// ======================================== + +// GET /admin/public — Lister toutes les listes publiques du catalogue (admin uniquement) +router.get('/admin/public', requireAdmin, async (req, res) => { + try { + const { page = 1, limit = 50, search = '' } = req.query; + const safePage = Math.max(1, parseInt(page) || 1); + const safeLimit = Math.max(1, Math.min(parseInt(limit) || 50, 100)); + const offset = (safePage - 1) * safeLimit; + + const rows = await dbAll( + 'SELECT * FROM shared_lists WHERE is_public_in_catalog = 1 AND moderation_flagged = 0 ORDER BY updated_at DESC LIMIT ? OFFSET ?', + [safeLimit, offset] + ); + + const totalResult = await dbGet( + 'SELECT COUNT(*) as total FROM shared_lists WHERE is_public_in_catalog = 1 AND moderation_flagged = 0' + ); + + // Enrichir avec les données utilisateur et la liste + const enrichedLists = await Promise.all(rows.map(async (row) => { + const data = await buildAndCacheSharedList( + row.share_code, row.user_id, row.user_type, row.profile_id, row.list_id, true + ); + return { + id: row.id, + shareCode: row.share_code, + userId: row.user_id, + userType: row.user_type, + profileId: row.profile_id, + listId: row.list_id, + createdAt: row.created_at, + updatedAt: row.updated_at, + username: data?.username || 'Inconnu', + avatar: data?.avatar || null, + isVip: data?.isVip || false, + listName: data?.listName || 'Sans nom', + itemCount: data?.itemCount || 0, + items: (data?.items || []).slice(0, 6) // max 6 items pour l'aperçu admin + }; + })); + + // Stats globales + const statsResult = await dbGet(` + SELECT + COUNT(*) as total, + SUM(CASE WHEN is_public_in_catalog = 1 AND moderation_flagged = 0 THEN 1 ELSE 0 END) as public_count, + SUM(CASE WHEN moderation_flagged = 1 THEN 1 ELSE 0 END) as moderated_count + FROM shared_lists + `); + + res.json({ + lists: enrichedLists, + total: totalResult.total, + stats: { + total: statsResult.total, + publicCount: statsResult.public_count, + moderatedCount: statsResult.moderated_count + }, + page: safePage, + limit: safeLimit, + hasMore: offset + enrichedLists.length < totalResult.total + }); + } catch (error) { + console.error('Erreur GET /admin/public:', error.message); + res.status(500).json({ error: 'Erreur serveur' }); + } +}); + +// DELETE /admin/public/:id — Supprimer une liste publique (admin uniquement) +router.delete('/admin/public/:id', requireAdmin, async (req, res) => { + try { + const { id } = req.params; + + // Récupérer le share_code pour invalider le cache + const row = await dbGet('SELECT share_code FROM shared_lists WHERE id = ?', [id]); + if (!row) { + return res.status(404).json({ error: 'Liste non trouvée' }); + } + + // Supprimer de MySQL + await dbRun('DELETE FROM shared_lists WHERE id = ?', [id]); + + // Invalider le cache Redis + try { await redis.del(`sharedList:${row.share_code}`); } catch { /* ignore */ } + + console.log(`🗑️ Liste partagée ID ${id} supprimée par admin`); + res.json({ success: true, message: 'Liste supprimée' }); + } catch (error) { + console.error('Erreur DELETE /admin/public/:id:', error.message); + res.status(500).json({ error: 'Erreur serveur' }); + } +}); + +// GET /admin/moderated — Lister les listes flaggées par Gemini (admin uniquement) +router.get('/admin/moderated', requireAdmin, async (req, res) => { + try { + const { page = 1, limit = 50 } = req.query; + const safePage = Math.max(1, parseInt(page) || 1); + const safeLimit = Math.max(1, Math.min(parseInt(limit) || 50, 100)); + const offset = (safePage - 1) * safeLimit; + + const rows = await dbAll( + 'SELECT * FROM shared_lists WHERE moderation_flagged = 1 ORDER BY moderated_at DESC LIMIT ? OFFSET ?', + [safeLimit, offset] + ); + + const totalResult = await dbGet( + 'SELECT COUNT(*) as total FROM shared_lists WHERE moderation_flagged = 1' + ); + + // Enrichir avec les données utilisateur et la liste + const enrichedLists = await Promise.all(rows.map(async (row) => { + const profileData = await getUserProfileData(row.user_id, row.user_type, row.profile_id); + const customLists = await getProfileCustomLists(row.user_id, row.user_type, row.profile_id); + const list = customLists.find(l => String(l.id) === String(row.list_id)); + + return { + id: row.id, + shareCode: row.share_code, + userId: row.user_id, + userType: row.user_type, + profileId: row.profile_id, + listId: row.list_id, + createdAt: row.created_at, + updatedAt: row.updated_at, + moderatedAt: row.moderated_at, + moderationReason: row.moderation_reason, + moderationDetails: row.moderation_details, + username: profileData.username, + avatar: profileData.avatar, + isVip: profileData.isVip, + listName: list?.name || 'Liste supprimée', + itemCount: list?.items?.length || 0, + items: (list?.items || []).slice(0, 6) + }; + })); + + res.json({ + lists: enrichedLists, + total: totalResult.total, + page: safePage, + limit: safeLimit, + hasMore: offset + enrichedLists.length < totalResult.total + }); + } catch (error) { + console.error('Erreur GET /admin/moderated:', error.message); + res.status(500).json({ error: 'Erreur serveur' }); + } +}); + +// PUT /admin/moderated/:id/approve — Approuver une liste modérée (remettre dans le catalogue) +router.put('/admin/moderated/:id/approve', requireAdmin, async (req, res) => { + try { + const { id } = req.params; + + const row = await dbGet('SELECT share_code FROM shared_lists WHERE id = ? AND moderation_flagged = 1', [id]); + if (!row) { + return res.status(404).json({ error: 'Liste modérée non trouvée' }); + } + + // Remettre dans le catalogue et enlever le flag de modération + await dbRun( + 'UPDATE shared_lists SET is_public_in_catalog = 1, moderation_flagged = 0 WHERE id = ?', + [id] + ); + + // Invalider le cache Redis pour forcer un rafraîchissement + try { await redis.del(`sharedList:${row.share_code}`); } catch { /* ignore */ } + + console.log(`✅ Liste partagée ID ${id} approuvée par admin (remise au catalogue)`); + res.json({ success: true, message: 'Liste approuvée et remise au catalogue' }); + } catch (error) { + console.error('Erreur PUT /admin/moderated/:id/approve:', error.message); + res.status(500).json({ error: 'Erreur serveur' }); + } +}); + +// DELETE /admin/moderated/:id — Supprimer définitivement une liste modérée +router.delete('/admin/moderated/:id', requireAdmin, async (req, res) => { + try { + const { id } = req.params; + + const row = await dbGet('SELECT share_code FROM shared_lists WHERE id = ?', [id]); + if (!row) { + return res.status(404).json({ error: 'Liste non trouvée' }); + } + + await dbRun('DELETE FROM shared_lists WHERE id = ?', [id]); + + try { await redis.del(`sharedList:${row.share_code}`); } catch { /* ignore */ } + + console.log(`🗑️ Liste modérée ID ${id} supprimée définitivement par admin`); + res.json({ success: true, message: 'Liste supprimée définitivement' }); + } catch (error) { + console.error('Erreur DELETE /admin/moderated/:id:', error.message); + res.status(500).json({ error: 'Erreur serveur' }); + } +}); + +module.exports = router; diff --git a/API/Mainapi/top10Routes.js b/API/Mainapi/top10Routes.js new file mode 100644 index 0000000..f2ebd58 --- /dev/null +++ b/API/Mainapi/top10Routes.js @@ -0,0 +1,474 @@ +/** + * Movix Top 10 - Public endpoint + * Returns the top 10 most watched movies and series by logged-in users + * Based on aggregated data from wrapped_viewing_data table + * Uses Redis for caching + */ + +const express = require('express'); +const router = express.Router(); +const { fetchTmdbDetails } = require('./utils/tmdbCache'); + +const TMDB_API_URL = 'https://api.themoviedb.org/3'; + +let pool = null; +let redis = null; + +const CACHE_REFRESH = 1800; // 30 min — seuil de rafraîchissement en arrière-plan +const CACHE_TTL = 86400; // 24h — TTL Redis réel (stale-while-revalidate) +const CACHE_PREFIX = 'top10:'; + +// Verrous en mémoire pour éviter les rafraîchissements simultanés +const refreshLocks = new Set(); + +/** + * Initialize with MySQL pool and Redis instance + */ +function initTop10Routes(mysqlPool, redisInstance) { + pool = mysqlPool; + redis = redisInstance || null; +} + +/** + * Redis cache helpers — stale-while-revalidate + * On stocke { data, updatedAt } avec un TTL long (24h). + * Si updatedAt > 30min, on rafraîchit en arrière-plan. + */ +async function cacheGet(key) { + if (!redis) return null; + try { + const raw = await redis.get(`${CACHE_PREFIX}${key}`); + return raw ? JSON.parse(raw) : null; + } catch (err) { + console.warn('[Top10] Redis GET error:', err.message); + return null; + } +} + +async function cacheSet(key, value) { + if (!redis) return; + try { + const wrapper = { data: value, updatedAt: Date.now() }; + await redis.set(`${CACHE_PREFIX}${key}`, JSON.stringify(wrapper), 'EX', CACHE_TTL); + } catch (err) { + console.warn('[Top10] Redis SET error:', err.message); + } +} + +function isStale(wrapper) { + if (!wrapper || !wrapper.updatedAt) return true; + return (Date.now() - wrapper.updatedAt) > CACHE_REFRESH * 1000; +} + +/** + * Fetch TMDB details for enrichment (via tmdbCache Redis centralisé) + */ +async function fetchTMDBDetails(contentId, contentType) { + if (contentType === 'live-tv') return null; + const mediaType = contentType === 'anime' ? 'tv' : contentType; + + const data = await fetchTmdbDetails(TMDB_API_URL, process.env.TMDB_API_KEY, contentId, mediaType, 'fr-FR'); + if (!data) return null; + + return { + title: data.title || data.name, + poster_path: data.poster_path, + backdrop_path: data.backdrop_path, + overview: data.overview, + vote_average: data.vote_average || null, + genres: (data.genres || []).map(g => typeof g === 'string' ? g : g.name), + release_date: data.release_date || data.first_air_date || null, + runtime: data.runtime || data.episode_run_time?.[0] || null, + }; +} + + +/** + * GET /api/top10/movies + * Public - no auth required + * Returns top 10 most watched movies across all logged-in users + */ +router.get('/movies', async (req, res) => { + try { + if (!pool) { + return res.status(503).json({ success: false, error: 'Database not available' }); + } + + // Stale-while-revalidate : renvoyer le cache immédiatement, rafraîchir en arrière-plan + const wrapper = await cacheGet('movies'); + if (wrapper && wrapper.data) { + res.json(wrapper.data); + // Rafraîchir en arrière-plan si périmé + if (isStale(wrapper) && !refreshLocks.has('movies')) { + refreshLocks.add('movies'); + refreshTop10('movies').finally(() => refreshLocks.delete('movies')); + } + return; + } + + // Pas de cache du tout — requête synchrone + const result = await buildTop10Movies(); + await cacheSet('movies', result); + res.json(result); + } catch (error) { + console.error('[Top10] Error fetching movies:', error); + res.status(500).json({ success: false, error: 'Internal server error' }); + } +}); + +/** + * GET /api/top10/tv + * Public - no auth required + * Returns top 10 most watched TV series across all logged-in users + */ +router.get('/tv', async (req, res) => { + try { + if (!pool) { + return res.status(503).json({ success: false, error: 'Database not available' }); + } + + const wrapper = await cacheGet('tv'); + if (wrapper && wrapper.data) { + res.json(wrapper.data); + if (isStale(wrapper) && !refreshLocks.has('tv')) { + refreshLocks.add('tv'); + refreshTop10('tv').finally(() => refreshLocks.delete('tv')); + } + return; + } + + const result = await buildTop10Tv(); + await cacheSet('tv', result); + res.json(result); + } catch (error) { + console.error('[Top10] Error fetching TV:', error); + res.status(500).json({ success: false, error: 'Internal server error' }); + } +}); + +/** + * GET /api/top10/anime + * Public - no auth required + * Returns top 10 most watched anime across all logged-in users + */ +router.get('/anime', async (req, res) => { + try { + if (!pool) { + return res.status(503).json({ success: false, error: 'Database not available' }); + } + + const wrapper = await cacheGet('anime'); + if (wrapper && wrapper.data) { + res.json(wrapper.data); + if (isStale(wrapper) && !refreshLocks.has('anime')) { + refreshLocks.add('anime'); + refreshTop10('anime').finally(() => refreshLocks.delete('anime')); + } + return; + } + + const result = await buildTop10Anime(); + await cacheSet('anime', result); + res.json(result); + } catch (error) { + console.error('[Top10] Error fetching anime:', error); + res.status(500).json({ success: false, error: 'Internal server error' }); + } +}); + +/** + * GET /api/top10/stats + * Public - global platform stats + * Optional query param: + * - type=movies|tv|anime to get stats per category + */ +router.get('/stats', async (req, res) => { + try { + if (!pool) { + return res.status(503).json({ success: false, error: 'Database not available' }); + } + + const requestedType = typeof req.query.type === 'string' ? req.query.type.toLowerCase() : null; + const typeConfig = requestedType ? { + movies: { contentType: 'movie', minDuration: 1200 }, + tv: { contentType: 'tv', minDuration: 300 }, + anime: { contentType: 'anime', minDuration: 300 }, + }[requestedType] : null; + + if (requestedType && !typeConfig) { + return res.status(400).json({ + success: false, + error: 'Invalid type. Allowed values: movies, tv, anime', + }); + } + + const cacheKey = requestedType ? `stats:${requestedType}` : 'stats'; + const wrapper = await cacheGet(cacheKey); + if (wrapper && wrapper.data) { + res.json(wrapper.data); + if (isStale(wrapper) && !refreshLocks.has(cacheKey)) { + refreshLocks.add(cacheKey); + refreshStats(requestedType, typeConfig).finally(() => refreshLocks.delete(cacheKey)); + } + return; + } + + let statsQuery = ` + SELECT + COUNT(DISTINCT user_id) AS total_active_users, + COUNT(DISTINCT content_id) AS total_unique_content, + ROUND(SUM(watch_duration) / 3600, 0) AS total_hours_watched, + COUNT(*) AS total_sessions, + ROUND(AVG(watch_duration) / 60, 0) AS avg_session_minutes, + MIN(created_at) AS data_from, + MAX(created_at) AS data_to + FROM wrapped_viewing_data + WHERE watch_duration >= ? + `; + let statsParams = [300]; + + // watch_duration is stored in SECONDS + if (typeConfig) { + statsQuery = ` + SELECT + COUNT(DISTINCT user_id) AS total_active_users, + COUNT(DISTINCT content_id) AS total_unique_content, + ROUND(SUM(watch_duration) / 3600, 0) AS total_hours_watched, + COUNT(*) AS total_sessions, + ROUND(AVG(watch_duration) / 60, 0) AS avg_session_minutes, + MIN(created_at) AS data_from, + MAX(created_at) AS data_to + FROM wrapped_viewing_data + WHERE content_type = ? + AND watch_duration >= ? + `; + statsParams = [typeConfig.contentType, typeConfig.minDuration]; + } + + const [stats] = await pool.execute(statsQuery, statsParams); + + const result = { + success: true, + type: requestedType || 'global', + stats: { + totalActiveUsers: parseInt(stats[0].total_active_users) || 0, + totalUniqueContent: parseInt(stats[0].total_unique_content) || 0, + totalHoursWatched: parseInt(stats[0].total_hours_watched) || 0, + totalSessions: parseInt(stats[0].total_sessions) || 0, + avgSessionMinutes: parseInt(stats[0].avg_session_minutes) || 0, + dataFrom: stats[0].data_from ? new Date(stats[0].data_from).toISOString() : null, + dataTo: stats[0].data_to ? new Date(stats[0].data_to).toISOString() : null, + }, + updatedAt: new Date().toISOString(), + }; + + await cacheSet(cacheKey, result); + res.json(result); + } catch (error) { + console.error('[Top10] Error fetching stats:', error); + res.status(500).json({ success: false, error: 'Internal server error' }); + } +}); + +// --------------------------------------------------------------------------- +// Fonctions de construction des top 10 (extraites des routes pour réutilisation) +// --------------------------------------------------------------------------- + +async function buildTop10Movies() { + const [rows] = await pool.execute(` + SELECT + content_id, + MAX(content_title) AS content_title, + COUNT(DISTINCT user_id) AS unique_viewers, + ROUND(SUM(watch_duration) / 3600, 1) AS total_hours, + COUNT(*) AS total_sessions, + ROUND(AVG(watch_duration) / 60, 0) AS avg_session_minutes + FROM wrapped_viewing_data + WHERE content_type = 'movie' + AND watch_duration >= 1200 + GROUP BY content_id + ORDER BY unique_viewers DESC, total_hours DESC + LIMIT 10 + `); + + const enriched = await Promise.all(rows.map(async (row, index) => { + const tmdb = await fetchTMDBDetails(row.content_id, 'movie'); + return { + rank: index + 1, + contentId: row.content_id, + title: tmdb?.title || row.content_title || `Film #${row.content_id}`, + posterPath: tmdb?.poster_path || null, + backdropPath: tmdb?.backdrop_path || null, + overview: tmdb?.overview || null, + voteAverage: tmdb?.vote_average || null, + genres: tmdb?.genres || [], + releaseDate: tmdb?.release_date || null, + uniqueViewers: parseInt(row.unique_viewers), + totalHours: parseFloat(row.total_hours), + totalSessions: parseInt(row.total_sessions), + avgSessionMinutes: parseInt(row.avg_session_minutes), + }; + })); + + return { success: true, type: 'movies', top10: enriched, updatedAt: new Date().toISOString() }; +} + +async function buildTop10Tv() { + const [rows] = await pool.execute(` + SELECT + content_id, + MAX(content_title) AS content_title, + COUNT(DISTINCT user_id) AS unique_viewers, + ROUND(SUM(watch_duration) / 3600, 1) AS total_hours, + COUNT(*) AS total_sessions, + ROUND(AVG(watch_duration) / 60, 0) AS avg_session_minutes, + COUNT(DISTINCT CONCAT(IFNULL(season_number, ''), '-', IFNULL(episode_number, ''))) AS episodes_watched + FROM wrapped_viewing_data + WHERE content_type = 'tv' + AND watch_duration >= 300 + GROUP BY content_id + ORDER BY unique_viewers DESC, total_hours DESC + LIMIT 10 + `); + + const enriched = await Promise.all(rows.map(async (row, index) => { + const tmdb = await fetchTMDBDetails(row.content_id, 'tv'); + return { + rank: index + 1, + contentId: row.content_id, + title: tmdb?.title || row.content_title || `Série #${row.content_id}`, + posterPath: tmdb?.poster_path || null, + backdropPath: tmdb?.backdrop_path || null, + overview: tmdb?.overview || null, + voteAverage: tmdb?.vote_average || null, + genres: tmdb?.genres || [], + releaseDate: tmdb?.release_date || null, + uniqueViewers: parseInt(row.unique_viewers), + totalHours: parseFloat(row.total_hours), + totalSessions: parseInt(row.total_sessions), + avgSessionMinutes: parseInt(row.avg_session_minutes), + episodesWatched: parseInt(row.episodes_watched), + }; + })); + + return { success: true, type: 'tv', top10: enriched, updatedAt: new Date().toISOString() }; +} + +async function buildTop10Anime() { + const [rows] = await pool.execute(` + SELECT + content_id, + MAX(content_title) AS content_title, + COUNT(DISTINCT user_id) AS unique_viewers, + ROUND(SUM(watch_duration) / 3600, 1) AS total_hours, + COUNT(*) AS total_sessions, + ROUND(AVG(watch_duration) / 60, 0) AS avg_session_minutes, + COUNT(DISTINCT CONCAT(IFNULL(season_number, ''), '-', IFNULL(episode_number, ''))) AS episodes_watched + FROM wrapped_viewing_data + WHERE content_type = 'anime' + AND watch_duration >= 300 + GROUP BY content_id + ORDER BY unique_viewers DESC, total_hours DESC + LIMIT 10 + `); + + const enriched = await Promise.all(rows.map(async (row, index) => { + const tmdb = await fetchTMDBDetails(row.content_id, 'anime'); + return { + rank: index + 1, + contentId: row.content_id, + title: tmdb?.title || row.content_title || `Anime #${row.content_id}`, + posterPath: tmdb?.poster_path || null, + backdropPath: tmdb?.backdrop_path || null, + overview: tmdb?.overview || null, + voteAverage: tmdb?.vote_average || null, + genres: tmdb?.genres || [], + releaseDate: tmdb?.release_date || null, + uniqueViewers: parseInt(row.unique_viewers), + totalHours: parseFloat(row.total_hours), + totalSessions: parseInt(row.total_sessions), + avgSessionMinutes: parseInt(row.avg_session_minutes), + episodesWatched: parseInt(row.episodes_watched), + }; + })); + + return { success: true, type: 'anime', top10: enriched, updatedAt: new Date().toISOString() }; +} + +// --------------------------------------------------------------------------- +// Rafraîchissement en arrière-plan (stale-while-revalidate) +// --------------------------------------------------------------------------- + +const builders = { movies: buildTop10Movies, tv: buildTop10Tv, anime: buildTop10Anime }; + +async function refreshTop10(category) { + try { + const builder = builders[category]; + if (!builder) return; + const result = await builder(); + await cacheSet(category, result); + console.log(`[Top10] Cache ${category} rafraîchi en arrière-plan`); + } catch (err) { + console.error(`[Top10] Erreur rafraîchissement ${category}:`, err.message); + } +} + +async function refreshStats(requestedType, typeConfig) { + try { + const cacheKey = requestedType ? `stats:${requestedType}` : 'stats'; + let statsQuery, statsParams; + + if (typeConfig) { + statsQuery = ` + SELECT + COUNT(DISTINCT user_id) AS total_active_users, + COUNT(DISTINCT content_id) AS total_unique_content, + ROUND(SUM(watch_duration) / 3600, 0) AS total_hours_watched, + COUNT(*) AS total_sessions, + ROUND(AVG(watch_duration) / 60, 0) AS avg_session_minutes, + MIN(created_at) AS data_from, + MAX(created_at) AS data_to + FROM wrapped_viewing_data + WHERE content_type = ? + AND watch_duration >= ? + `; + statsParams = [typeConfig.contentType, typeConfig.minDuration]; + } else { + statsQuery = ` + SELECT + COUNT(DISTINCT user_id) AS total_active_users, + COUNT(DISTINCT content_id) AS total_unique_content, + ROUND(SUM(watch_duration) / 3600, 0) AS total_hours_watched, + COUNT(*) AS total_sessions, + ROUND(AVG(watch_duration) / 60, 0) AS avg_session_minutes, + MIN(created_at) AS data_from, + MAX(created_at) AS data_to + FROM wrapped_viewing_data + WHERE watch_duration >= ? + `; + statsParams = [300]; + } + + const [stats] = await pool.execute(statsQuery, statsParams); + const result = { + success: true, + type: requestedType || 'global', + stats: { + totalActiveUsers: parseInt(stats[0].total_active_users) || 0, + totalUniqueContent: parseInt(stats[0].total_unique_content) || 0, + totalHoursWatched: parseInt(stats[0].total_hours_watched) || 0, + totalSessions: parseInt(stats[0].total_sessions) || 0, + avgSessionMinutes: parseInt(stats[0].avg_session_minutes) || 0, + dataFrom: stats[0].data_from ? new Date(stats[0].data_from).toISOString() : null, + dataTo: stats[0].data_to ? new Date(stats[0].data_to).toISOString() : null, + }, + updatedAt: new Date().toISOString(), + }; + await cacheSet(cacheKey, result); + console.log(`[Top10] Cache stats ${cacheKey} rafraîchi en arrière-plan`); + } catch (err) { + console.error(`[Top10] Erreur rafraîchissement stats:`, err.message); + } +} + +module.exports = { router, initTop10Routes }; diff --git a/API/Mainapi/utils/accountLinks.js b/API/Mainapi/utils/accountLinks.js new file mode 100644 index 0000000..083b018 --- /dev/null +++ b/API/Mainapi/utils/accountLinks.js @@ -0,0 +1,203 @@ +const { getPool } = require('../mysqlPool'); + +const SUPPORTED_PROVIDERS = ['discord', 'google', 'bip39']; +const SUPPORTED_USER_TYPES = ['oauth', 'bip39']; + +let ensureAccountLinksStoragePromise = null; + +function isSupportedProvider(provider) { + return SUPPORTED_PROVIDERS.includes(provider); +} + +function isSupportedUserType(userType) { + return SUPPORTED_USER_TYPES.includes(userType); +} + +async function ensureAccountLinksStorage() { + if (ensureAccountLinksStoragePromise) { + return ensureAccountLinksStoragePromise; + } + + ensureAccountLinksStoragePromise = (async () => { + const pool = getPool(); + if (!pool) { + throw new Error('MySQL pool not ready for account links'); + } + + await pool.execute(` + CREATE TABLE IF NOT EXISTS account_links ( + provider ENUM('discord', 'google', 'bip39') NOT NULL, + provider_user_id VARCHAR(255) NOT NULL, + target_user_type ENUM('oauth', 'bip39') NOT NULL, + target_user_id VARCHAR(255) NOT NULL, + linked_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (provider, provider_user_id), + UNIQUE KEY uniq_account_links_target_provider (target_user_type, target_user_id, provider), + KEY idx_account_links_target (target_user_type, target_user_id) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci + `); + })().catch((error) => { + ensureAccountLinksStoragePromise = null; + throw error; + }); + + return ensureAccountLinksStoragePromise; +} + +function toIsoString(value) { + if (!value) return null; + if (value instanceof Date) return value.toISOString(); + + const parsed = new Date(value); + return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString(); +} + +function normalizeRecord(row) { + if (!row || !isSupportedProvider(row.provider) || !isSupportedUserType(row.target_user_type)) { + return null; + } + + return { + provider: row.provider, + providerUserId: String(row.provider_user_id), + targetUserType: row.target_user_type, + targetUserId: String(row.target_user_id), + linkedAt: toIsoString(row.linked_at), + updatedAt: toIsoString(row.updated_at), + }; +} + +async function getLinkedTarget(provider, providerUserId) { + if (!isSupportedProvider(provider)) return null; + + await ensureAccountLinksStorage(); + const pool = getPool(); + const [rows] = await pool.execute( + `SELECT provider, provider_user_id, target_user_type, target_user_id, linked_at, updated_at + FROM account_links + WHERE provider = ? AND provider_user_id = ? + LIMIT 1`, + [provider, String(providerUserId)] + ); + + return normalizeRecord(rows[0]); +} + +async function getLinksForTarget(targetUserType, targetUserId) { + if (!isSupportedUserType(targetUserType)) { + return []; + } + + await ensureAccountLinksStorage(); + const pool = getPool(); + const [rows] = await pool.execute( + `SELECT provider, provider_user_id, target_user_type, target_user_id, linked_at, updated_at + FROM account_links + WHERE target_user_type = ? AND target_user_id = ? + ORDER BY provider ASC`, + [targetUserType, String(targetUserId)] + ); + + return rows + .map(normalizeRecord) + .filter(Boolean); +} + +async function setLink({ provider, providerUserId, targetUserType, targetUserId }) { + if (!isSupportedProvider(provider)) { + throw new Error(`Unsupported provider: ${provider}`); + } + + if (!isSupportedUserType(targetUserType)) { + throw new Error(`Unsupported target user type: ${targetUserType}`); + } + + await ensureAccountLinksStorage(); + const pool = getPool(); + const connection = await pool.getConnection(); + const now = new Date(); + + try { + await connection.beginTransaction(); + + await connection.execute( + `DELETE FROM account_links + WHERE target_user_type = ? AND target_user_id = ? AND provider = ? AND provider_user_id <> ?`, + [targetUserType, String(targetUserId), provider, String(providerUserId)] + ); + + await connection.execute( + `INSERT INTO account_links ( + provider, + provider_user_id, + target_user_type, + target_user_id, + linked_at, + updated_at + ) VALUES (?, ?, ?, ?, ?, ?) + ON DUPLICATE KEY UPDATE + target_user_type = VALUES(target_user_type), + target_user_id = VALUES(target_user_id), + linked_at = account_links.linked_at, + updated_at = VALUES(updated_at)`, + [provider, String(providerUserId), targetUserType, String(targetUserId), now, now] + ); + + await connection.commit(); + } catch (error) { + await connection.rollback(); + throw error; + } finally { + connection.release(); + } + + const record = await getLinkedTarget(provider, providerUserId); + if (!record) { + throw new Error('Failed to persist account link'); + } + + return record; +} + +async function removeLink(provider, providerUserId) { + if (!isSupportedProvider(provider)) { + return false; + } + + await ensureAccountLinksStorage(); + const pool = getPool(); + const [result] = await pool.execute( + 'DELETE FROM account_links WHERE provider = ? AND provider_user_id = ?', + [provider, String(providerUserId)] + ); + + return result.affectedRows > 0; +} + +async function removeLinksForTargetProvider(targetUserType, targetUserId, provider) { + if (!isSupportedUserType(targetUserType) || !isSupportedProvider(provider)) { + return false; + } + + await ensureAccountLinksStorage(); + const pool = getPool(); + const [result] = await pool.execute( + `DELETE FROM account_links + WHERE target_user_type = ? AND target_user_id = ? AND provider = ?`, + [targetUserType, String(targetUserId), provider] + ); + + return result.affectedRows > 0; +} + +module.exports = { + SUPPORTED_PROVIDERS, + isSupportedProvider, + getLinkedTarget, + getLinksForTarget, + setLink, + removeLink, + removeLinksForTargetProvider, + ensureAccountLinksStorage, +}; diff --git a/API/Mainapi/utils/axiosHelpers.js b/API/Mainapi/utils/axiosHelpers.js new file mode 100644 index 0000000..12f2a72 --- /dev/null +++ b/API/Mainapi/utils/axiosHelpers.js @@ -0,0 +1,921 @@ +/** + * High-level axios request helpers for each streaming site. + * Extracted from server.js — wraps proxy logic with site-specific headers and cookies. + * + * Some helpers depend on axios instances / session state that live in route modules + * (e.g. axiosFStream, axiosAnimeSama, axiosCoflix, cookieJar). + * Call `configure(deps)` once at startup to inject those dependencies. + */ + +const axios = require('axios'); +const fsp = require('fs').promises; +const path = require('path'); +const writeFileAtomic = require('write-file-atomic'); + +const { + ENABLE_DARKINO_PROXY, + ENABLE_COFLIX_PROXY, + ENABLE_FRENCH_STREAM_PROXY, + ENABLE_LECTEURVIDEO_PROXY, + ENABLE_FSTREAM_PROXY, + ENABLE_ANIME_PROXY, + ENABLE_WIFLIX_PROXY, + DARKINO_403_COOLDOWN_MS, + DARKINO_PROXIES, + PROXIES, + HTTP_PROXIES, + CLOUDFLARE_WORKERS_PROXIES, + getProxyAgent, + getDarkinoHttpProxyAgent, + getAvailableProxies, + markProxyAsErrored, + markProxyAsHealthy, + buildProxiedUrl, + makeRequestWithCorsFallback, + makeCoflixRequest, + makeLecteurVideoRequest +} = require('./proxyManager'); + +// Lazy-bound dependencies injected via configure() +let deps = { + darkiHeaders: {}, + coflixHeaders: {}, + cookieJar: null, + axiosCoflix: null, + axiosAnimeSama: null, + axiosFStream: null, + COFLIX_BASE_URL: '', + ANIME_SAMA_URL: '', + FSTREAM_BASE_URL: '', + ensureFStreamSession: async () => {}, + fstreamCookies: {}, + fstreamRequestCounter: 0, + getFstreamRequestCounter: () => 0, + incrementFstreamRequestCounter: () => {} +}; + +const WIFLIX_BASE_URL = 'https://flemmix.golf'; + +const truncateForLog = (value, maxLength = 300) => { + if (typeof value !== 'string') return value; + return value.length > maxLength ? `${value.slice(0, maxLength)}...` : value; +}; + +const summarizeRequestErrorForLog = (error) => { + const responseBody = error?.response?.data; + return { + message: error?.message, + code: error?.code, + status: error?.response?.status, + statusText: error?.response?.statusText, + responseSnippet: typeof responseBody === 'string' + ? truncateForLog(responseBody, 500) + : responseBody && typeof responseBody === 'object' + ? truncateForLog(JSON.stringify(responseBody), 500) + : undefined + }; +}; + +const BYPASS403_SERVER_URL = String(process.env.BYPASS403_SERVER_URL || '') + .trim() + .replace(/\/+$/, ''); + +function buildBypass403RequestUrl(targetUrl) { + if (!BYPASS403_SERVER_URL) { + return targetUrl; + } + + return `${BYPASS403_SERVER_URL}/proxy/${targetUrl}`; +} + +/** + * Inject site-specific dependencies that live outside this module. + * Call once at server startup after creating axios instances. + * + * @param {object} injected - Map of dependency names to values + */ +function configure(injected) { + Object.assign(deps, injected); +} + +// === Proxy manager re-exports for convenience (used by axiosDarkinoRequest) === +// We need mutable access to darkino403CooldownUntil via the proxyManager module +const proxyManager = require('./proxyManager'); + +// Fonction utilitaire pour g\u00e9n\u00e9rer le referer dynamiquement +function generateDarkiReferer(url) { + const baseUrl = 'https://darkiworld2026.com'; + + if (url.includes('/season/') && url.includes('/episode/') && url.includes('/download')) { + // Pour les \u00e9pisodes de s\u00e9ries: /titles/{titleId}/season/{seasonId}/episode/{episodeId}/download + const match = url.match(/\/titles\/(\d+)\/season\/(\d+)\/episode\/(\d+)\/download/); + if (match) { + const [, titleId, seasonId, episodeId] = match; + return `${baseUrl}/titles/${titleId}/season/${seasonId}/episode/${episodeId}/download?filters=W3sia2V5IjoiaWRfaG9zdCIsInZhbHVlIjoyLCJpc0luYWN0aXZlIjpmYWxzZSwidmFsdWVLZXkiOjJ9XQ%3D%3D`; + } + } else if (url.includes('/titles/') && url.includes('/download')) { + // Pour les films: /titles/{id}/download + const match = url.match(/\/titles\/(\d+)\/download/); + if (match) { + const [, titleId] = match; + return `${baseUrl}/titles/${titleId}/download`; + } + } else if (url.includes('/search/')) { + // Pour la recherche + return `${baseUrl}/search`; + } + + // Par d\u00e9faut, utiliser l'URL de base + return baseUrl; +} + +// Fonction utilitaire pour requ\u00eates Darkino avec proxies (SOCKS5h) +async function axiosDarkinoRequest(config) { + // V\u00e9rifier si on est en cooldown apr\u00e8s une erreur 403 + if (Date.now() < proxyManager.darkino403CooldownUntil) { + const remainingMs = proxyManager.darkino403CooldownUntil - Date.now(); + const remainingMin = Math.ceil(remainingMs / 60000); + const error = new Error(`Darkino en cooldown (403 Cloudflare). R\u00e9essayez dans ${remainingMin} minute(s).`); + error.isDarkinoCooldown = true; + error.response = { status: 403 }; + throw error; + } + + const requestUrl = `https://darkiworld2026.com${config.url}`; + + // G\u00e9n\u00e9rer le referer dynamiquement selon l'URL + const dynamicReferer = generateDarkiReferer(config.url); + + // Headers pour les requ\u00eates Darkino + const darkinoRequestHeaders = { + ...deps.darkiHeaders, + 'referer': dynamicReferer, + ...config.headers, + }; + + if (!ENABLE_DARKINO_PROXY) { + // Si le proxy est d\u00e9sactiv\u00e9, faire la requ\u00eate directe + try { + const response = await axios({ + ...config, + url: requestUrl, + headers: darkinoRequestHeaders, + timeout: 5000, + withCredentials: false, + decompress: true + }); + + const setCookieHeader = response.headers['set-cookie']; + if (setCookieHeader && deps.cookieJar) { + await Promise.all(setCookieHeader.map(cookie => deps.cookieJar.setCookie(cookie, 'https://darkiworld2026.com'))); + } + return response; + } catch (error) { + console.error(`[DARKINO REQUEST][DIRECT ERROR] ${String(config.method || 'get').toUpperCase()} ${config.url}`, summarizeRequestErrorForLog(error)); + if (error.response && error.response.headers['set-cookie'] && deps.cookieJar) { + const setCookieHeader = error.response.headers['set-cookie']; + await Promise.all(setCookieHeader.map(cookie => deps.cookieJar.setCookie(cookie, 'https://darkiworld2026.com'))); + } + // En cas d'erreur 403, activer le cooldown + if (error.response?.status === 403) { + proxyManager.darkino403CooldownUntil = Date.now() + DARKINO_403_COOLDOWN_MS; + console.log(`[DARKINO] Erreur 403 d\u00e9tect\u00e9e (direct) - Cooldown activ\u00e9 pour 5 minutes`); + } + throw error; + } + } + + // Utiliser les proxies HTTP sp\u00e9cifiques de Darkino avec rotation al\u00e9atoire + const darkinoProxies = [...DARKINO_PROXIES]; // Copie pour pouvoir m\u00e9langer + + // M\u00e9langer al\u00e9atoirement les proxies + for (let i = darkinoProxies.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [darkinoProxies[i], darkinoProxies[j]] = [darkinoProxies[j], darkinoProxies[i]]; + } + + let lastError = null; + const maxRetries = 1; // Une seule tentative + + for (let i = 0; i < maxRetries; i++) { + const proxy = darkinoProxies[i]; + const agents = getDarkinoHttpProxyAgent(proxy); + + try { + const response = await axios({ + ...config, + method: config.method || 'get', + url: requestUrl, + headers: darkinoRequestHeaders, + timeout: 5000, + withCredentials: false, + decompress: true, + httpAgent: agents.httpAgent, + httpsAgent: agents.httpsAgent, + proxy: false + }); + + // Mettre \u00e0 jour le cookieJar avec la r\u00e9ponse + const setCookieHeader = response.headers['set-cookie']; + if (setCookieHeader && deps.cookieJar) { + await Promise.all(setCookieHeader.map(cookie => deps.cookieJar.setCookie(cookie, 'https://darkiworld2026.com'))); + } + return response; + } catch (error) { + lastError = error; + const statusCode = error.response?.status; + console.warn(`[DARKINO REQUEST][PROXY ERROR] ${String(config.method || 'get').toUpperCase()} ${config.url}`, { + attempt: i + 1, + status: statusCode, + error: summarizeRequestErrorForLog(error) + }); + + // Mettre \u00e0 jour les cookies m\u00eame en cas d'erreur si le header est pr\u00e9sent + if (error.response && error.response.headers['set-cookie'] && deps.cookieJar) { + const setCookieHeader = error.response.headers['set-cookie']; + await Promise.all(setCookieHeader.map(cookie => deps.cookieJar.setCookie(cookie, 'https://darkiworld2026.com'))); + } + + // En cas d'erreur 429 (Too Many Requests), essayer avec le prochain proxy si disponible + if (statusCode === 429) { + continue; + } + + // En cas d'erreur 403 (Cloudflare challenge), activer le cooldown de 5 minutes + if (statusCode === 403) { + proxyManager.darkino403CooldownUntil = Date.now() + DARKINO_403_COOLDOWN_MS; + throw error; + } + + // Pour les autres erreurs (400, 500, etc.), arr\u00eater imm\u00e9diatement + if (statusCode && statusCode !== 429) { + throw error; + } + } + } + + // Si on arrive ici, tous les proxies ont \u00e9chou\u00e9 + console.error(`[DARKINO REQUEST][ALL FAILED] ${String(config.method || 'get').toUpperCase()} ${config.url}`, summarizeRequestErrorForLog(lastError)); + throw lastError || new Error('Tous les proxies Darkino ont \u00e9chou\u00e9'); +} + +// Fonction utilitaire pour requ\u00eates Coflix avec rotation Cloudflare Workers +async function axiosCoflixRequest(config) { + // Si URL relative, on consid\u00e8re que c'est Coflix. + const targetUrl = config.url || ''; + const isAbsolute = /^https?:\/\//i.test(targetUrl); + const isCoflixDomain = isAbsolute ? /^https?:\/\/(?:www\.)?coflix\.[^/]+/i.test(targetUrl) : true; + + try { + if (!ENABLE_COFLIX_PROXY || !isCoflixDomain) { + return await deps.axiosCoflix({ ...config }); + } + + // Utiliser makeCoflixRequest avec rotation SOCKS5 + const absoluteUrl = isAbsolute + ? targetUrl + : `${deps.COFLIX_BASE_URL}${targetUrl.startsWith('/') ? '' : '/'}${targetUrl}`; + + return await makeCoflixRequest(absoluteUrl, { + headers: { ...deps.coflixHeaders, ...(config.headers || {}) }, + timeout: config.timeout || 7000, + decompress: true, + responseType: config.responseType + }); + } catch (error) { + // Logger les erreurs 403 + if (error.response?.status === 403) { + console.log(`[Coflix] Erreur 403 Forbidden dans axiosCoflixRequest`); + console.log(`[Coflix] URL: ${targetUrl}`); + if (error.coflixProxy) { + console.log(`[Coflix] Cloudflare Worker: ${error.coflixProxy}`); + } + if (error.coflixProxiedUrl) { + console.log(`[Coflix] Proxied URL: ${error.coflixProxiedUrl}`); + } + } + throw error; + } +} + +// Fonction utilitaire pour requ\u00eates French-Stream (SPA) via CORS fallback +async function axiosFrenchStreamRequest(config) { + const targetUrl = config.url || ''; + const isAbsolute = /^https?:\/\//i.test(targetUrl); + const baseMatches = config.baseURL && /french-?stream/i.test(config.baseURL); + const isFrenchStream = /french-?stream/i.test(targetUrl) || baseMatches; + + if (!ENABLE_FRENCH_STREAM_PROXY || !isFrenchStream) { + return axios({ timeout: 15000, ...config }); + } + + const absoluteUrl = isAbsolute + ? targetUrl + : (config.baseURL ? `${config.baseURL.replace(/\/$/, '')}/${targetUrl.replace(/^\//, '')}` : targetUrl); + + return makeRequestWithCorsFallback(absoluteUrl, { + headers: { ...(config.headers || {}) }, + timeout: config.timeout || 5000, + decompress: true, + responseType: config.responseType + }); +} + +// Fonction utilitaire pour requ\u00eates LecteurVideo avec proxies Wiflix +async function axiosLecteurVideoRequest(config) { + const urlStr = config.url || ''; + const isLecteur = /lecteurvideo|lecteur-video|lecteur/i.test(urlStr) || (config.baseURL && /lecteurvideo|lecteur-video|lecteur/i.test(config.baseURL)); + + if (!ENABLE_LECTEURVIDEO_PROXY || !isLecteur) { + return axios({ timeout: 15000, ...config }); + } + + try { + // Construire l'URL absolue si n\u00e9cessaire + let absoluteUrl = config.url; + if (config.baseURL && !config.url.startsWith('http')) { + // Nettoyer les URLs avant la concat\u00e9nation pour \u00e9viter les espaces + const cleanBaseURL = config.baseURL.trim(); + const cleanUrl = config.url.trim(); + absoluteUrl = cleanBaseURL + cleanUrl; + } + + // Utiliser makeLecteurVideoRequest avec les proxies Wiflix + return await makeLecteurVideoRequest(absoluteUrl, { + timeout: config.timeout || 5000, + headers: config.headers, + decompress: config.decompress !== false, + responseType: config.responseType, + responseEncoding: config.responseEncoding + }); + } catch (error) { + throw error; + } +} + +// Fonction utilitaire pour requ\u00eates FStream avec proxy (retry sur 429, pool SOCKS5 + Darkino) +async function axiosFStreamRequest(config) { + const urlStr = config.url || ''; + const fstreamBaseUrl = deps.FSTREAM_BASE_URL || ''; + const isFStream = urlStr.includes(fstreamBaseUrl.replace('https://', '').replace('http://', '')) || + (config.baseURL && config.baseURL.includes(fstreamBaseUrl.replace('https://', '').replace('http://', ''))); + + if (!ENABLE_FSTREAM_PROXY || !isFStream) { + await deps.ensureFStreamSession(); + const existingHeaders = config.headers || {}; + const cookieHeader = Object.entries(deps.fstreamCookies) + .filter(([, v]) => v !== '' && v != null) + .map(([k, v]) => `${k}=${v}`) + .join('; '); + const response = await deps.axiosFStream({ + ...config, + timeout: 8000, + headers: { + ...existingHeaders, + 'Cookie': existingHeaders['Cookie'] || cookieHeader + } + }); + deps.incrementFstreamRequestCounter(); + return response; + } + + // Pool combine SOCKS5 + Darkino HTTP, 1 proxy aleatoire + const allProxies = []; + if (PROXIES && PROXIES.length > 0) { + PROXIES.forEach(p => allProxies.push({ proxy: p, type: 'socks5' })); + } + if (DARKINO_PROXIES && DARKINO_PROXIES.length > 0) { + DARKINO_PROXIES.forEach(p => allProxies.push({ proxy: p, type: 'darkino' })); + } + const entry = allProxies[Math.floor(Math.random() * allProxies.length)]; + const proxyLabel = `${entry.type}:${entry.proxy.host}:${entry.proxy.port}`; + + try { + let agents; + if (entry.type === 'socks5') { + const agent = getProxyAgent(entry.proxy); + agents = { httpAgent: agent, httpsAgent: agent }; + } else { + agents = getDarkinoHttpProxyAgent(entry.proxy); + } + + await deps.ensureFStreamSession(); + const existingHeaders = config.headers || {}; + const cookieHeader = Object.entries(deps.fstreamCookies) + .filter(([, v]) => v !== '' && v != null) + .map(([k, v]) => `${k}=${v}`) + .join('; '); + const response = await deps.axiosFStream({ + ...config, + timeout: 8000, + decompress: true, + httpAgent: agents.httpAgent, + httpsAgent: agents.httpsAgent, + proxy: false, + headers: { + ...existingHeaders, + 'Cookie': existingHeaders['Cookie'] || cookieHeader + } + }); + deps.incrementFstreamRequestCounter(); + return response; + } catch (error) { + const status = error.response?.status; + console.error(`[FSTREAM REQUEST] Erreur ${status || error.code || 'unknown'} avec proxy ${proxyLabel}: ${error.message}`); + throw error; + } +} + +// Fonction utilitaire pour requ\u00eates AnimeSama via BYPASS403 + ProxyScrape +async function axiosAnimeSamaRequest(config) { + const MAX_ANIMESAMA_PROXY_ATTEMPTS = 2; + let urlStr = config.url || ''; + + const isAnimeSama = urlStr.includes('anime-sama.to') || urlStr.includes('anime-sama.si') || urlStr.includes('anime-sama.fr') || + (config.baseURL && (config.baseURL.includes('anime-sama.to') || config.baseURL.includes('anime-sama.si') || config.baseURL.includes('anime-sama.fr'))); + + if (!ENABLE_ANIME_PROXY || !isAnimeSama) { + return deps.axiosAnimeSama({ ...config, timeout: 30000 }); + } + + // Construire l'URL compl\u00e8te + let absoluteUrl = urlStr; + if (config.baseURL && !urlStr.startsWith('http')) { + absoluteUrl = config.baseURL + urlStr; + } else if (!urlStr.startsWith('http') && !absoluteUrl.startsWith('http')) { + // Si l'URL n'est pas compl\u00e8te et qu'on n'a pas de baseURL, utiliser ANIME_SAMA_URL + absoluteUrl = deps.ANIME_SAMA_URL + (urlStr.startsWith('/') ? urlStr.substring(1) : urlStr); + } + + const requestUrl = buildBypass403RequestUrl(absoluteUrl); + + // Headers pour les requ\u00eates Anime-Sama via proxy + const animeSamaHeaders = { + 'Accept-Language': 'fr-FR,fr;q=0.6', + 'Cache-Control': 'no-cache', + 'Pragma': 'no-cache', + 'Priority': 'u=0, i', + 'Sec-CH-UA': '"Chromium";v="142", "Brave";v="142", "Not_A Brand";v="99"', + 'Sec-CH-UA-Mobile': '?0', + 'Sec-CH-UA-Platform': '"Windows"', + 'Sec-Fetch-Dest': 'document', + 'Sec-Fetch-Mode': 'navigate', + 'Sec-Fetch-Site': 'none', + 'Sec-Fetch-User': '?1', + 'Sec-GPC': '1', + 'Upgrade-Insecure-Requests': '1', + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36' + }; + + // Supprimer les headers li\u00e9s \u00e0 l'IP d'origine pour \u00e9viter de les transmettre + const headersToRemove = ['X-Forwarded-For', 'X-Real-IP', 'X-Client-IP', 'CF-Connecting-IP', 'True-Client-IP', 'X-Original-Forwarded-For']; + const cleanHeaders = { ...animeSamaHeaders }; + + // Si config.headers existe, le nettoyer aussi + if (config.headers) { + const configHeaders = { ...config.headers }; + headersToRemove.forEach(header => { + delete configHeaders[header]; + delete configHeaders[header.toLowerCase()]; + }); + Object.assign(cleanHeaders, configHeaders); + } + + const proxyscrapePool = [ + ...PROXIES.map(proxy => ({ proxy, type: 'socks5' })), + ...HTTP_PROXIES.map(proxy => ({ proxy, type: 'http' })) + ] + .sort(() => Math.random() - 0.5) + .slice(0, MAX_ANIMESAMA_PROXY_ATTEMPTS); + + if (proxyscrapePool.length === 0) { + return deps.axiosAnimeSama({ + ...config, + url: requestUrl, + headers: cleanHeaders, + timeout: 30000, + decompress: true + }); + } + + let lastError = null; + + // Essayer quelques proxies ProxyScrape vers le serveur BYPASS403 + for (let i = 0; i < proxyscrapePool.length; i++) { + const entry = proxyscrapePool[i]; + const agents = getDarkinoHttpProxyAgent(entry.proxy); + const proxyLabel = `${entry.type}:${entry.proxy.host}:${entry.proxy.port}`; + + try { + const response = await deps.axiosAnimeSama({ + ...config, + url: requestUrl, + headers: cleanHeaders, + timeout: 30000, + decompress: true, + httpAgent: agents.httpAgent, + httpsAgent: agents.httpsAgent, + proxy: false + }); + return response; + } catch (error) { + lastError = error; + const statusCode = error.response?.status; + const errorCode = statusCode || error.code || 'unknown'; + + if (statusCode === 403 || statusCode === 429) { + console.warn(`[ANIMESAMA REQUEST] ${proxyLabel} bloque (${statusCode}), retry...`); + continue; + } + + if (statusCode >= 500 && statusCode < 600) { + console.warn(`[ANIMESAMA REQUEST] ${proxyLabel} erreur ${statusCode}, retry...`); + continue; + } + + if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') { + console.warn(`[ANIMESAMA REQUEST] ${proxyLabel} timeout (${errorCode}), retry...`); + continue; + } + + throw error; + } + } + + if (lastError) { + throw lastError; + } + + throw new Error('Erreur inconnue lors de la requ\u00eate Anime Sama'); +} + +// Fonction utilitaire pour requ\u00eates Wiflix avec proxy +async function axiosWiflixRequest(config) { + const urlStr = config.url || ''; + const isWiflix = urlStr.includes(WIFLIX_BASE_URL) || urlStr.includes('flemmix') || + (config.baseURL && (config.baseURL.includes(WIFLIX_BASE_URL) || config.baseURL.includes('flemmix'))); + + if (!ENABLE_WIFLIX_PROXY || !isWiflix) { + const defaultConfig = { + timeout: 15000, + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', + 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', + 'Accept-Language': 'fr-FR,fr;q=0.9,en;q=0.8', + 'Accept-Encoding': 'gzip, deflate, br', + 'DNT': '1', + 'Connection': 'keep-alive', + 'Upgrade-Insecure-Requests': '1' + } + }; + + const finalConfig = { ...defaultConfig, ...config }; + + try { + const response = await axios(finalConfig); + return response; + } catch (error) { + // Ajouter des informations sur l'URL utilis\u00e9e \u00e0 l'erreur + error.wiflixUrl = config.url || urlStr; + error.wiflixProxy = 'Direct (sans proxy)'; + error.wiflixProxiedUrl = config.url || urlStr; + console.error(`[WIFLIX REQUEST] Erreur: ${error.message}`); + throw error; + } + } + + // Construire l'URL compl\u00e8te + let absoluteUrl = urlStr; + if (config.baseURL && !urlStr.startsWith('http')) { + absoluteUrl = config.baseURL + urlStr; + } else if (!urlStr.startsWith('http')) { + absoluteUrl = WIFLIX_BASE_URL + (urlStr.startsWith('/') ? urlStr : '/' + urlStr); + } + + // Filtrer les proxies disponibles (non en cooldown) + const availableProxies = getAvailableProxies(CLOUDFLARE_WORKERS_PROXIES); + + const defaultHeaders = { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', + 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', + 'Accept-Language': 'fr-FR,fr;q=0.9,en;q=0.8', + 'Accept-Encoding': 'gzip, deflate, br', + 'DNT': '1', + 'Connection': 'keep-alive', + 'Upgrade-Insecure-Requests': '1', + ...(config.headers || {}) + }; + + let lastError = null; + + // Essayer avec les proxies Cloudflare disponibles + for (let i = 0; i < availableProxies.length; i++) { + const cloudflareProxy = availableProxies[i]; + const proxiedUrl = buildProxiedUrl(cloudflareProxy, absoluteUrl); + + try { + // Extraire url et headers de config pour \u00e9viter les conflits + const { url: _, headers: __, ...restConfig } = config; + const response = await axios({ + url: proxiedUrl, + method: restConfig.method || 'GET', + headers: defaultHeaders, + timeout: restConfig.timeout || 15000, + decompress: true, + responseType: restConfig.responseType || 'text', + ...restConfig + }); + + // Succ\u00e8s : marquer le proxy comme sain + markProxyAsHealthy(cloudflareProxy); + return response; + } catch (error) { + const statusCode = error.response?.status; + const errorCode = statusCode || error.code || 'unknown'; + + // Ajouter des informations sur l'URL et le proxy utilis\u00e9 \u00e0 l'erreur + error.wiflixUrl = absoluteUrl; + error.wiflixProxy = cloudflareProxy; + error.wiflixProxiedUrl = proxiedUrl; + lastError = error; + + // En cas d'erreur 429 (Too Many Requests), marquer le proxy et essayer le suivant + if (statusCode === 429) { + markProxyAsErrored(cloudflareProxy, 429); + continue; + } + + // En cas d'erreur 5xx, marquer le proxy et essayer le suivant + if (statusCode >= 500 && statusCode < 600) { + markProxyAsErrored(cloudflareProxy, statusCode); + continue; + } + + // En cas de timeout, marquer le proxy et essayer le suivant + if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') { + markProxyAsErrored(cloudflareProxy, errorCode); + continue; + } + + // Pour les autres erreurs, throw imm\u00e9diatement sans essayer d'autres proxies + throw error; + } + } + + // Si on arrive ici, tous les proxies ont \u00e9chou\u00e9 + if (lastError) throw lastError; + throw new Error('Erreur inconnue lors de la requ\u00eate Wiflix'); +} + +// === UTILITY: Fusion des streaming_links par langue === +function mergeStreamingLinks(oldLinks, newLinks) { + // oldLinks et newLinks sont des tableaux d'objets { language, players } + const merged = {}; + + // D'abord, copier les anciens liens + (oldLinks || []).forEach(l => { + merged[l.language] = Array.isArray(l.players) ? [...l.players] : []; + }); + + // Ensuite, remplacer par les nouveaux liens si disponibles + (newLinks || []).forEach(l => { + if (l.players && l.players.length > 0) { + // Si on a de nouveaux lecteurs, on remplace compl\u00e8tement les anciens + merged[l.language] = Array.isArray(l.players) ? [...l.players] : []; + } + }); + + // Retourne sous forme d'array d'objets + return Object.entries(merged).map(([language, players]) => ({ language, players })); +} + +// === UTILITY: Migration des anciens fichiers de cache s\u00e9par\u00e9s vers le cache unifi\u00e9 === +async function migrateOldCacheFiles(safeAnimeName, animeCacheDir) { + try { + const allCacheFiles = await fsp.readdir(animeCacheDir).catch(() => []); + const oldSeasonFiles = allCacheFiles.filter(f => f.startsWith(safeAnimeName + '_') && f.endsWith('.json')); + + if (oldSeasonFiles.length === 0) return; + + const migratedSeasons = {}; + + for (const seasonFile of oldSeasonFiles) { + try { + const seasonContent = await fsp.readFile(path.join(animeCacheDir, seasonFile), 'utf-8'); + const seasonCache = JSON.parse(seasonContent); + const seasonName = seasonFile.replace(safeAnimeName + '_', '').replace('.json', ''); + + migratedSeasons[seasonName] = { + timestamp: seasonCache.timestamp || Date.now(), + episodes: seasonCache.episodes || [] + }; + } catch (e) { + } + } + + if (Object.keys(migratedSeasons).length > 0) { + const unifiedCacheData = { + timestamp: Date.now(), + seasons: migratedSeasons + }; + + const animeCachePath = path.join(animeCacheDir, `${safeAnimeName}.json`); + await writeFileAtomic(animeCachePath, JSON.stringify(unifiedCacheData), 'utf-8'); + + // Nettoyer les anciens fichiers apr\u00e8s migration r\u00e9ussie + await cleanupOldCacheFiles(safeAnimeName, animeCacheDir); + } + } catch (e) { + } +} + +// === UTILITY: Nettoyage des anciens fichiers de cache s\u00e9par\u00e9s === +async function cleanupOldCacheFiles(safeAnimeName, animeCacheDir) { + try { + const allCacheFiles = await fsp.readdir(animeCacheDir).catch(() => []); + const oldSeasonFiles = allCacheFiles.filter(f => f.startsWith(safeAnimeName + '_') && f.endsWith('.json')); + + for (const oldFile of oldSeasonFiles) { + try { + await fsp.unlink(path.join(animeCacheDir, oldFile)); + } catch (e) { + } + } + } catch (e) { + } +} + +// Fonction pour supprimer les lecteurs fsvid des r\u00e9ponses FStream +function removeFsvidPlayers(data, isVip = false) { + // Si pas de donn\u00e9es, retourner tel quel + if (!data) { + return data; + } + + // Si l'utilisateur est VIP, ne pas filtrer les lecteurs fsvid + if (isVip) { + return data; + } + + // Par d\u00e9faut, toujours filtrer les lecteurs fsvid (m\u00eame si remove_fsvid est false) + + // Pour les films : filtrer players.organized + if (data.players && typeof data.players === 'object') { + const filteredPlayers = {}; + let totalPlayers = 0; + + Object.keys(data.players).forEach(playerType => { + if (Array.isArray(data.players[playerType])) { + // Filtrer les lecteurs dont l'URL contient "fsvid" + const filteredPlayerList = data.players[playerType].filter(player => { + return !player.url || !player.url.includes('fsvid'); + }); + + if (filteredPlayerList.length > 0) { + filteredPlayers[playerType] = filteredPlayerList; + totalPlayers += filteredPlayerList.length; + } + } else { + // Si ce n'est pas un array, garder tel quel + filteredPlayers[playerType] = data.players[playerType]; + } + }); + + return { + ...data, + players: filteredPlayers, + total: totalPlayers, + metadata: { + ...data.metadata, + fsvidFiltered: true + } + }; + } + + // Pour les s\u00e9ries : filtrer episodes + if (data.episodes && typeof data.episodes === 'object') { + const filteredEpisodes = {}; + let totalPlayers = 0; + + Object.keys(data.episodes).forEach(episodeKey => { + const episode = data.episodes[episodeKey]; + if (episode && typeof episode === 'object') { + const filteredEpisode = { ...episode }; + + // V\u00e9rifier si l'\u00e9pisode a une structure "languages" + if (episode.languages && typeof episode.languages === 'object') { + const filteredLanguages = {}; + + Object.keys(episode.languages).forEach(languageKey => { + const languagePlayers = episode.languages[languageKey]; + + if (Array.isArray(languagePlayers)) { + // Filtrer les lecteurs dont l'URL contient "fsvid" + const filteredPlayerList = languagePlayers.filter(player => { + return !player.url || !player.url.includes('fsvid'); + }); + + if (filteredPlayerList.length > 0) { + filteredLanguages[languageKey] = filteredPlayerList; + totalPlayers += filteredPlayerList.length; + } + } else { + // Si ce n'est pas un array, garder tel quel + filteredLanguages[languageKey] = languagePlayers; + } + }); + + filteredEpisode.languages = filteredLanguages; + } else { + // Structure ancienne sans "languages" - filtrer directement + Object.keys(episode).forEach(playerType => { + if (Array.isArray(episode[playerType])) { + // Filtrer les lecteurs dont l'URL contient "fsvid" + const filteredPlayerList = episode[playerType].filter(player => { + return !player.url || !player.url.includes('fsvid'); + }); + + if (filteredPlayerList.length > 0) { + filteredEpisode[playerType] = filteredPlayerList; + totalPlayers += filteredPlayerList.length; + } + } + }); + } + + // Garder l'\u00e9pisode seulement s'il a encore des lecteurs + if (episode.languages ? Object.keys(filteredEpisode.languages).length > 0 : Object.keys(filteredEpisode).some(key => Array.isArray(filteredEpisode[key]) && filteredEpisode[key].length > 0)) { + filteredEpisodes[episodeKey] = filteredEpisode; + } + } + }); + + return { + ...data, + episodes: filteredEpisodes, + total: totalPlayers, + metadata: { + ...data.metadata, + fsvidFiltered: true + } + }; + } + + return data; +} + +// Fonction pour formater les erreurs Coflix +function formatCoflixError(error, context = '') { + if (error && error.isAxiosError) { + const url = error.config && error.config.url ? error.config.url : ''; + const statusCode = error.response ? error.response.status : ''; + const statusText = error.response ? error.response.statusText : ''; + + // Ne pas logger les erreurs 400 + if (statusCode === 400) { + return ''; + } + + return `[AxiosError] ${error.code || ''} ${error.message} ${statusCode ? `(${statusCode} ${statusText})` : ''} ${url}`; + } else { + const msg = error && error.message + ? error.message + : (typeof error === 'string' ? error : JSON.stringify(error)); + return msg; + } +} + +module.exports = { + configure, + + // Darkino + generateDarkiReferer, + axiosDarkinoRequest, + + // Coflix + axiosCoflixRequest, + formatCoflixError, + + // French-Stream + axiosFrenchStreamRequest, + + // LecteurVideo + axiosLecteurVideoRequest, + + // FStream + axiosFStreamRequest, + + // AnimeSama + axiosAnimeSamaRequest, + + // Wiflix + axiosWiflixRequest, + + // Streaming link utilities + mergeStreamingLinks, + migrateOldCacheFiles, + cleanupOldCacheFiles, + + // FStream player filter + removeFsvidPlayers +}; diff --git a/API/Mainapi/utils/cacheManager.js b/API/Mainapi/utils/cacheManager.js new file mode 100644 index 0000000..e498a18 --- /dev/null +++ b/API/Mainapi/utils/cacheManager.js @@ -0,0 +1,430 @@ +/** + * Cache management utilities. + * Extracted from server.js — centralizes all file-based and memory cache helpers. + */ + +const fsp = require('fs').promises; +const path = require('path'); +const crypto = require('crypto'); +const writeFileAtomic = require('write-file-atomic'); +const { memoryCache } = require('../config/redis'); + +// === CACHE DIRECTORIES === +// NOTE: __dirname is API/utils/, so we go up one level to reach API/ +const ANIME_SAMA_CACHE_DIR = path.join(__dirname, '..', 'cache', 'anime-sama'); + +const CACHE_DIR = { + ANIME_SAMA: ANIME_SAMA_CACHE_DIR, + COFLIX: path.join(__dirname, '..', 'cache', 'coflix'), + FSTREAM: path.join(__dirname, '..', 'cache', 'fstream'), + CPASMAL: path.join(__dirname, '..', 'cache', 'cpasmal'), + TVDIRECT: path.join(__dirname, '..', 'cache', 'tvdirect'), + PURSTREAM: path.join(__dirname, '..', 'cache', 'purstream'), + NOCTAFLIX: path.join(__dirname, '..', 'cache', 'noctaflix'), + FTV: path.join(__dirname, '..', 'cache', 'ftv') +}; + +const DEFAULT_CACHE_REFRESH_WINDOW_MS = 40 * 60 * 1000; + +// Cr\u00e9er les dossiers de cache s'ils n'existent pas +(async () => { + for (const dir of Object.values(CACHE_DIR)) { + try { + await fsp.access(dir); + } catch { + await fsp.mkdir(dir, { recursive: true }); + } + } +})(); + +// Fonction pour g\u00e9n\u00e9rer une cl\u00e9 de cache bas\u00e9e sur les param\u00e8tres +const generateCacheKey = (params) => { + const stringParams = typeof params === 'string' ? params : JSON.stringify(params); + return crypto.createHash('md5').update(stringParams).digest('hex'); +}; + +// Fonction pour corriger le type de stream bas\u00e9 sur l'URL +const correctStreamType = (streamData) => { + if (streamData && streamData.url && streamData.url.includes('.mp4')) { + return { + ...streamData, + type: 'mp4' + }; + } + return streamData; +}; + +// Fonction pour v\u00e9rifier si une donn\u00e9e est en cache avec expiration de 8h +const getFromCacheWithExpiration = async (cacheDir, key, expirationHours = 8) => { + try { + // 1. V\u00e9rifier le cache m\u00e9moire (L1) (rapide) + // Si c'est en m\u00e9moire (TTL 5 min), c'est forc\u00e9ment valide (< 8h) + const memKey = `${cacheDir}:${key}`; + const memData = await memoryCache.get(memKey); + if (memData) { + if (process.env.DEBUG_CACHE) console.log(`[Cache] Memory hit for ${key}`); + return memData; + } + + // 2. V\u00e9rifier le cache fichier (L2) (lent) + const cacheFilePath = path.join(cacheDir, `${key}.json`); + let stats; + try { + stats = await fsp.stat(cacheFilePath); + } catch (e) { + if (e.code === 'ENOENT') return null; + throw e; + } + + const now = Date.now(); + const fileTime = stats.mtime.getTime(); + const expirationTime = expirationHours * 60 * 60 * 1000; // en millisecondes + + // V\u00e9rifier si le cache a expir\u00e9 + if (now - fileTime > expirationTime) { + return null; + } + + const fileContent = await fsp.readFile(cacheFilePath, 'utf8'); + const cacheData = JSON.parse(fileContent); + + // Mettre \u00e0 jour le cache m\u00e9moire pour les prochaines fois + await memoryCache.set(memKey, cacheData); + + return cacheData; + } catch (error) { + if (error.code === 'ENOENT') { + return null; + } + console.error(`Erreur lors de la r\u00e9cup\u00e9ration du cache pour ${key}:`, error); + return null; + } +}; + +// Fonction pour sauvegarder des donn\u00e9es en cache +const saveToCache = async (cacheDir, key, data) => { + try { + const cacheFilePath = path.join(cacheDir, `${key}.json`); + + // S'assurer que le dossier de cache existe + await fsp.mkdir(cacheDir, { recursive: true }); + + // OPTIMISATION: Utiliser write-file-atomic directement sans lockfile + // lockfile (utilis\u00e9 dans safeWriteFile) ajoute 50-100ms de latence par \u00e9criture + // Pour des fichiers de cache temporaires, atomic write suffit largement + await writeFileAtomic(cacheFilePath, JSON.stringify(data), { encoding: 'utf8', fsync: false }); + + // Mettre aussi en cache m\u00e9moire pour \u00e9viter les lectures disque + await memoryCache.set(`${cacheDir}:${key}`, data); + return true; + } catch (error) { + console.error(`Erreur lors de la sauvegarde en cache pour ${key}:`, error); + return false; + } +}; + +// === CACHE EN MÉMOIRE POUR ÉVITER LES REQUÊTES DUPLIQUÉES === +// Map pour stocker les promesses en cours d'exécution +const ongoingFStreamRequests = new Map(); +const FSTREAM_REQUEST_TIMEOUT = 8000; +const FSTREAM_STALE_CLEANUP_MS = 5 * 60 * 1000; // 5 min max + +// Fonction pour obtenir ou créer une requête FStream partagée +const getOrCreateFStreamRequest = async (cacheKey, requestFunction) => { + // Si une requête est déjà en cours pour cette clé, retourner la promesse existante + if (ongoingFStreamRequests.has(cacheKey)) { + const entry = ongoingFStreamRequests.get(cacheKey); + let dedupTimer; + return Promise.race([ + entry.promise.finally(() => clearTimeout(dedupTimer)), + new Promise((_, reject) => { dedupTimer = setTimeout(() => reject(new Error('timeout of 6000ms exceeded')), FSTREAM_REQUEST_TIMEOUT); }) + ]); + } + + // Créer une nouvelle promesse et la stocker + const requestPromise = (async () => { + let timeoutTimer; + try { + const result = await Promise.race([ + requestFunction().finally(() => clearTimeout(timeoutTimer)), + new Promise((_, reject) => { + timeoutTimer = setTimeout(() => { + ongoingFStreamRequests.delete(cacheKey); + reject(new Error('timeout of 6000ms exceeded')); + }, FSTREAM_REQUEST_TIMEOUT); + }) + ]); + return result; + } finally { + clearTimeout(timeoutTimer); + ongoingFStreamRequests.delete(cacheKey); + } + })(); + + ongoingFStreamRequests.set(cacheKey, { promise: requestPromise, createdAt: Date.now() }); + + return requestPromise; +}; + +// Nettoyage automatique des requêtes expirées (toutes les 2 minutes pour réagir plus vite) +setInterval(() => { + const now = Date.now(); + let cleaned = 0; + + for (const [key, entry] of ongoingFStreamRequests) { + if (entry.createdAt && (now - entry.createdAt > FSTREAM_STALE_CLEANUP_MS)) { + ongoingFStreamRequests.delete(key); + cleaned++; + } + } + + if (cleaned > 0) { + console.log(`[FSTREAM DEDUP] Nettoyage automatique: ${cleaned} requêtes expirées supprimées`); + } +}, 2 * 60 * 1000).unref(); // Toutes les 2 minutes — unref to not prevent process exit + +// Fonction pour sauvegarder des donn\u00e9es FStream en cache +const saveFStreamToCache = async (cacheKey, data) => { + try { + const cacheFilePath = path.join(CACHE_DIR.FSTREAM, `${cacheKey}.json`); + const cacheData = { + data: data + }; + + // Utiliser l'\u00e9criture atomique pour les fichiers de cache FStream + await writeFileAtomic(cacheFilePath, JSON.stringify(cacheData), 'utf8'); + // Mettre aussi en cache m\u00e9moire + await memoryCache.set(`fstream:${cacheKey}`, cacheData); + return true; + } catch (error) { + console.error(`[FSTREAM CACHE] Erreur lors de la sauvegarde en cache pour ${cacheKey}:`, error); + return false; + } +}; + +// Fonction pour g\u00e9n\u00e9rer une cl\u00e9 de cache FStream +const generateFStreamCacheKey = (type, id, season = null, episode = null) => { + const params = { type, id, season, episode }; + return crypto.createHash('md5').update(JSON.stringify(params)).digest('hex'); +}; + +// Fonction pour nettoyer le cache FStream +const clearFStreamCache = async () => { + try { + const cacheDir = CACHE_DIR.FSTREAM; + const files = await fsp.readdir(cacheDir); + + for (const file of files) { + if (file.endsWith('.json')) { + await fsp.unlink(path.join(cacheDir, file)); + } + } + + return { success: true, deletedFiles: files.length }; + } catch (error) { + console.error(`[FSTREAM CACHE] Erreur lors du nettoyage: ${error.message}`); + return { success: false, error: error.message }; + } +}; + +// Fonction pour v\u00e9rifier si une donn\u00e9e FStream est en cache +const getFStreamFromCache = async (cacheKey) => { + try { + const cacheFilePath = path.join(CACHE_DIR.FSTREAM, `${cacheKey}.json`); + const cacheData = JSON.parse(await fsp.readFile(cacheFilePath, 'utf8')); + + return cacheData.data; + } catch (error) { + if (error.code === 'ENOENT') { + return null; + } + console.error(`[FSTREAM CACHE] Erreur lors de la r\u00e9cup\u00e9ration du cache pour ${cacheKey}:`, error); + return null; + } +}; + +// Fonction pour vérifier si une donnée est en cache sans vérifier la date d'expiration +const getFromCacheNoExpiration = async (cacheDir, key) => { + try { + // 1. Vérifier le cache mémoire (L1) + const memKey = `${cacheDir}:${key}`; + const memData = await memoryCache.get(memKey); + if (memData) { + return memData; + } + + const cacheFilePath = path.join(cacheDir, `${key}.json`); + let fileContent; + try { + fileContent = await fsp.readFile(cacheFilePath, 'utf8'); + } catch (e) { + if (e.code === 'ENOENT') return null; + throw e; + } + + const cacheData = JSON.parse(fileContent); + + // Validation: s'assurer que les données en cache ne sont pas du texte "Maintenance en cours" + if (typeof cacheData === 'string' && cacheData.includes('Maintenance en cours')) { + console.error(`Cache invalide détecté pour ${key} - contient "Maintenance en cours"`); + try { await fsp.unlink(cacheFilePath); } catch (unlinkError) { } + return null; + } + + // Validation: s'assurer que les données en cache sont bien du JSON valide et pas du texte brut + if (typeof cacheData === 'string' || cacheData === null || cacheData === undefined) { + console.error(`Cache invalide détecté pour ${key} - données non-JSON ou nulles`); + try { await fsp.unlink(cacheFilePath); } catch (unlinkError) { } + return null; + } + + // Mettre en cache mémoire + await memoryCache.set(memKey, cacheData); + + return cacheData; + } catch (error) { + if (error.code === 'ENOENT') { + return null; + } + console.error(`Erreur lors de la récupération du cache pour ${key}:`, error); + return null; + } +}; + +// Fonction utilitaire pour vérifier si un fichier de cache a été modifié dans les 40 dernières minutes +const shouldUpdateCache = async (cacheDir, cacheKey) => { + const cacheFilePath = path.join(cacheDir, `${cacheKey}.json`); + try { + const stats = await fsp.stat(cacheFilePath); + const now = Date.now(); + const fileAge = now - stats.mtime.getTime(); + const fortyMinutes = 40 * 60 * 1000; // 40 minutes en millisecondes + + if (fileAge < fortyMinutes) { + return false; // Ne pas mettre à jour le cache + } + return true; // Mettre à jour le cache + } catch (error) { + // Si le fichier n'existe pas ou erreur de lecture, continuer avec la mise à jour + return true; + } +}; + +// Fonction pour vérifier si le cache French-Stream doit être mis à jour (3 heures) +const getCacheRefreshInfo = async (cacheDir, cacheKey, refreshWindowMs = DEFAULT_CACHE_REFRESH_WINDOW_MS) => { + const cacheFilePath = path.join(cacheDir, `${cacheKey}.json`); + try { + const stats = await fsp.stat(cacheFilePath); + const now = Date.now(); + const lastModifiedAtMs = stats.mtime.getTime(); + const refreshAvailableAtMs = lastModifiedAtMs + refreshWindowMs; + const refreshInMs = Math.max(refreshAvailableAtMs - now, 0); + + return { + shouldRefreshNow: refreshInMs === 0, + cacheLastModifiedAt: new Date(lastModifiedAtMs).toISOString(), + refreshAvailableAt: new Date(refreshAvailableAtMs).toISOString(), + refreshInMs, + refreshInMinutes: Math.ceil(refreshInMs / 60000) + }; + } catch (error) { + return { + shouldRefreshNow: true, + cacheLastModifiedAt: null, + refreshAvailableAt: null, + refreshInMs: 0, + refreshInMinutes: 0 + }; + } +}; + +// Fonction pour rafraichir la date d'un cache sans ecraser son contenu +const touchCacheEntry = async (cacheDir, key) => { + try { + const cacheFilePath = path.join(cacheDir, `${key}.json`); + const now = new Date(); + await fsp.utimes(cacheFilePath, now, now); + return true; + } catch (error) { + if (error.code === 'ENOENT') { + return false; + } + console.error(`Erreur lors du rafraichissement du cache pour ${key}:`, error); + return false; + } +}; + +const shouldUpdateCacheFrenchStream = async (cacheDir, cacheKey) => { + const cacheFilePath = path.join(cacheDir, `${cacheKey}.json`); + try { + const stats = await fsp.stat(cacheFilePath); + const now = Date.now(); + const fileAge = now - stats.mtime.getTime(); + const threeHours = 3 * 60 * 60 * 1000; // 3 heures en millisecondes + + if (fileAge < threeHours) { + return false; // Ne pas mettre à jour le cache + } + return true; // Mettre à jour le cache + } catch (error) { + return true; + } +}; + +// Fonction pour vérifier si le cache LecteurVideo doit être mis à jour (2 heures) +const shouldUpdateCacheLecteurVideo = async (cacheDir, cacheKey) => { + const cacheFilePath = path.join(cacheDir, `${cacheKey}.json`); + try { + const stats = await fsp.stat(cacheFilePath); + const now = Date.now(); + const fileAge = now - stats.mtime.getTime(); + const twoHours = 2 * 60 * 60 * 1000; // 2 heures en millisecondes + + if (fileAge < twoHours) { + return false; // Ne pas mettre à jour le cache + } + return true; // Mettre à jour le cache + } catch (error) { + return true; + } +}; + +// Fonction pour vérifier si le cache doit être mis à jour (24 heures) - utilisée pour la route decode +const shouldUpdateCache24h = async (cacheDir, cacheKey) => { + const cacheFilePath = path.join(cacheDir, `${cacheKey}.json`); + try { + const stats = await fsp.stat(cacheFilePath); + const now = Date.now(); + const fileAge = now - stats.mtime.getTime(); + const twentyFourHours = 24 * 60 * 60 * 1000; // 24 heures en millisecondes + + if (fileAge < twentyFourHours) { + return false; // Ne pas mettre à jour le cache + } + return true; // Mettre à jour le cache + } catch (error) { + return true; + } +}; + +module.exports = { + CACHE_DIR, + ANIME_SAMA_CACHE_DIR, + generateCacheKey, + correctStreamType, + getFromCacheWithExpiration, + getFromCacheNoExpiration, + saveToCache, + touchCacheEntry, + getCacheRefreshInfo, + shouldUpdateCache, + shouldUpdateCacheFrenchStream, + shouldUpdateCacheLecteurVideo, + shouldUpdateCache24h, + ongoingFStreamRequests, + getOrCreateFStreamRequest, + saveFStreamToCache, + generateFStreamCacheKey, + clearFStreamCache, + getFStreamFromCache +}; diff --git a/API/Mainapi/utils/cloneLinks.js b/API/Mainapi/utils/cloneLinks.js new file mode 100644 index 0000000..84ec787 --- /dev/null +++ b/API/Mainapi/utils/cloneLinks.js @@ -0,0 +1,565 @@ +const axios = require('axios'); +const { getPool } = require('../mysqlPool'); + +const UQLOAD_BASE_URL = 'https://uqload.is'; +const DEFAULT_PENDING_RECHECK_MS = 60 * 1000; +const DEFAULT_FAILED_RETRY_MS = 30 * 60 * 1000; +const CLONE_LINKS_TABLE = 'clone_links'; +const LEGACY_CLONE_LINKS_TABLE = 'coflix_clone_links'; + +let ensureCloneLinksStoragePromise = null; +const ongoingCloneSyncs = new Map(); + +function getConfiguredUqloadBaseUrl() { + return UQLOAD_BASE_URL.replace(/\/+$/, ''); +} + +function getUqloadApiKey() { + return String(process.env.UQLOAD_API_KEY || '').trim(); +} + +function getUqloadApiBaseUrl() { + return `${getConfiguredUqloadBaseUrl()}/api`; +} + +function getPendingRecheckMs() { + const parsed = parseInt(process.env.CLONE_LINKS_PENDING_RECHECK_MS || '', 10); + return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_PENDING_RECHECK_MS; +} + +function getFailedRetryMs() { + const parsed = parseInt(process.env.CLONE_LINKS_FAILED_RETRY_MS || '', 10); + return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_FAILED_RETRY_MS; +} + +function normalizeScope({ mediaType, tmdbId, seasonNumber = 0, episodeNumber = 0 }) { + return { + mediaType: mediaType === 'tv' ? 'tv' : 'movie', + tmdbId: Number(tmdbId) || 0, + seasonNumber: mediaType === 'tv' ? Number(seasonNumber) || 0 : 0, + episodeNumber: mediaType === 'tv' ? Number(episodeNumber) || 0 : 0 + }; +} + +function getSyncKey(scope, sourceFileCode) { + return [ + scope.mediaType, + scope.tmdbId, + scope.seasonNumber, + scope.episodeNumber, + sourceFileCode + ].join(':'); +} + +function runWithSyncDedup(syncKey, task) { + if (ongoingCloneSyncs.has(syncKey)) { + return ongoingCloneSyncs.get(syncKey); + } + + const promise = (async () => { + try { + return await task(); + } finally { + ongoingCloneSyncs.delete(syncKey); + } + })(); + + ongoingCloneSyncs.set(syncKey, promise); + return promise; +} + +function shouldRecheck(lastCheckedAt, intervalMs) { + if (!lastCheckedAt) return true; + + const parsedDate = new Date(lastCheckedAt); + if (Number.isNaN(parsedDate.getTime())) return true; + + return Date.now() - parsedDate.getTime() >= intervalMs; +} + +function sanitizeError(error) { + if (!error) return 'Erreur inconnue'; + if (typeof error === 'string') return error.slice(0, 1000); + if (error.response?.data?.msg) return String(error.response.data.msg).slice(0, 1000); + if (error.message) return String(error.message).slice(0, 1000); + try { + return JSON.stringify(error).slice(0, 1000); + } catch { + return 'Erreur inconnue'; + } +} + +function buildUqloadEmbedUrl(fileCode) { + if (!fileCode) return null; + return `${getConfiguredUqloadBaseUrl()}/embed-${fileCode}.html`; +} + +function isUqloadUrl(rawUrl) { + if (!rawUrl || typeof rawUrl !== 'string') return false; + + const lowerUrl = rawUrl.toLowerCase(); + if (lowerUrl.includes('uqload')) { + return true; + } + + try { + const configuredHost = new URL(getConfiguredUqloadBaseUrl()).hostname.toLowerCase(); + const parsedHost = new URL(rawUrl).hostname.toLowerCase(); + return parsedHost === configuredHost; + } catch { + return false; + } +} + +function extractUqloadFileCode(rawUrl) { + if (!rawUrl || typeof rawUrl !== 'string') return null; + + const candidates = [rawUrl]; + try { + candidates.push(decodeURIComponent(rawUrl)); + } catch { + // Ignore malformed encoded URLs. + } + + const patterns = [ + /embed-([a-z0-9]+)\.html/i, + /\/e\/([a-z0-9]+)/i, + /\/f\/([a-z0-9]+)/i, + /\/([a-z0-9]{8,})(?:\.html)?(?:[?#].*)?$/i + ]; + + for (const candidate of candidates) { + if (!isUqloadUrl(candidate)) { + continue; + } + + for (const pattern of patterns) { + const match = candidate.match(pattern); + if (match?.[1]) { + return match[1]; + } + } + } + + return null; +} + +function getPreferredCloneUrl(playerLink) { + if (!playerLink || typeof playerLink !== 'object') return ''; + if (typeof playerLink.clone_url === 'string' && playerLink.clone_url.trim()) return playerLink.clone_url.trim(); + if (typeof playerLink.decoded_url === 'string' && playerLink.decoded_url.trim()) return playerLink.decoded_url.trim(); + if (typeof playerLink.iframe_src === 'string' && playerLink.iframe_src.trim()) return playerLink.iframe_src.trim(); + if (typeof playerLink.url === 'string' && playerLink.url.trim()) return playerLink.url.trim(); + return ''; +} + +async function ensureCloneLinksStorage() { + if (ensureCloneLinksStoragePromise) { + return ensureCloneLinksStoragePromise; + } + + ensureCloneLinksStoragePromise = (async () => { + const pool = getPool(); + if (!pool) { + throw new Error('MySQL pool not ready for clone links'); + } + + await pool.execute(` + CREATE TABLE IF NOT EXISTS ${CLONE_LINKS_TABLE} ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + provider ENUM('uqload') NOT NULL, + media_type ENUM('movie', 'tv') NOT NULL, + tmdb_id INT NOT NULL, + season_number INT NOT NULL DEFAULT 0, + episode_number INT NOT NULL DEFAULT 0, + source_file_code VARCHAR(64) NOT NULL, + clone_file_code VARCHAR(64) DEFAULT NULL, + clone_embed_url VARCHAR(2048) DEFAULT NULL, + status ENUM('pending', 'ready', 'failed') NOT NULL DEFAULT 'pending', + last_error TEXT DEFAULT NULL, + last_checked_at DATETIME DEFAULT NULL, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + UNIQUE KEY uniq_clone_scope (provider, media_type, tmdb_id, season_number, episode_number, source_file_code), + KEY idx_clone_lookup (media_type, tmdb_id, season_number, episode_number), + KEY idx_clone_status (status) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci + `); + + const [legacyTables] = await pool.query(`SHOW TABLES LIKE ?`, [LEGACY_CLONE_LINKS_TABLE]); + if (Array.isArray(legacyTables) && legacyTables.length > 0) { + await pool.query(` + INSERT IGNORE INTO ${CLONE_LINKS_TABLE} ( + id, + provider, + media_type, + tmdb_id, + season_number, + episode_number, + source_file_code, + clone_file_code, + clone_embed_url, + status, + last_error, + last_checked_at, + created_at, + updated_at + ) + SELECT + id, + provider, + media_type, + tmdb_id, + season_number, + episode_number, + source_file_code, + clone_file_code, + clone_embed_url, + status, + last_error, + last_checked_at, + created_at, + updated_at + FROM ${LEGACY_CLONE_LINKS_TABLE} + `); + } + })().catch((error) => { + ensureCloneLinksStoragePromise = null; + throw error; + }); + + return ensureCloneLinksStoragePromise; +} + +async function getCloneRow(scope, sourceFileCode) { + await ensureCloneLinksStorage(); + const pool = getPool(); + const [rows] = await pool.execute( + `SELECT id, provider, media_type, tmdb_id, season_number, episode_number, source_file_code, + clone_file_code, clone_embed_url, status, last_error, last_checked_at, created_at, updated_at + FROM ${CLONE_LINKS_TABLE} + WHERE provider = 'uqload' + AND media_type = ? + AND tmdb_id = ? + AND season_number = ? + AND episode_number = ? + AND source_file_code = ? + LIMIT 1`, + [scope.mediaType, scope.tmdbId, scope.seasonNumber, scope.episodeNumber, sourceFileCode] + ); + + return rows[0] || null; +} + +async function getReadyCloneRows(scope, sourceFileCodes) { + await ensureCloneLinksStorage(); + const uniqueCodes = [...new Set(sourceFileCodes.filter(Boolean))]; + if (uniqueCodes.length === 0) { + return []; + } + + const pool = getPool(); + const placeholders = uniqueCodes.map(() => '?').join(', '); + const [rows] = await pool.execute( + `SELECT source_file_code, clone_file_code, clone_embed_url, status + FROM ${CLONE_LINKS_TABLE} + WHERE provider = 'uqload' + AND media_type = ? + AND tmdb_id = ? + AND season_number = ? + AND episode_number = ? + AND status = 'ready' + AND source_file_code IN (${placeholders})`, + [scope.mediaType, scope.tmdbId, scope.seasonNumber, scope.episodeNumber, ...uniqueCodes] + ); + + return rows; +} + +async function persistCloneRow(scope, payload) { + await ensureCloneLinksStorage(); + const pool = getPool(); + const lastCheckedAt = payload.lastCheckedAt || new Date(); + + await pool.execute( + `INSERT INTO ${CLONE_LINKS_TABLE} ( + provider, + media_type, + tmdb_id, + season_number, + episode_number, + source_file_code, + clone_file_code, + clone_embed_url, + status, + last_error, + last_checked_at + ) VALUES ('uqload', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON DUPLICATE KEY UPDATE + clone_file_code = IFNULL(VALUES(clone_file_code), clone_file_code), + clone_embed_url = IFNULL(VALUES(clone_embed_url), clone_embed_url), + status = VALUES(status), + last_error = VALUES(last_error), + last_checked_at = VALUES(last_checked_at), + updated_at = CURRENT_TIMESTAMP`, + [ + scope.mediaType, + scope.tmdbId, + scope.seasonNumber, + scope.episodeNumber, + payload.sourceFileCode, + payload.cloneFileCode || null, + payload.cloneEmbedUrl || null, + payload.status || 'pending', + payload.lastError || null, + lastCheckedAt + ] + ); + + return getCloneRow(scope, payload.sourceFileCode); +} + +async function callUqloadApi(endpoint, params = {}) { + const apiKey = getUqloadApiKey(); + if (!apiKey) { + throw new Error('UQLOAD_API_KEY manquante'); + } + const response = await axios.get(`${getUqloadApiBaseUrl()}${endpoint}`, { + params: { + key: apiKey, + ...params + }, + timeout: 15000, + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36', + 'Accept': 'application/json' + }, + validateStatus: () => true + }); + + if (response.status >= 400) { + throw new Error(`Uqload HTTP ${response.status}`); + } + + const payload = response.data; + if (!payload || Number(payload.status) !== 200) { + throw new Error(payload?.msg || 'Erreur API Uqload'); + } + + return payload.result; +} + +function extractReturnedFileCode(result) { + if (!result) return null; + if (typeof result === 'string' && result.trim()) return result.trim(); + if (Array.isArray(result)) { + for (const item of result) { + const nestedCode = extractReturnedFileCode(item); + if (nestedCode) return nestedCode; + } + return null; + } + + return result.filecode || result.file_code || result.code || result.clone_file_code || null; +} + +async function cloneFileByCode(sourceFileCode) { + const result = await callUqloadApi('/file/clone', { file_code: sourceFileCode }); + const cloneFileCode = extractReturnedFileCode(result); + + if (!cloneFileCode) { + throw new Error('Aucun filecode renvoye par file/clone'); + } + + return cloneFileCode; +} + +async function fetchCloneFileInfo(fileCode) { + const result = await callUqloadApi('/file/info', { file_code: fileCode }); + const fileInfo = Array.isArray(result) ? result[0] : null; + + if (!fileInfo) { + return null; + } + + return { + fileCode: fileInfo.file_code || fileCode, + canPlay: Number(fileInfo.canplay) === 1 + }; +} + +async function syncSingleUqloadClone(scope, playerLink) { + const sourceFileCode = extractUqloadFileCode(playerLink?.decoded_url); + if (!sourceFileCode) { + return null; + } + + const syncKey = getSyncKey(scope, sourceFileCode); + return runWithSyncDedup(syncKey, async () => { + let existingRow = await getCloneRow(scope, sourceFileCode); + + if (existingRow?.status === 'ready' && (existingRow.clone_embed_url || existingRow.clone_file_code)) { + return existingRow; + } + + const canCheckPending = existingRow?.clone_file_code && + existingRow.status === 'pending' && + shouldRecheck(existingRow.last_checked_at, getPendingRecheckMs()); + + const canRetryFailed = existingRow?.status === 'failed' && + shouldRecheck(existingRow.last_checked_at, getFailedRetryMs()); + + if (canCheckPending || (existingRow?.status === 'ready' && existingRow.clone_file_code)) { + try { + const fileInfo = await fetchCloneFileInfo(existingRow.clone_file_code); + if (fileInfo?.canPlay) { + return await persistCloneRow(scope, { + sourceFileCode, + cloneFileCode: fileInfo.fileCode, + cloneEmbedUrl: buildUqloadEmbedUrl(fileInfo.fileCode), + status: 'ready', + lastError: null, + lastCheckedAt: new Date() + }); + } + + return await persistCloneRow(scope, { + sourceFileCode, + cloneFileCode: existingRow.clone_file_code, + cloneEmbedUrl: existingRow.clone_embed_url || buildUqloadEmbedUrl(existingRow.clone_file_code), + status: 'pending', + lastError: null, + lastCheckedAt: new Date() + }); + } catch (error) { + console.warn(`[CLONE LINKS] File info check failed for ${sourceFileCode}: ${sanitizeError(error)}`); + return existingRow; + } + } + + if (existingRow?.status === 'pending' && existingRow.clone_file_code && !canCheckPending) { + return existingRow; + } + + if (existingRow?.status === 'failed' && !canRetryFailed) { + return existingRow; + } + + try { + const cloneFileCode = await cloneFileByCode(sourceFileCode); + existingRow = await persistCloneRow(scope, { + sourceFileCode, + cloneFileCode, + cloneEmbedUrl: buildUqloadEmbedUrl(cloneFileCode), + status: 'pending', + lastError: null, + lastCheckedAt: new Date() + }); + + try { + const fileInfo = await fetchCloneFileInfo(cloneFileCode); + if (fileInfo?.canPlay) { + return await persistCloneRow(scope, { + sourceFileCode, + cloneFileCode: fileInfo.fileCode, + cloneEmbedUrl: buildUqloadEmbedUrl(fileInfo.fileCode), + status: 'ready', + lastError: null, + lastCheckedAt: new Date() + }); + } + } catch (error) { + console.warn(`[CLONE LINKS] Immediate file info check failed for ${sourceFileCode}: ${sanitizeError(error)}`); + } + + return existingRow; + } catch (error) { + console.error(`[CLONE LINKS] Upload failed for ${sourceFileCode}: ${sanitizeError(error)}`); + return await persistCloneRow(scope, { + sourceFileCode, + cloneFileCode: existingRow?.clone_file_code || null, + cloneEmbedUrl: existingRow?.clone_embed_url || null, + status: 'failed', + lastError: sanitizeError(error), + lastCheckedAt: new Date() + }); + } + }); +} + +async function applyCloneUrlsToPlayerLinks({ mediaType, tmdbId, seasonNumber = 0, episodeNumber = 0, playerLinks }) { + try { + if (!Array.isArray(playerLinks) || playerLinks.length === 0) { + return Array.isArray(playerLinks) ? playerLinks : []; + } + + const scope = normalizeScope({ mediaType, tmdbId, seasonNumber, episodeNumber }); + const sourceCodes = playerLinks + .map((playerLink) => extractUqloadFileCode(playerLink?.decoded_url)) + .filter(Boolean); + + if (sourceCodes.length === 0) { + return playerLinks; + } + + const readyRows = await getReadyCloneRows(scope, sourceCodes); + const readyMap = new Map( + readyRows.map((row) => [ + row.source_file_code, + row.clone_embed_url || buildUqloadEmbedUrl(row.clone_file_code) + ]) + ); + + return playerLinks.map((playerLink) => { + const sourceFileCode = extractUqloadFileCode(playerLink?.decoded_url); + if (!sourceFileCode) { + return playerLink; + } + + const cloneUrl = readyMap.get(sourceFileCode); + if (!cloneUrl) { + return playerLink; + } + + return { + ...playerLink, + clone_url: cloneUrl + }; + }); + } catch (error) { + console.error(`[CLONE LINKS] applyCloneUrlsToPlayerLinks failed: ${sanitizeError(error)}`); + return Array.isArray(playerLinks) ? playerLinks : []; + } +} + +async function syncCloneLinksForPlayerLinks({ mediaType, tmdbId, seasonNumber = 0, episodeNumber = 0, playerLinks }) { + try { + if (!Array.isArray(playerLinks) || playerLinks.length === 0) { + return Array.isArray(playerLinks) ? playerLinks : []; + } + + const scope = normalizeScope({ mediaType, tmdbId, seasonNumber, episodeNumber }); + for (const playerLink of playerLinks) { + if (!extractUqloadFileCode(playerLink?.decoded_url)) { + continue; + } + + await syncSingleUqloadClone(scope, playerLink); + } + + return applyCloneUrlsToPlayerLinks({ mediaType, tmdbId, seasonNumber, episodeNumber, playerLinks }); + } catch (error) { + console.error(`[CLONE LINKS] syncCloneLinksForPlayerLinks failed: ${sanitizeError(error)}`); + return Array.isArray(playerLinks) ? playerLinks : []; + } +} + +module.exports = { + ensureCloneLinksStorage, + getConfiguredUqloadBaseUrl, + buildUqloadEmbedUrl, + extractUqloadFileCode, + getPreferredCloneUrl, + applyCloneUrlsToPlayerLinks, + syncCloneLinksForPlayerLinks +}; diff --git a/API/Mainapi/utils/concurrency.js b/API/Mainapi/utils/concurrency.js new file mode 100644 index 0000000..2a5d237 --- /dev/null +++ b/API/Mainapi/utils/concurrency.js @@ -0,0 +1,56 @@ +/** + * Concurrency limiter (p-limit style). + * Extracted from server.js — limits parallel promise execution. + */ + +// === LIMITEUR DE CONCURRENCE (p-limit style) === +// Fonction pour limiter le nombre de promesses exécutées en parallèle +function createConcurrencyLimiter(concurrency, maxQueueSize = 200) { + const queue = []; + let activeCount = 0; + + const next = () => { + activeCount = Math.max(0, activeCount - 1); + if (queue.length > 0) { + queue.shift()(); + } + }; + + const run = async (fn) => { + activeCount++; + try { + return await fn(); + } finally { + next(); + } + }; + + const enqueue = (fn) => { + return new Promise((resolve, reject) => { + if (activeCount >= concurrency && queue.length >= maxQueueSize) { + reject(new Error(`Concurrency queue full (${maxQueueSize} pending tasks)`)); + return; + } + const task = () => run(fn).then(resolve, reject); + if (activeCount < concurrency) { + task(); + } else { + queue.push(task); + } + }); + }; + + return enqueue; +} + +// Limiteurs pré-configurés pour différents cas d'usage +const limitConcurrency5 = createConcurrencyLimiter(5); // Pour les requêtes réseau légères +const limitConcurrency3 = createConcurrencyLimiter(3); // Pour les requêtes réseau lourdes +const limitConcurrency10 = createConcurrencyLimiter(10); // Pour les opérations I/O locales + +module.exports = { + createConcurrencyLimiter, + limitConcurrency5, + limitConcurrency3, + limitConcurrency10 +}; diff --git a/API/Mainapi/utils/discord.js b/API/Mainapi/utils/discord.js new file mode 100644 index 0000000..598fb97 --- /dev/null +++ b/API/Mainapi/utils/discord.js @@ -0,0 +1,44 @@ +/** + * Discord webhook for sync error logging. + * Extracted from server.js — sends error embeds to a Discord channel. + */ + +const axios = require('axios'); + +// === DISCORD WEBHOOK POUR LES ERREURS DE SYNC === +const SYNC_ERROR_WEBHOOK = process.env.DISCORD_SYNC_ERROR_WEBHOOK_URL; + +async function logSyncErrorToDiscord(errorMessage, context = {}) { + if (!SYNC_ERROR_WEBHOOK) return; // Skip if webhook not configured + try { + const embed = { + title: '\u274c Erreur de Sync', + color: 0xff0000, + description: errorMessage, + fields: [ + { name: 'User Type', value: context.userType || 'N/A', inline: true }, + { name: 'User ID', value: context.userId ? `\`${context.userId.substring(0, 8)}...\`` : 'N/A', inline: true }, + { name: 'Profile ID', value: context.profileId ? `\`${context.profileId.substring(0, 8)}...\`` : 'N/A', inline: true }, + ], + timestamp: new Date().toISOString(), + footer: { text: 'Movix Sync API' } + }; + + if (context.error) { + embed.fields.push({ name: 'D\u00e9tails Erreur', value: `\`\`\`${String(context.error).substring(0, 500)}\`\`\``, inline: false }); + } + + if (context.payload) { + // Tronquer le payload pour éviter de dépasser la limite Discord (1024 chars par field) + const payloadStr = JSON.stringify(context.payload, null, 2); + const truncatedPayload = payloadStr.length > 900 ? payloadStr.substring(0, 900) + '\n... (tronqu\u00e9)' : payloadStr; + embed.fields.push({ name: 'Payload Requ\u00eate', value: `\`\`\`json\n${truncatedPayload}\`\`\``, inline: false }); + } + + await axios.post(SYNC_ERROR_WEBHOOK, { embeds: [embed] }, { timeout: 5000 }).catch(() => { }); + } catch (e) { + // Silently fail - don't break sync if webhook fails + } +} + +module.exports = { logSyncErrorToDiscord }; diff --git a/API/Mainapi/utils/proxyManager.js b/API/Mainapi/utils/proxyManager.js new file mode 100644 index 0000000..f6216a6 --- /dev/null +++ b/API/Mainapi/utils/proxyManager.js @@ -0,0 +1,1378 @@ +/** + * Proxy management utilities. + * Extracted from server.js — centralizes all proxy configuration, agent caching, + * Cloudflare Workers proxy rotation, CORS fallback, and site-specific request helpers. + */ + +const axios = require('axios'); +const http = require('http'); +const https = require('https'); +const { SocksProxyAgent } = require('socks-proxy-agent'); +const { HttpProxyAgent } = require('http-proxy-agent'); +const { HttpsProxyAgent } = require('https-proxy-agent'); +const tough = require('tough-cookie'); +const initCycleTLS = require('cycletls'); + +// === PROXY AGENT CACHES === +const proxyAgentCache = new Map(); +const darkinoProxyAgentCache = new Map(); +const proxyRotationState = new Map(); + +// Initialize global agent keep-alive with socket limits +http.globalAgent.keepAlive = true; +http.globalAgent.maxSockets = 128; +http.globalAgent.maxFreeSockets = 32; +https.globalAgent.keepAlive = true; +https.globalAgent.maxSockets = 128; +https.globalAgent.maxFreeSockets = 32; + +// === PROXY CONFIGURATION FLAGS === +const ENABLE_DARKINO_PROXY = true; // Passe \u00e0 false pour d\u00e9sactiver le proxy pour Darkino +const ENABLE_COFLIX_PROXY = true; // Passe \u00e0 false pour d\u00e9sactiver le proxy pour Coflix +const ENABLE_FRENCH_STREAM_PROXY = true; // Active/d\u00e9sactive le proxy pour French-Stream +const ENABLE_LECTEURVIDEO_PROXY = true; // Active/d\u00e9sactive le proxy pour LecteurVideo +const ENABLE_FSTREAM_PROXY = true; // Active/d\u00e9sactive le proxy pour FStream +const ENABLE_ANIME_PROXY = true; // Active/d\u00e9sactive le proxy pour AnimeSama (via Cloudflare Workers) +const ENABLE_WIFLIX_PROXY = true; // Active/d\u00e9sactive le proxy pour Wiflix +const MAX_LECTEURVIDEO_PROXY_ATTEMPTS = 2; + +// Constante pour l'enhancement Darkino +const darkiworld_premium = false; // Passe \u00e0 false pour d\u00e9sactiver l'enhancement Darkino + +// === DARKINO 403 COOLDOWN === +// Cooldown de 5 minutes apr\u00e8s une erreur 403 (Cloudflare challenge) +const DARKINO_403_COOLDOWN_MS = 5 * 60 * 1000; // 5 minutes +let darkino403CooldownUntil = 0; // Timestamp jusqu'auquel on ne fait plus de requ\u00eates + +// === CPASMAL CONFIGURATION === +const CPASMAL_BASE_URL = 'https://www.cpasmal.rip'; + +const cpasmalJar = new tough.CookieJar(null, { rejectPublicSuffixes: false }); + + +// Cache pour les agents SOCKS5 Cpasmal (Keep-Alive) +const cpasmalAgentCache = new Map(); + +function getCpasmalAgent(proxy) { + if (!proxy) return null; + const cacheKey = `${proxy.type}:${proxy.host}:${proxy.port}:${proxy.auth}`; + + if (cpasmalAgentCache.has(cacheKey)) { + return cpasmalAgentCache.get(cacheKey); + } + + // Configuration Keep-Alive optimis\u00e9e + const agentOpts = { + keepAlive: true, + keepAliveMsecs: 15000, // 15s keep-alive + maxSockets: 50, + maxFreeSockets: 10, + timeout: 30000 + }; + + let agent; + if (proxy.type === 'socks5' || proxy.type === 'socks5h') { + const info = { + hostname: proxy.host, + port: proxy.port, + protocol: 'socks:', + tls: { rejectUnauthorized: false }, + ...agentOpts + }; + + // Auth handling + if (proxy.auth) { + const parts = proxy.auth.split(':'); + info.username = parts[0]; // Correction: userId -> username + info.password = parts[1]; + } + + agent = new SocksProxyAgent(info); + } + + if (agent) { + cpasmalAgentCache.set(cacheKey, agent); + } + return agent; +} + +// Fonction pour faire des requ\u00eates vers Cpasmal avec rotation de proxies SOCKS5 +async function axiosCpasmalRequest(config) { + const urlStr = config.url || ''; + + // Constante pour Cpasmal Base URL si relative + const baseURL = CPASMAL_BASE_URL; + + // Headers par d\u00e9faut + const defaultHeaders = { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', + 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', + 'Accept-Language': 'fr-FR,fr;q=0.9,en;q=0.8', + 'Accept-Encoding': 'gzip, deflate, br', + 'Connection': 'keep-alive', + ...(config.headers || {}) + }; + + // Gestion des cookies (r\u00e9cup\u00e9ration manuelle pour compatibilit\u00e9 avec proxy agent) + if (urlStr || config.baseURL) { + try { + // Reconstitution approximative de l'URL pour les cookies + const targetUrl = urlStr.startsWith('http') ? urlStr : (config.baseURL || baseURL) + urlStr; + const cookieString = await cpasmalJar.getCookieString(targetUrl); + if (cookieString) { + defaultHeaders['Cookie'] = cookieString; + } + } catch (err) { + console.error('[Cpasmal CookieJar] Error getting cookies:', err); + } + } + + // Déterminer les agents proxy à utiliser : + // 1. _cpasmalAgents fournis (session scopée avec DARKINO_PROXIES HTTP) + // 2. _cpasmalProxy fourni (SOCKS5 override) + // 3. Sinon : proxy SOCKS5 aléatoire (legacy) + let httpAgent, httpsAgent, proxyLabel; + + if (config._cpasmalAgents) { + httpAgent = config._cpasmalAgents.httpAgent; + httpsAgent = config._cpasmalAgents.httpsAgent; + proxyLabel = config._cpasmalAgents._label || 'HTTP proxy'; + } else { + const proxy = config._cpasmalProxy !== undefined ? config._cpasmalProxy : pickRandomProxyOrNone(); + const agent = getCpasmalAgent(proxy); + httpAgent = agent; + httpsAgent = agent; + proxyLabel = proxy ? `${proxy.host}:${proxy.port}` : 'Direct'; + } + + // Nettoyer les champs internes avant de passer à axios + const { _cpasmalProxy, _cpasmalAgents, ...cleanConfig } = config; + + try { + if (process.env.DEBUG_CPASMAL === 'true') console.time(`[Cpasmal] Request ${urlStr} (Proxy: ${proxyLabel})`); + + const response = await axios({ + ...cleanConfig, + headers: defaultHeaders, + httpAgent, + httpsAgent, + proxy: false, + timeout: config.timeout || 5000, + decompress: true + }); + + if (process.env.DEBUG_CPASMAL === 'true') console.timeEnd(`[Cpasmal] Request ${urlStr} (Proxy: ${proxyLabel})`); + + // Gestion des cookies (sauvegarde manuelle) + if (response.headers['set-cookie']) { + const cookies = response.headers['set-cookie']; + const url = response.config.url; + try { + if (Array.isArray(cookies)) { + for (const cookie of cookies) { + await cpasmalJar.setCookie(cookie, url); + } + } else { + await cpasmalJar.setCookie(cookies, url); + } + } catch (err) { + console.error('[Cpasmal CookieJar] Error setting cookies:', err); + } + } + + return response; + } catch (error) { + // Ajouter infos debug + error.cpasmalUrl = urlStr; + error.cpasmalProxy = proxyLabel; + + // Propager l'erreur immédiatement + throw error; + } +} + +// === CLOUDFLARE WORKERS PROXIES CONFIGURATION === +const CLOUDFLARE_WORKERS_PROXIES = (process.env.CLOUDFLARE_WORKERS_PROXIES || '') + .split(',') + .map(proxy => proxy.trim()) + .filter(Boolean); + +// === CACHE POUR LES PROXIES CLOUDFLARE EN ERREUR === +// Cache pour m\u00e9moriser les proxies en erreur (429, 500, timeout, etc.) +// Les proxies en erreur seront ignor\u00e9s pendant PROXY_ERROR_COOLDOWN_MS millisecondes +const proxyErrorCache = new Map(); // Map<proxyUrl, { errorTime: timestamp, errorCode: number|string, errorCount: number }> +const PROXY_ERROR_COOLDOWN_MS = 60000; // 60 secondes de cooldown pour un proxy en erreur +const PROXY_ERROR_COOLDOWN_429_MS = 120000; // 2 minutes de cooldown sp\u00e9cifique pour erreur 429 (rate limit) +const PROXY_ERROR_COOLDOWN_5XX_MS = 90000; // 1.5 minutes pour les erreurs serveur (500, 502, 503, 504) +const MAX_CONSECUTIVE_ERRORS = 3; // Nombre max d'erreurs cons\u00e9cutives avant cooldown prolong\u00e9 +const PROXY_EXTENDED_COOLDOWN_MS = 300000; // 5 minutes de cooldown prolong\u00e9 si trop d'erreurs cons\u00e9cutives + +/** + * Marque un proxy comme \u00e9tant en erreur + * @param {string} proxyUrl - URL du proxy + * @param {number|string} errorCode - Code d'erreur (429, 500, 'timeout', etc.) + */ +function markProxyAsErrored(proxyUrl, errorCode) { + const existing = proxyErrorCache.get(proxyUrl); + const errorCount = existing ? existing.errorCount + 1 : 1; + + proxyErrorCache.set(proxyUrl, { + errorTime: Date.now(), + errorCode, + errorCount + }); + + // Log seulement si DEBUG activ\u00e9 + if (process.env.DEBUG_PROXY) { + console.log(`[PROXY CACHE] Proxy marqu\u00e9 en erreur: ${proxyUrl} (code: ${errorCode}, count: ${errorCount})`); + } +} + +/** + * V\u00e9rifie si un proxy est actuellement en cooldown (\u00e0 \u00e9viter) + * @param {string} proxyUrl - URL du proxy + * @returns {boolean} - true si le proxy doit \u00eatre ignor\u00e9 + */ +function isProxyInCooldown(proxyUrl) { + const errorInfo = proxyErrorCache.get(proxyUrl); + if (!errorInfo) return false; + + const now = Date.now(); + const timeSinceError = now - errorInfo.errorTime; + + // D\u00e9terminer le cooldown appropri\u00e9 selon le type d'erreur et le nombre d'erreurs + let cooldownMs; + if (errorInfo.errorCount >= MAX_CONSECUTIVE_ERRORS) { + cooldownMs = PROXY_EXTENDED_COOLDOWN_MS; + } else if (errorInfo.errorCode === 429) { + cooldownMs = PROXY_ERROR_COOLDOWN_429_MS; + } else if (errorInfo.errorCode >= 500 && errorInfo.errorCode < 600) { + cooldownMs = PROXY_ERROR_COOLDOWN_5XX_MS; + } else { + cooldownMs = PROXY_ERROR_COOLDOWN_MS; + } + + // Si le cooldown est pass\u00e9, supprimer l'entr\u00e9e du cache + if (timeSinceError >= cooldownMs) { + proxyErrorCache.delete(proxyUrl); + return false; + } + + return true; +} + +/** + * Retourne la liste des proxies disponibles (non en cooldown) + * @param {string[]} allProxies - Liste de tous les proxies + * @returns {string[]} - Liste des proxies disponibles + */ +function getAvailableProxies(allProxies) { + const available = allProxies.filter(proxy => !isProxyInCooldown(proxy)); + + // Si tous les proxies sont en cooldown, on r\u00e9initialise le cache et on retourne tous les proxies + // pour \u00e9viter de bloquer compl\u00e8tement le service + if (available.length === 0) { + if (process.env.DEBUG_PROXY) { + console.log('[PROXY CACHE] Tous les proxies sont en cooldown, r\u00e9initialisation du cache'); + } + proxyErrorCache.clear(); + return allProxies; + } + + return available; +} + +/** + * R\u00e9initialise le compteur d'erreurs d'un proxy apr\u00e8s un succ\u00e8s + * @param {string} proxyUrl - URL du proxy + */ +function markProxyAsHealthy(proxyUrl) { + proxyErrorCache.delete(proxyUrl); +} + +// Nettoyage p\u00e9riodique du proxyErrorCache — supprime les entr\u00e9es dont le cooldown a expir\u00e9 +setInterval(() => { + const now = Date.now(); + for (const [proxyUrl, errorInfo] of proxyErrorCache) { + const maxCooldown = PROXY_EXTENDED_COOLDOWN_MS; // 5 min = cooldown le plus long + if (now - errorInfo.errorTime > maxCooldown) { + proxyErrorCache.delete(proxyUrl); + } + } +}, 5 * 60 * 1000).unref(); // Toutes les 5 minutes — unref to not prevent process exit + +/** + * Construit l'URL proxy en fonction du type de proxy + * Les proxies se terminant par '/' attendent l'URL encod\u00e9e + * Les proxies se terminant par '?' attendent l'URL non-encod\u00e9e + * @param {string} proxyUrl - URL du proxy Cloudflare + * @param {string} targetUrl - URL cible \u00e0 proxyer + * @returns {string} - URL finale \u00e0 appeler + */ +function buildProxiedUrl(proxyUrl, targetUrl) { + if (proxyUrl.endsWith('/')) { + // Proxy qui attend l'URL encod\u00e9e (ex: cors-worker-1) + return proxyUrl + encodeURIComponent(targetUrl); + } else { + // Proxy qui attend l'URL en query string (ex: ?url=...) + return proxyUrl + targetUrl; + } +} + +// Fonction pour faire une requ\u00eate avec fallback CORS en cas d'erreur 429 +async function makeRequestWithCorsFallback(targetUrl, options = {}) { + const { timeout = 7000, headers = {}, decompress = true, ...otherOptions } = options; + + // Filtrer les proxies disponibles (non en cooldown) + const availableProxies = getAvailableProxies(CLOUDFLARE_WORKERS_PROXIES); + + // Utiliser directement les proxies Cloudflare Workers disponibles + let lastError = null; + + for (let i = 0; i < availableProxies.length; i++) { + const currentProxy = availableProxies[i]; + try { + // Construire l'URL compl\u00e8te : proxy Cloudflare + URL cible (encodage si n\u00e9cessaire) + const finalProxyUrl = buildProxiedUrl(currentProxy, targetUrl); + + const response = await axios.get(finalProxyUrl, { + headers: { + 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', + 'accept-language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7', + 'priority': 'u=1, i', + 'sec-ch-ua': '"Chromium";v="140", "Not=A?Brand";v="24", "Brave";v="140"', + 'sec-ch-ua-mobile': '?0', + 'sec-ch-ua-platform': '"Windows"', + 'sec-fetch-dest': 'document', + 'sec-fetch-mode': 'navigate', + 'sec-fetch-site': 'cross-site', + 'sec-gpc': '1', + 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36', + ...headers + }, + timeout, + decompress, + ...otherOptions + }); + + // Succ\u00e8s : marquer le proxy comme sain + markProxyAsHealthy(currentProxy); + return response; + } catch (proxyError) { + lastError = proxyError; + const statusCode = proxyError.response?.status; + const errorCode = statusCode || proxyError.code || 'unknown'; + + // En cas d'erreur 400 ou 403, arr\u00eat imm\u00e9diat sans r\u00e9essayer avec d'autres proxies + if (statusCode === 400 || statusCode === 403) { + throw proxyError; + } + + // Marquer le proxy en erreur pour les codes 429, 5xx, timeout, etc. + if (statusCode === 429 || (statusCode >= 500 && statusCode < 600) || proxyError.code === 'ECONNABORTED' || proxyError.code === 'ETIMEDOUT') { + markProxyAsErrored(currentProxy, errorCode); + } + + // Si c'est le dernier proxy et qu'on a une erreur, throw l'erreur + if (i === availableProxies.length - 1) { + throw proxyError; + } + // Sinon continuer avec le prochain proxy (429, etc.) + } + } + + // Si on arrive ici, tous les proxies ont \u00e9chou\u00e9 + throw lastError || new Error('Tous les proxies ont \u00e9chou\u00e9'); +} + +// Fonction pour faire une requ\u00eate Coflix avec rotation Cloudflare Workers. +async function makeCoflixRequest(targetUrl, options = {}) { + const { timeout = 15000, headers = {}, decompress = true, ...otherOptions } = options; + + // Nettoyer l'URL pour \u00e9viter les espaces ind\u00e9sirables + const cleanTargetUrl = targetUrl.trim(); + + // Headers pour les requ\u00eates Coflix via proxy + const coflixProxyHeaders = { + 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', + 'accept-encoding': 'gzip, deflate, br', + 'accept-language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7', + 'cache-control': 'no-cache', + 'pragma': 'no-cache', + 'sec-ch-ua': '"Chromium";v="140", "Not=A?Brand";v="24", "Brave";v="140"', + 'sec-ch-ua-mobile': '?0', + 'sec-ch-ua-platform': '"Windows"', + 'sec-fetch-dest': 'document', + 'sec-fetch-mode': 'navigate', + 'sec-fetch-site': 'cross-site', + 'sec-gpc': '1', + 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36', + ...headers + }; + + // Supprimer les headers li\u00e9s \u00e0 l'IP d'origine pour \u00e9viter de les transmettre + const headersToRemove = ['X-Forwarded-For', 'X-Real-IP', 'X-Client-IP', 'CF-Connecting-IP', 'True-Client-IP', 'X-Original-Forwarded-For']; + const cleanHeaders = { ...coflixProxyHeaders }; + headersToRemove.forEach(header => { + delete cleanHeaders[header]; + delete cleanHeaders[header.toLowerCase()]; + }); + + const proxyCandidates = getAvailableProxies(CLOUDFLARE_WORKERS_PROXIES); + let lastError = null; + + if (proxyCandidates.length === 0) { + throw new Error('Aucun Cloudflare Worker proxy disponible pour Coflix'); + } + + // Un 403/429 peut d\u00e9pendre du worker utilise : on tente chaque worker avant d'abandonner. + for (let i = 0; i < proxyCandidates.length; i++) { + const cloudflareProxy = proxyCandidates[i]; + const proxiedUrl = buildProxiedUrl(cloudflareProxy, cleanTargetUrl); + + try { + const response = await axios({ + url: proxiedUrl, + method: otherOptions.method || 'GET', + headers: cleanHeaders, + timeout, + decompress, + responseType: 'text', + responseEncoding: 'utf8', + ...otherOptions + }); + + markProxyAsHealthy(cloudflareProxy); + return response; + } catch (error) { + lastError = error; + const statusCode = error.response?.status; + const errorCode = error.code || 'unknown'; + + error.coflixUrl = cleanTargetUrl; + error.coflixProxy = cloudflareProxy; + error.coflixProxiedUrl = proxiedUrl; + + if (statusCode === 403 || statusCode === 429) { + markProxyAsErrored(cloudflareProxy, statusCode); + continue; + } + + if (statusCode >= 500 && statusCode < 600) { + markProxyAsErrored(cloudflareProxy, statusCode); + continue; + } + + if ( + errorCode === 'ECONNABORTED' || + errorCode === 'ETIMEDOUT' || + errorCode === 'ECONNRESET' || + errorCode === 'EHOSTUNREACH' || + errorCode === 'ENETUNREACH' + ) { + markProxyAsErrored(cloudflareProxy, errorCode); + continue; + } + + // Pour les erreurs fonctionnelles (400, 404, parsing, etc.), arr\u00eater imm\u00e9diatement. + throw error; + } + } + + if (lastError) throw lastError; + throw new Error('Tous les Cloudflare Workers proxies ont \u00e9chou\u00e9 (Coflix)'); +} + +// Fonction pour faire une requete LecteurVideo avec CycleTLS. +// On limite volontairement la rotation a 2 proxies max pour eviter de balayer tout le pool. +// Instance CycleTLS partagee (singleton) +let cycleTLSInstance = null; +let cycleTLSInitializing = false; +const cycleTLSWaiters = []; + +async function getCycleTLS() { + if (cycleTLSInstance) return cycleTLSInstance; + if (cycleTLSInitializing) { + return new Promise((resolve) => cycleTLSWaiters.push(resolve)); + } + cycleTLSInitializing = true; + try { + cycleTLSInstance = await initCycleTLS(); + cycleTLSInitializing = false; + for (const waiter of cycleTLSWaiters) waiter(cycleTLSInstance); + cycleTLSWaiters.length = 0; + return cycleTLSInstance; + } catch (err) { + cycleTLSInitializing = false; + // Reject all waiters so they don't leak forever + for (const waiter of cycleTLSWaiters) waiter(Promise.reject(err)); + cycleTLSWaiters.length = 0; + throw err; + } +} + +// Graceful shutdown: kill CycleTLS Go subprocess +async function shutdownCycleTLS() { + if (cycleTLSInstance) { + try { + await cycleTLSInstance.exit(); + } catch { /* ignore */ } + cycleTLSInstance = null; + } +} + +// JA3 fingerprint Chrome 120+ +const CHROME_JA3 = '771,4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157-47-53,0-23-65281-10-11-35-16-5-13-18-51-45-43-27-17513,29-23-24,0'; +const CHROME_UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'; + +function pickLecteurVideoProxyCandidates() { + const httpPool = HTTP_PROXIES.length > 0 + ? HTTP_PROXIES + : parseProxyPayload(process.env.HTTP_PROXIES, 'http') + .map(entry => sanitizeProxyEntry(entry, 'http')) + .filter(Boolean); + + const socksPool = PROXIES.length > 0 + ? PROXIES + : parseProxyPayload(process.env.SOCKS5_PROXIES, 'socks5') + .map(entry => sanitizeProxyEntry(entry, 'socks5')) + .filter(Boolean); + + const preferredPool = httpPool.length > 0 + ? { proxies: httpPool, useSocks: false, label: 'HTTP_PROXIES' } + : { proxies: socksPool, useSocks: true, label: 'SOCKS5_PROXIES' }; + + if (!preferredPool.proxies || preferredPool.proxies.length === 0) { + return { + proxies: [], + useSocks: false, + label: 'aucun', + totalAvailable: 0 + }; + } + + const selectedProxies = [...preferredPool.proxies] + .sort(() => Math.random() - 0.5) + .slice(0, MAX_LECTEURVIDEO_PROXY_ATTEMPTS); + + return { + proxies: selectedProxies, + useSocks: preferredPool.useSocks, + label: preferredPool.label, + totalAvailable: preferredPool.proxies.length + }; +} + +async function makeLecteurVideoRequest(targetUrl, options = {}) { + const { headers = {} } = options; + const cleanTargetUrl = targetUrl.trim(); + + const { + proxies, + useSocks, + label: proxyPoolLabel, + totalAvailable + } = pickLecteurVideoProxyCandidates(); + + if (!proxies || proxies.length === 0) { + throw new Error('[LECTEURVIDEO] Aucun proxy disponible (HTTP_PROXIES / SOCKS5_PROXIES)'); + } + + const cycleTLS = await getCycleTLS(); + let lastError = null; + + console.log( + `[LECTEURVIDEO] ${proxies.length} proxy(s) retenu(s) sur ${totalAvailable} depuis ${proxyPoolLabel}` + ); + + for (let i = 0; i < proxies.length; i++) { + const proxy = proxies[i]; + const auth = proxy.auth ? `${proxy.auth}@` : ''; + const proxyUrl = useSocks + ? `socks5h://${auth}${proxy.host}:${proxy.port}` + : `http://${auth}${proxy.host}:${proxy.port}`; + + console.log( + `[LECTEURVIDEO] tentative ${i + 1}/${proxies.length} via cycletls + ${proxy.host}:${proxy.port} (${proxyPoolLabel})` + ); + + try { + const response = await cycleTLS(cleanTargetUrl, { + body: '', + ja3: CHROME_JA3, + userAgent: CHROME_UA, + proxy: proxyUrl, + headers: { + 'Referer': 'https://coflix.space/', + 'Origin': 'https://coflix.space', + 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', + 'Accept-Language': 'fr-FR,fr;q=0.9', + ...headers, + }, + timeout: 15, + }, 'get'); + + const body = typeof response.body === 'string' ? response.body : JSON.stringify(response.body); + const title = body.match(/<title>(.*?)<\/title>/i)?.[1] || 'no title'; + console.log(`[LECTEURVIDEO] ${proxy.host}:${proxy.port} -> ${response.status} | title: ${title} | ${body.length} chars`); + + if (response.status === 403 && (body.includes('cf-wrapper') || body.includes('cloudflare'))) { + console.warn(`[LECTEURVIDEO] proxy ${i + 1}/${proxies.length} (${proxy.host}) bloque par Cloudflare, retry...`); + continue; + } + + return { data: body, status: response.status, headers: response.headers || {} }; + } catch (error) { + console.error(`[LECTEURVIDEO] proxy ${i + 1}/${proxies.length} (${proxy.host}) echoue: ${error.message?.substring(0, 100)}`); + lastError = error; + continue; + } + } + + console.error(`[LECTEURVIDEO] tous les proxies ont echoue pour ${cleanTargetUrl}`); + throw lastError || new Error('[LECTEURVIDEO] Tous les proxies ont echoue'); +} + +// === SOCKS5 PROXIES (from env) === +const parseJsonArrayEnv = (envName, fallback = []) => { + const rawValue = process.env[envName]; + if (!rawValue) return fallback; + try { + const parsed = JSON.parse(rawValue); + return Array.isArray(parsed) ? parsed : fallback; + } catch { + return fallback; + } +}; + +const { redis } = require('../config/redis'); +const { acquireRedisLock } = require('./redisLock'); + +const PROXY_ROTATION_REDIS_PREFIX = 'proxyscrape:rotation:v1'; + +function reserveLocalProxyWindow(poolName, poolLength, batchSize) { + const existingCursor = proxyRotationState.get(poolName); + const startIndex = Number.isInteger(existingCursor) + ? existingCursor % poolLength + : Math.floor(Math.random() * poolLength); + + proxyRotationState.set(poolName, (startIndex + batchSize) % poolLength); + return startIndex; +} + +async function reserveProxyWindow(poolName, poolLength, batchSize = 1) { + if (!Number.isFinite(poolLength) || poolLength <= 0) { + return 0; + } + + const safeBatchSize = Math.min( + poolLength, + Math.max(1, Math.floor(Number(batchSize) || 1)) + ); + + try { + const rotationKey = `${PROXY_ROTATION_REDIS_PREFIX}:${poolName}`; + const nextValue = await redis.incrby(rotationKey, safeBatchSize); + const startIndex = Number(nextValue) - safeBatchSize; + return ((startIndex % poolLength) + poolLength) % poolLength; + } catch { + return reserveLocalProxyWindow(poolName, poolLength, safeBatchSize); + } +} + +async function pickNextProxyBatch(pool, count = 1, poolName = 'default') { + if (!Array.isArray(pool) || pool.length === 0) { + return []; + } + + const safeCount = Math.min( + pool.length, + Math.max(1, Math.floor(Number(count) || 1)) + ); + const startIndex = await reserveProxyWindow(poolName, pool.length, safeCount); + const selected = []; + + for (let offset = 0; offset < safeCount; offset++) { + selected.push(pool[(startIndex + offset) % pool.length]); + } + + return selected; +} + +async function pickNextSocks5Proxy() { + const [proxy] = await pickNextProxyBatch(PROXIES, 1, 'SOCKS5_PROXIES'); + return proxy || null; +} + +const splitCsvEnv = (envName, fallback = []) => { + const rawValue = process.env[envName]; + if (!rawValue) return [...fallback]; + return rawValue + .split(',') + .map(value => value.trim()) + .filter(Boolean); +}; + +const parsePositiveIntEnv = (envName, fallback) => { + const rawValue = process.env[envName]; + const parsed = Number.parseInt(rawValue || '', 10); + return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback; +}; + +function normalizeProxyType(type, fallback = 'http') { + const normalized = String(type || fallback).toLowerCase().replace(/:$/, '').trim(); + if (normalized === 'socks' || normalized === 'socks5h' || normalized.startsWith('socks5')) { + return 'socks5'; + } + if (normalized.startsWith('http')) { + return 'http'; + } + return fallback; +} + +function updateArrayInPlace(target, nextValues) { + target.splice(0, target.length, ...nextValues); + return target; +} + +function dedupeProxyEntries(entries = []) { + const seen = new Set(); + return entries.filter(entry => { + if (!entry || !entry.host || !entry.port) return false; + const key = `${entry.type}:${entry.host}:${entry.port}:${entry.auth || ''}`; + if (seen.has(key)) return false; + seen.add(key); + return true; + }); +} + +function sanitizeProxyEntry(entry, fallbackType = 'http') { + if (!entry || !entry.host || !entry.port) return null; + const port = Number.parseInt(entry.port, 10); + if (!Number.isFinite(port) || port <= 0) return null; + return { + host: String(entry.host).trim(), + port, + auth: entry.auth ? String(entry.auth).trim() : undefined, + type: normalizeProxyType(entry.type, fallbackType) + }; +} + +function parseProxyString(value, defaultType = 'http') { + if (!value || typeof value !== 'string') return null; + const rawValue = value.trim(); + if (!rawValue) return null; + + if (/^[a-z]+:\/\//i.test(rawValue)) { + try { + const parsedUrl = new URL(rawValue); + return sanitizeProxyEntry({ + host: parsedUrl.hostname, + port: parsedUrl.port, + auth: parsedUrl.username + ? `${decodeURIComponent(parsedUrl.username)}${parsedUrl.password ? `:${decodeURIComponent(parsedUrl.password)}` : ''}` + : undefined, + type: parsedUrl.protocol.replace(':', '') + }, defaultType); + } catch { + return null; + } + } + + const authSplitIndex = rawValue.lastIndexOf('@'); + let authPart = ''; + let hostPortPart = rawValue; + if (authSplitIndex !== -1) { + authPart = rawValue.slice(0, authSplitIndex).trim(); + hostPortPart = rawValue.slice(authSplitIndex + 1).trim(); + } + + const segments = hostPortPart.split(':').map(segment => segment.trim()).filter(Boolean); + if (segments.length === 2) { + return sanitizeProxyEntry({ + host: segments[0], + port: segments[1], + auth: authPart || undefined, + type: defaultType + }, defaultType); + } + + if (!authPart && segments.length === 4) { + const [a, b, c, d] = segments; + if (/^\d+$/.test(b)) { + return sanitizeProxyEntry({ + host: a, + port: b, + auth: `${c}:${d}`, + type: defaultType + }, defaultType); + } + if (/^\d+$/.test(d)) { + return sanitizeProxyEntry({ + host: c, + port: d, + auth: `${a}:${b}`, + type: defaultType + }, defaultType); + } + } + + return null; +} + +function parseProxyPayload(payload, defaultType = 'http') { + if (!payload) return []; + + if (Array.isArray(payload)) { + return dedupeProxyEntries( + payload + .flatMap(item => parseProxyPayload(item, defaultType)) + .filter(Boolean) + ); + } + + if (typeof payload === 'string') { + const trimmed = payload.trim(); + if (!trimmed) return []; + + if (trimmed.startsWith('[') || trimmed.startsWith('{')) { + try { + return parseProxyPayload(JSON.parse(trimmed), defaultType); + } catch { + // Keep parsing as raw text below. + } + } + + return dedupeProxyEntries( + trimmed + .split(/\r?\n/) + .map(line => parseProxyString(line, defaultType)) + .filter(Boolean) + ); + } + + if (typeof payload === 'object') { + if (payload.host && payload.port) { + return dedupeProxyEntries([sanitizeProxyEntry(payload, defaultType)].filter(Boolean)); + } + + const candidateKeys = ['proxies', 'data', 'items', 'results', 'list']; + for (const key of candidateKeys) { + if (payload[key] !== undefined) { + const parsed = parseProxyPayload(payload[key], defaultType); + if (parsed.length > 0) return parsed; + } + } + + const arrayValues = Object.values(payload).filter(Array.isArray); + for (const value of arrayValues) { + const parsed = parseProxyPayload(value, defaultType); + if (parsed.length > 0) return parsed; + } + } + + return []; +} + +function proxyToUrl(proxy, forcedType) { + const safeProxy = sanitizeProxyEntry(proxy, forcedType || proxy?.type || 'http'); + if (!safeProxy) return null; + const type = normalizeProxyType(forcedType || safeProxy.type, 'http'); + const auth = safeProxy.auth ? `${safeProxy.auth}@` : ''; + return `${type}://${auth}${safeProxy.host}:${safeProxy.port}`; +} + +const PROXY_POOL_REDIS_KEY = 'proxyscrape:mainapi:pools:v1'; +const PROXYSCRAPE_API_TOKEN = (process.env.PROXYSCRAPE_API_TOKEN || process.env.PROXYSCRAPE_API_KEY || '').trim(); +const PROXYSCRAPE_ACCOUNT_ID = (process.env.PROXYSCRAPE_ACCOUNT_ID || '').trim(); +const PROXYSCRAPE_ENABLED = Boolean(PROXYSCRAPE_API_TOKEN && PROXYSCRAPE_ACCOUNT_ID); +const PROXY_POOL_REDIS_TTL_SECONDS = 60 * 60; +const PROXYSCRAPE_ACCOUNT_BASE_URL = 'https://api.proxyscrape.com'; +const PROXYSCRAPE_ACCOUNT_PATH = '/v4/account/{accountId}/datacenter_shared/proxy-list'; +const PROXYSCRAPE_TIMEOUT_MS = 12000; +const PROXYSCRAPE_REFRESH_MS = 15 * 60 * 1000; +const PROXYSCRAPE_MAX_PER_PROTOCOL = 1000; +const PROXYSCRAPE_HTTP_PROTOCOLS = ['http']; +const PROXYSCRAPE_SOCKS_PROTOCOLS = ['socks']; +const PROXYSCRAPE_ALLOW_LEGACY_FALLBACK = false; +const PROXYSCRAPE_DEBUG = false; + +const legacySocksEnv = PROXYSCRAPE_ENABLED && !PROXYSCRAPE_ALLOW_LEGACY_FALLBACK + ? [] + : parseJsonArrayEnv('SOCKS5_PROXIES', []); +const legacyHttpEnv = PROXYSCRAPE_ENABLED && !PROXYSCRAPE_ALLOW_LEGACY_FALLBACK + ? [] + : parseJsonArrayEnv('HTTP_PROXIES', []); + +const PROXIES = dedupeProxyEntries( + (legacySocksEnv.length > 0 ? legacySocksEnv : parseProxyPayload(process.env.SOCKS5_PROXIES, 'socks5')) + .map(entry => sanitizeProxyEntry(entry, 'socks5')) + .filter(Boolean) +); + +const COFLIX_SOCKS5_PROXIES = dedupeProxyEntries( + parseProxyPayload(process.env.SOCKS5_PROXIES, 'socks5') + .map(entry => sanitizeProxyEntry(entry, 'socks5')) + .filter(Boolean) +); + +const HTTP_PROXIES = dedupeProxyEntries( + (legacyHttpEnv.length > 0 ? legacyHttpEnv : parseProxyPayload(process.env.HTTP_PROXIES, 'http')) + .map(entry => sanitizeProxyEntry(entry, 'http')) + .filter(Boolean) +); + +const DARKINO_HTTP_PROXIES = []; +const DARKINO_PROXIES = []; + +function syncDerivedHttpProxyPools(httpEntries) { + const normalizedHttpEntries = dedupeProxyEntries( + httpEntries + .map(entry => sanitizeProxyEntry(entry, 'http')) + .filter(Boolean) + ); + + updateArrayInPlace(HTTP_PROXIES, normalizedHttpEntries); + updateArrayInPlace( + DARKINO_PROXIES, + normalizedHttpEntries.map(entry => ({ ...entry, type: 'http' })) + ); + updateArrayInPlace( + DARKINO_HTTP_PROXIES, + DARKINO_PROXIES + .map(proxy => proxyToUrl(proxy, 'http')) + .filter(Boolean) + ); +} + +syncDerivedHttpProxyPools(HTTP_PROXIES); + +const proxyScrapeState = { + refreshPromise: null, + lastRefreshAt: 0, + lastRefreshError: null, + lastSuccessMeta: { + socks: null, + http: null + } +}; + +function getProxyPoolAgeMs(updatedAt = proxyScrapeState.lastRefreshAt) { + const timestamp = Number(updatedAt); + if (!Number.isFinite(timestamp) || timestamp <= 0) { + return Number.POSITIVE_INFINITY; + } + return Date.now() - timestamp; +} + +function isProxyPoolFresh(updatedAt = proxyScrapeState.lastRefreshAt) { + return getProxyPoolAgeMs(updatedAt) < PROXYSCRAPE_REFRESH_MS; +} + +function buildProxyScrapeResult(source) { + return { + enabled: true, + socks: PROXIES.length, + http: HTTP_PROXIES.length, + meta: proxyScrapeState.lastSuccessMeta, + source + }; +} + +function limitProxyEntries(entries) { + if (!Number.isFinite(PROXYSCRAPE_MAX_PER_PROTOCOL) || PROXYSCRAPE_MAX_PER_PROTOCOL <= 0) { + return entries; + } + return entries.slice(0, PROXYSCRAPE_MAX_PER_PROTOCOL); +} + +function buildProxyScrapeCandidates(protocol) { + if (!PROXYSCRAPE_ACCOUNT_ID) { + return []; + } + + const accountPath = PROXYSCRAPE_ACCOUNT_PATH.replace('{accountId}', PROXYSCRAPE_ACCOUNT_ID); + return [{ + url: `${PROXYSCRAPE_ACCOUNT_BASE_URL}${accountPath}`, + headers: { 'api-token': PROXYSCRAPE_API_TOKEN }, + params: { + type: 'getproxies', + protocol, + format: 'normal' + }, + label: `v4 account ${accountPath}` + }]; +} + +function applyStoredProxyPools(storedPools) { + if (!storedPools || typeof storedPools !== 'object') return false; + + const socks = dedupeProxyEntries( + (storedPools.socks || []) + .map(entry => sanitizeProxyEntry(entry, 'socks5')) + .filter(Boolean) + ); + const httpEntries = dedupeProxyEntries( + (storedPools.http || []) + .map(entry => sanitizeProxyEntry(entry, 'http')) + .filter(Boolean) + ); + + if (socks.length === 0 || httpEntries.length === 0) { + return false; + } + + updateArrayInPlace(PROXIES, socks.map(entry => ({ ...entry, type: 'socks5' }))); + syncDerivedHttpProxyPools(httpEntries); + proxyAgentCache.clear(); + darkinoProxyAgentCache.clear(); + cpasmalAgentCache.clear(); + return true; +} + +async function loadProxyPoolsFromRedis() { + try { + const rawValue = await redis.get(PROXY_POOL_REDIS_KEY); + if (!rawValue) return false; + const parsed = JSON.parse(rawValue); + if (!applyStoredProxyPools(parsed)) return false; + proxyScrapeState.lastRefreshAt = Number(parsed.updatedAt) || proxyScrapeState.lastRefreshAt; + proxyScrapeState.lastSuccessMeta = parsed.meta || proxyScrapeState.lastSuccessMeta; + return true; + } catch { + return false; + } +} + +async function saveProxyPoolsToRedis(payload) { + try { + await redis.set(PROXY_POOL_REDIS_KEY, JSON.stringify(payload), 'EX', PROXY_POOL_REDIS_TTL_SECONDS); + } catch { + // ignore Redis persistence failures + } +} + +async function fetchProxyScrapeProtocol(defaultType, protocols) { + const attemptErrors = []; + + for (const protocol of protocols) { + const candidates = buildProxyScrapeCandidates(protocol); + + for (const candidate of candidates) { + try { + if (PROXYSCRAPE_DEBUG) { + console.log( + `[PROXYSCRAPE DEBUG] tentative ${candidate.label} | protocol=${protocol} | url=${candidate.url} | params=${JSON.stringify(candidate.params)}` + ); + } + + const response = await axios.get(candidate.url, { + headers: candidate.headers, + params: candidate.params, + timeout: PROXYSCRAPE_TIMEOUT_MS, + responseType: 'text', + transformResponse: [data => data] + }); + + const proxies = limitProxyEntries( + dedupeProxyEntries(parseProxyPayload(response.data, defaultType)) + ); + + if (proxies.length === 0) { + const message = `[PROXYSCRAPE] ${candidate.label} (${protocol}) a retourne 0 proxy`; + attemptErrors.push(message); + if (PROXYSCRAPE_DEBUG) { + console.warn(`${message} | body=${String(response.data || '').slice(0, 300)}`); + } + continue; + } + + if (PROXYSCRAPE_DEBUG) { + console.log(`[PROXYSCRAPE DEBUG] succes ${candidate.label} (${protocol}) -> ${proxies.length} proxies`); + } + + return { + proxies, + meta: { + protocol, + endpoint: candidate.label, + count: proxies.length + } + }; + } catch (error) { + const status = error.response?.status; + const message = `[PROXYSCRAPE] ${candidate.label} (${protocol}) a echoue: ${status || error.code || error.message}`; + attemptErrors.push(message); + if (PROXYSCRAPE_DEBUG) { + console.warn(`${message} | body=${String(error.response?.data || '').slice(0, 300)}`); + } + } + } + } + + throw new Error(attemptErrors.length > 0 + ? attemptErrors.join(' | ') + : '[PROXYSCRAPE] Aucun endpoint n a repondu'); +} + +async function refreshProxyScrapeProxies(options = {}) { + const { force = false, silent = false } = options; + + if (!PROXYSCRAPE_ENABLED) { + return { + enabled: false, + socks: PROXIES.length, + http: HTTP_PROXIES.length + }; + } + + if (!force && proxyScrapeState.refreshPromise) { + return proxyScrapeState.refreshPromise; + } + + if (proxyScrapeState.refreshPromise) { + return proxyScrapeState.refreshPromise; + } + + if (!force) { + const loadedFromRedis = await loadProxyPoolsFromRedis(); + if (loadedFromRedis && isProxyPoolFresh()) { + if (!silent) { + console.log(`[PROXYSCRAPE] Pools frais charges depuis Redis: ${PROXIES.length} SOCKS5, ${HTTP_PROXIES.length} HTTP`); + } + return buildProxyScrapeResult('redis-fresh'); + } + } + + proxyScrapeState.refreshPromise = (async () => { + const lock = await acquireRedisLock(PROXY_POOL_REDIS_KEY, { + ttl: Math.max(10, Math.ceil(PROXYSCRAPE_TIMEOUT_MS / 1000) * 2), + retries: 40, + retryDelay: 500 + }); + + if (!lock) { + const loadedFromRedis = await loadProxyPoolsFromRedis(); + if (loadedFromRedis) { + if (!silent) { + console.log(`[PROXYSCRAPE] Pools charges depuis Redis: ${PROXIES.length} SOCKS5, ${HTTP_PROXIES.length} HTTP`); + } + return buildProxyScrapeResult('redis'); + } + } + + try { + if (!force) { + const loadedFromRedis = await loadProxyPoolsFromRedis(); + if (loadedFromRedis && isProxyPoolFresh()) { + if (!silent) { + console.log(`[PROXYSCRAPE] Pools frais recharges depuis Redis: ${PROXIES.length} SOCKS5, ${HTTP_PROXIES.length} HTTP`); + } + return buildProxyScrapeResult('redis-fresh'); + } + } + + const socksResult = await fetchProxyScrapeProtocol('socks5', PROXYSCRAPE_SOCKS_PROTOCOLS); + const httpResult = await fetchProxyScrapeProtocol('http', PROXYSCRAPE_HTTP_PROTOCOLS); + + updateArrayInPlace(PROXIES, socksResult.proxies.map(proxy => ({ ...proxy, type: 'socks5' }))); + syncDerivedHttpProxyPools(httpResult.proxies); + + proxyAgentCache.clear(); + darkinoProxyAgentCache.clear(); + cpasmalAgentCache.clear(); + + proxyScrapeState.lastRefreshAt = Date.now(); + proxyScrapeState.lastRefreshError = null; + proxyScrapeState.lastSuccessMeta = { + socks: socksResult.meta, + http: httpResult.meta + }; + + await saveProxyPoolsToRedis({ + updatedAt: proxyScrapeState.lastRefreshAt, + socks: PROXIES, + http: HTTP_PROXIES, + meta: proxyScrapeState.lastSuccessMeta + }); + + if (!silent) { + console.log( + `[PROXYSCRAPE] Refresh OK: ${PROXIES.length} SOCKS5 via ${socksResult.meta.endpoint}, ${HTTP_PROXIES.length} HTTP via ${httpResult.meta.endpoint}` + ); + } + + return { + enabled: true, + socks: PROXIES.length, + http: HTTP_PROXIES.length, + meta: proxyScrapeState.lastSuccessMeta, + source: 'api' + }; + } catch (error) { + proxyScrapeState.lastRefreshError = error.message; + + const loadedFromRedis = await loadProxyPoolsFromRedis(); + if (loadedFromRedis) { + if (!silent) { + console.warn(`[PROXYSCRAPE] Refresh API echoue, fallback Redis utilise: ${error.message}`); + } + return buildProxyScrapeResult('redis-fallback'); + } + + if (!silent) { + console.error(`[PROXYSCRAPE] Refresh echoue: ${error.message}`); + } + throw error; + } finally { + if (lock && typeof lock.release === 'function') { + await lock.release(); + } + } + })().finally(() => { + proxyScrapeState.refreshPromise = null; + }); + + return proxyScrapeState.refreshPromise; +} + +function scheduleProxyScrapeRefresh() { + if (!PROXYSCRAPE_ENABLED) return; + + setTimeout(() => { + loadProxyPoolsFromRedis().catch(() => {}); + }, 0).unref(); + + setInterval(() => { + refreshProxyScrapeProxies({ silent: false }).catch(() => {}); + }, PROXYSCRAPE_REFRESH_MS).unref(); +} + +scheduleProxyScrapeRefresh(); + +// Fonction utilitaire pour choisir aléatoirement un proxy (toujours utiliser un proxy) +function pickRandomProxyOrNone() { + // Sélectionner toujours un proxy aléatoire parmi la liste + if (!PROXIES || PROXIES.length === 0) return null; + const idx = Math.floor(Math.random() * PROXIES.length); + return PROXIES[idx] || null; +} + +// Sélectionne un proxy aléatoire — retourne null si la liste est vide +function pickRandomProxy() { + if (!PROXIES || PROXIES.length === 0) return null; + const idx = Math.floor(Math.random() * PROXIES.length); + return PROXIES[idx]; +} + +// Fonction utilitaire pour cr\u00e9er un agent proxy SOCKS5 (avec cache) +function getProxyAgent(proxy) { + if (!proxy) return null; + const auth = proxy.auth ? `${proxy.auth}@` : ''; + const proxyType = normalizeProxyType(proxy.type, 'socks5'); + const cacheKey = `${proxyType}:${proxy.host}:${proxy.port}:${auth}`; + + // V\u00e9rifier le cache d'abord + if (proxyAgentCache.has(cacheKey)) { + return proxyAgentCache.get(cacheKey); + } + + const protocol = proxyType === 'socks5' ? 'socks5h' : proxyType; + const proxyUrl = `${protocol}://${auth}${proxy.host}:${proxy.port}`; + const agent = new SocksProxyAgent(proxyUrl); + + // Mettre en cache l'agent + proxyAgentCache.set(cacheKey, agent); + return agent; +} + +// Fonction utilitaire pour cr\u00e9er un agent proxy (pour Darkino) - avec cache +function getDarkinoHttpProxyAgent(proxy) { + if (!proxy) return null; + const auth = proxy.auth ? `${proxy.auth}@` : ''; + const proxyType = normalizeProxyType(proxy.type, 'http'); + const cacheKey = `${proxyType}:${proxy.host}:${proxy.port}:${auth}`; + + // V\u00e9rifier le cache d'abord + if (darkinoProxyAgentCache.has(cacheKey)) { + return darkinoProxyAgentCache.get(cacheKey); + } + + let agents; + if (proxyType === 'socks5') { + const proxyUrl = `socks5://${auth}${proxy.host}:${proxy.port}`; + const agent = new SocksProxyAgent(proxyUrl); + agents = { + httpAgent: agent, + httpsAgent: agent + }; + } else { + const proxyUrl = `http://${auth}${proxy.host}:${proxy.port}`; + agents = { + httpAgent: new HttpProxyAgent(proxyUrl), + httpsAgent: new HttpsProxyAgent(proxyUrl) + }; + } + + // Mettre en cache les agents + darkinoProxyAgentCache.set(cacheKey, agents); + return agents; +} + +module.exports = { + // Proxy agent caches + proxyAgentCache, + darkinoProxyAgentCache, + + // Proxy configuration flags + ENABLE_DARKINO_PROXY, + ENABLE_COFLIX_PROXY, + ENABLE_FRENCH_STREAM_PROXY, + ENABLE_LECTEURVIDEO_PROXY, + ENABLE_FSTREAM_PROXY, + ENABLE_ANIME_PROXY, + ENABLE_WIFLIX_PROXY, + darkiworld_premium, + + // Darkino 403 cooldown (expose getter/setter since it's mutable) + DARKINO_403_COOLDOWN_MS, + get darkino403CooldownUntil() { return darkino403CooldownUntil; }, + set darkino403CooldownUntil(val) { darkino403CooldownUntil = val; }, + + // Cpasmal + CPASMAL_BASE_URL, + cpasmalJar, + getCpasmalAgent, + axiosCpasmalRequest, + + // Cloudflare Workers proxies + CLOUDFLARE_WORKERS_PROXIES, + proxyErrorCache, + markProxyAsErrored, + isProxyInCooldown, + getAvailableProxies, + markProxyAsHealthy, + buildProxiedUrl, + + // Request helpers + makeRequestWithCorsFallback, + makeCoflixRequest, + makeLecteurVideoRequest, + + // SOCKS5 proxies + PROXIES, + HTTP_PROXIES, + DARKINO_HTTP_PROXIES, + DARKINO_PROXIES, + refreshProxyScrapeProxies, + + // Agent helpers + pickRandomProxyOrNone, + pickRandomProxy, + pickNextSocks5Proxy, + getProxyAgent, + getDarkinoHttpProxyAgent, + + // Cleanup + shutdownCycleTLS +}; diff --git a/API/Mainapi/utils/redisLock.js b/API/Mainapi/utils/redisLock.js new file mode 100644 index 0000000..90bf130 --- /dev/null +++ b/API/Mainapi/utils/redisLock.js @@ -0,0 +1,71 @@ +/** + * Redis distributed lock (replaces proper-lockfile). + * Extracted from server.js — uses SET NX EX for atomic locking with TTL auto-expiration. + * More reliable than filesystem lockfiles (no orphan .lock files, works in cluster). + */ + +const { redis } = require('../config/redis'); + +// === REDIS DISTRIBUTED LOCK (remplace proper-lockfile) === +// Utilise SET NX EX pour un verrou atomique avec TTL auto-expiration. +// Plus fiable que les lockfiles filesystem (pas de .lock orphelins, fonctionne en cluster). +const LOCK_PREFIX = 'lock:'; +const LOCK_DEFAULT_TTL = 10; // secondes — TTL auto-expiration du verrou +const LOCK_RETRY_DELAY = 100; // ms entre chaque tentative +const LOCK_MAX_RETRIES = 50; // 50 × 100ms = 5s max d'attente + +/** + * Acquiert un verrou distribué Redis sur une clé donnée. + * @param {string} resourceKey - Identifiant unique de la ressource (ex: chemin de fichier) + * @param {object} opts - Options : ttl (sec), retries, retryDelay (ms) + * @returns {Promise<{release: Function}|null>} - Objet avec release(), ou null si échec + */ +async function acquireRedisLock(resourceKey, opts = {}) { + const ttl = opts.ttl || LOCK_DEFAULT_TTL; + const retries = opts.retries ?? LOCK_MAX_RETRIES; + const retryDelay = opts.retryDelay || LOCK_RETRY_DELAY; + const lockKey = LOCK_PREFIX + resourceKey; + const lockValue = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; + + for (let attempt = 0; attempt <= retries; attempt++) { + try { + // SET key value NX EX ttl — atomique, ne set que si la clé n'existe pas + const result = await redis.set(lockKey, lockValue, 'EX', ttl, 'NX'); + if (result === 'OK') { + // Verrou acquis — retourner une fonction release sécurisée + return { + release: async () => { + try { + // Script Lua atomique : ne supprime que si la valeur correspond (évite de libérer le lock d'un autre process) + const luaScript = ` + if redis.call("get", KEYS[1]) == ARGV[1] then + return redis.call("del", KEYS[1]) + else + return 0 + end + `; + await redis.eval(luaScript, 1, lockKey, lockValue); + } catch (e) { + console.warn(`[RedisLock] Erreur release ${resourceKey}:`, e.message); + } + } + }; + } + } catch (err) { + // Redis indisponible — on abandonne immédiatement + console.warn(`[RedisLock] Redis indisponible pour ${resourceKey}:`, err.message); + return null; + } + + // Attendre avant de réessayer + if (attempt < retries) { + await new Promise(r => setTimeout(r, retryDelay)); + } + } + + // Timeout — impossible d'acquérir le verrou + console.warn(`[RedisLock] Timeout: impossible d'acquérir le verrou pour ${resourceKey} après ${retries} tentatives`); + return null; +} + +module.exports = { acquireRedisLock }; diff --git a/API/Mainapi/utils/redisRateLimitStore.js b/API/Mainapi/utils/redisRateLimitStore.js new file mode 100644 index 0000000..97910fa --- /dev/null +++ b/API/Mainapi/utils/redisRateLimitStore.js @@ -0,0 +1,110 @@ +const { redis } = require('../config/redis'); + +function buildResetTime(ttlMs, windowMs) { + const safeTtlMs = Number.isFinite(ttlMs) && ttlMs > 0 ? ttlMs : windowMs; + return new Date(Date.now() + safeTtlMs); +} + +class RedisRateLimitStore { + constructor(options = {}) { + this.windowMs = Number(options.windowMs) || 60_000; + this.prefix = String(options.prefix || 'rate-limit:'); + this.localKeys = false; + } + + init(options) { + if (options?.windowMs) { + this.windowMs = Number(options.windowMs); + } + } + + getKey(key) { + return `${this.prefix}${key}`; + } + + async get(key) { + const redisKey = this.getKey(key); + + try { + const [rawHits, rawTtlMs] = await redis + .multi() + .get(redisKey) + .pttl(redisKey) + .exec(); + + const totalHits = Number(rawHits?.[1] || 0); + const ttlMs = Number(rawTtlMs?.[1] || 0); + + if (!Number.isFinite(totalHits) || totalHits <= 0) { + return undefined; + } + + return { + totalHits, + resetTime: buildResetTime(ttlMs, this.windowMs) + }; + } catch { + return undefined; + } + } + + async increment(key) { + const redisKey = this.getKey(key); + + try { + const [rawHits, rawTtlMs] = await redis + .multi() + .incr(redisKey) + .pttl(redisKey) + .exec(); + + const totalHits = Number(rawHits?.[1] || 1); + let ttlMs = Number(rawTtlMs?.[1] || 0); + + if (!Number.isFinite(ttlMs) || ttlMs <= 0 || totalHits === 1) { + ttlMs = this.windowMs; + await redis.pexpire(redisKey, this.windowMs); + } + + return { + totalHits, + resetTime: buildResetTime(ttlMs, this.windowMs) + }; + } catch { + return { + totalHits: 1, + resetTime: buildResetTime(this.windowMs, this.windowMs) + }; + } + } + + async decrement(key) { + const redisKey = this.getKey(key); + + try { + const remaining = Number(await redis.decr(redisKey)); + if (Number.isFinite(remaining) && remaining <= 0) { + await redis.del(redisKey); + } + } catch { + // ignore + } + } + + async resetKey(key) { + try { + await redis.del(this.getKey(key)); + } catch { + // ignore + } + } +} + +function createRedisRateLimitStore(options) { + return new RedisRateLimitStore(options); +} + +module.exports = { + RedisRateLimitStore, + createRedisRateLimitStore +}; diff --git a/API/Mainapi/utils/safeFile.js b/API/Mainapi/utils/safeFile.js new file mode 100644 index 0000000..0586288 --- /dev/null +++ b/API/Mainapi/utils/safeFile.js @@ -0,0 +1,141 @@ +/** + * Safe file read/write operations with Redis distributed locking and atomic writes. + * Extracted from server.js — provides safeWriteFile, safeWriteJsonFile, safeReadJsonFile. + */ + +const fsp = require('fs').promises; +const path = require('path'); +const writeFileAtomic = require('write-file-atomic'); +const { acquireRedisLock } = require('./redisLock'); + +// ===== FONCTIONS SECURISEES POUR LES ECRITURES DE FICHIERS ===== + +/** + * Écriture sécurisée avec verrou de fichier et écriture atomique + * @param {string} filePath - Chemin du fichier à écrire + * @param {string|Buffer} data - Données à écrire + * @param {object} options - Options pour l'écriture + * @returns {Promise<boolean>} - Succès de l'opération + */ +async function safeWriteFile(filePath, data, options = {}) { + const defaultOptions = { + encoding: 'utf8', + mode: 0o644, + lockTtl: 10, // TTL du verrou Redis en secondes + retries: 3, + retryDelay: 100 + }; + + const finalOptions = { ...defaultOptions, ...options }; + let lock = null; + + try { + // Créer le répertoire parent si nécessaire + await fsp.mkdir(path.dirname(filePath), { recursive: true }); + + // Tentative d'acquisition du verrou Redis (avec fallback si échec) + // Clé de lock basée sur le chemin absolu normalisé + const lockResource = path.resolve(filePath).replace(/\\/g, '/'); + lock = await acquireRedisLock(lockResource, { + ttl: finalOptions.lockTtl, + retries: finalOptions.retries * 10, // plus de tentatives car Redis est rapide + retryDelay: finalOptions.retryDelay + }); + + if (!lock) { + // Redis indisponible ou timeout — on continue l'écriture sans verrou + console.warn(`[SafeWriteFile] AVERTISSEMENT: Impossible de verrouiller ${path.basename(filePath)} via Redis, écriture forcée sans verrou.`); + } + + // Écrire le fichier de manière atomique (même si le lock a échoué) + // flush: false désactive fsync pour améliorer les performances sur software RAID + await writeFileAtomic(filePath, data, { + encoding: finalOptions.encoding, + mode: finalOptions.mode, + fsync: false // Désactiver fsync pour perf sur software RAID OVH + }); + + return true; + } catch (error) { + console.error(`[SafeWriteFile] Échec pour ${filePath}:`, error.message, error.code || ''); + return false; + } finally { + // Libérer le verrou Redis si acquis + if (lock) { + try { + await lock.release(); + } catch (releaseError) { + console.error(`[SafeWriteFile] Erreur release Redis lock pour ${filePath}:`, releaseError); + } + } + } +} + +/** + * Écriture sécurisée de données JSON avec verrou de fichier et écriture atomique + * @param {string} filePath - Chemin du fichier à écrire + * @param {object} data - Objet JSON à écrire + * @param {object} options - Options pour l'écriture + * @returns {Promise<boolean>} - Succès de l'opération + */ +async function safeWriteJsonFile(filePath, data, options = {}) { + const jsonOptions = { + ...options, + encoding: 'utf8' + }; + + try { + const jsonString = JSON.stringify(data); + return await safeWriteFile(filePath, jsonString, jsonOptions); + } catch (error) { + console.error(`Erreur lors de la sérialisation JSON pour ${filePath}:`, error); + return false; + } +} + +/** + * Lecture sécurisée avec verrou de fichier + * @param {string} filePath - Chemin du fichier à lire + * @param {object} options - Options pour la lecture + * @returns {Promise<object|null>} - Données lues ou null en cas d'erreur + */ +async function safeReadJsonFile(filePath, options = {}) { + const defaultOptions = { + encoding: 'utf8', + retries: 2, + retryDelay: 50 + }; + + const finalOptions = { ...defaultOptions, ...options }; + + // Petite boucle de retry en cas d'accès concurrentiel très rare + for (let attempt = 0; attempt <= finalOptions.retries; attempt++) { + try { + const fileContent = await fsp.readFile(filePath, finalOptions.encoding); + try { + return JSON.parse(fileContent); + } catch (parseError) { + // Si JSON temporairement invalide, réessayer brièvement + if (attempt < finalOptions.retries) { + await new Promise(r => setTimeout(r, finalOptions.retryDelay)); + continue; + } + console.error(`Erreur de parse JSON pour ${filePath}:`, parseError); + return null; + } + } catch (error) { + if (error.code === 'ENOENT') { + return null; // Fichier absent + } + if (attempt < finalOptions.retries) { + await new Promise(r => setTimeout(r, finalOptions.retryDelay)); + continue; + } + console.error(`Erreur lors de la lecture de ${filePath}:`, error); + return null; + } + } + return null; +} + +module.exports = { safeWriteFile, safeWriteJsonFile, safeReadJsonFile }; diff --git a/API/Mainapi/utils/syncPolicy.js b/API/Mainapi/utils/syncPolicy.js new file mode 100644 index 0000000..3d0baf7 --- /dev/null +++ b/API/Mainapi/utils/syncPolicy.js @@ -0,0 +1,430 @@ +const path = require('path'); + +const ALLOWED_SYNC_USER_TYPES = Object.freeze(['oauth', 'bip39']); +const RESERVED_OBJECT_KEYS = new Set(['__proto__', 'prototype', 'constructor']); +const SAFE_SYNC_KEY_PATTERN = /^[A-Za-z0-9:_-]{1,120}$/; +const SAFE_USER_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/; +const SAFE_PROFILE_ID_PATTERN = /^[A-Za-z0-9-]{1,64}$/; +const SAFE_GUEST_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/; + +const SYNCABLE_EXACT_KEYS = new Set([ + 'access_code', + 'access_code_expires', + 'adWarningAccepted', + 'anti_spoiler', + 'continueWatching', + 'custom_lists', + 'episodeReleaseAlerts', + 'favorite_collections', + 'favorite_movie', + 'favorite_movies', + 'favorites_tv', + 'miniPlayerPosition', + 'miniPlayerVolume', + 'movix_intro_enabled', + 'movix_intro_seen', + 'privacy_data_collection', + 'recentEmojis', + 'screensaver_enabled', + 'screensaver_mode', + 'screensaver_timeout', + 'snow_enabled', + 'subtitleStyle', + 'support_popup_seen', + 'user_language', + 'is_vip', + 'watched_movie', + 'watched_tv', + 'watchPartyNickname' +]); + +const SYNCABLE_PREFIXES = Object.freeze([ + 'favorite_', + 'favorites_', + 'miniPlayer', + 'movix_intro_', + 'player', + 'progress_', + 'screensaver_', + 'settings_', + 'watchlist_', + 'watched_' +]); + +const BLOCKED_SYNC_KEYS = new Set([ + 'access_token', + 'auth', + 'auth_method', + 'auth_token', + 'avatar_url', + 'bip39_auth', + 'clear', + 'discord_auth', + 'discord_last_check', + 'discord_rate_limit', + 'discord_token', + 'discord_user', + 'episodeAlertsLastCheck', + 'google_auth', + 'google_token', + 'google_user', + 'guest_uuid', + 'is_admin', + 'lastCommentTime', + 'lastReplyTime', + 'movix_pending_auth_action', + 'removeItem', + 'resolved_user_id', + 'resolved_user_type', + 'selectedProfile', + 'selected_profile', + 'selected_profile_id', + 'session_id', + 'setItem', + 'user_id', + 'user_name', + 'user_type' +]); + +const SYNC_LIMITS = Object.freeze({ + maxRequestBytes: 5 * 1024 * 1024, + maxOpsPerRequest: 200, + maxKeysPerProfile: 600, + maxDeltaProperties: 200, + maxStringValueBytes: 256 * 1024, + maxStructuredValueBytes: 128 * 1024, + maxProfileBytes: 5 * 1024 * 1024, + maxLegacyUserBytes: 512 * 1024, + maxUserDataBytes: 1024 * 1024, + maxValueDepth: 8 +}); + +class SyncPolicyError extends Error { + constructor(message, status = 400, code = 'SYNC_POLICY_ERROR') { + super(message); + this.name = 'SyncPolicyError'; + this.status = status; + this.code = code; + } +} + +function canonicalPath(value) { + const resolved = path.resolve(value); + return process.platform === 'win32' ? resolved.toLowerCase() : resolved; +} + +function isPathInside(baseDir, targetPath) { + const normalizedBase = canonicalPath(baseDir); + const normalizedTarget = canonicalPath(targetPath); + const baseWithSep = normalizedBase.endsWith(path.sep) ? normalizedBase : `${normalizedBase}${path.sep}`; + return normalizedTarget === normalizedBase || normalizedTarget.startsWith(baseWithSep); +} + +function resolveInside(baseDir, ...segments) { + const resolved = path.resolve(baseDir, ...segments); + if (!isPathInside(baseDir, resolved)) { + throw new SyncPolicyError('Chemin de stockage invalide', 400, 'INVALID_STORAGE_PATH'); + } + return resolved; +} + +function getUtf8ByteLength(value) { + const serialized = typeof value === 'string' ? value : JSON.stringify(value); + return Buffer.byteLength(serialized, 'utf8'); +} + +function assertWithinBytes(value, maxBytes, message, status = 413, code = 'PAYLOAD_TOO_LARGE') { + if (getUtf8ByteLength(value) > maxBytes) { + throw new SyncPolicyError(message, status, code); + } +} + +function isPlainObject(value) { + return Object.prototype.toString.call(value) === '[object Object]'; +} + +function ensureSafeSegment(value, label, pattern, code = 'INVALID_IDENTIFIER') { + if (typeof value !== 'string' || !value.trim()) { + throw new SyncPolicyError(`${label} manquant`, 400, code); + } + + const normalized = value.trim(); + if (!pattern.test(normalized)) { + throw new SyncPolicyError(`${label} invalide`, 400, code); + } + + return normalized; +} + +function ensureValidUserType(userType) { + if (!ALLOWED_SYNC_USER_TYPES.includes(userType)) { + throw new SyncPolicyError('Type d\'utilisateur invalide', 400, 'INVALID_USER_TYPE'); + } + return userType; +} + +function ensureSafeUserId(userId) { + return ensureSafeSegment(userId, 'userId', SAFE_USER_ID_PATTERN, 'INVALID_USER_ID'); +} + +function ensureSafeProfileId(profileId) { + return ensureSafeSegment(profileId, 'profileId', SAFE_PROFILE_ID_PATTERN, 'INVALID_PROFILE_ID'); +} + +function ensureSafeGuestId(guestId) { + return ensureSafeSegment(guestId, 'guestId', SAFE_GUEST_ID_PATTERN, 'INVALID_GUEST_ID'); +} + +function ensureSafeNestedKey(key) { + if (typeof key !== 'string' || !key || key.length > 120 || RESERVED_OBJECT_KEYS.has(key)) { + throw new SyncPolicyError('Cle interne invalide dans les donnees synchronisees', 400, 'INVALID_NESTED_KEY'); + } + return key; +} + +function isSyncableStorageKey(key) { + if (typeof key !== 'string') return false; + if (BLOCKED_SYNC_KEYS.has(key)) return false; + if (RESERVED_OBJECT_KEYS.has(key)) return false; + if (!SAFE_SYNC_KEY_PATTERN.test(key)) return false; + if (SYNCABLE_EXACT_KEYS.has(key)) return true; + return SYNCABLE_PREFIXES.some((prefix) => key.startsWith(prefix)); +} + +function ensureSyncableStorageKey(key) { + if (!isSyncableStorageKey(key)) { + throw new SyncPolicyError(`Cle de synchronisation refusee: ${String(key)}`, 400, 'INVALID_SYNC_KEY'); + } + return key; +} + +function sanitizeStructuredValue(value, depth = 0) { + if (depth > SYNC_LIMITS.maxValueDepth) { + throw new SyncPolicyError('Structure de donnees trop profonde', 400, 'VALUE_TOO_DEEP'); + } + + if (value === null) { + return null; + } + + const valueType = typeof value; + if (valueType === 'string') { + assertWithinBytes(value, SYNC_LIMITS.maxStructuredValueBytes, 'Valeur trop volumineuse', 413, 'VALUE_TOO_LARGE'); + return value; + } + + if (valueType === 'number') { + if (!Number.isFinite(value)) { + throw new SyncPolicyError('Nombre invalide dans les donnees synchronisees', 400, 'INVALID_NUMBER'); + } + return value; + } + + if (valueType === 'boolean') { + return value; + } + + if (Array.isArray(value)) { + const next = value.map((item) => sanitizeStructuredValue(item, depth + 1)); + assertWithinBytes(next, SYNC_LIMITS.maxStructuredValueBytes, 'Tableau trop volumineux', 413, 'VALUE_TOO_LARGE'); + return next; + } + + if (!isPlainObject(value)) { + throw new SyncPolicyError('Structure de donnees non supportee', 400, 'INVALID_VALUE_TYPE'); + } + + const next = {}; + for (const [entryKey, entryValue] of Object.entries(value)) { + next[ensureSafeNestedKey(entryKey)] = sanitizeStructuredValue(entryValue, depth + 1); + } + + assertWithinBytes(next, SYNC_LIMITS.maxStructuredValueBytes, 'Objet trop volumineux', 413, 'VALUE_TOO_LARGE'); + return next; +} + +function sanitizeDelta(delta) { + if (!isPlainObject(delta)) { + throw new SyncPolicyError('Delta de synchronisation invalide', 400, 'INVALID_DELTA'); + } + + const rawSet = delta.set === undefined ? {} : delta.set; + const rawRemove = delta.remove === undefined ? [] : delta.remove; + + if (!isPlainObject(rawSet) || !Array.isArray(rawRemove)) { + throw new SyncPolicyError('Delta de synchronisation invalide', 400, 'INVALID_DELTA'); + } + + const setEntries = Object.entries(rawSet); + if (setEntries.length + rawRemove.length > SYNC_LIMITS.maxDeltaProperties) { + throw new SyncPolicyError('Trop de modifications dans une seule operation', 413, 'DELTA_TOO_LARGE'); + } + + const set = {}; + for (const [key, value] of setEntries) { + set[ensureSafeNestedKey(key)] = sanitizeStructuredValue(value); + } + + const remove = rawRemove.map((key) => ensureSafeNestedKey(key)); + + return { set, remove }; +} + +function validateAndNormalizeOps(ops) { + if (!Array.isArray(ops)) { + throw new SyncPolicyError('Operations de synchronisation invalides', 400, 'INVALID_OPS'); + } + + if (ops.length > SYNC_LIMITS.maxOpsPerRequest) { + throw new SyncPolicyError('Trop d\'operations de synchronisation dans une seule requete', 413, 'TOO_MANY_OPS'); + } + + return ops.map((rawOp) => { + if (!isPlainObject(rawOp)) { + throw new SyncPolicyError('Operation de synchronisation invalide', 400, 'INVALID_OP'); + } + + const key = ensureSyncableStorageKey(rawOp.key); + const op = typeof rawOp.op === 'string' ? rawOp.op : ''; + + switch (op) { + case 'set': { + if (typeof rawOp.value !== 'string') { + throw new SyncPolicyError('Valeur de synchronisation invalide', 400, 'INVALID_SET_VALUE'); + } + assertWithinBytes(rawOp.value, SYNC_LIMITS.maxStringValueBytes, 'Valeur trop volumineuse', 413, 'VALUE_TOO_LARGE'); + return { op, key, value: rawOp.value }; + } + + case 'remove': + case 'arrayClear': + return { op, key }; + + case 'arrayAdd': + case 'arrayRemove': { + const value = sanitizeStructuredValue(rawOp.value); + return { op, key, value }; + } + + case 'objPatch': + return { op, key, delta: sanitizeDelta(rawOp.delta) }; + + default: + throw new SyncPolicyError('Operation de synchronisation inconnue', 400, 'INVALID_OP'); + } + }); +} + +function sanitizeStorageObject(rawData, options = {}) { + const { + maxBytes = SYNC_LIMITS.maxProfileBytes, + maxKeys = SYNC_LIMITS.maxKeysPerProfile + } = options; + + const sanitized = {}; + let changed = !isPlainObject(rawData); + + if (isPlainObject(rawData)) { + for (const [key, value] of Object.entries(rawData)) { + if (!isSyncableStorageKey(key) || typeof value !== 'string') { + changed = true; + continue; + } + + if (getUtf8ByteLength(value) > SYNC_LIMITS.maxStringValueBytes) { + changed = true; + continue; + } + + sanitized[key] = value; + } + } + + const keyCount = Object.keys(sanitized).length; + if (keyCount > maxKeys) { + throw new SyncPolicyError('Trop de cles synchronisees pour ce profil', 413, 'TOO_MANY_KEYS'); + } + + const bytes = keyCount === 0 ? 0 : getUtf8ByteLength(sanitized); + if (bytes > maxBytes) { + throw new SyncPolicyError('Quota de stockage depasse pour ce profil', 413, 'PROFILE_QUOTA_EXCEEDED'); + } + + return { + data: sanitized, + changed, + stats: { + bytes, + keyCount + } + }; +} + +function sanitizeProfileData(rawData) { + return sanitizeStorageObject(rawData, { + maxBytes: SYNC_LIMITS.maxProfileBytes, + maxKeys: SYNC_LIMITS.maxKeysPerProfile + }); +} + +function sanitizeLegacySyncData(rawData) { + return sanitizeStorageObject(rawData, { + maxBytes: SYNC_LIMITS.maxLegacyUserBytes, + maxKeys: SYNC_LIMITS.maxKeysPerProfile + }); +} + +function assertUserDataSize(rawData) { + assertWithinBytes(rawData, SYNC_LIMITS.maxUserDataBytes, 'Donnees utilisateur trop volumineuses', 413, 'USER_DATA_TOO_LARGE'); +} + +function getUserDataFilePath({ usersDir, guestsDir }, userType, userId) { + if (userType === 'guest') { + const safeGuestId = ensureSafeGuestId(userId); + return resolveInside(guestsDir, `guest-${safeGuestId}.json`); + } + + const safeUserType = ensureValidUserType(userType); + const safeUserId = ensureSafeUserId(userId); + const fileName = safeUserType === 'bip39' ? `bip39-${safeUserId}.json` : `${safeUserId}.json`; + return resolveInside(usersDir, fileName); +} + +function getProfileFilePath(usersDir, userType, userId, profileId) { + const safeUserType = ensureValidUserType(userType); + const safeUserId = ensureSafeUserId(userId); + const safeProfileId = ensureSafeProfileId(profileId); + return resolveInside(usersDir, 'profiles', safeUserType, safeUserId, `${safeProfileId}.json`); +} + +function getOwnedProfile(userData, profileId) { + const safeProfileId = ensureSafeProfileId(profileId); + const profiles = Array.isArray(userData?.profiles) ? userData.profiles : []; + const profile = profiles.find((item) => item && item.id === safeProfileId); + + if (!profile) { + throw new SyncPolicyError('Profil introuvable', 404, 'PROFILE_NOT_FOUND'); + } + + return profile; +} + +module.exports = { + ALLOWED_SYNC_USER_TYPES, + BLOCKED_SYNC_KEYS, + SYNC_LIMITS, + SyncPolicyError, + assertUserDataSize, + ensureSafeProfileId, + ensureSafeUserId, + ensureValidUserType, + getOwnedProfile, + getProfileFilePath, + getUserDataFilePath, + getUtf8ByteLength, + isSyncableStorageKey, + resolveInside, + sanitizeLegacySyncData, + sanitizeProfileData, + validateAndNormalizeOps +}; diff --git a/API/Mainapi/utils/tmdbCache.js b/API/Mainapi/utils/tmdbCache.js new file mode 100644 index 0000000..51e76e1 --- /dev/null +++ b/API/Mainapi/utils/tmdbCache.js @@ -0,0 +1,201 @@ +/** + * Cache Redis centralisé pour les appels TMDB API. + * Partagé entre tous les workers du cluster — évite les appels TMDB redondants. + * + * Pattern identique à wrappedRoutes.js : redisReady() + get/set avec TTL. + * Préfixe Redis : "tmdb:" + */ + +const axios = require('axios'); +const { redis } = require('../config/redis'); + +// TTL par type de requête +const TTL_DETAILS = 24 * 60 * 60; // 24h — les détails d'un film/série changent rarement +const TTL_SEARCH = 12 * 60 * 60; // 12h — les résultats de recherche peuvent évoluer + +function redisReady() { + return redis && redis.status === 'ready'; +} + +async function redisGet(key) { + if (!redisReady()) return null; + try { + const data = await redis.get(key); + return data ? JSON.parse(data) : null; + } catch { return null; } +} + +async function redisSet(key, value, ttl) { + if (!redisReady()) return; + try { + await redis.set(key, JSON.stringify(value), 'EX', ttl); + } catch { /* ignore */ } +} + +/** + * Récupère les détails TMDB pour un ID donné, avec cache Redis. + * Clé : tmdb:details:{type}:{id} + * + * @param {string} tmdbApiUrl - Ex: "https://api.themoviedb.org/3" + * @param {string} tmdbApiKey - Clé API TMDB + * @param {string|number} id - ID TMDB + * @param {string} type - "movie" ou "tv" + * @param {string} [language] - Langue (défaut: "fr-FR") + * @returns {object|null} + */ +async function fetchTmdbDetails(tmdbApiUrl, tmdbApiKey, id, type, language = 'fr-FR') { + const redisKey = `tmdb:details:${type}:${id}:${language}`; + + // 1. Cache Redis + const cached = await redisGet(redisKey); + if (cached) return cached; + + // 2. Appel API TMDB + try { + const response = await axios.get(`${tmdbApiUrl}/${type}/${id}`, { + params: { api_key: tmdbApiKey, language }, + timeout: 10000 + }); + + if (!response.data) return null; + + // 3. Sauvegarder dans Redis + await redisSet(redisKey, response.data, TTL_DETAILS); + return response.data; + } catch (error) { + // Ne pas cacher les erreurs + return null; + } +} + +/** + * Recherche TMDB avec cache Redis. + * Clé : tmdb:search:{type}:{query}:{year}:{language} + * + * @param {string} tmdbApiUrl + * @param {string} tmdbApiKey + * @param {string} type - "movie" ou "tv" + * @param {string} query - Terme de recherche + * @param {object} [extraParams] - Params additionnels (first_air_date_year, year, etc.) + * @param {string} [language] + * @returns {object|null} - response.data complet (avec .results) + */ +async function searchTmdb(tmdbApiUrl, tmdbApiKey, type, query, extraParams = {}, language = 'fr-FR') { + const paramsSuffix = Object.entries(extraParams).sort().map(([k, v]) => `${k}=${v}`).join('&'); + const redisKey = `tmdb:search:${type}:${query}:${paramsSuffix}:${language}`; + + const cached = await redisGet(redisKey); + if (cached) return cached; + + try { + const response = await axios.get(`${tmdbApiUrl}/search/${type}`, { + params: { api_key: tmdbApiKey, query, language, ...extraParams }, + timeout: 10000 + }); + + if (response.data) { + await redisSet(redisKey, response.data, TTL_SEARCH); + } + return response.data; + } catch (error) { + return null; + } +} + +/** + * Récupère les détails d'une saison TMDB avec cache Redis. + * Clé : tmdb:season:{tvId}:{seasonNumber}:{language} + */ +async function fetchTmdbSeason(tmdbApiUrl, tmdbApiKey, tvId, seasonNumber, language = 'fr-FR') { + const redisKey = `tmdb:season:${tvId}:${seasonNumber}:${language}`; + + const cached = await redisGet(redisKey); + if (cached) return cached; + + try { + const response = await axios.get(`${tmdbApiUrl}/tv/${tvId}/season/${seasonNumber}`, { + params: { api_key: tmdbApiKey, language }, + timeout: 10000 + }); + + if (response.data) { + await redisSet(redisKey, response.data, TTL_DETAILS); + } + return response.data; + } catch (error) { + return null; + } +} + +/** + * Récupère l'année de sortie française d'un film via /movie/{id}/release_dates. + * Clé : tmdb:release_dates:movie:{id} + */ +async function fetchTmdbFrenchReleaseYear(tmdbApiUrl, tmdbApiKey, id) { + const redisKey = `tmdb:release_dates:movie:${id}`; + + const cached = await redisGet(redisKey); + if (cached) { + const frRelease = cached.results ? cached.results.find(r => r.iso_3166_1 === 'FR') : null; + if (frRelease && frRelease.release_dates && frRelease.release_dates.length > 0) { + const date = frRelease.release_dates[0].release_date; + if (date) return new Date(date).getFullYear(); + } + return null; + } + + try { + const response = await axios.get(`${tmdbApiUrl}/movie/${id}/release_dates`, { + params: { api_key: tmdbApiKey }, + timeout: 10000 + }); + + if (response.data) { + await redisSet(redisKey, response.data, TTL_DETAILS); + } + + const frRelease = response.data?.results?.find(r => r.iso_3166_1 === 'FR'); + if (frRelease && frRelease.release_dates && frRelease.release_dates.length > 0) { + const date = frRelease.release_dates[0].release_date; + if (date) return new Date(date).getFullYear(); + } + return null; + } catch (error) { + return null; + } +} + +/** + * Récupère toutes les images TMDB (posters + backdrops, toutes langues). + * Clé : tmdb:images:{type}:{id} + */ +async function fetchTmdbImages(tmdbApiUrl, tmdbApiKey, id, type) { + const redisKey = `tmdb:images:${type}:${id}`; + + const cached = await redisGet(redisKey); + if (cached) return cached; + + try { + const response = await axios.get(`${tmdbApiUrl}/${type}/${id}/images`, { + params: { api_key: tmdbApiKey }, + timeout: 10000 + }); + + if (response.data) { + await redisSet(redisKey, response.data, TTL_DETAILS); + } + return response.data; + } catch (error) { + return null; + } +} + +module.exports = { + fetchTmdbDetails, + searchTmdb, + fetchTmdbSeason, + fetchTmdbFrenchReleaseYear, + fetchTmdbImages, + TTL_DETAILS, + TTL_SEARCH +}; diff --git a/API/Mainapi/utils/turnstile.js b/API/Mainapi/utils/turnstile.js new file mode 100644 index 0000000..dc88e66 --- /dev/null +++ b/API/Mainapi/utils/turnstile.js @@ -0,0 +1,49 @@ +/** + * Utilitaire partagé pour la vérification Cloudflare Turnstile. + */ + +const axios = require('axios'); + +const TURNSTILE_SECRET_KEY = process.env.TURNSTILE_SECRET_KEY; + +async function verifyTurnstile(token, ip, secretKey) { + try { + const response = await axios.post('https://challenges.cloudflare.com/turnstile/v0/siteverify', { + secret: secretKey || TURNSTILE_SECRET_KEY, + response: token, + remoteip: ip, + }, { timeout: 10000 }); + return response.data.success === true; + } catch (error) { + console.error('Turnstile verification error:', error.message); + return false; + } +} + +/** + * Vérifie le token Turnstile à partir d'une requête Express. + * Retourne { valid: true } si OK, ou { valid: false, status, error } si échec. + * Si aucune secretKey n'est fournie et TURNSTILE_SECRET_KEY n'est pas configuré, la vérification est ignorée. + * @param {object} req - Express request + * @param {string} turnstileToken - Token du client + * @param {string} [secretKey] - Clé secrète optionnelle (sinon utilise TURNSTILE_SECRET_KEY) + */ +async function verifyTurnstileFromRequest(req, turnstileToken, secretKey) { + const key = secretKey || TURNSTILE_SECRET_KEY; + if (!key) return { valid: true }; + + if (!turnstileToken) { + return { valid: false, status: 400, error: 'Vérification de sécurité requise' }; + } + + const ip = req.headers['cf-connecting-ip'] || req.headers['x-forwarded-for']?.split(',')[0]?.trim() || req.ip; + const isValid = await verifyTurnstile(turnstileToken, ip, key); + + if (!isValid) { + return { valid: false, status: 403, error: 'Vérification de sécurité échouée. Réessayez.' }; + } + + return { valid: true }; +} + +module.exports = { verifyTurnstile, verifyTurnstileFromRequest }; diff --git a/API/Mainapi/utils/vipDonations.js b/API/Mainapi/utils/vipDonations.js new file mode 100644 index 0000000..cf598f5 --- /dev/null +++ b/API/Mainapi/utils/vipDonations.js @@ -0,0 +1,1902 @@ +const crypto = require('crypto'); +const axios = require('axios'); +const bitcoin = require('bitcoinjs-lib'); +const ecc = require('tiny-secp256k1'); +const { BIP32Factory } = require('bip32'); + +const { invalidateVipCache } = require('../checkVip'); + +bitcoin.initEccLib(ecc); + +const bip32 = BIP32Factory(ecc); + +const VIP_PACKS = Object.freeze({ + 5: { amountEur: 5, vipYears: 1, durationLabel: '1 an' }, + 7: { amountEur: 7, vipYears: 1.5, durationLabel: '18 mois' }, + 10: { amountEur: 10, vipYears: 2, durationLabel: '2 ans' }, + 15: { amountEur: 15, vipYears: 3, durationLabel: '3 ans' }, + 20: { amountEur: 20, vipYears: 4, durationLabel: '4 ans' } +}); + +const VIP_PAYMENT_METHODS = Object.freeze({ + btc: { type: 'crypto', coin: 'btc' }, + ltc: { type: 'crypto', coin: 'ltc' }, + paygate_hosted: { type: 'paygate', coin: null } +}); + +const DEFAULT_SUPPORT_TELEGRAM_URL = 'https://t.me/movix_site'; +const FINAL_STATUSES = new Set(['delivered', 'cancelled']); +const DEFAULT_EXPIRATION_MINUTES = 210; +const PAYGATE_DEFAULT_DOMAIN = 'checkout.paygate.to'; +const DEFAULT_PAYGATE_MIN_PAID_RATIO = 0.60; +const DEFAULT_PAYGATE_MIN_AMOUNT_EUR = 6.25; +const DEFAULT_PAYGATE_MIN_PACK_EUR = 7; +const SATOSHI_FACTOR = 1e8; +const PAYGATE_USDC_POLYGON_CONTRACT = '0x3c499c542cef5e3811e1192ce70d8cc03d5c3359'; +const STATUS_REASONS = { + awaiting_payment: 'Aucun paiement détecté pour le moment.', + partial_payment: 'Paiement détecté mais montant insuffisant.', + confirming: 'Paiement détecté, confirmations en cours.', + paid: 'Paiement confirmé sur la blockchain.', + delivered: 'Clé VIP livrée.', + expired: 'Invoice expirée.', + cancelled: 'Invoice annulée.' +}; + +const BTC_NETWORK = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bc', + bip32: { + public: 0x0488b21e, + private: 0x0488ade4 + }, + pubKeyHash: 0x00, + scriptHash: 0x05, + wif: 0x80 +}; + +const LTC_NETWORK = { + messagePrefix: '\x19Litecoin Signed Message:\n', + bech32: 'ltc', + bip32: { + public: 0x019da462, + private: 0x019d9cfe + }, + pubKeyHash: 0x30, + scriptHash: 0x32, + wif: 0xb0 +}; + +const EXTENDED_KEY_FORMATS = { + btc: { + xpub: { bip32Public: 0x0488b21e, defaultAddressType: 'legacy' }, + ypub: { bip32Public: 0x049d7cb2, defaultAddressType: 'p2sh-segwit' }, + zpub: { bip32Public: 0x04b24746, defaultAddressType: 'segwit' } + }, + ltc: { + xpub: { bip32Public: 0x0488b21e, defaultAddressType: 'legacy' }, + Ltub: { bip32Public: 0x019da462, defaultAddressType: 'legacy' } + } +}; + +const BLOCKCYPHER_MAPPING = { + btc: 'btc/main', + ltc: 'ltc/main' +}; + +const PAYGATE_PRICE_CONVERT_COINS = new Set(['polygon_pol', 'eth', 'bep20_bnb']); + +function parseNumber(value, fallback = 0) { + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : fallback; +} + +function roundFiat(value) { + return Number(parseNumber(value).toFixed(2)); +} + +function roundCrypto(value) { + return Number(parseNumber(value).toFixed(8)); +} + +function toSqlDateTime(dateInput) { + const date = dateInput instanceof Date ? dateInput : new Date(dateInput); + return date.toISOString().slice(0, 19).replace('T', ' '); +} + +function fromSqlDateTime(dateInput) { + if (!dateInput) return null; + return new Date(dateInput); +} + +function normalizeBaseUrl(value) { + return String(value || '').trim().replace(/\/+$/, ''); +} + +function getSupportTelegramUrl() { + return process.env.VIP_SUPPORT_TELEGRAM_URL || DEFAULT_SUPPORT_TELEGRAM_URL; +} + +function buildFrontendUrl(pathname) { + const baseUrl = normalizeBaseUrl(process.env.FRONTEND_BASE_URL); + if (!baseUrl) return pathname; + return `${baseUrl}${pathname.startsWith('/') ? pathname : `/${pathname}`}`; +} + +function getInvoicePath(publicId) { + return `/vip/invoice/${encodeURIComponent(publicId)}`; +} + +function getGiftPath(giftToken) { + return `/vip/cadeau/${encodeURIComponent(giftToken)}`; +} + +function hashIp(ipAddress) { + if (!ipAddress) return null; + const secret = process.env.JWT_SECRET || 'movix-vip-ip'; + return crypto.createHmac('sha256', secret).update(ipAddress).digest('hex'); +} + +function getClientIp(req) { + return req.headers['cf-connecting-ip'] + || req.headers['x-forwarded-for']?.split(',')[0].trim() + || req.ip + || null; +} + +function resolvePack(packEur) { + const normalizedAmount = parseNumber(packEur); + return VIP_PACKS[normalizedAmount] || null; +} + +function normalizePaymentMethod(method, fallbackCoin = null) { + const normalized = String(method || '').trim().toLowerCase(); + if (VIP_PAYMENT_METHODS[normalized]) { + return normalized; + } + + return normalizeCoin(fallbackCoin); +} + +function normalizeCoin(coin) { + const normalized = String(coin || '').trim().toLowerCase(); + return normalized === 'btc' || normalized === 'ltc' ? normalized : null; +} + +function isCryptoPaymentMethod(paymentMethod) { + return paymentMethod === 'btc' || paymentMethod === 'ltc'; +} + +function isPaygatePaymentMethod(paymentMethod) { + return paymentMethod === 'paygate_hosted'; +} + +function getInvoicePaymentMethod(invoice) { + if (!invoice) return null; + + const paymentMethod = normalizePaymentMethod(invoice.payment_method, invoice.coin); + if (paymentMethod) { + return paymentMethod; + } + + return null; +} + +function normalizeRecipientMode(mode) { + const normalized = String(mode || '').trim().toLowerCase(); + return normalized === 'self' || normalized === 'gift' ? normalized : null; +} + +function normalizeEmailAddress(email) { + const normalized = String(email || '').trim().toLowerCase(); + if (!normalized) return null; + const isValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(normalized); + return isValid ? normalized : null; +} + +function getCoinEnvPrefix(coin) { + return coin === 'btc' ? 'BTC' : 'LTC'; +} + +function normalizeAddressType(addressType, fallback) { + const normalized = String(addressType || '').trim().toLowerCase(); + if (normalized === 'legacy' || normalized === 'segwit' || normalized === 'p2sh-segwit') { + return normalized; + } + return fallback; +} + +function getPaygateCheckoutDomain() { + return String(process.env.VIP_PAYGATE_DOMAIN || PAYGATE_DEFAULT_DOMAIN) + .trim() + .replace(/^https?:\/\//i, '') + .replace(/\/+$/, ''); +} + +function getPaygatePayoutWallet() { + const wallet = String(process.env.VIP_PAYGATE_SETTLEMENT_WALLET || '').trim(); + if (!wallet) { + return ''; + } + + if (!/^0x[a-fA-F0-9]{40}$/.test(wallet)) { + throw new Error('VIP_PAYGATE_SETTLEMENT_WALLET invalide: adresse EVM/Polygon attendue'); + } + + if (wallet.toLowerCase() === PAYGATE_USDC_POLYGON_CONTRACT) { + throw new Error('VIP_PAYGATE_SETTLEMENT_WALLET invalide: utilise ton wallet, pas le contrat USDC Polygon'); + } + + return wallet; +} + +function getPaygateMinPaidRatio() { + const ratio = parseNumber(process.env.VIP_PAYGATE_MIN_PAID_RATIO, DEFAULT_PAYGATE_MIN_PAID_RATIO); + return Math.min(1, Math.max(0.5, ratio)); +} + +function getPaygateMinimumAmountEur() { + return roundFiat(Math.max( + 0, + parseNumber(process.env.VIP_PAYGATE_MIN_AMOUNT_EUR, DEFAULT_PAYGATE_MIN_AMOUNT_EUR) + )); +} + +function getPaygateCheckoutAmountEur(amountEur) { + return roundFiat(Math.max(parseNumber(amountEur), getPaygateMinimumAmountEur())); +} + +function isPaygatePackAllowed(pack) { + if (!pack) { + return false; + } + + return parseNumber(pack.amountEur, 0) >= parseNumber( + process.env.VIP_PAYGATE_MIN_PACK_EUR, + DEFAULT_PAYGATE_MIN_PACK_EUR + ); +} + +function getPaygateBranding() { + return { + logo: String(process.env.VIP_PAYGATE_LOGO_URL || '').trim(), + background: String(process.env.VIP_PAYGATE_BACKGROUND || '').trim(), + theme: String(process.env.VIP_PAYGATE_THEME || '').trim(), + button: String(process.env.VIP_PAYGATE_BUTTON || '').trim() + }; +} + +function getPaygateCallbackBaseUrl(context = {}) { + const envBaseUrl = normalizeBaseUrl(process.env.VIP_PAYGATE_CALLBACK_BASE_URL); + if (envBaseUrl) { + return envBaseUrl; + } + + return normalizeBaseUrl(context.callbackBaseUrl); +} + +function buildPaygateCallbackUrl(publicId, callbackNonce, context = {}) { + const callbackBaseUrl = getPaygateCallbackBaseUrl(context); + if (!callbackBaseUrl) { + throw new Error('VIP PayGate callback URL introuvable'); + } + + const query = new URLSearchParams({ + publicId, + nonce: callbackNonce + }); + + return `${callbackBaseUrl}/api/vip/paygate/callback?${query.toString()}`; +} + +function buildPaygateCheckoutUrl({ trackingAddress, amountEur, payerEmail, branding = {} }) { + const domain = getPaygateCheckoutDomain(); + if (!domain) { + throw new Error('VIP PayGate domain manquant'); + } + + const queryParts = [ + `address=${String(trackingAddress || '').trim()}`, + `amount=${roundFiat(amountEur).toFixed(2)}`, + `email=${encodeURIComponent(String(payerEmail || '').trim())}`, + 'currency=EUR' + ]; + + if (branding.logo) queryParts.push(`logo=${encodeURIComponent(branding.logo)}`); + if (branding.background) queryParts.push(`background=${encodeURIComponent(branding.background)}`); + if (branding.theme) queryParts.push(`theme=${encodeURIComponent(branding.theme)}`); + if (branding.button) queryParts.push(`button=${encodeURIComponent(branding.button)}`); + + return `https://${domain}/pay.php?${queryParts.join('&')}`; +} + +function resolvePaygateCheckoutUrl(invoice) { + if (!invoice) { + return null; + } + + const trackingAddress = String(invoice.paygate_tracking_address || invoice.payment_address || '').trim(); + const payerEmail = normalizeEmailAddress(invoice.paygate_payer_email); + + if (!trackingAddress || !payerEmail) { + return invoice.paygate_checkout_url || null; + } + + try { + return buildPaygateCheckoutUrl({ + trackingAddress, + amountEur: getPaygateCheckoutAmountEur(invoice.amount_eur), + payerEmail, + branding: getPaygateBranding() + }); + } catch (error) { + return invoice.paygate_checkout_url || null; + } +} + +function getStartDerivationIndex(coin) { + const envPrefix = getCoinEnvPrefix(coin); + return Math.max(0, parseNumber(process.env[`VIP_${envPrefix}_START_INDEX`], 0)); +} + +function getExtendedKeyFormat(coin, extendedKey) { + const formats = EXTENDED_KEY_FORMATS[coin] || {}; + return Object.entries(formats).find(([prefix]) => extendedKey.startsWith(prefix)) || null; +} + +function derivePaymentAddress(coin, derivationIndex) { + const envPrefix = getCoinEnvPrefix(coin); + const xpub = String(process.env[`VIP_${envPrefix}_XPUB`] || '').trim(); + if (!xpub) { + throw new Error(`VIP_${envPrefix}_XPUB manquant`); + } + + const formatEntry = getExtendedKeyFormat(coin, xpub); + if (!formatEntry) { + throw new Error(`Format de xpub non supporté pour ${coin.toUpperCase()}`); + } + + const [, format] = formatEntry; + const baseNetwork = coin === 'btc' ? BTC_NETWORK : LTC_NETWORK; + const addressType = normalizeAddressType( + process.env[`VIP_${envPrefix}_ADDRESS_TYPE`], + format.defaultAddressType + ); + + const parsingNetwork = { + ...baseNetwork, + bip32: { + public: format.bip32Public, + private: baseNetwork.bip32.private + } + }; + + const accountNode = bip32.fromBase58(xpub, parsingNetwork); + const chainIndex = parseNumber(process.env[`VIP_${envPrefix}_CHAIN`], 0); + const childNode = accountNode.derive(chainIndex).derive(derivationIndex); + const publicKey = Buffer.from(childNode.publicKey); + + let payment; + if (addressType === 'segwit') { + payment = bitcoin.payments.p2wpkh({ pubkey: publicKey, network: baseNetwork }); + } else if (addressType === 'p2sh-segwit') { + payment = bitcoin.payments.p2sh({ + redeem: bitcoin.payments.p2wpkh({ pubkey: publicKey, network: baseNetwork }), + network: baseNetwork + }); + } else { + payment = bitcoin.payments.p2pkh({ pubkey: publicKey, network: baseNetwork }); + } + + if (!payment.address) { + throw new Error(`Impossible de dériver une adresse ${coin.toUpperCase()}`); + } + + return { + address: payment.address, + addressType, + derivationIndex + }; +} + +async function fetchCoinbaseSpotPrices(coin) { + const symbol = coin.toUpperCase(); + const [eurResponse, usdResponse] = await Promise.all([ + axios.get(`https://api.coinbase.com/v2/prices/${symbol}-EUR/spot`, { timeout: 15000 }), + axios.get(`https://api.coinbase.com/v2/prices/${symbol}-USD/spot`, { timeout: 15000 }) + ]); + + return { + eurPricePerCoin: parseNumber(eurResponse.data?.data?.amount), + usdPricePerCoin: parseNumber(usdResponse.data?.data?.amount) + }; +} + +async function fetchCoinGeckoSpotPrices(coin) { + const coinId = coin === 'btc' ? 'bitcoin' : 'litecoin'; + const response = await axios.get( + 'https://api.coingecko.com/api/v3/simple/price', + { + params: { + ids: coinId, + vs_currencies: 'eur,usd' + }, + timeout: 15000 + } + ); + + return { + eurPricePerCoin: parseNumber(response.data?.[coinId]?.eur), + usdPricePerCoin: parseNumber(response.data?.[coinId]?.usd) + }; +} + +async function buildPricingSnapshot(coin, amountEur) { + let prices; + try { + prices = await fetchCoinbaseSpotPrices(coin); + } catch (error) { + prices = await fetchCoinGeckoSpotPrices(coin); + } + + if (!prices.eurPricePerCoin || !prices.usdPricePerCoin) { + throw new Error(`Impossible de récupérer le prix ${coin.toUpperCase()}`); + } + + return { + amountEur: roundFiat(amountEur), + amountUsd: roundFiat((amountEur / prices.eurPricePerCoin) * prices.usdPricePerCoin), + amountCryptoExpected: roundCrypto(amountEur / prices.eurPricePerCoin), + eurPricePerCoin: roundFiat(prices.eurPricePerCoin), + usdPricePerCoin: roundFiat(prices.usdPricePerCoin) + }; +} + +async function fetchPaygateConvertedUsd(amount, fromCurrency = 'eur') { + const response = await axios.get( + 'https://api.paygate.to/control/convert.php', + { + params: { + value: roundFiat(amount).toFixed(2), + from: String(fromCurrency || 'eur').trim().toLowerCase() + }, + timeout: 15000 + } + ); + + const usdAmount = parseNumber(response.data?.value_coin); + if (!usdAmount) { + throw new Error('Impossible de convertir le montant via PayGate'); + } + + return roundFiat(usdAmount); +} + +async function fetchPaygateTemporaryWallet(callbackUrl) { + const payoutWallet = getPaygatePayoutWallet(); + if (!payoutWallet) { + throw new Error('VIP_PAYGATE_SETTLEMENT_WALLET manquant'); + } + + const response = await axios.get( + 'https://api.paygate.to/control/wallet.php', + { + params: { + address: payoutWallet, + callback: callbackUrl + }, + timeout: 15000 + } + ); + + const trackingAddress = String(response.data?.address_in || '').trim(); + const temporaryWalletAddress = String(response.data?.polygon_address_in || '').trim(); + const callbackUrlFromGateway = String(response.data?.callback_url || '').trim(); + + if (!trackingAddress) { + throw new Error('PayGate n\'a pas retourné d\'adresse de suivi'); + } + + return { + trackingAddress, + temporaryWalletAddress: temporaryWalletAddress || null, + callbackUrl: callbackUrlFromGateway || null + }; +} + +async function normalizePaygatePaidUsdValue(receivedCoin, paidValue) { + const rawValue = parseNumber(paidValue); + if (!rawValue) { + return 0; + } + + const normalizedCoin = String(receivedCoin || '').trim().toLowerCase(); + if (!PAYGATE_PRICE_CONVERT_COINS.has(normalizedCoin)) { + return roundFiat(rawValue); + } + + try { + const coinPath = normalizedCoin.replace('_', '/'); + const response = await axios.get( + `https://api.paygate.to/crypto/${coinPath}/info.php`, + { timeout: 15000 } + ); + const usdPrice = parseNumber(response.data?.prices?.USD); + if (!usdPrice) { + return roundFiat(rawValue); + } + + return roundFiat(rawValue * usdPrice); + } catch (error) { + return roundFiat(rawValue); + } +} + +function buildQrPayload(coin, address, amountCryptoExpected) { + const scheme = coin === 'btc' ? 'bitcoin' : 'litecoin'; + return `${scheme}:${address}?amount=${roundCrypto(amountCryptoExpected).toFixed(8)}`; +} + +async function reserveDerivationIndex(pool, coin) { + const connection = await pool.getConnection(); + try { + await connection.beginTransaction(); + + const [rows] = await connection.execute( + 'SELECT next_index FROM vip_derivation_counters WHERE coin = ? FOR UPDATE', + [coin] + ); + + const startIndex = getStartDerivationIndex(coin); + let derivationIndex = startIndex; + if (rows.length === 0) { + await connection.execute( + 'INSERT INTO vip_derivation_counters (coin, next_index, created_at, updated_at) VALUES (?, ?, NOW(), NOW())', + [coin, derivationIndex + 1] + ); + } else { + derivationIndex = Math.max(parseNumber(rows[0].next_index, 0), startIndex); + await connection.execute( + 'UPDATE vip_derivation_counters SET next_index = ?, updated_at = NOW() WHERE coin = ?', + [derivationIndex + 1, coin] + ); + } + + await connection.commit(); + return derivationIndex; + } catch (error) { + await connection.rollback(); + throw error; + } finally { + connection.release(); + } +} + +async function logVipInvoiceEvent(db, invoiceId, eventType, message, payload, actorType = 'system', actorId = null) { + await db.execute( + `INSERT INTO vip_invoice_events + (invoice_id, event_type, actor_type, actor_id, message, payload_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, NOW())`, + [ + invoiceId, + eventType, + actorType, + actorId, + message || null, + payload ? JSON.stringify(payload) : null + ] + ); +} + +async function fetchInvoiceByPublicId(pool, publicId) { + const [rows] = await pool.execute( + 'SELECT * FROM vip_invoices WHERE public_id = ? LIMIT 1', + [publicId] + ); + return rows[0] || null; +} + +async function fetchInvoiceById(pool, invoiceId) { + const [rows] = await pool.execute( + 'SELECT * FROM vip_invoices WHERE id = ? LIMIT 1', + [invoiceId] + ); + return rows[0] || null; +} + +async function fetchInvoiceByGiftToken(pool, giftToken) { + const [rows] = await pool.execute( + 'SELECT * FROM vip_invoices WHERE gift_token = ? LIMIT 1', + [giftToken] + ); + return rows[0] || null; +} + +async function generateUniqueVipKey(db) { + for (let attempt = 0; attempt < 10; attempt += 1) { + const candidate = `VIP-${crypto.randomBytes(8).toString('hex').toUpperCase()}`; + const [rows] = await db.execute( + 'SELECT key_value FROM access_keys WHERE key_value = ? LIMIT 1', + [candidate] + ); + if (rows.length === 0) { + return candidate; + } + } + + throw new Error('Impossible de générer une clé VIP unique'); +} + +function buildDurationLabel(vipYears) { + const normalizedYears = parseNumber(vipYears, 1); + const totalMonths = Math.max(1, Math.round(normalizedYears * 12)); + + if (totalMonths % 12 === 0) { + const totalYears = totalMonths / 12; + return `${totalYears} ${totalYears > 1 ? 'ans' : 'an'}`; + } + + return `${totalMonths} mois`; +} + +async function deliverInvoiceIfReady(pool, invoiceId, actorType = 'system', actorId = null, reason = 'auto') { + const connection = await pool.getConnection(); + try { + await connection.beginTransaction(); + + const [rows] = await connection.execute( + 'SELECT * FROM vip_invoices WHERE id = ? FOR UPDATE', + [invoiceId] + ); + + if (rows.length === 0) { + throw new Error('Invoice introuvable'); + } + + const invoice = rows[0]; + if (invoice.status === 'delivered' && invoice.vip_key_value) { + await connection.commit(); + return invoice; + } + + if (invoice.status !== 'paid') { + await connection.commit(); + return invoice; + } + + const vipYears = parseNumber(invoice.vip_years, 0); + const totalMonths = Math.max(1, Math.round(vipYears * 12)); + const durationLabel = buildDurationLabel(vipYears); + const keyValue = await generateUniqueVipKey(connection); + const expiresAt = new Date(); + expiresAt.setMonth(expiresAt.getMonth() + totalMonths); + + await connection.execute( + `INSERT INTO access_keys + (key_value, active, used, duree_validite, expires_at, created_at, updated_at) + VALUES (?, 1, 0, ?, ?, NOW(), NOW())`, + [keyValue, durationLabel, expiresAt.getTime()] + ); + + await connection.execute( + `UPDATE vip_invoices + SET status = 'delivered', + vip_key_value = ?, + delivered_at = COALESCE(delivered_at, NOW()), + paid_at = COALESCE(paid_at, NOW()), + updated_at = NOW() + WHERE id = ?`, + [keyValue, invoiceId] + ); + + await logVipInvoiceEvent( + connection, + invoiceId, + 'invoice_delivered', + 'Clé VIP livrée automatiquement.', + { + reason, + keyValue, + vipYears, + durationMonths: totalMonths, + durationLabel + }, + actorType, + actorId + ); + + await connection.commit(); + invalidateVipCache(keyValue); + + return fetchInvoiceById(pool, invoiceId); + } catch (error) { + await connection.rollback(); + throw error; + } finally { + connection.release(); + } +} + +function getRequiredConfirmations(coin) { + const envPrefix = getCoinEnvPrefix(coin); + return Math.max(1, parseNumber(process.env[`VIP_${envPrefix}_CONFIRMATIONS`], 1)); +} + +async function fetchAddressActivity(coin, address, options = {}) { + const chain = BLOCKCYPHER_MAPPING[coin]; + if (!chain) { + throw new Error(`Coin non supporté pour la surveillance: ${coin}`); + } + + const response = await axios.get( + `https://api.blockcypher.com/v1/${chain}/addrs/${encodeURIComponent(address)}/full`, + { + params: { + limit: 50, + txlimit: 50, + ...(process.env.BLOCKCYPHER_TOKEN ? { token: process.env.BLOCKCYPHER_TOKEN } : {}) + }, + timeout: 15000, + validateStatus: (status) => status >= 200 && status < 500 + } + ); + + if (response.status === 404) { + return { + totalReceived: 0, + confirmedReceived: 0, + confirmations: 0, + txHashes: [] + }; + } + + if (response.status >= 400) { + throw new Error(`Erreur BlockCypher ${response.status}`); + } + + const txs = Array.isArray(response.data?.txs) ? response.data.txs : []; + let totalReceived = 0; + let confirmedReceived = 0; + let maxConfirmations = 0; + const txHashes = []; + const requiredConfirmations = getRequiredConfirmations(coin); + const ignoreBeforeMs = options.ignoreBefore ? new Date(options.ignoreBefore).getTime() : 0; + const ignoreBeforeToleranceMs = 1500; + + for (const tx of txs) { + const txTimestamp = Date.parse(tx?.received || tx?.confirmed || ''); + if ( + ignoreBeforeMs + && (!Number.isFinite(txTimestamp) || txTimestamp < (ignoreBeforeMs - ignoreBeforeToleranceMs)) + ) { + continue; + } + + let amountForAddress = 0; + const confirmations = parseNumber(tx.confirmations, 0); + for (const output of Array.isArray(tx.outputs) ? tx.outputs : []) { + if (Array.isArray(output.addresses) && output.addresses.includes(address)) { + amountForAddress += parseNumber(output.value, 0) / SATOSHI_FACTOR; + } + } + + if (amountForAddress <= 0) { + continue; + } + + totalReceived += amountForAddress; + if (confirmations >= requiredConfirmations) { + confirmedReceived += amountForAddress; + } + if (confirmations > maxConfirmations) { + maxConfirmations = confirmations; + } + if (tx.hash) { + txHashes.push(tx.hash); + } + } + + return { + totalReceived: roundCrypto(totalReceived), + confirmedReceived: roundCrypto(confirmedReceived), + confirmations: maxConfirmations, + txHashes + }; +} + +function determineInvoiceStatus(invoice, addressActivity) { + const expected = roundCrypto(parseNumber(invoice.amount_crypto_expected)); + const received = roundCrypto(addressActivity.totalReceived); + const confirmed = roundCrypto(addressActivity.confirmedReceived); + const isExpired = fromSqlDateTime(invoice.expires_at)?.getTime() < Date.now(); + + if (confirmed >= expected && expected > 0) { + return 'paid'; + } + + if (received >= expected && expected > 0) { + return 'confirming'; + } + + if (received > 0) { + return 'partial_payment'; + } + + if (isExpired) { + return 'expired'; + } + + return 'awaiting_payment'; +} + +function safeJsonParse(value) { + try { + return JSON.parse(value); + } catch { + return null; + } +} + +function serializePublicInvoice(invoice) { + if (!invoice) return null; + + const paymentMethod = getInvoicePaymentMethod(invoice); + const isCryptoInvoice = isCryptoPaymentMethod(paymentMethod); + const invoicePath = getInvoicePath(invoice.public_id); + const giftPath = invoice.gift_token ? getGiftPath(invoice.gift_token) : null; + const isGiftDelivered = invoice.recipient_mode === 'gift' && invoice.status === 'delivered' && invoice.gift_token; + const isSelfDelivered = invoice.recipient_mode === 'self' && invoice.status === 'delivered' && invoice.vip_key_value; + + return { + publicId: invoice.public_id, + status: invoice.status, + paymentMethod, + coin: isCryptoInvoice ? normalizeCoin(invoice.coin) : null, + packEur: roundFiat(invoice.pack_eur), + amountEur: roundFiat(invoice.amount_eur), + amountUsd: roundFiat(invoice.amount_usd), + amountCryptoExpected: isCryptoInvoice ? roundCrypto(invoice.amount_crypto_expected) : null, + amountCryptoReceived: isCryptoInvoice ? roundCrypto(invoice.amount_crypto_received) : null, + vipYears: parseNumber(invoice.vip_years), + durationLabel: buildDurationLabel(parseNumber(invoice.vip_years)), + recipientMode: invoice.recipient_mode, + paymentAddress: isCryptoInvoice ? invoice.payment_address : null, + trackingAddress: isPaygatePaymentMethod(paymentMethod) + ? (invoice.paygate_tracking_address || invoice.payment_address || null) + : null, + checkoutUrl: isPaygatePaymentMethod(paymentMethod) + ? resolvePaygateCheckoutUrl(invoice) + : null, + addressType: isCryptoInvoice ? (invoice.address_type || null) : null, + confirmations: isCryptoInvoice ? parseNumber(invoice.confirmations) : null, + requiredConfirmations: isCryptoInvoice ? parseNumber(invoice.required_confirmations) : null, + expiresAt: fromSqlDateTime(invoice.expires_at)?.toISOString() || null, + paidAt: fromSqlDateTime(invoice.paid_at)?.toISOString() || null, + deliveredAt: fromSqlDateTime(invoice.delivered_at)?.toISOString() || null, + createdAt: fromSqlDateTime(invoice.created_at)?.toISOString() || null, + qrPayload: isCryptoInvoice ? invoice.qr_payload : null, + invoicePath, + invoiceUrl: buildFrontendUrl(invoicePath), + giftPath: isGiftDelivered ? giftPath : null, + giftUrl: isGiftDelivered ? buildFrontendUrl(giftPath) : null, + vipKey: isSelfDelivered ? invoice.vip_key_value : null, + supportTelegramUrl: getSupportTelegramUrl() + }; +} + +function serializeAdminInvoice(invoice) { + if (!invoice) return null; + + return { + ...serializePublicInvoice(invoice), + id: parseNumber(invoice.id), + derivationIndex: parseNumber(invoice.derivation_index, -1) >= 0 + ? parseNumber(invoice.derivation_index) + : null, + txHash: invoice.tx_hash || null, + giftToken: invoice.gift_token || null, + giftSealed: Boolean(invoice.gift_sealed), + giftUnsealedAt: fromSqlDateTime(invoice.gift_unsealed_at)?.toISOString() || null, + giftUnsealCount: parseNumber(invoice.gift_unseal_count), + createdByUserId: invoice.created_by_user_id || null, + createdByUserType: invoice.created_by_user_type || null, + createdBySessionId: invoice.created_by_session_id || null, + createdIpHash: invoice.created_ip_hash || null, + payerEmail: invoice.paygate_payer_email || null, + temporaryWalletAddress: invoice.paygate_temporary_wallet_address || null, + callbackUrl: invoice.paygate_callback_url || null, + paidCoin: invoice.paygate_paid_coin || null, + paidValue: invoice.paygate_paid_value !== null && invoice.paygate_paid_value !== undefined + ? roundFiat(invoice.paygate_paid_value) + : null, + paidTxid: invoice.paygate_paid_txid || null, + reason: STATUS_REASONS[invoice.status] || null + }; +} + +function serializeGift(invoice) { + if (!invoice || invoice.recipient_mode !== 'gift') { + return null; + } + + return { + giftToken: invoice.gift_token, + status: invoice.gift_sealed ? 'sealed' : 'unsealed', + invoiceStatus: invoice.status, + vipYears: parseNumber(invoice.vip_years), + durationLabel: buildDurationLabel(parseNumber(invoice.vip_years)), + createdAt: fromSqlDateTime(invoice.created_at)?.toISOString() || null, + unsealedAt: fromSqlDateTime(invoice.gift_unsealed_at)?.toISOString() || null, + vipKey: !invoice.gift_sealed && invoice.status === 'delivered' ? invoice.vip_key_value : null, + supportTelegramUrl: getSupportTelegramUrl() + }; +} + +async function refreshInvoiceStatus(pool, invoiceInput, options = {}) { + const invoice = invoiceInput?.id ? invoiceInput : await fetchInvoiceById(pool, invoiceInput); + if (!invoice) { + return null; + } + + if (FINAL_STATUSES.has(invoice.status)) { + return invoice; + } + + const now = Date.now(); + const nextCheckAt = invoice.next_check_at ? new Date(invoice.next_check_at).getTime() : 0; + const force = options.force === true; + + if (!force && nextCheckAt > now) { + return invoice; + } + + const paymentMethod = getInvoicePaymentMethod(invoice); + if (isPaygatePaymentMethod(paymentMethod)) { + const isExpired = fromSqlDateTime(invoice.expires_at)?.getTime() < Date.now(); + const shouldExpire = invoice.status === 'awaiting_payment' && isExpired; + + if (shouldExpire) { + await pool.execute( + `UPDATE vip_invoices + SET status = 'expired', + next_check_at = DATE_ADD(NOW(), INTERVAL 25 SECOND), + updated_at = NOW() + WHERE id = ?`, + [invoice.id] + ); + + await logVipInvoiceEvent( + pool, + invoice.id, + 'invoice_status_updated', + STATUS_REASONS.expired, + { + from: invoice.status, + to: 'expired' + }, + options.actorType || 'system', + options.actorId || null + ); + } else { + await pool.execute( + 'UPDATE vip_invoices SET next_check_at = DATE_ADD(NOW(), INTERVAL 25 SECOND), updated_at = NOW() WHERE id = ?', + [invoice.id] + ); + } + + const refreshedInvoice = await fetchInvoiceById(pool, invoice.id); + if (refreshedInvoice?.status === 'paid') { + return deliverInvoiceIfReady( + pool, + refreshedInvoice.id, + options.actorType || 'system', + options.actorId || null, + 'paygate_callback' + ); + } + + return refreshedInvoice; + } + + const addressActivity = await fetchAddressActivity(invoice.coin, invoice.payment_address, { + ignoreBefore: invoice.created_at + }); + const newStatus = determineInvoiceStatus(invoice, addressActivity); + const amountReceived = roundCrypto(addressActivity.totalReceived); + const txHash = addressActivity.txHashes[0] || invoice.tx_hash || null; + const shouldMarkPaidAt = newStatus === 'paid' && !invoice.paid_at; + const hasChanged = newStatus !== invoice.status + || roundCrypto(parseNumber(invoice.amount_crypto_received)) !== amountReceived + || parseNumber(invoice.confirmations) !== addressActivity.confirmations + || txHash !== (invoice.tx_hash || null); + + if (hasChanged) { + await pool.execute( + `UPDATE vip_invoices + SET status = ?, + amount_crypto_received = ?, + confirmations = ?, + tx_hash = ?, + paid_at = CASE WHEN ? THEN COALESCE(paid_at, NOW()) ELSE paid_at END, + next_check_at = DATE_ADD(NOW(), INTERVAL 25 SECOND), + updated_at = NOW() + WHERE id = ?`, + [ + newStatus, + amountReceived, + addressActivity.confirmations, + txHash, + shouldMarkPaidAt ? 1 : 0, + invoice.id + ] + ); + + await logVipInvoiceEvent( + pool, + invoice.id, + 'invoice_status_updated', + STATUS_REASONS[newStatus] || 'Statut d\'invoice mis à jour.', + { + from: invoice.status, + to: newStatus, + amountCryptoReceived: amountReceived, + confirmations: addressActivity.confirmations, + txHash + }, + options.actorType || 'system', + options.actorId || null + ); + } else { + await pool.execute( + 'UPDATE vip_invoices SET next_check_at = DATE_ADD(NOW(), INTERVAL 25 SECOND), updated_at = NOW() WHERE id = ?', + [invoice.id] + ); + } + + const refreshedInvoice = await fetchInvoiceById(pool, invoice.id); + if (refreshedInvoice?.status === 'paid') { + return deliverInvoiceIfReady( + pool, + refreshedInvoice.id, + options.actorType || 'system', + options.actorId || null, + 'blockchain_confirmed' + ); + } + + return refreshedInvoice; +} + +async function listVipInvoices(pool, options = {}) { + const page = Math.max(1, parseNumber(options.page, 1)); + const limit = Math.min(100, Math.max(1, parseNumber(options.limit, 30))); + const offset = (page - 1) * limit; + const conditions = []; + const params = []; + + if (options.status) { + conditions.push('status = ?'); + params.push(options.status); + } + + if (options.search) { + conditions.push(`( + public_id LIKE ? + OR payment_address LIKE ? + OR COALESCE(tx_hash, '') LIKE ? + OR COALESCE(vip_key_value, '') LIKE ? + OR COALESCE(gift_token, '') LIKE ? + OR COALESCE(paygate_tracking_address, '') LIKE ? + OR COALESCE(paygate_paid_txid, '') LIKE ? + OR COALESCE(paygate_payer_email, '') LIKE ? + )`); + const searchTerm = `%${options.search}%`; + params.push( + searchTerm, + searchTerm, + searchTerm, + searchTerm, + searchTerm, + searchTerm, + searchTerm, + searchTerm + ); + } + + const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''; + + const [rows] = await pool.execute( + `SELECT * FROM vip_invoices ${whereClause} ORDER BY created_at DESC LIMIT ? OFFSET ?`, + [...params, limit, offset] + ); + const [countRows] = await pool.execute( + `SELECT COUNT(*) AS total FROM vip_invoices ${whereClause}`, + params + ); + + const total = parseNumber(countRows[0]?.total, 0); + + return { + items: rows.map(serializeAdminInvoice), + total, + page, + limit, + hasMore: offset + rows.length < total + }; +} + +async function getVipInvoiceDetails(pool, invoiceId) { + const invoice = await fetchInvoiceById(pool, invoiceId); + if (!invoice) { + return null; + } + + const [events] = await pool.execute( + 'SELECT * FROM vip_invoice_events WHERE invoice_id = ? ORDER BY created_at DESC, id DESC', + [invoiceId] + ); + + return { + invoice: serializeAdminInvoice(invoice), + events: events.map((event) => ({ + id: event.id, + eventType: event.event_type, + actorType: event.actor_type, + actorId: event.actor_id, + message: event.message, + payload: event.payload_json ? safeJsonParse(event.payload_json) : null, + createdAt: fromSqlDateTime(event.created_at)?.toISOString() || null + })) + }; +} + +function createVipInvoiceError(message, statusCode = 400) { + const error = new Error(message); + error.statusCode = statusCode; + return error; +} + +async function createCryptoVipInvoice(pool, payload, context = {}) { + const pack = payload.pack; + const coin = payload.coin; + const recipientMode = payload.recipientMode; + + if (!pack || !coin || !recipientMode) { + throw createVipInvoiceError('Paramètres d\'invoice invalides'); + } + + const pricing = await buildPricingSnapshot(coin, pack.amountEur); + const derivationIndex = await reserveDerivationIndex(pool, coin); + const derivedAddress = derivePaymentAddress(coin, derivationIndex); + const publicId = `inv_${crypto.randomBytes(12).toString('hex')}`; + const giftToken = recipientMode === 'gift' ? `gift_${crypto.randomBytes(16).toString('hex')}` : null; + const expiresAt = new Date(Date.now() + (Math.max(1, parseNumber(process.env.VIP_INVOICE_EXPIRATION_MINUTES, DEFAULT_EXPIRATION_MINUTES)) * 60 * 1000)); + const qrPayload = buildQrPayload(coin, derivedAddress.address, pricing.amountCryptoExpected); + const createdIpHash = hashIp(context.ipAddress); + const auth = context.auth || null; + + const [insertResult] = await pool.execute( + `INSERT INTO vip_invoices + (public_id, payment_method, status, coin, pack_eur, amount_eur, amount_usd, amount_crypto_expected, + amount_crypto_received, vip_years, recipient_mode, payment_address, address_type, + derivation_index, confirmations, required_confirmations, tx_hash, qr_payload, gift_token, + gift_sealed, gift_unsealed_at, gift_unseal_count, gift_unsealed_by_ip_hash, + vip_key_value, created_by_user_id, created_by_user_type, created_by_session_id, + created_ip_hash, expires_at, next_check_at, created_at, updated_at) + VALUES (?, ?, 'awaiting_payment', ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, 0, ?, NULL, ?, ?, 1, NULL, 0, NULL, NULL, ?, ?, ?, ?, ?, NOW(), NOW(), NOW())`, + [ + publicId, + coin, + coin, + pack.amountEur, + pricing.amountEur, + pricing.amountUsd, + pricing.amountCryptoExpected, + pack.vipYears, + recipientMode, + derivedAddress.address, + derivedAddress.addressType, + derivationIndex, + getRequiredConfirmations(coin), + qrPayload, + giftToken, + auth?.userId || null, + auth?.userType || null, + auth?.sessionId || null, + createdIpHash, + toSqlDateTime(expiresAt) + ] + ); + + await logVipInvoiceEvent( + pool, + insertResult.insertId, + 'invoice_created', + 'Invoice VIP créée.', + { + paymentMethod: coin, + coin, + packEur: pack.amountEur, + amountCryptoExpected: pricing.amountCryptoExpected, + vipYears: pack.vipYears, + recipientMode, + derivationIndex, + paymentAddress: derivedAddress.address + }, + auth ? 'user' : 'guest', + auth?.userId || null + ); + + return fetchInvoiceById(pool, insertResult.insertId); +} + +async function createPaygateVipInvoice(pool, payload, context = {}) { + const pack = payload.pack; + const recipientMode = payload.recipientMode; + const normalizedEmail = normalizeEmailAddress(payload.payerEmail); + + if (!pack || !recipientMode || !normalizedEmail) { + throw createVipInvoiceError('Adresse email invalide pour PayGate'); + } + + const publicId = `inv_${crypto.randomBytes(12).toString('hex')}`; + const callbackNonce = crypto.randomBytes(24).toString('hex'); + const callbackUrl = buildPaygateCallbackUrl(publicId, callbackNonce, context); + const checkoutAmountEur = getPaygateCheckoutAmountEur(pack.amountEur); + const amountUsd = await fetchPaygateConvertedUsd(checkoutAmountEur, 'eur'); + const paygateWallet = await fetchPaygateTemporaryWallet(callbackUrl); + const expiresAt = new Date(Date.now() + (Math.max(1, parseNumber(process.env.VIP_INVOICE_EXPIRATION_MINUTES, DEFAULT_EXPIRATION_MINUTES)) * 60 * 1000)); + const giftToken = recipientMode === 'gift' ? `gift_${crypto.randomBytes(16).toString('hex')}` : null; + const createdIpHash = hashIp(context.ipAddress); + const auth = context.auth || null; + const checkoutUrl = buildPaygateCheckoutUrl({ + trackingAddress: paygateWallet.trackingAddress, + amountEur: checkoutAmountEur, + payerEmail: normalizedEmail, + branding: getPaygateBranding() + }); + + const [insertResult] = await pool.execute( + `INSERT INTO vip_invoices + (public_id, payment_method, status, coin, pack_eur, amount_eur, amount_usd, amount_crypto_expected, + amount_crypto_received, vip_years, recipient_mode, payment_address, address_type, + derivation_index, confirmations, required_confirmations, tx_hash, qr_payload, gift_token, + gift_sealed, gift_unsealed_at, gift_unseal_count, gift_unsealed_by_ip_hash, + vip_key_value, created_by_user_id, created_by_user_type, created_by_session_id, + created_ip_hash, expires_at, next_check_at, paygate_tracking_address, paygate_temporary_wallet_address, + paygate_callback_url, paygate_callback_nonce, paygate_checkout_url, paygate_payer_email, + paygate_paid_coin, paygate_paid_value, paygate_paid_txid, created_at, updated_at) + VALUES (?, 'paygate_hosted', 'awaiting_payment', NULL, ?, ?, ?, 0, 0, ?, ?, ?, NULL, + -1, 0, 0, NULL, '', ?, 1, NULL, 0, NULL, NULL, ?, ?, ?, ?, ?, NOW(), + ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, NOW(), NOW())`, + [ + publicId, + pack.amountEur, + checkoutAmountEur, + amountUsd, + pack.vipYears, + recipientMode, + paygateWallet.trackingAddress, + giftToken, + auth?.userId || null, + auth?.userType || null, + auth?.sessionId || null, + createdIpHash, + toSqlDateTime(expiresAt), + paygateWallet.trackingAddress, + paygateWallet.temporaryWalletAddress, + paygateWallet.callbackUrl || callbackUrl, + callbackNonce, + checkoutUrl, + normalizedEmail + ] + ); + + await logVipInvoiceEvent( + pool, + insertResult.insertId, + 'invoice_created', + 'Invoice VIP PayGate créée.', + { + paymentMethod: 'paygate_hosted', + packEur: pack.amountEur, + checkoutAmountEur, + amountUsd, + vipYears: pack.vipYears, + recipientMode, + payerEmail: normalizedEmail, + trackingAddress: paygateWallet.trackingAddress + }, + auth ? 'user' : 'guest', + auth?.userId || null + ); + + return fetchInvoiceById(pool, insertResult.insertId); +} + +async function handlePaygateCallback(pool, payload = {}) { + const publicId = String(payload.publicId || payload.public_id || '').trim(); + const callbackNonce = String(payload.nonce || '').trim(); + const paidCoin = String(payload.coin || '').trim().toLowerCase() || null; + const paidTxid = String(payload.txid_out || payload.txid || '').trim() || null; + const rawPaidValue = payload.value_coin; + + if (!publicId) { + throw createVipInvoiceError('publicId PayGate manquant'); + } + if (!callbackNonce) { + throw createVipInvoiceError('nonce PayGate manquant', 403); + } + + const connection = await pool.getConnection(); + try { + await connection.beginTransaction(); + + const [rows] = await connection.execute( + 'SELECT * FROM vip_invoices WHERE public_id = ? FOR UPDATE', + [publicId] + ); + + if (rows.length === 0) { + throw createVipInvoiceError('Invoice PayGate introuvable', 404); + } + + const invoice = rows[0]; + if (!isPaygatePaymentMethod(getInvoicePaymentMethod(invoice))) { + throw createVipInvoiceError('Cette invoice n\'utilise pas PayGate', 409); + } + if (!invoice.paygate_callback_nonce || invoice.paygate_callback_nonce !== callbackNonce) { + throw createVipInvoiceError('Nonce PayGate invalide', 403); + } + + if (invoice.status === 'delivered' || invoice.status === 'cancelled') { + await connection.commit(); + return invoice; + } + + const paidValue = await normalizePaygatePaidUsdValue(paidCoin, rawPaidValue); + const minimumPaidAmount = roundFiat(parseNumber(invoice.amount_usd) * getPaygateMinPaidRatio()); + const nextStatus = paidValue >= minimumPaidAmount && paidValue > 0 ? 'paid' : 'partial_payment'; + const shouldMarkPaidAt = nextStatus === 'paid' && !invoice.paid_at; + + await connection.execute( + `UPDATE vip_invoices + SET status = ?, + tx_hash = COALESCE(?, tx_hash), + paid_at = CASE WHEN ? THEN COALESCE(paid_at, NOW()) ELSE paid_at END, + paygate_paid_coin = ?, + paygate_paid_value = ?, + paygate_paid_txid = ?, + next_check_at = DATE_ADD(NOW(), INTERVAL 25 SECOND), + updated_at = NOW() + WHERE id = ?`, + [ + nextStatus, + paidTxid, + shouldMarkPaidAt ? 1 : 0, + paidCoin, + paidValue, + paidTxid, + invoice.id + ] + ); + + await logVipInvoiceEvent( + connection, + invoice.id, + 'invoice_paygate_callback', + nextStatus === 'paid' + ? 'Callback PayGate validé, invoice marquée comme payée.' + : 'Callback PayGate reçu avec montant insuffisant.', + { + previousStatus: invoice.status, + nextStatus, + paidCoin, + paidValue, + paidTxid, + minimumPaidAmount + }, + 'gateway', + 'paygate' + ); + + await connection.commit(); + } catch (error) { + await connection.rollback(); + throw error; + } finally { + connection.release(); + } + + const refreshedInvoice = await fetchInvoiceByPublicId(pool, publicId); + if (refreshedInvoice?.status === 'paid') { + return deliverInvoiceIfReady(pool, refreshedInvoice.id, 'gateway', 'paygate', 'paygate_callback'); + } + + return refreshedInvoice; +} + +async function createVipInvoice(pool, payload, context = {}) { + const pack = resolvePack(payload.packEur); + const paymentMethod = normalizePaymentMethod(payload.paymentMethod, payload.coin); + const recipientMode = normalizeRecipientMode(payload.recipientMode); + + if (!pack || !paymentMethod || !recipientMode) { + throw createVipInvoiceError('Paramètres d\'invoice invalides'); + } + + if (isPaygatePaymentMethod(paymentMethod)) { + if (!isPaygatePackAllowed(pack)) { + throw createVipInvoiceError('PayGate est indisponible sur le pack 5 EUR. Utilise BTC/LTC ou choisis le pack 7 EUR.'); + } + + const paygateEnabled = String(process.env.VIP_PAYGATE_ENABLED || 'true').trim().toLowerCase(); + if (['0', 'false', 'no', 'off'].includes(paygateEnabled)) { + throw createVipInvoiceError('Paiement PayGate indisponible pour le moment'); + } + + return createPaygateVipInvoice( + pool, + { + pack, + recipientMode, + payerEmail: payload.payerEmail + }, + context + ); + } + + return createCryptoVipInvoice( + pool, + { + pack, + coin: paymentMethod, + recipientMode + }, + context + ); +} + +async function forceValidateInvoice(pool, invoiceId, admin) { + const connection = await pool.getConnection(); + try { + await connection.beginTransaction(); + + const [rows] = await connection.execute( + 'SELECT * FROM vip_invoices WHERE id = ? FOR UPDATE', + [invoiceId] + ); + + if (rows.length === 0) { + throw new Error('Invoice introuvable'); + } + + const invoice = rows[0]; + const paymentMethod = getInvoicePaymentMethod(invoice); + if (invoice.status === 'cancelled') { + throw new Error('Cette invoice est annulée'); + } + if (invoice.status !== 'delivered') { + await connection.execute( + `UPDATE vip_invoices + SET status = 'paid', + confirmations = CASE + WHEN ? = 'paygate_hosted' THEN confirmations + ELSE GREATEST(confirmations, required_confirmations) + END, + amount_crypto_received = CASE + WHEN ? = 'paygate_hosted' THEN amount_crypto_received + WHEN amount_crypto_received < amount_crypto_expected THEN amount_crypto_expected + ELSE amount_crypto_received + END, + paygate_paid_coin = CASE + WHEN ? = 'paygate_hosted' THEN COALESCE(paygate_paid_coin, 'manual') + ELSE paygate_paid_coin + END, + paygate_paid_value = CASE + WHEN ? = 'paygate_hosted' THEN COALESCE(paygate_paid_value, amount_usd) + ELSE paygate_paid_value + END, + paid_at = COALESCE(paid_at, NOW()), + updated_at = NOW() + WHERE id = ?`, + [paymentMethod, paymentMethod, paymentMethod, paymentMethod, invoiceId] + ); + + await logVipInvoiceEvent( + connection, + invoiceId, + 'invoice_admin_validated', + 'Invoice marquée comme payée par un administrateur.', + { + previousStatus: invoice.status, + adminId: admin?.userId || null + }, + 'admin', + admin?.userId || null + ); + } + + await connection.commit(); + } catch (error) { + await connection.rollback(); + throw error; + } finally { + connection.release(); + } + + return deliverInvoiceIfReady(pool, invoiceId, 'admin', admin?.userId || null, 'admin_override'); +} + +async function cancelInvoice(pool, invoiceId, admin) { + const connection = await pool.getConnection(); + try { + await connection.beginTransaction(); + + const [rows] = await connection.execute( + 'SELECT * FROM vip_invoices WHERE id = ? FOR UPDATE', + [invoiceId] + ); + + if (rows.length === 0) { + throw new Error('Invoice introuvable'); + } + + const invoice = rows[0]; + if (invoice.status === 'delivered') { + throw new Error('Impossible d\'annuler une invoice déjà livrée'); + } + + if (invoice.status !== 'cancelled') { + await connection.execute( + `UPDATE vip_invoices + SET status = 'cancelled', + updated_at = NOW() + WHERE id = ?`, + [invoiceId] + ); + + await logVipInvoiceEvent( + connection, + invoiceId, + 'invoice_cancelled', + 'Invoice annulée par un administrateur.', + { + previousStatus: invoice.status, + adminId: admin?.userId || null + }, + 'admin', + admin?.userId || null + ); + } + + await connection.commit(); + } catch (error) { + await connection.rollback(); + throw error; + } finally { + connection.release(); + } + + return fetchInvoiceById(pool, invoiceId); +} + +async function unsealGift(pool, giftToken, ipAddress) { + const connection = await pool.getConnection(); + try { + await connection.beginTransaction(); + + const [rows] = await connection.execute( + 'SELECT * FROM vip_invoices WHERE gift_token = ? FOR UPDATE', + [giftToken] + ); + + if (rows.length === 0) { + throw new Error('Cadeau introuvable'); + } + + const invoice = rows[0]; + if (invoice.recipient_mode !== 'gift') { + throw new Error('Ce lien ne correspond pas à un cadeau'); + } + if (invoice.status !== 'delivered' || !invoice.vip_key_value) { + throw new Error('La clé cadeau n\'est pas encore disponible'); + } + + if (invoice.gift_sealed) { + await connection.execute( + `UPDATE vip_invoices + SET gift_sealed = 0, + gift_unsealed_at = COALESCE(gift_unsealed_at, NOW()), + gift_unseal_count = gift_unseal_count + 1, + gift_unsealed_by_ip_hash = COALESCE(gift_unsealed_by_ip_hash, ?), + updated_at = NOW() + WHERE id = ?`, + [hashIp(ipAddress), invoice.id] + ); + + await logVipInvoiceEvent( + connection, + invoice.id, + 'gift_unsealed', + 'Cadeau descellé.', + { + giftToken, + ipHash: hashIp(ipAddress) + }, + 'gift', + giftToken + ); + } + + await connection.commit(); + } catch (error) { + await connection.rollback(); + throw error; + } finally { + connection.release(); + } + + return fetchInvoiceByGiftToken(pool, giftToken); +} + +async function ensureColumnExists(pool, tableName, columnName, definitionSql) { + const [rows] = await pool.execute( + `SELECT COLUMN_NAME + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = ? + AND COLUMN_NAME = ? + LIMIT 1`, + [tableName, columnName] + ); + + if (rows.length === 0) { + await pool.execute(`ALTER TABLE \`${tableName}\` ADD COLUMN ${definitionSql}`); + } +} + +async function ensureIndexExists(pool, tableName, indexName, definitionSql) { + const [rows] = await pool.execute( + `SELECT INDEX_NAME + FROM INFORMATION_SCHEMA.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = ? + AND INDEX_NAME = ? + LIMIT 1`, + [tableName, indexName] + ); + + if (rows.length === 0) { + await pool.execute(`ALTER TABLE \`${tableName}\` ADD ${definitionSql}`); + } +} + +async function ensureVipDonationsTables(pool) { + await pool.execute(` + CREATE TABLE IF NOT EXISTS vip_derivation_counters ( + coin ENUM('btc', 'ltc') PRIMARY KEY, + next_index INT NOT NULL DEFAULT 0, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci + `); + + await pool.execute(` + CREATE TABLE IF NOT EXISTS vip_invoices ( + id INT AUTO_INCREMENT PRIMARY KEY, + public_id VARCHAR(64) NOT NULL UNIQUE, + payment_method ENUM('btc', 'ltc', 'paygate_hosted') NOT NULL, + status ENUM('awaiting_payment', 'partial_payment', 'confirming', 'paid', 'delivered', 'expired', 'cancelled') NOT NULL DEFAULT 'awaiting_payment', + coin ENUM('btc', 'ltc') DEFAULT NULL, + pack_eur DECIMAL(10,2) NOT NULL, + amount_eur DECIMAL(10,2) NOT NULL, + amount_usd DECIMAL(10,2) NOT NULL, + amount_crypto_expected DECIMAL(20,8) NOT NULL, + amount_crypto_received DECIMAL(20,8) NOT NULL DEFAULT 0, + vip_years DECIMAL(5,2) NOT NULL, + recipient_mode ENUM('self', 'gift') NOT NULL, + payment_address VARCHAR(128) NOT NULL, + address_type VARCHAR(32) DEFAULT NULL, + derivation_index INT NOT NULL, + confirmations INT NOT NULL DEFAULT 0, + required_confirmations INT NOT NULL DEFAULT 1, + tx_hash VARCHAR(128) DEFAULT NULL, + qr_payload TEXT NOT NULL, + gift_token VARCHAR(64) DEFAULT NULL UNIQUE, + gift_sealed TINYINT(1) NOT NULL DEFAULT 1, + gift_unsealed_at DATETIME DEFAULT NULL, + gift_unseal_count INT NOT NULL DEFAULT 0, + gift_unsealed_by_ip_hash VARCHAR(128) DEFAULT NULL, + vip_key_value VARCHAR(255) DEFAULT NULL, + created_by_user_id VARCHAR(255) DEFAULT NULL, + created_by_user_type VARCHAR(32) DEFAULT NULL, + created_by_session_id VARCHAR(255) DEFAULT NULL, + created_ip_hash VARCHAR(128) DEFAULT NULL, + expires_at DATETIME NOT NULL, + paid_at DATETIME DEFAULT NULL, + delivered_at DATETIME DEFAULT NULL, + next_check_at DATETIME DEFAULT NULL, + paygate_tracking_address VARCHAR(255) DEFAULT NULL, + paygate_temporary_wallet_address VARCHAR(255) DEFAULT NULL, + paygate_callback_url TEXT DEFAULT NULL, + paygate_callback_nonce VARCHAR(128) DEFAULT NULL, + paygate_checkout_url TEXT DEFAULT NULL, + paygate_payer_email VARCHAR(255) DEFAULT NULL, + paygate_paid_coin VARCHAR(64) DEFAULT NULL, + paygate_paid_value DECIMAL(18,8) DEFAULT NULL, + paygate_paid_txid VARCHAR(255) DEFAULT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + INDEX idx_vip_invoices_payment_method (payment_method), + INDEX idx_vip_invoices_status (status), + INDEX idx_vip_invoices_coin (coin), + INDEX idx_vip_invoices_created_at (created_at), + INDEX idx_vip_invoices_payment_address (payment_address), + INDEX idx_vip_invoices_vip_key (vip_key_value), + INDEX idx_vip_invoices_paygate_paid_txid (paygate_paid_txid) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci + `); + + await pool.execute(` + CREATE TABLE IF NOT EXISTS vip_invoice_events ( + id INT AUTO_INCREMENT PRIMARY KEY, + invoice_id INT NOT NULL, + event_type VARCHAR(64) NOT NULL, + actor_type VARCHAR(32) DEFAULT NULL, + actor_id VARCHAR(255) DEFAULT NULL, + message VARCHAR(255) DEFAULT NULL, + payload_json LONGTEXT DEFAULT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + INDEX idx_vip_invoice_events_invoice (invoice_id), + INDEX idx_vip_invoice_events_type (event_type), + CONSTRAINT fk_vip_invoice_events_invoice + FOREIGN KEY (invoice_id) REFERENCES vip_invoices(id) ON DELETE CASCADE + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci + `); + + await pool.execute( + `INSERT IGNORE INTO vip_derivation_counters (coin, next_index, created_at, updated_at) + VALUES ('btc', 0, NOW(), NOW()), ('ltc', 0, NOW(), NOW())` + ); + + await ensureColumnExists( + pool, + 'vip_invoices', + 'payment_method', + "`payment_method` ENUM('btc', 'ltc', 'paygate_hosted') NULL AFTER `public_id`" + ); + await ensureColumnExists( + pool, + 'vip_invoices', + 'paygate_tracking_address', + "`paygate_tracking_address` VARCHAR(255) DEFAULT NULL AFTER `next_check_at`" + ); + await ensureColumnExists( + pool, + 'vip_invoices', + 'paygate_temporary_wallet_address', + "`paygate_temporary_wallet_address` VARCHAR(255) DEFAULT NULL AFTER `paygate_tracking_address`" + ); + await ensureColumnExists( + pool, + 'vip_invoices', + 'paygate_callback_url', + "`paygate_callback_url` TEXT DEFAULT NULL AFTER `paygate_temporary_wallet_address`" + ); + await ensureColumnExists( + pool, + 'vip_invoices', + 'paygate_callback_nonce', + "`paygate_callback_nonce` VARCHAR(128) DEFAULT NULL AFTER `paygate_callback_url`" + ); + await ensureColumnExists( + pool, + 'vip_invoices', + 'paygate_checkout_url', + "`paygate_checkout_url` TEXT DEFAULT NULL AFTER `paygate_callback_nonce`" + ); + await ensureColumnExists( + pool, + 'vip_invoices', + 'paygate_payer_email', + "`paygate_payer_email` VARCHAR(255) DEFAULT NULL AFTER `paygate_checkout_url`" + ); + await ensureColumnExists( + pool, + 'vip_invoices', + 'paygate_paid_coin', + "`paygate_paid_coin` VARCHAR(64) DEFAULT NULL AFTER `paygate_payer_email`" + ); + await ensureColumnExists( + pool, + 'vip_invoices', + 'paygate_paid_value', + "`paygate_paid_value` DECIMAL(18,8) DEFAULT NULL AFTER `paygate_paid_coin`" + ); + await ensureColumnExists( + pool, + 'vip_invoices', + 'paygate_paid_txid', + "`paygate_paid_txid` VARCHAR(255) DEFAULT NULL AFTER `paygate_paid_value`" + ); + + await pool.execute(` + UPDATE vip_invoices + SET payment_method = coin + WHERE payment_method IS NULL AND coin IS NOT NULL + `); + + await pool.execute(` + ALTER TABLE vip_invoices + MODIFY COLUMN vip_years DECIMAL(5,2) NOT NULL + `); + await pool.execute(` + ALTER TABLE vip_invoices + MODIFY COLUMN payment_method ENUM('btc', 'ltc', 'paygate_hosted') NOT NULL + `); + await pool.execute(` + ALTER TABLE vip_invoices + MODIFY COLUMN coin ENUM('btc', 'ltc') NULL + `); + + await ensureIndexExists( + pool, + 'vip_invoices', + 'idx_vip_invoices_payment_method', + 'INDEX `idx_vip_invoices_payment_method` (`payment_method`)' + ); + await ensureIndexExists( + pool, + 'vip_invoices', + 'idx_vip_invoices_paygate_paid_txid', + 'INDEX `idx_vip_invoices_paygate_paid_txid` (`paygate_paid_txid`)' + ); +} + +module.exports = { + VIP_PACKS, + STATUS_REASONS, + DEFAULT_EXPIRATION_MINUTES, + createVipInvoice, + handlePaygateCallback, + fetchInvoiceByPublicId, + fetchInvoiceById, + fetchInvoiceByGiftToken, + refreshInvoiceStatus, + forceValidateInvoice, + cancelInvoice, + getVipInvoiceDetails, + listVipInvoices, + serializePublicInvoice, + serializeAdminInvoice, + serializeGift, + unsealGift, + ensureVipDonationsTables, + getClientIp, + getSupportTelegramUrl, + parseNumber, + roundCrypto, + roundFiat, + resolvePack, + normalizePaymentMethod, + normalizeCoin, + normalizeRecipientMode, + buildPricingSnapshot, + reserveDerivationIndex, + derivePaymentAddress, + buildQrPayload, + logVipInvoiceEvent, + deliverInvoiceIfReady, + determineInvoiceStatus, + fetchAddressActivity, + getRequiredConfirmations, + hashIp, + safeJsonParse, + buildDurationLabel, + toSqlDateTime, + fromSqlDateTime, + buildFrontendUrl, + getInvoicePath, + getGiftPath +}; diff --git a/API/Mainapi/wishboardRoutes.js b/API/Mainapi/wishboardRoutes.js new file mode 100644 index 0000000..8c24931 --- /dev/null +++ b/API/Mainapi/wishboardRoutes.js @@ -0,0 +1,1006 @@ +/** + * Wishboard / Greenlight API Routes + * Content request management system + * + * Uses MySQL database (same as the rest of the app) + */ + +const express = require('express'); +const jwt = require('jsonwebtoken'); +const fs = require('fs').promises; +const path = require('path'); +const { verifyAccessKey } = require('./checkVip'); +const { searchTmdb } = require('./utils/tmdbCache'); +const { verifyTurnstileFromRequest } = require('./utils/turnstile'); + +const TURNSTILE_INVISIBLE_SECRETKEY = process.env.TURNSTILE_INVISIBLE_SECRETKEY; +const TMDB_API_URL = 'https://api.themoviedb.org/3'; +// JWT Secret (same as commentsRoutes and server.js) +const JWT_SECRET = process.env.JWT_SECRET; + +/** + * Search TMDB by name and return matching TMDB IDs. + * Utilise searchTmdb centralisé (cache Redis partagé). + */ +async function searchTmdbIds(query) { + try { + const [movieData, tvData] = await Promise.all([ + searchTmdb(TMDB_API_URL, process.env.TMDB_API_KEY, 'movie', query, { page: 1 }).catch(() => null), + searchTmdb(TMDB_API_URL, process.env.TMDB_API_KEY, 'tv', query, { page: 1 }).catch(() => null) + ]); + + const movieIds = (movieData?.results || []).map(r => r.id); + const tvIds = (tvData?.results || []).map(r => r.id); + return [...new Set([...movieIds, ...tvIds])]; + } catch (error) { + console.error('TMDB search error:', error.message); + return []; + } +} + +function createWishboardRouter(mysqlPool, redis) { + const router = express.Router(); + + // Middleware to verify JWT token with MySQL session validation + const requireAuth = async (req, res, next) => { + const token = req.headers.authorization?.split(' ')[1]; + if (!token) { + return res.status(401).json({ error: 'Non authentifié' }); + } + + try { + const decoded = jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] }); + const { sub: userId, userType, sessionId } = decoded; + + if (!['oauth', 'bip39'].includes(userType) || !userId || !sessionId) { + return res.status(401).json({ error: 'Token invalide' }); + } + + // Vérifier que la session existe en MySQL + if (!mysqlPool) { + return res.status(503).json({ error: 'Service temporairement indisponible' }); + } + + const [rows] = await mysqlPool.execute( + 'SELECT id FROM user_sessions WHERE id = ? AND user_id = ? AND user_type = ?', + [sessionId, userId, userType] + ); + + if (rows.length === 0) { + return res.status(401).json({ error: 'Session invalide ou expirée' }); + } + + req.user = { + userId: userId, + userType: userType, + sessionId: sessionId + }; + next(); + } catch (error) { + return res.status(401).json({ error: 'Token invalide' }); + } + }; + + // Middleware to check admin or uploader status (same pattern as server.js isUploaderOrAdmin) + const requireUploaderOrAdmin = async (req, res, next) => { + try { + if (!mysqlPool) { + return res.status(503).json({ error: 'Service temporairement indisponible' }); + } + + const authType = req.user.userType === 'bip39' ? 'bip-39' : req.user.userType; + const [rows] = await mysqlPool.execute( + 'SELECT * FROM admins WHERE user_id = ? AND auth_type = ?', + [req.user.userId, authType] + ); + + if (rows.length === 0) { + return res.status(403).json({ error: 'Accès refusé - Droits requis' }); + } + + // Récupérer le rôle (par défaut 'admin' si non défini) + const role = rows[0].role || 'admin'; + + // Autoriser les rôles 'admin' et 'uploader' + if (role !== 'admin' && role !== 'uploader') { + return res.status(403).json({ error: 'Accès refusé - Droits insuffisants' }); + } + + req.admin = { userId: req.user.userId, userType: req.user.userType, role }; + next(); + } catch (error) { + console.error('Admin/Uploader check error:', error); + return res.status(500).json({ error: 'Erreur lors de la vérification des droits' }); + } + }; + + // Helper to get user data from JSON files (adapted from commentsRoutes.js) + async function getUserData(userId, userType, profileId = null) { + try { + let userData = { username: 'Utilisateur', avatar: null, isVip: false, isAdmin: false }; + const safeUserId = String(userId).replace(/[^a-zA-Z0-9_\-]/g, ''); + const safeUserType = ['oauth', 'bip39'].includes(userType) ? userType : 'oauth'; + + let userFilePath; + if (userType === 'bip39') { + userFilePath = path.join(__dirname, 'data', 'users', `bip39-${safeUserId}.json`); + } else { + userFilePath = path.join(__dirname, 'data', 'users', `${safeUserId}.json`); + } + + try { + const userFile = await fs.readFile(userFilePath, 'utf8'); + const user = JSON.parse(userFile); + + if (user.profiles && user.profiles.length > 0) { + let profile; + if (profileId) { + profile = user.profiles.find(p => p.id === profileId); + } + if (!profile) { + profile = user.profiles[0]; + } + if (profile) { + userData.username = profile.name || 'Utilisateur'; + userData.avatar = profile.avatar; + } + } + } catch (err) { + console.error('Error reading user file:', err.message); + } + + // Vérifier le statut VIP en lisant l'access_code depuis les données du profil + if (profileId && safeUserId) { + try { + const safeProfileId = String(profileId).replace(/[^a-zA-Z0-9_\-]/g, ''); + const profileDataPath = path.join(__dirname, 'data', 'users', 'profiles', safeUserType, safeUserId, `${safeProfileId}.json`); + const profileData = JSON.parse(await fs.readFile(profileDataPath, 'utf8')); + const storedAccessCode = profileData.access_code || null; + if (storedAccessCode) { + const vipStatus = await verifyAccessKey(storedAccessCode); + userData.isVip = vipStatus.vip; + } + } catch (err) { + // Pas de données de profil ou pas d'access_code — isVip reste false + } + } + + return userData; + } catch (error) { + console.error('Error getUserData:', error); + return { isVip: false }; + } + } + + // Check request limit helper + const checkLimit = async (userId, userType, profileId, req) => { + // Enforce limits: 1 per 48h for Free, 3 per 48h for VIP + + const [recentRequests] = await mysqlPool.execute( + `SELECT COUNT(*) as count FROM wishboard_requests + WHERE profile_id = ? + AND created_at >= DATE_SUB(NOW(), INTERVAL 48 HOUR)`, + [profileId] + ); + + const count = recentRequests[0].count; + + // Vérifier le statut VIP en lisant l'access_code depuis les données du profil + let isVip = false; + if (profileId && userId) { + try { + const safeUserId = String(userId).replace(/[^a-zA-Z0-9_\-]/g, ''); + const safeUserType = ['oauth', 'bip39'].includes(userType) ? userType : 'oauth'; + const safeProfileId = String(profileId).replace(/[^a-zA-Z0-9_\-]/g, ''); + const profileDataPath = path.join(__dirname, 'data', 'users', 'profiles', safeUserType, safeUserId, `${safeProfileId}.json`); + const profileData = JSON.parse(await fs.readFile(profileDataPath, 'utf8')); + const storedAccessCode = profileData.access_code || null; + if (storedAccessCode) { + const vipStatus = await verifyAccessKey(storedAccessCode); + isVip = vipStatus.vip; + } + } catch (err) { + // Pas de données de profil — isVip reste false + } + } + + const limit = isVip ? 3 : 1; + const remaining = Math.max(0, limit - count); + + return { count, limit, remaining, isVip }; + }; + + // Get profile ID from headers or body + const getProfileId = (req) => { + return req.headers['x-profile-id'] || req.body?.profileId || req.query?.profileId || null; + }; + + // Verify that the profileId belongs to the authenticated user + async function verifyProfileOwnership(userId, userType, profileId) { + try { + const safeUserId = String(userId).replace(/[^a-zA-Z0-9_\-]/g, ''); + let userFilePath; + if (userType === 'bip39') { + userFilePath = path.join(__dirname, 'data', 'users', `bip39-${safeUserId}.json`); + } else { + userFilePath = path.join(__dirname, 'data', 'users', `${safeUserId}.json`); + } + const userFile = await fs.readFile(userFilePath, 'utf8'); + const user = JSON.parse(userFile); + if (user.profiles) { + return user.profiles.some(p => p.id === profileId); + } + return false; + } catch { + return false; + } + } + + // Helper to record status change in history + const recordStatusHistory = async (requestId, status, reason = null, adminId = null, adminAuthType = null) => { + try { + const [result] = await mysqlPool.execute( + 'INSERT INTO wishboard_status_history (request_id, status, reason, admin_id, admin_auth_type) VALUES (?, ?, ?, ?, ?)', + [requestId, status, reason, adminId, adminAuthType] + ); + return result.insertId; + } catch (error) { + console.error('Error recording status history:', error); + return null; + } + }; + + // ===================================== + // PUBLIC ENDPOINTS + // ===================================== + + /** + * GET /api/wishboard + * List all requests with filters and pagination + */ + router.get('/', async (req, res) => { + try { + const { page = 1, limit = 20, search, media_type, status, sort = 'votes_desc' } = req.query; + const offset = (parseInt(page) - 1) * parseInt(limit); + const profileId = getProfileId(req); + + let whereConditions = ['1=1']; + let whereParams = []; + + if (search) { + const isNumericSearch = /^\d+$/.test(search.trim()); + if (isNumericSearch) { + // Direct TMDB ID search + whereConditions.push('tmdb_id = ?'); + whereParams.push(parseInt(search)); + } else { + // Text search: query TMDB API to find matching IDs + const tmdbIds = await searchTmdbIds(search.trim()); + if (tmdbIds.length > 0) { + whereConditions.push(`tmdb_id IN (${tmdbIds.map(() => '?').join(',')})`); + whereParams.push(...tmdbIds); + } else { + // No TMDB results found, return empty + return res.json({ requests: [], has_more: false, stats: { total: 0, pending: 0, added_this_month: 0, movies: 0, tv: 0 } }); + } + } + } + + if (media_type && media_type !== 'all') { + whereConditions.push('media_type = ?'); + whereParams.push(media_type); + } + + if (status && status !== 'all') { + whereConditions.push('status = ?'); + whereParams.push(status); + } + + const whereClause = whereConditions.join(' AND '); + + // Determine sort order + let orderBy = 'vote_count DESC'; + switch (sort) { + case 'votes_asc': + orderBy = 'vote_count ASC'; + break; + case 'date_desc': + orderBy = 'created_at DESC'; + break; + case 'date_asc': + orderBy = 'created_at ASC'; + break; + default: + orderBy = 'vote_count DESC'; + } + + // Get requests + const [requests] = await mysqlPool.execute( + `SELECT * FROM wishboard_requests WHERE ${whereClause} ORDER BY ${orderBy} LIMIT ? OFFSET ?`, + [...whereParams, parseInt(limit), offset] + ); + + // Check vote status and get public notes for each request + const requestsWithVotes = await Promise.all(requests.map(async (r) => { + let hasVoted = false; + if (profileId) { + const [voteRows] = await mysqlPool.execute( + 'SELECT id FROM wishboard_votes WHERE request_id = ? AND profile_id = ?', + [r.id, profileId] + ); + hasVoted = voteRows.length > 0; + } + + // Get public notes + const [notes] = await mysqlPool.execute( + 'SELECT id, note, is_public, created_at FROM wishboard_notes WHERE request_id = ? AND is_public = 1 ORDER BY created_at DESC', + [r.id] + ); + + // Get status history + const [statusHistory] = await mysqlPool.execute( + 'SELECT status, reason, changed_at FROM wishboard_status_history WHERE request_id = ? ORDER BY changed_at ASC', + [r.id] + ); + + return { ...r, has_voted: hasVoted, notes, statusHistory }; + })); + + // Get total count + const [countResult] = await mysqlPool.execute( + `SELECT COUNT(*) as total FROM wishboard_requests WHERE ${whereClause}`, + whereParams + ); + + // Get stats + const [statsResult] = await mysqlPool.execute(` + SELECT + COUNT(*) as total, + SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending, + SUM(CASE WHEN status = 'added' AND updated_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 ELSE 0 END) as added_this_month, + SUM(CASE WHEN media_type = 'movie' THEN 1 ELSE 0 END) as movies, + SUM(CASE WHEN media_type = 'tv' THEN 1 ELSE 0 END) as tv + FROM wishboard_requests + `); + + res.json({ + requests: requestsWithVotes, + has_more: countResult[0].total > offset + requests.length, + stats: { + total: statsResult[0].total || 0, + pending: statsResult[0].pending || 0, + added_this_month: statsResult[0].added_this_month || 0, + movies: statsResult[0].movies || 0, + tv: statsResult[0].tv || 0 + } + }); + } catch (error) { + console.error('Error fetching wishboard:', error); + res.status(500).json({ error: 'Failed to fetch wishboard' }); + } + }); + + /** + * POST /api/wishboard + * Create a new content request + */ + router.post('/', requireAuth, async (req, res) => { + try { + const { tmdb_id, media_type, season_number, season_numbers } = req.body; + const userId = req.user.userId; + const profileId = getProfileId(req); + + if (!tmdb_id || !media_type) { + return res.status(400).json({ error: 'tmdb_id and media_type are required' }); + } + + if (!profileId) { + return res.status(400).json({ error: 'Profile ID is required' }); + } + + const isOwner = await verifyProfileOwnership(userId, req.user.userType, profileId); + if (!isOwner) { + return res.status(403).json({ error: 'Ce profil ne vous appartient pas' }); + } + + // Check Limits + const { remaining, limit } = await checkLimit(userId, req.user.userType, profileId, req); + if (remaining <= 0) { + return res.status(429).json({ + error: `Limite atteinte. Vous avez droit à ${limit} demande(s) toutes les 48h.`, + limit_reached: true + }); + } + + // Handle both old single season_number and new season_numbers array + // Database column is INTEGER, so we store a single season number + let seasonParam = null; + if (season_numbers && Array.isArray(season_numbers) && season_numbers.length > 0) { + // If array has one element, store just that number + // If array has multiple elements, store the first one (or 0 for "all seasons") + if (season_numbers.length === 1) { + seasonParam = parseInt(season_numbers[0], 10); + } else { + // Multiple seasons requested - store 0 to indicate "all seasons" or first season + seasonParam = season_numbers.includes(0) ? 0 : parseInt(season_numbers[0], 10); + } + } else if (season_number !== undefined && season_number !== null) { + // Backwards compatibility: single number + seasonParam = parseInt(season_number, 10); + } + + // Check if request already exists (check for exact match) + let existingQuery; + let existingParams; + + if (seasonParam === null) { + existingQuery = 'SELECT id FROM wishboard_requests WHERE tmdb_id = ? AND media_type = ? AND season_number IS NULL'; + existingParams = [tmdb_id, media_type]; + } else { + existingQuery = 'SELECT id FROM wishboard_requests WHERE tmdb_id = ? AND media_type = ? AND season_number = ?'; + existingParams = [tmdb_id, media_type, seasonParam]; + } + + const [existing] = await mysqlPool.execute(existingQuery, existingParams); + + if (existing.length > 0) { + return res.status(409).json({ + error: 'Cette demande existe déjà', + existing_id: existing[0].id + }); + } + + // Insert new request + const [result] = await mysqlPool.execute( + 'INSERT INTO wishboard_requests (user_id, profile_id, tmdb_id, media_type, season_number, status, vote_count) VALUES (?, ?, ?, ?, ?, ?, ?)', + [userId, profileId, tmdb_id, media_type, seasonParam, 'pending', 0] + ); + + const insertId = result.insertId; + + // Record initial status in history + await recordStatusHistory(insertId, 'pending'); + + res.status(201).json({ + id: insertId, + message: 'Demande créée avec succès' + }); + } catch (error) { + console.error('Error creating wishboard request:', error); + res.status(500).json({ error: 'Failed to create request' }); + } + }); + + /** + * POST /api/wishboard/:id/vote + * Vote for a request + */ + router.post('/:id/vote', requireAuth, async (req, res) => { + try { + if (TURNSTILE_INVISIBLE_SECRETKEY) { + const { turnstileToken } = req.body || {}; + const check = await verifyTurnstileFromRequest(req, turnstileToken, TURNSTILE_INVISIBLE_SECRETKEY); + if (!check.valid) { + return res.status(check.status).json({ error: check.error }); + } + } + + const requestId = req.params.id; + const userId = req.user.userId; + const profileId = getProfileId(req); + + if (!profileId) { + return res.status(400).json({ error: 'Profile ID is required' }); + } + + const isOwner = await verifyProfileOwnership(userId, req.user.userType, profileId); + if (!isOwner) { + return res.status(403).json({ error: 'Ce profil ne vous appartient pas' }); + } + + // Check if already voted (dedup by user_id to prevent vote stuffing) + const [existing] = await mysqlPool.execute( + 'SELECT id FROM wishboard_votes WHERE request_id = ? AND user_id = ?', + [requestId, userId] + ); + + if (existing.length > 0) { + return res.status(409).json({ error: 'Vous avez déjà voté pour cette demande' }); + } + + // Add vote + await mysqlPool.execute( + 'INSERT INTO wishboard_votes (request_id, user_id, profile_id) VALUES (?, ?, ?)', + [requestId, userId, profileId] + ); + + res.json({ message: 'Vote enregistré' }); + } catch (error) { + console.error('Error voting:', error); + res.status(500).json({ error: 'Failed to vote' }); + } + }); + + /** + * DELETE /api/wishboard/:id/vote + * Remove vote from a request + */ + router.delete('/:id/vote', requireAuth, async (req, res) => { + try { + if (TURNSTILE_INVISIBLE_SECRETKEY) { + const { turnstileToken } = req.body || {}; + const check = await verifyTurnstileFromRequest(req, turnstileToken, TURNSTILE_INVISIBLE_SECRETKEY); + if (!check.valid) { + return res.status(check.status).json({ error: check.error }); + } + } + + const requestId = req.params.id; + const userId = req.user.userId; + + await mysqlPool.execute( + 'DELETE FROM wishboard_votes WHERE request_id = ? AND user_id = ?', + [requestId, userId] + ); + + res.json({ message: 'Vote retiré' }); + } catch (error) { + console.error('Error removing vote:', error); + res.status(500).json({ error: 'Failed to remove vote' }); + } + }); + + /** + * GET /api/wishboard/user/requests + * Get current user's requests + */ + router.get('/user/requests', requireAuth, async (req, res) => { + try { + const profileId = getProfileId(req); + + if (!profileId) { + return res.status(400).json({ error: 'Profile ID is required' }); + } + + const isOwner = await verifyProfileOwnership(req.user.userId, req.user.userType, profileId); + if (!isOwner) { + return res.status(403).json({ error: 'Ce profil ne vous appartient pas' }); + } + + const [requests] = await mysqlPool.execute( + 'SELECT * FROM wishboard_requests WHERE profile_id = ? ORDER BY created_at DESC', + [profileId] + ); + + // Get public notes and vote status for each request + const requestsWithNotes = await Promise.all(requests.map(async (r) => { + const [notes] = await mysqlPool.execute( + 'SELECT id, note, is_public, created_at FROM wishboard_notes WHERE request_id = ? AND is_public = 1 ORDER BY created_at DESC', + [r.id] + ); + + const [voteRows] = await mysqlPool.execute( + 'SELECT id FROM wishboard_votes WHERE request_id = ? AND profile_id = ?', + [r.id, profileId] + ); + + // Get status history + const [statusHistory] = await mysqlPool.execute( + 'SELECT status, reason, changed_at FROM wishboard_status_history WHERE request_id = ? ORDER BY changed_at ASC', + [r.id] + ); + + return { ...r, notes, has_voted: voteRows.length > 0, statusHistory }; + })); + + res.json({ requests: requestsWithNotes }); + } catch (error) { + console.error('Error fetching user requests:', error); + res.status(500).json({ error: 'Failed to fetch requests' }); + } + }); + + /** + * GET /api/wishboard/user/votes + * Get current user's voted requests + */ + router.get('/user/votes', requireAuth, async (req, res) => { + try { + const profileId = getProfileId(req); + + if (!profileId) { + return res.status(400).json({ error: 'Profile ID is required' }); + } + + const isOwner = await verifyProfileOwnership(req.user.userId, req.user.userType, profileId); + if (!isOwner) { + return res.status(403).json({ error: 'Ce profil ne vous appartient pas' }); + } + + const [requests] = await mysqlPool.execute( + `SELECT r.* FROM wishboard_requests r + INNER JOIN wishboard_votes v ON v.request_id = r.id + WHERE v.profile_id = ? AND r.profile_id != ? + ORDER BY v.created_at DESC`, + [profileId, profileId] + ); + + const requestsWithVoted = await Promise.all(requests.map(async (r) => { + // Get status history + const [statusHistory] = await mysqlPool.execute( + 'SELECT status, reason, changed_at FROM wishboard_status_history WHERE request_id = ? ORDER BY changed_at ASC', + [r.id] + ); + return { ...r, has_voted: true, statusHistory }; + })); + + res.json({ requests: requestsWithVoted }); + } catch (error) { + console.error('Error fetching voted requests:', error); + res.status(500).json({ error: 'Failed to fetch votes' }); + } + }); + + // ===================================== + // LIMITS ENDPOINT + // ===================================== + + /** + * GET /api/wishboard/limits + * Get user's request limit status (quota) + */ + router.get('/limits', requireAuth, async (req, res) => { + try { + const profileId = getProfileId(req); + if (!profileId) { + return res.status(400).json({ error: 'Profile ID is required' }); + } + + const isOwner = await verifyProfileOwnership(req.user.userId, req.user.userType, profileId); + if (!isOwner) { + return res.status(403).json({ error: 'Ce profil ne vous appartient pas' }); + } + + const limitStatus = await checkLimit(req.user.userId, req.user.userType, profileId, req); + res.json(limitStatus); + } catch (error) { + console.error('Error fetching limits:', error); + res.status(500).json({ error: 'Failed to fetch limits' }); + } + }); + + // ===================================== + // ADMIN ENDPOINTS + // ===================================== + + /** + * GET /api/wishboard/admin + * Admin list with all details + */ + router.get('/admin', requireAuth, requireUploaderOrAdmin, async (req, res) => { + try { + const { search, media_type, status, vip_only, page = '1', limit = '50' } = req.query; + const pageNum = Math.max(1, parseInt(page) || 1); + const limitNum = Math.min(100, Math.max(1, parseInt(limit) || 50)); + const offset = (pageNum - 1) * limitNum; + + let whereConditions = ['1=1']; + let whereParams = []; + + if (search) { + const isNumericSearch = /^\d+$/.test(search.trim()); + if (isNumericSearch) { + // Direct TMDB ID or request ID search + const numSearch = parseInt(search); + whereConditions.push('(tmdb_id = ? OR id = ?)'); + whereParams.push(numSearch, numSearch); + } else { + // Text search: query TMDB API to find matching IDs + const tmdbIds = await searchTmdbIds(search.trim()); + if (tmdbIds.length > 0) { + whereConditions.push(`tmdb_id IN (${tmdbIds.map(() => '?').join(',')})`); + whereParams.push(...tmdbIds); + } else { + // No TMDB results, return empty + return res.json({ requests: [], stats: { total: 0, pending: 0, added: 0, rejected: 0, not_found: 0 }, hasMore: false }); + } + } + } + + if (media_type && media_type !== 'all') { + whereConditions.push('media_type = ?'); + whereParams.push(media_type); + } + + if (status && status !== 'all') { + whereConditions.push('status = ?'); + whereParams.push(status); + } + + const whereClause = whereConditions.join(' AND '); + + // Get requests with pagination (fetch one extra to check hasMore) + const [requests] = await mysqlPool.execute( + `SELECT * FROM wishboard_requests WHERE ${whereClause} ORDER BY created_at DESC LIMIT ? OFFSET ?`, + [...whereParams, String(limitNum + 1), String(offset)] + ); + + const hasMore = requests.length > limitNum; + const paginatedRequests = hasMore ? requests.slice(0, limitNum) : requests; + + // Get notes for each request and user info + const requestsWithNotes = await Promise.all(paginatedRequests.map(async (r) => { + const [notes] = await mysqlPool.execute( + 'SELECT id, admin_id, note, is_public, created_at FROM wishboard_notes WHERE request_id = ? ORDER BY created_at DESC', + [r.id] + ); + // Get status history + const [statusHistory] = await mysqlPool.execute( + 'SELECT id, status, reason, changed_at FROM wishboard_status_history WHERE request_id = ? ORDER BY changed_at ASC', + [r.id] + ); + + // Get user info + let user = { username: 'Inconnu', isVip: false }; + try { + // Determine user type (bip39 or oauth) + let userType = 'oauth'; // Default to oauth + try { + await fs.access(path.join(__dirname, 'data', 'users', `bip39-${r.user_id}.json`)); + userType = 'bip39'; + } catch { + // Keep oauth + } + user = await getUserData(r.user_id, userType, r.profile_id); + } catch (e) { + // Ignore error, keep default + } + + return { ...r, notes, statusHistory, user }; + })); + + // Filter VIP-only after fetching user data + const filteredRequests = vip_only === 'true' + ? requestsWithNotes.filter(r => r.user?.isVip) + : requestsWithNotes; + + // Get stats + const [statsResult] = await mysqlPool.execute(` + SELECT + COUNT(*) as total, + SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending, + SUM(CASE WHEN status = 'added' THEN 1 ELSE 0 END) as added, + SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected, + SUM(CASE WHEN status IN ('not_found', 'not_found_recent') THEN 1 ELSE 0 END) as not_found + FROM wishboard_requests + `); + + res.json({ + requests: filteredRequests, + hasMore, + stats: { + total: statsResult[0].total || 0, + pending: statsResult[0].pending || 0, + added: statsResult[0].added || 0, + rejected: statsResult[0].rejected || 0, + not_found: statsResult[0].not_found || 0 + } + }); + } catch (error) { + console.error('Error fetching admin wishboard:', error); + res.status(500).json({ error: 'Failed to fetch admin wishboard' }); + } + }); + + /** + * PUT /api/wishboard/admin/:id/status + * Update request status + */ + router.put('/admin/:id/status', requireAuth, requireUploaderOrAdmin, async (req, res) => { + try { + const requestId = req.params.id; + const { status, reason } = req.body; + + const validStatuses = ['pending', 'not_found', 'not_found_recent', 'searching', 'added', 'rejected']; + if (!validStatuses.includes(status)) { + return res.status(400).json({ error: 'Invalid status' }); + } + + // Get admin info from middleware + const adminId = req.admin ? req.admin.userId : null; + const adminAuthType = req.admin ? (req.admin.userType === 'bip39' ? 'bip-39' : req.admin.userType) : null; + + await mysqlPool.execute( + 'UPDATE wishboard_requests SET status = ?, updated_at = NOW() WHERE id = ?', + [status, requestId] + ); + + // Record status history with reason and admin info + const historyId = await recordStatusHistory(requestId, status, reason, adminId, adminAuthType); + + res.json({ message: 'Statut mis à jour', historyId }); + } catch (error) { + console.error('Error updating status:', error); + res.status(500).json({ error: 'Failed to update status' }); + } + }); + + /** + * PUT /api/wishboard/admin/history/:historyId + * Update status history reason + */ + router.put('/admin/history/:historyId', requireAuth, requireUploaderOrAdmin, async (req, res) => { + try { + const historyId = req.params.historyId; + const { reason } = req.body; + + await mysqlPool.execute( + 'UPDATE wishboard_status_history SET reason = ? WHERE id = ?', + [reason, historyId] + ); + + res.json({ message: 'Raison mise à jour' }); + } catch (error) { + console.error('Error updating history reason:', error); + res.status(500).json({ error: 'Failed to update reason' }); + } + }); + + /** + * POST /api/wishboard/admin/:id/notes + * Add note to request + */ + router.post('/admin/:id/notes', requireAuth, requireUploaderOrAdmin, async (req, res) => { + try { + const requestId = req.params.id; + const { note, is_public = true } = req.body; + const adminId = req.user.userId; + + if (!note || !note.trim()) { + return res.status(400).json({ error: 'Note content is required' }); + } + + // Check if note already exists for this request + const [existing] = await mysqlPool.execute('SELECT id FROM wishboard_notes WHERE request_id = ?', [requestId]); + + let resultId; + if (existing.length > 0) { + // Update existing + await mysqlPool.execute( + 'UPDATE wishboard_notes SET note = ?, is_public = ?, admin_id = ?, updated_at = NOW() WHERE request_id = ?', + [note.trim(), is_public ? 1 : 0, adminId, requestId] + ); + resultId = existing[0].id; + } else { + // Insert new + const [result] = await mysqlPool.execute( + 'INSERT INTO wishboard_notes (request_id, admin_id, note, is_public) VALUES (?, ?, ?, ?)', + [requestId, adminId, note.trim(), is_public ? 1 : 0] + ); + resultId = result.insertId; + } + + res.status(201).json({ + id: resultId, + admin_id: adminId, + note: note.trim(), + is_public: is_public ? 1 : 0, + created_at: new Date().toISOString() + }); + } catch (error) { + console.error('Error adding note:', error); + res.status(500).json({ error: 'Failed to add note' }); + } + }); + + /** + * GET /api/wishboard/admin/leaderboard + * Get monthly leaderboard of admins/uploaders by greenlight count + */ + router.get('/admin/leaderboard', requireAuth, requireUploaderOrAdmin, async (req, res) => { + try { + const monthParam = Array.isArray(req.query.month) ? req.query.month[0] : req.query.month; + const monthMatch = typeof monthParam === 'string' && monthParam.trim() + ? monthParam.trim().match(/^(\d{4})-(\d{2})$/) + : null; + + if (monthParam && (!monthMatch || Number(monthMatch[2]) < 1 || Number(monthMatch[2]) > 12)) { + return res.status(400).json({ error: 'Invalid month format. Expected YYYY-MM' }); + } + + const targetDate = monthMatch + ? new Date(Number(monthMatch[1]), Number(monthMatch[2]) - 1, 1) + : new Date(); + const periodStart = new Date(targetDate.getFullYear(), targetDate.getMonth(), 1); + const periodEnd = new Date(targetDate.getFullYear(), targetDate.getMonth() + 1, 1); + const formatSqlDate = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`; + + // Get all admins/uploaders who have greenlighted at least one request for the selected month + const [rows] = await mysqlPool.execute(` + SELECT + h.admin_id, + h.admin_auth_type, + COUNT(*) as greenlight_count, + MAX(h.changed_at) as last_greenlight_at + FROM wishboard_status_history h + WHERE h.status = 'added' + AND h.admin_id IS NOT NULL + AND h.changed_at >= ? + AND h.changed_at < ? + GROUP BY h.admin_id, h.admin_auth_type + ORDER BY greenlight_count DESC, last_greenlight_at DESC + `, [formatSqlDate(periodStart), formatSqlDate(periodEnd)]); + + // Get admin roles from admins table + const adminIds = rows.map(r => r.admin_id); + let adminRoles = {}; + if (adminIds.length > 0) { + const placeholders = adminIds.map(() => '?').join(','); + const [roleRows] = await mysqlPool.execute( + `SELECT user_id, role FROM admins WHERE user_id IN (${placeholders})`, + adminIds + ); + for (const r of roleRows) { + adminRoles[r.user_id] = r.role || 'admin'; + } + } + + // Resolve user data (username, avatar) for each admin + const leaderboard = await Promise.all(rows.map(async (row) => { + let userData = { username: 'Admin', avatar: null }; + try { + const userType = row.admin_auth_type === 'bip-39' ? 'bip39' : 'oauth'; + const basicData = await getUserData(row.admin_id, userType); + if (basicData.username) userData.username = basicData.username; + if (basicData.avatar) userData.avatar = basicData.avatar; + } catch (err) { + // Keep defaults + } + + return { + admin_id: row.admin_id, + admin_auth_type: row.admin_auth_type, + role: adminRoles[row.admin_id] || 'admin', + username: userData.username, + avatar: userData.avatar, + greenlight_count: row.greenlight_count, + last_greenlight_at: row.last_greenlight_at + }; + })); + + res.json({ + leaderboard, + month: `${periodStart.getFullYear()}-${String(periodStart.getMonth() + 1).padStart(2, '0')}` + }); + } catch (error) { + console.error('Error fetching leaderboard:', error); + res.status(500).json({ error: 'Failed to fetch leaderboard' }); + } + }); + + /** + * DELETE /api/wishboard/admin/:id + * Delete a request + */ + router.delete('/admin/:id', requireAuth, requireUploaderOrAdmin, async (req, res) => { + try { + const requestId = req.params.id; + + // Delete related votes first + await mysqlPool.execute('DELETE FROM wishboard_votes WHERE request_id = ?', [requestId]); + // Delete related notes + await mysqlPool.execute('DELETE FROM wishboard_notes WHERE request_id = ?', [requestId]); + // Delete request + await mysqlPool.execute('DELETE FROM wishboard_requests WHERE id = ?', [requestId]); + + res.json({ message: 'Demande supprimée' }); + } catch (error) { + console.error('Error deleting request:', error); + res.status(500).json({ error: 'Failed to delete request' }); + } + }); + + return router; +} + +module.exports = { createWishboardRouter }; diff --git a/API/Mainapi/wrappedRoutes.js b/API/Mainapi/wrappedRoutes.js new file mode 100644 index 0000000..de9ac7b --- /dev/null +++ b/API/Mainapi/wrappedRoutes.js @@ -0,0 +1,1622 @@ +/** + * Movix Wrapped 2026 - Data Collection Routes + * Collects viewing data and page visits for the annual Wrapped summary + * + * Performance notes: + * - Redis is used for generated-wrapped cache AND TMDB detail cache + * - All independent SQL queries run in Promise.all (parallel) + * - TMDB enrichment uses Redis-backed batch lookup + */ + +const express = require('express'); +const router = express.Router(); +const jwt = require('jsonwebtoken'); +const { fetchTmdbDetails } = require('./utils/tmdbCache'); + +// Lazy import pour éviter les dépendances circulaires au démarrage +let _syncModule = null; +function getSyncModule() { + if (!_syncModule) _syncModule = require('./routes/sync'); + return _syncModule; +} + +// TMDB API Configuration +const TMDB_API_URL = 'https://api.themoviedb.org/3'; + +// Redis key prefixes & TTLs +const WRAPPED_CACHE_PREFIX = 'wrapped:gen:'; // generated wrapped result +const PERCENTILE_CACHE_PREFIX = 'wrapped:pctile:'; // percentile ranking (global, heavy query) +const WRAPPED_CACHE_TTL = 10 * 60; // 10 min (seconds) +const PERCENTILE_CACHE_TTL = 30 * 60; // 30 min (seconds) - global data, doesn't change fast + +// Same secret as server.js +const JWT_SECRET = process.env.JWT_SECRET; + +// Set by server.js via initWrappedRoutes() +let pool = null; +let redis = null; + +/** + * Initialize the router with MySQL pool and Redis client + * @param {object} mysqlPool - MySQL connection pool + * @param {object} redisClient - ioredis instance (optional but recommended) + */ +function initWrappedRoutes(mysqlPool, redisClient) { + pool = mysqlPool; + redis = redisClient || null; +} + +// ─── Helpers: Redis-safe get / set ─────────────────────────────────────────── +function redisReady() { + return redis && redis.status === 'ready'; +} + +async function redisGet(key) { + if (!redisReady()) return null; + try { return await redis.get(key); } catch { return null; } +} + +async function redisSet(key, value, ttlSeconds) { + if (!redisReady()) return; + try { await redis.set(key, value, 'EX', ttlSeconds); } catch { /* ignore */ } +} + +// ─── Rate limiting par profil (Redis-backed) ──────────────────────────────── +const RATE_LIMIT_PREFIX = 'wrapped:rl:'; + +/** + * Crée un middleware de rate limiting par profileId (fallback userId). + * @param {string} endpoint - Nom de l'endpoint (pour la clé Redis) + * @param {number} maxRequests - Nombre max de requêtes dans la fenêtre + * @param {number} windowSeconds - Durée de la fenêtre en secondes + * @param {function} extractId - Fonction (req) => identifiant pour le rate limit + */ +function rateLimitPerProfile(endpoint, maxRequests, windowSeconds, extractId) { + return async (req, res, next) => { + if (!redisReady()) return next(); // pas de Redis = pas de rate limit + + const id = extractId(req); + if (!id) return next(); // pas d'identifiant = skip + + const key = `${RATE_LIMIT_PREFIX}${endpoint}:${id}`; + try { + const current = await redis.incr(key); + if (current === 1) { + await redis.expire(key, windowSeconds); + } + // Headers informatifs + res.set('X-RateLimit-Limit', String(maxRequests)); + res.set('X-RateLimit-Remaining', String(Math.max(0, maxRequests - current))); + + if (current > maxRequests) { + const ttl = await redis.ttl(key); + res.set('Retry-After', String(ttl > 0 ? ttl : windowSeconds)); + return res.status(429).json({ + success: false, + error: 'Trop de requêtes. Réessaie dans quelques instants.' + }); + } + next(); + } catch { + next(); // en cas d'erreur Redis, on laisse passer + } + }; +} + +// /track : le frontend envoie ~2 req/30s en usage normal, avec les changements +// de visibilité/contenu/épisode ça peut monter. 30 req/min est très confortable. +const trackRateLimit = rateLimitPerProfile('track', 30, 60, (req) => { + return req.body?.profileId || req.user?.sub; +}); + +// /generate : requête lourde (SQL + TMDB). 6 req/min suffit largement +// (un refresh + quelques changements d'année). +const generateRateLimit = rateLimitPerProfile('generate', 6, 60, (req) => { + return req.headers['x-profile-id'] || req.query.profileId || req.user?.sub; +}); + +// ─── TMDB helpers (via tmdbCache centralisé) ──────────────────────────────── + +/** + * Extrait les champs nécessaires à Wrapped depuis une réponse TMDB complète. + */ +function extractWrappedFields(data) { + if (!data) return null; + return { + title: data.title || data.name, + poster_path: data.poster_path, + genres: (data.genres || []).map(g => typeof g === 'string' ? g : g.name), + vote_average: data.vote_average || null, + runtime: data.runtime || data.episode_run_time?.[0] || null + }; +} + +/** + * Fetch details from TMDB (via tmdbCache Redis centralisé) + */ +async function fetchTMDBDetails(contentId, contentType) { + // Skip live-tv as it's not from TMDB + if (contentType === 'live-tv') { + return { title: `Live TV #${contentId}`, poster_path: null, genres: [] }; + } + + const mediaType = contentType === 'anime' ? 'tv' : contentType; + const data = await fetchTmdbDetails(TMDB_API_URL, process.env.TMDB_API_KEY, contentId, mediaType, 'fr-FR'); + return extractWrappedFields(data); +} + +/** + * Enrich content array with TMDB data (parallel, Redis-cached) + */ +async function enrichWithTMDBData(contents) { + return Promise.all(contents.map(async (content) => { + if (content.content_title && content.poster_path) { + return content; // Already has data + } + const details = await fetchTMDBDetails(content.content_id, content.content_type); + return { + ...content, + content_title: details?.title || content.content_title || `${content.content_type} #${content.content_id}`, + poster_path: details?.poster_path || content.poster_path || null, + genres: details?.genres || [], + vote_average: details?.vote_average || null + }; + })); +} + +/** + * Middleware to verify JWT token + */ +const verifyToken = (req, res, next) => { + const authHeader = req.headers['authorization']; + const token = authHeader && authHeader.split(' ')[1]; + + if (!token) { + // If no token, check if we can proceed without it (e.g. for simple tracking?) + // But user asked for verification "like other routes", so we enforce it. + // However, wrapped tracker might not have header set if useWrappedTracker uses standard fetch without setting headers. + // Let's check useWrappedTracker.ts... It uses fetch without custom headers? + // Wait, I need to check useWrappedTracker.ts. + // If useWrappedTracker doesn't send Authorization header, this will break tracking. + return res.status(401).json({ success: false, error: 'Access denied. No token provided.' }); + } + + try { + const decoded = jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] }); + req.user = decoded; + next(); + } catch (error) { + return res.status(403).json({ success: false, error: 'Invalid token.' }); + } +}; + +/** + * Create required tables if they don't exist + */ +async function initTables() { + if (!pool) { + console.error('[Wrapped] Cannot init tables - no database pool'); + return; + } + + try { + // Create wrapped_viewing_data table + await pool.execute(` + CREATE TABLE IF NOT EXISTS wrapped_viewing_data ( + id INT AUTO_INCREMENT PRIMARY KEY, + user_id VARCHAR(255) NOT NULL, + profile_id VARCHAR(255), + content_type ENUM('movie', 'tv', 'anime', 'live-tv') NOT NULL, + content_id VARCHAR(255) NOT NULL, + content_title VARCHAR(255), + season_number INT DEFAULT NULL, + episode_number INT DEFAULT NULL, + watch_duration INT NOT NULL DEFAULT 0, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + hour_of_day TINYINT DEFAULT NULL, + month INT NOT NULL, + year INT NOT NULL, + INDEX idx_user_year (user_id, year), + INDEX idx_content (content_type, content_id), + INDEX idx_hour (user_id, year, hour_of_day) + ) + `); + + // Create wrapped_pages_data table + await pool.execute(` + CREATE TABLE IF NOT EXISTS wrapped_pages_data ( + id INT AUTO_INCREMENT PRIMARY KEY, + user_id VARCHAR(255) NOT NULL, + profile_id VARCHAR(255), + page_name VARCHAR(100) NOT NULL, + duration INT DEFAULT 0, + meta_data JSON, + month INT NOT NULL, + year INT NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + INDEX idx_page_stats (user_id, page_name, year) + ) + `); + + // Migration: add hour_of_day column if it doesn't exist (for tables created before this column was added) + try { + await pool.execute(` + ALTER TABLE wrapped_viewing_data ADD COLUMN hour_of_day TINYINT DEFAULT NULL AFTER created_at + `); + console.log('[Wrapped] Migration: added hour_of_day column'); + } catch (alterErr) { + // ER_DUP_FIELDNAME (1060) means column already exists — that's fine + if (alterErr.errno !== 1060) { + console.warn('[Wrapped] Migration warning (hour_of_day):', alterErr.message); + } + } + + // Migration: add idx_hour index if it doesn't exist + try { + await pool.execute(` + CREATE INDEX idx_hour ON wrapped_viewing_data (user_id, year, hour_of_day) + `); + console.log('[Wrapped] Migration: added idx_hour index'); + } catch (indexErr) { + // ER_DUP_KEYNAME (1061) means index already exists — that's fine + if (indexErr.errno !== 1061) { + console.warn('[Wrapped] Migration warning (idx_hour):', indexErr.message); + } + } + + // Migration: add composite index for the track upsert SELECT (covers all lookup columns) + try { + await pool.execute(` + CREATE INDEX idx_viewing_lookup ON wrapped_viewing_data + (user_id, profile_id, content_type, content_id, month, year, hour_of_day) + `); + console.log('[Wrapped] Migration: added idx_viewing_lookup index'); + } catch (indexErr) { + if (indexErr.errno !== 1061) { + console.warn('[Wrapped] Migration warning (idx_viewing_lookup):', indexErr.message); + } + } + + // Migration: add composite index for page data upsert SELECT + try { + await pool.execute(` + CREATE INDEX idx_page_lookup ON wrapped_pages_data + (user_id, profile_id, page_name, month, year) + `); + console.log('[Wrapped] Migration: added idx_page_lookup index'); + } catch (indexErr) { + if (indexErr.errno !== 1061) { + console.warn('[Wrapped] Migration warning (idx_page_lookup):', indexErr.message); + } + } + + // Migration: index on (year) alone for the global percentile query + try { + await pool.execute(`CREATE INDEX idx_year ON wrapped_viewing_data (year)`); + console.log('[Wrapped] Migration: added idx_year index'); + } catch (indexErr) { + if (indexErr.errno !== 1061) { + console.warn('[Wrapped] Migration warning (idx_year):', indexErr.message); + } + } + + // Migration: covering index for generate queries (user_id, year, watch_duration, content_id, content_type) + try { + await pool.execute(` + CREATE INDEX idx_generate_cover ON wrapped_viewing_data + (user_id, year, profile_id, content_type, content_id, watch_duration) + `); + console.log('[Wrapped] Migration: added idx_generate_cover index'); + } catch (indexErr) { + if (indexErr.errno !== 1061) { + console.warn('[Wrapped] Migration warning (idx_generate_cover):', indexErr.message); + } + } + + // Migration: index for first/last watch ORDER BY created_at + try { + await pool.execute(` + CREATE INDEX idx_user_year_created ON wrapped_viewing_data (user_id, year, created_at) + `); + console.log('[Wrapped] Migration: added idx_user_year_created index'); + } catch (indexErr) { + if (indexErr.errno !== 1061) { + console.warn('[Wrapped] Migration warning (idx_user_year_created):', indexErr.message); + } + } + + // Migration: index for pages generate (user_id, year, page_name, duration) + try { + await pool.execute(` + CREATE INDEX idx_page_generate ON wrapped_pages_data (user_id, year, profile_id, page_name, duration) + `); + console.log('[Wrapped] Migration: added idx_page_generate index'); + } catch (indexErr) { + if (indexErr.errno !== 1061) { + console.warn('[Wrapped] Migration warning (idx_page_generate):', indexErr.message); + } + } + + // Migration: covering index for the global percentile GROUP BY query + // Allows MySQL to compute SUM(watch_duration) GROUP BY user_id entirely from the index + try { + await pool.execute(` + CREATE INDEX idx_percentile_cover ON wrapped_viewing_data (year, user_id, watch_duration) + `); + console.log('[Wrapped] Migration: added idx_percentile_cover index'); + } catch (indexErr) { + if (indexErr.errno !== 1061) { + console.warn('[Wrapped] Migration warning (idx_percentile_cover):', indexErr.message); + } + } + + console.log('[Wrapped] Tables initialized successfully'); + } catch (error) { + console.error('[Wrapped] Error initializing tables:', error); + } +} + +/** + * POST /api/wrapped/track + * Batch endpoint to receive viewing/page data + */ +router.post('/track', verifyToken, trackRateLimit, async (req, res) => { + try { + if (!pool) { + return res.status(503).json({ success: false, error: 'Database not available' }); + } + + const { + userId, + profileId, + type, + month, + year, + duration, + // Viewing-specific fields + contentType, + contentId, + contentTitle, + seasonNumber, + episodeNumber, + hourOfDay, + // Page-specific fields + pageName, + meta, + } = req.body; + + // Security: userId du body doit correspondre au JWT + if (!req.user || !req.user.sub) { + return res.status(401).json({ success: false, error: 'Token invalide' }); + } + if (userId !== req.user.sub) { + console.warn(`[Wrapped] User ID mismatch blocked: Body ${userId} vs Token ${req.user.sub}`); + return res.status(403).json({ success: false, error: 'User ID mismatch' }); + } + + // Security: vérifier que le profileId appartient bien à cet utilisateur + if (profileId) { + try { + const userType = req.user.userType || 'oauth'; + const { readUserData } = getSyncModule(); + const userData = await readUserData(userType, req.user.sub); + const profiles = userData?.profiles || []; + if (!profiles.some(p => p.id === profileId)) { + console.warn(`[Wrapped] Profile ownership denied: ${profileId} not owned by ${req.user.sub}`); + return res.status(403).json({ success: false, error: 'Profile does not belong to this user' }); + } + } catch (err) { + console.error(`[Wrapped] Error checking profile ownership:`, err.message); + return res.status(500).json({ success: false, error: 'Could not verify profile ownership' }); + } + } + + // Validate required fields + if (!userId || !type || !month || !year || duration === undefined) { + return res.status(400).json({ + success: false, + error: 'Missing required fields: userId, type, month, year, duration' + }); + } + + // Validate numeric ranges to prevent data pollution + const parsedMonth = parseInt(month); + const parsedYear = parseInt(year); + const parsedDuration = parseInt(duration); + const currentYear = new Date().getFullYear(); + + if (isNaN(parsedMonth) || parsedMonth < 1 || parsedMonth > 12) { + return res.status(400).json({ success: false, error: 'Invalid month (1-12)' }); + } + if (isNaN(parsedYear) || parsedYear < 2024 || parsedYear > currentYear) { + return res.status(400).json({ success: false, error: `Invalid year (2024-${currentYear})` }); + } + if (isNaN(parsedDuration) || parsedDuration < 0 || parsedDuration > 60) { + return res.status(400).json({ success: false, error: 'Invalid duration (0-60 seconds)' }); + } + if (!['viewing', 'page'].includes(type)) { + return res.status(400).json({ success: false, error: 'Invalid type. Must be "viewing" or "page"' }); + } + + if (type === 'viewing') { + // Validate viewing-specific fields + if (!contentType || !contentId) { + return res.status(400).json({ + success: false, + error: 'Missing required fields for viewing: contentType, contentId' + }); + } + + // Resolve hour: prefer client-sent hourOfDay, fallback to server hour + const resolvedHour = hourOfDay !== undefined && hourOfDay !== null ? parseInt(hourOfDay) : new Date().getHours(); + + // Try to update existing record for the same content in the same month AND same hour + // Splitting by hour ensures accurate listening clock data + const [existingRows] = await pool.execute( + `SELECT id, watch_duration FROM wrapped_viewing_data + WHERE user_id = ? AND profile_id <=> ? AND content_type = ? AND content_id = ? + AND month = ? AND year = ? AND hour_of_day <=> ? + AND season_number <=> ? AND episode_number <=> ? + LIMIT 1`, + [userId, profileId || null, contentType, contentId, month, year, + resolvedHour, seasonNumber || null, episodeNumber || null] + ); + + if (existingRows.length > 0) { + // Update existing record + const newDuration = existingRows[0].watch_duration + Math.floor(duration); + await pool.execute( + `UPDATE wrapped_viewing_data SET watch_duration = ? WHERE id = ?`, + [newDuration, existingRows[0].id] + ); + } else { + // Insert new record + await pool.execute( + `INSERT INTO wrapped_viewing_data + (user_id, profile_id, content_type, content_id, content_title, season_number, episode_number, watch_duration, hour_of_day, month, year) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + [userId, profileId || null, contentType, contentId, contentTitle || null, + seasonNumber || null, episodeNumber || null, Math.floor(duration), + resolvedHour, month, year] + ); + } + } else if (type === 'page') { + // Validate page-specific fields + if (!pageName) { + return res.status(400).json({ + success: false, + error: 'Missing required field for page: pageName' + }); + } + + // Try to update existing record for the same page in the same month + const [existingRows] = await pool.execute( + `SELECT id, duration FROM wrapped_pages_data + WHERE user_id = ? AND profile_id <=> ? AND page_name = ? AND month = ? AND year = ? + LIMIT 1`, + [userId, profileId || null, pageName, month, year] + ); + + if (existingRows.length > 0) { + // Update existing record + const newDuration = existingRows[0].duration + Math.floor(duration); + await pool.execute( + `UPDATE wrapped_pages_data SET duration = ? WHERE id = ?`, + [newDuration, existingRows[0].id] + ); + } else { + // Insert new record + await pool.execute( + `INSERT INTO wrapped_pages_data + (user_id, profile_id, page_name, duration, meta_data, month, year) + VALUES (?, ?, ?, ?, ?, ?, ?)`, + [userId, profileId || null, pageName, Math.floor(duration), + meta ? JSON.stringify(meta) : null, month, year] + ); + } + } else { + return res.status(400).json({ + success: false, + error: 'Invalid type. Must be "viewing" or "page"' + }); + } + + res.json({ success: true }); + } catch (error) { + console.error('[Wrapped] Error tracking data:', error); + res.status(500).json({ success: false, error: 'Internal server error' }); + } +}); + +/** + * Generate Wrapped summary using templates (like Spotify - no AI) + * Header 'x-profile-id': Optional profile ID to filter stats + * + * PERFORMANCE: All independent SQL queries run in Promise.all, + * TMDB results are cached in Redis (24 h), generated wrapped in Redis (10 min). + */ +router.get('/generate/:year', verifyToken, generateRateLimit, async (req, res) => { + const _t = { start: Date.now() }; + const { year } = req.params; + const userId = req.user.sub; + const profileId = req.headers['x-profile-id'] || req.query.profileId; + + console.log(`[Wrapped][PERF] ── Generate ${year} for user=${userId} profile=${profileId || 'all'} ──`); + + // Validate year parameter + const parsedYear = parseInt(year); + if (isNaN(parsedYear) || parsedYear < 2024 || parsedYear > new Date().getFullYear()) { + return res.status(400).json({ success: false, error: 'Invalid year' }); + } + + if (!pool) { + return res.status(500).json({ success: false, error: 'Database not initialized' }); + } + + // ── 0. Redis cache check (skip if ?fresh=1) ──────────────────────────────── + const cacheKey = `${WRAPPED_CACHE_PREFIX}${userId}-${profileId || 'all'}-${year}`; + if (!req.query.fresh) { + const cached = await redisGet(cacheKey); + if (cached) { + try { + console.log(`[Wrapped][PERF] ⚡ Redis cache HIT — total ${Date.now() - _t.start}ms`); + return res.json(JSON.parse(cached)); + } catch { /* regenerate */ } + } + console.log(`[Wrapped][PERF] Redis cache MISS (${Date.now() - _t.start}ms)`); + } else { + console.log(`[Wrapped][PERF] Cache skipped (?fresh=1)`); + } + + try { + // Base query conditions + let whereClause = 'WHERE user_id = ? AND year = ?'; + let queryParams = [userId, year]; + if (profileId) { + whereClause += ' AND profile_id = ?'; + queryParams.push(profileId); + } + + // ── Helper: timed query ──────────────────────────────────────────────── + const _sqlTimings = {}; + async function timedQuery(label, queryFn) { + const t0 = Date.now(); + const result = await queryFn(); + _sqlTimings[label] = Date.now() - t0; + return result; + } + + // ── Helper: fetch percentile (Redis cache or SQL fallback) ────────────── + async function fetchPercentile() { + const pctCacheKey = `${PERCENTILE_CACHE_PREFIX}${year}`; + const cachedPct = await redisGet(pctCacheKey); + if (cachedPct) { + try { + const rankings = JSON.parse(cachedPct); + const totalUsers = rankings.length; + const userRank = rankings.findIndex(u => u.user_id === userId) + 1; + const pct = totalUsers > 1 ? Math.round(((totalUsers - userRank) / totalUsers) * 100) : 99; + _sqlTimings['percentile'] = 0; + console.log(`[Wrapped][PERF] 📊 Percentile: Redis HIT — rank ${userRank}/${totalUsers} = top ${100 - pct}%`); + return pct; + } catch { /* fallback to SQL */ } + } + // Expensive SQL — runs once per 30 min then cached for all users/workers + const pctT0 = Date.now(); + const [allUsersStats] = await pool.execute(` + SELECT user_id, ROUND(SUM(watch_duration) / 60) as total + FROM wrapped_viewing_data WHERE year = ? + GROUP BY user_id ORDER BY total DESC + `, [year]); + _sqlTimings['percentile'] = Date.now() - pctT0; + console.log(`[Wrapped][PERF] 📊 Percentile: SQL in ${_sqlTimings['percentile']}ms (${allUsersStats.length} users)`); + redisSet(pctCacheKey, JSON.stringify(allUsersStats), PERCENTILE_CACHE_TTL); + const totalUsers = allUsersStats.length; + const userRank = allUsersStats.findIndex(u => u.user_id === userId) + 1; + return totalUsers > 1 ? Math.round(((totalUsers - userRank) / totalUsers) * 100) : 99; + } + + // ── 1. Fire ALL queries in parallel (user-scoped + percentile) ────────── + _t.sqlStart = Date.now(); + const [ + [viewingStats], + [typeStats], + [topContentAll], + [monthlyStats], + [topPages], + [hourlyStats], + [dailyActivity], + [firstWatch], + [lastWatch], + percentile + ] = await Promise.all([ + // 1. Viewing Stats + timedQuery('viewingStats', () => pool.execute(` + SELECT + ROUND(SUM(watch_duration) / 60) as total_duration, + COUNT(DISTINCT content_id) as unique_titles, + COUNT(*) as total_sessions + FROM wrapped_viewing_data ${whereClause} + `, queryParams)), + + // 2. Distribution by Type + timedQuery('typeStats', () => pool.execute(` + SELECT content_type, ROUND(SUM(watch_duration) / 60) as duration, COUNT(DISTINCT content_id) as count + FROM wrapped_viewing_data ${whereClause} + GROUP BY content_type ORDER BY duration DESC + `, queryParams)), + + // 3. Top Content (Top 10 — replaces old top5 + top10-genres queries) + timedQuery('topContent', () => pool.execute(` + SELECT content_title, content_id, content_type, ROUND(SUM(watch_duration) / 60) as duration + FROM wrapped_viewing_data ${whereClause} + GROUP BY content_title, content_id, content_type + ORDER BY duration DESC LIMIT 10 + `, queryParams)), + + // 4. Monthly breakdown + timedQuery('monthlyStats', () => pool.execute(` + SELECT month, ROUND(SUM(watch_duration) / 60) as duration + FROM wrapped_viewing_data ${whereClause} + GROUP BY month ORDER BY duration DESC + `, queryParams)), + + // 5. Top Pages + timedQuery('topPages', () => pool.execute(` + SELECT page_name, ROUND(SUM(duration) / 60) as duration + FROM wrapped_pages_data ${whereClause} + GROUP BY page_name ORDER BY duration DESC LIMIT 5 + `, queryParams)), + + // 6. Time-of-day distribution + timedQuery('hourlyStats', () => pool.execute(` + SELECT hour_of_day, ROUND(SUM(watch_duration) / 60) as duration, COUNT(*) as sessions + FROM wrapped_viewing_data ${whereClause} + AND hour_of_day IS NOT NULL + GROUP BY hour_of_day ORDER BY hour_of_day + `, queryParams)), + + // 7. Watching streaks (consecutive days) + timedQuery('dailyActivity', () => pool.execute(` + SELECT DISTINCT DATE(created_at) as watch_date + FROM wrapped_viewing_data ${whereClause} + ORDER BY watch_date + `, queryParams)), + + // 8a. First watch of the year + timedQuery('firstWatch', () => pool.execute(` + SELECT content_title, content_type, content_id, created_at + FROM wrapped_viewing_data ${whereClause} + ORDER BY created_at ASC LIMIT 1 + `, queryParams)), + + // 8b. Last watch of the year + timedQuery('lastWatch', () => pool.execute(` + SELECT content_title, content_type, content_id, created_at + FROM wrapped_viewing_data ${whereClause} + ORDER BY created_at DESC LIMIT 1 + `, queryParams)), + + // 10. Percentile (Redis-cached 30min, SQL fallback) + fetchPercentile() + ]); + + // Derive top5 and top10-for-genres from the single top10 result + const topContent = topContentAll.slice(0, 5); + const topContentForGenres = topContentAll; // all 10 + + _t.sqlEnd = Date.now(); + const timingsStr = Object.entries(_sqlTimings).map(([k, v]) => `${k}=${v}ms`).join(' | '); + console.log(`[Wrapped][PERF] 🗄️ SQL+Percentile (10 parallel): ${_t.sqlEnd - _t.sqlStart}ms — ${timingsStr}`); + + const totalMinutes = parseInt(viewingStats[0].total_duration) || 0; + const uniqueTitles = parseInt(viewingStats[0].unique_titles) || 0; + + if (totalMinutes === 0 && uniqueTitles === 0) { + console.log(`[Wrapped][PERF] No data — total ${Date.now() - _t.start}ms`); + return res.json({ success: true, wrapped: null, message: "Pas encore de données pour cette année." }); + } + + // ── 2. TMDB enrichment (parallel, Redis-cached) ──────────────────────── + _t.tmdbStart = Date.now(); + + // Deduplicate: merge top5 + top10-genres + first/last into a single unique set + const allContentToEnrich = new Map(); // key: "type:id" -> content row + [...topContent, ...topContentForGenres].forEach(c => { + const k = `${c.content_type}:${c.content_id}`; + if (!allContentToEnrich.has(k)) allContentToEnrich.set(k, c); + }); + const firstWatchData = firstWatch[0] || null; + const lastWatchData = lastWatch[0] || null; + if (firstWatchData && !firstWatchData.content_title) { + const k = `${firstWatchData.content_type}:${firstWatchData.content_id}`; + if (!allContentToEnrich.has(k)) allContentToEnrich.set(k, firstWatchData); + } + if (lastWatchData && !lastWatchData.content_title) { + const k = `${lastWatchData.content_type}:${lastWatchData.content_id}`; + if (!allContentToEnrich.has(k)) allContentToEnrich.set(k, lastWatchData); + } + + console.log(`[Wrapped][PERF] 🎯 TMDB: ${allContentToEnrich.size} unique items to enrich (deduped from ${topContent.length + topContentForGenres.length + (firstWatchData ? 1 : 0) + (lastWatchData ? 1 : 0)})`); + + // ── Batch TMDB: single MGET for all Redis cache keys, then API-fetch misses ── + const tmdbCache = new Map(); // key -> details + const itemsNeedingFetch = []; // [{key, content}] — items not already complete + + // Separate already-complete items from those needing TMDB lookup + for (const [key, content] of allContentToEnrich) { + if (content.content_title && content.poster_path) { + tmdbCache.set(key, { title: content.content_title, poster_path: content.poster_path, genres: content.genres || [], vote_average: content.vote_average || null }); + } else { + itemsNeedingFetch.push({ key, content }); + } + } + + if (itemsNeedingFetch.length > 0 && redisReady()) { + // Build Redis keys for MGET (même pattern que tmdbCache.js) + const redisKeys = itemsNeedingFetch.map(({ content }) => { + const mediaType = content.content_type === 'anime' ? 'tv' : content.content_type; + return `tmdb:details:${mediaType}:${content.content_id}:fr-FR`; + }); + + try { + const tMget = Date.now(); + const mgetResults = await redis.mget(...redisKeys); + console.log(`[Wrapped][TMDB] ⚡ MGET ${redisKeys.length} keys in ${Date.now() - tMget}ms`); + + const apiMisses = []; // items not found in Redis + for (let i = 0; i < itemsNeedingFetch.length; i++) { + const { key, content } = itemsNeedingFetch[i]; + if (mgetResults[i]) { + try { + tmdbCache.set(key, extractWrappedFields(JSON.parse(mgetResults[i]))); + continue; + } catch { /* treat as miss */ } + } + apiMisses.push({ key, content }); + } + + // Fetch remaining misses from TMDB API in parallel + if (apiMisses.length > 0) { + console.log(`[Wrapped][TMDB] 🌐 Fetching ${apiMisses.length} items from API (${apiMisses.length} Redis misses)`); + await Promise.all(apiMisses.map(async ({ key, content }) => { + const details = await fetchTMDBDetails(content.content_id, content.content_type); + if (details) tmdbCache.set(key, details); + })); + } + } catch (mgetErr) { + // Fallback: parallel individual fetches + console.warn('[Wrapped][TMDB] MGET failed, falling back to individual fetches:', mgetErr.message); + await Promise.all(itemsNeedingFetch.map(async ({ key, content }) => { + const details = await fetchTMDBDetails(content.content_id, content.content_type); + if (details) tmdbCache.set(key, details); + })); + } + } else if (itemsNeedingFetch.length > 0) { + // No Redis: parallel individual fetches + await Promise.all(itemsNeedingFetch.map(async ({ key, content }) => { + const details = await fetchTMDBDetails(content.content_id, content.content_type); + if (details) tmdbCache.set(key, details); + })); + } + + _t.tmdbEnd = Date.now(); + console.log(`[Wrapped][PERF] 🎬 TMDB enrichment: ${_t.tmdbEnd - _t.tmdbStart}ms (${tmdbCache.size} resolved)`); + + // Apply TMDB data back to arrays using the cache + function applyTMDB(arr) { + return arr.map(c => { + const k = `${c.content_type}:${c.content_id}`; + const d = tmdbCache.get(k); + if (!d) return { ...c, content_title: c.content_title || `${c.content_type} #${c.content_id}`, poster_path: c.poster_path || null, genres: [], vote_average: null }; + return { ...c, content_title: d.title || c.content_title, poster_path: d.poster_path || c.poster_path || null, genres: d.genres || [], vote_average: d.vote_average || null }; + }); + } + const enrichedTopContent = applyTMDB(topContent); + const enrichedForGenres = applyTMDB(topContentForGenres); + + // Apply to first/last watch + if (firstWatchData && !firstWatchData.content_title) { + const d = tmdbCache.get(`${firstWatchData.content_type}:${firstWatchData.content_id}`); + if (d) firstWatchData.content_title = d.title; + } + if (lastWatchData && !lastWatchData.content_title) { + const d = tmdbCache.get(`${lastWatchData.content_type}:${lastWatchData.content_id}`); + if (d) lastWatchData.content_title = d.title; + } + + // ── 3. Compute derived stats (pure JS, no I/O) ───────────────────────── + _t.computeStart = Date.now(); + + // Listening clock: peak hour + const hourlyMap = new Array(24).fill(0); + hourlyStats.forEach(h => { hourlyMap[h.hour_of_day] = parseInt(h.duration); }); + const peakHour = hourlyMap.indexOf(Math.max(...hourlyMap)); + const nightOwlMinutes = hourlyMap.slice(22, 24).reduce((a, b) => a + b, 0) + hourlyMap.slice(0, 5).reduce((a, b) => a + b, 0); + const earlyBirdMinutes = hourlyMap.slice(5, 10).reduce((a, b) => a + b, 0); + const isNightOwl = nightOwlMinutes > totalMinutes * 0.3; + const isEarlyBird = earlyBirdMinutes > totalMinutes * 0.3; + + // Watching streaks + let longestStreak = 0, currentStreak = 0; + const totalActiveDays = dailyActivity.length; + for (let i = 0; i < dailyActivity.length; i++) { + if (i === 0) { currentStreak = 1; } + else { + const prev = new Date(dailyActivity[i - 1].watch_date); + const curr = new Date(dailyActivity[i].watch_date); + const diffDays = Math.round((curr - prev) / (1000 * 60 * 60 * 24)); + currentStreak = diffDays === 1 ? currentStreak + 1 : 1; + } + longestStreak = Math.max(longestStreak, currentStreak); + } + + // Genre analysis + const genreMinutes = {}; + enrichedForGenres.forEach(item => { + const mins = parseInt(item.duration); + (item.genres || []).forEach(genre => { + genreMinutes[genre] = (genreMinutes[genre] || 0) + mins; + }); + }); + const topGenres = Object.entries(genreMinutes) + .sort((a, b) => b[1] - a[1]) + .slice(0, 5) + .map(([name, minutes]) => ({ name, minutes, percent: Math.round((minutes / totalMinutes) * 100) })); + + // Monthly graph (all 12 months) + const monthMap = {}; + monthlyStats.forEach(m => { monthMap[m.month] = parseInt(m.duration); }); + const monthlyGraph = Array.from({ length: 12 }, (_, i) => ({ month: i + 1, minutes: monthMap[i + 1] || 0 })); + + // Session stats + const totalSessions = parseInt(viewingStats[0].total_sessions) || 1; + const avgSessionMinutes = Math.round(totalMinutes / totalSessions); + + // Base stats + const totalHours = Math.round(totalMinutes / 60); + const totalDays = parseFloat((totalMinutes / 60 / 24).toFixed(1)); + const totalDurationLabel = formatDuration(totalMinutes); + + // Dominant type + const dominantType = typeStats[0] || { content_type: 'movie', duration: 0, count: 0 }; + const dominantPercent = totalMinutes > 0 ? Math.round((parseInt(dominantType.duration) / totalMinutes) * 100) : 0; + + // Top content + const topShow = enrichedTopContent[0] || null; + const topShowMinutes = topShow ? parseInt(topShow.duration) : 0; + const topShowHours = Math.round(topShowMinutes / 60); + const topShowDurationLabel = formatDuration(topShowMinutes); + const topShowTitle = topShow ? topShow.content_title : null; + const topShowType = topShow ? topShow.content_type : null; + + const secondShow = enrichedTopContent[1] || null; + const secondShowTitle = secondShow ? secondShow.content_title : null; + + // Peak / lowest month + const peakMonth = monthlyStats[0] || { month: 1, duration: 0 }; + const lowestMonth = monthlyStats[monthlyStats.length - 1] || peakMonth; + const monthNames = ['', 'Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre']; + + // Diversity / loyalty / binge + const diversityScore = totalHours > 0 ? (uniqueTitles / totalHours) : 0; + const isExplorer = diversityScore > 0.5; + const isLoyal = diversityScore < 0.1 && uniqueTitles < 20; + const isBinger = topShowHours > totalHours * 0.3; + + // Type percents + const animeStats = typeStats.find(t => t.content_type === 'anime'); + const movieStats = typeStats.find(t => t.content_type === 'movie'); + const tvStats = typeStats.find(t => t.content_type === 'tv'); + + const animePercent = animeStats ? Math.round((parseInt(animeStats.duration) / totalMinutes) * 100) : 0; + const moviePercent = movieStats ? Math.round((parseInt(movieStats.duration) / totalMinutes) * 100) : 0; + const tvPercent = tvStats ? Math.round((parseInt(tvStats.duration) / totalMinutes) * 100) : 0; + + _t.computeEnd = Date.now(); + console.log(`[Wrapped][PERF] 🧮 Compute stats: ${_t.computeEnd - _t.computeStart}ms`); + + // ── 4. Persona + slides (pure CPU) ────────────────────────────────────── + + const persona = determinePersona({ + totalHours, uniqueTitles, dominantPercent, dominantType, + animePercent, moviePercent, tvPercent, isExplorer, isLoyal, isBinger, + topShowType, topShowHours, isNightOwl + }); + + const slides = generateSlides({ + totalMinutes, totalHours, totalDays, totalDurationLabel, uniqueTitles, + topShowTitle, topShowHours, topShowMinutes, topShowDurationLabel, topShowType, + secondShowTitle, secondShow, + dominantType, dominantPercent, + peakMonth, lowestMonth, monthNames, + animePercent, moviePercent, tvPercent, + isExplorer, isLoyal, isBinger, + enrichedTopContent, typeStats, persona, + year, + percentile, peakHour, isNightOwl, isEarlyBird, + longestStreak, totalActiveDays, + firstWatchData, lastWatchData, + topGenres, avgSessionMinutes + }); + + _t.slidesEnd = Date.now(); + console.log(`[Wrapped][PERF] 🎨 Persona + slides: ${_t.slidesEnd - _t.computeEnd}ms`); + + // ── 5. Build response ─────────────────────────────────────────────────── + + const wrapped = { + year: parseInt(year), + persona, + slides, + stats: { + totalMinutes, totalHours, totalDays, uniqueTitles, + totalSessions: parseInt(viewingStats[0].total_sessions) || 0, + avgSessionMinutes, totalActiveDays, longestStreak, percentile + }, + topContent: enrichedTopContent.map((c, i) => { + const mins = parseInt(c.duration); + return { + rank: i + 1, + title: c.content_title, + type: c.content_type, + minutes: mins, + hours: Math.round(mins / 60), + durationLabel: formatDurationShort(mins), + tmdbId: c.content_type !== 'live-tv' ? parseInt(c.content_id) : null, + poster_path: c.poster_path, + genres: c.genres || [] + }; + }), + byType: typeStats.map(t => ({ + type: t.content_type, + minutes: parseInt(t.duration), + count: parseInt(t.count), + percent: Math.round((parseInt(t.duration) / totalMinutes) * 100) + })), + topGenres, + peakMonth: { month: peakMonth.month, name: monthNames[peakMonth.month], minutes: parseInt(peakMonth.duration) }, + monthlyGraph, + listeningClock: hourlyMap.map((minutes, hour) => ({ hour, minutes })), + peakHour, + firstWatch: firstWatchData ? { + title: firstWatchData.content_title, type: firstWatchData.content_type, + date: firstWatchData.created_at, + tmdbId: firstWatchData.content_type !== 'live-tv' ? parseInt(firstWatchData.content_id) : null + } : null, + lastWatch: lastWatchData ? { + title: lastWatchData.content_title, type: lastWatchData.content_type, + date: lastWatchData.created_at, + tmdbId: lastWatchData.content_type !== 'live-tv' ? parseInt(lastWatchData.content_id) : null + } : null, + topPages: topPages.map(p => ({ page: p.page_name, minutes: parseInt(p.duration) })) + }; + + // ── 6. Store in Redis cache (fire-and-forget) ─────────────────────────── + const responsePayload = { success: true, wrapped }; + redisSet(cacheKey, JSON.stringify(responsePayload), WRAPPED_CACHE_TTL); + + const totalTime = Date.now() - _t.start; + console.log(`[Wrapped][PERF] ── DONE in ${totalTime}ms ── Breakdown: SQL+Pctile(parallel)=${_t.sqlEnd - _t.sqlStart}ms | TMDB=${_t.tmdbEnd - _t.tmdbStart}ms | Compute=${_t.computeEnd - _t.computeStart}ms | Slides=${_t.slidesEnd - _t.computeEnd}ms | Build+Send=${Date.now() - _t.slidesEnd}ms`); + + res.json(responsePayload); + + } catch (error) { + console.error('[Wrapped] Error generating wrapped:', error); + res.status(500).json({ success: false, error: 'Generation failed' }); + } +}); + +// ============================================ +// === FONCTIONS DE GÉNÉRATION TEMPLATES === +// ============================================ + +/** + * Détermine la personnalité de visionnage de l'utilisateur + * Basé sur des règles de classification (comme le ML de Spotify) + */ +function determinePersona(data) { + const { + totalHours, uniqueTitles, dominantPercent, dominantType, + animePercent, moviePercent, tvPercent, isExplorer, isLoyal, isBinger, + topShowType, topShowHours, isNightOwl + } = data; + + // Personas par priorité (le premier qui matche gagne) + const personas = [ + // --- PERSONAS EXTRÊMES (basés sur l'intensité) --- + { + condition: totalHours > 1000, + persona: { + id: 'legend', + title: 'La Légende Vivante', + emoji: '👑', + subtitle: 'Tu as littéralement vécu sur Movix cette année', + description: 'Plus de 1000 heures. On devrait te payer à ce stade.', + color: '#FFD700' + } + }, + { + condition: totalHours > 500, + persona: { + id: 'marathon', + title: 'Le Marathonien Ultime', + emoji: '🏃‍♂️', + subtitle: 'Ton canapé a une empreinte permanente de toi', + description: 'Tu as transformé le binge-watching en sport olympique.', + color: '#FF6B35' + } + }, + // --- NIGHT OWL --- + { + condition: isNightOwl && totalHours > 100, + persona: { + id: 'night-owl', + title: 'L\'Oiseau de Nuit', + emoji: '🦉', + subtitle: 'La nuit, tous les écrans sont gris... sauf le tien', + description: 'Tu fais tes meilleures sessions entre minuit et 5h.', + color: '#1A237E' + } + }, + // --- PERSONAS PAR TYPE DOMINANT --- + { + condition: animePercent > 80, + persona: { + id: 'weeb-supreme', + title: 'Weeb Suprême', + emoji: '⛩️', + subtitle: 'Tu penses en sous-titres à ce stade', + description: 'Plus de 80% d\'anime. Tu es officiellement plus japonais que français.', + color: '#E91E63' + } + }, + { + condition: animePercent > 50, + persona: { + id: 'otaku', + title: 'L\'Otaku Assumé', + emoji: '🍜', + subtitle: 'Ton cœur bat au rythme des openings', + description: 'Les animes ne sont pas une phase, c\'est un mode de vie.', + color: '#9C27B0' + } + }, + { + condition: moviePercent > 70 && uniqueTitles > 50, + persona: { + id: 'critic', + title: 'Le Critique', + emoji: '🎬', + subtitle: 'Tu as un avis sur tout, et il est probablement juste', + description: 'Tu pourrais écrire pour les Cahiers du Cinéma.', + color: '#2196F3' + } + }, + { + condition: moviePercent > 70, + persona: { + id: 'cinephile', + title: 'Le Cinéphile', + emoji: '🎥', + subtitle: 'Le 7ème art coule dans tes veines', + description: 'Les films, c\'est ta religion.', + color: '#3F51B5' + } + }, + { + condition: tvPercent > 70 && isBinger, + persona: { + id: 'binger', + title: 'Le Binge-Watcher Pro', + emoji: '📺', + subtitle: '"Encore un épisode" est ton mantra', + description: 'Tu ne regardes pas les séries, tu les dévores.', + color: '#4CAF50' + } + }, + { + condition: tvPercent > 50, + persona: { + id: 'series-addict', + title: 'L\'Accro aux Séries', + emoji: '📡', + subtitle: 'Tu connais plus de personnages fictifs que de vraies personnes', + description: 'Les séries sont ta deuxième famille.', + color: '#009688' + } + }, + // --- PERSONAS PAR COMPORTEMENT --- + { + condition: isExplorer && uniqueTitles > 100, + persona: { + id: 'explorer-elite', + title: 'L\'Explorateur d\'Élite', + emoji: '🧭', + subtitle: 'Tu as vu des trucs dont personne n\'a entendu parler', + description: 'Plus de 100 titres ! Tu es la définition de la curiosité.', + color: '#FF9800' + } + }, + { + condition: isExplorer, + persona: { + id: 'explorer', + title: 'L\'Explorateur', + emoji: '🔍', + subtitle: 'Toujours en quête de la prochaine pépite', + description: 'Tu préfères découvrir que revoir.', + color: '#FFC107' + } + }, + { + condition: isLoyal && topShowHours > 50, + persona: { + id: 'superfan', + title: 'Le Superfan', + emoji: '💜', + subtitle: 'Tu as trouvé TON truc et tu t\'y tiens', + description: 'La loyauté, c\'est ta plus grande qualité.', + color: '#673AB7' + } + }, + { + condition: isLoyal, + persona: { + id: 'comfort-watcher', + title: 'L\'Amateur de Confort', + emoji: '🛋️', + subtitle: 'Pourquoi changer une équipe qui gagne ?', + description: 'Tu remates tes classiques, et c\'est très bien comme ça.', + color: '#795548' + } + } + ]; + + // Chercher le premier persona qui matche + for (const p of personas) { + if (p.condition === true) { + return p.persona; + } + } + + // Persona par défaut basé sur le type dominant + const defaultPersonas = { + 'anime': { + id: 'anime-fan', + title: 'L\'Anime Fan', + emoji: '✨', + subtitle: 'Tu apprécies l\'art de l\'animation japonaise', + description: 'Un équilibre sain d\'anime dans ta vie.', + color: '#E91E63' + }, + 'movie': { + id: 'movie-lover', + title: 'L\'Amoureux du Cinéma', + emoji: '🍿', + subtitle: 'Rien ne vaut un bon film', + description: 'Tu sais apprécier une bonne histoire.', + color: '#2196F3' + }, + 'tv': { + id: 'tv-enthusiast', + title: 'L\'Enthousiaste des Séries', + emoji: '📺', + subtitle: 'Les séries font partie de ta routine', + description: 'Un épisode par jour éloigne le médecin.', + color: '#4CAF50' + }, + 'live-tv': { + id: 'live-watcher', + title: 'Le Téléspectateur', + emoji: '📡', + subtitle: 'Tu restes connecté à l\'actualité', + description: 'La TV en direct, c\'est ton truc.', + color: '#607D8B' + } + }; + + return defaultPersonas[dominantType.content_type] || defaultPersonas['movie']; +} + +/** + * Formate une durée en minutes : affiche les heures si >= 60 min, sinon les minutes + * @param {number} minutes + * @returns {string} e.g. "12 heures" ou "45 minutes" + */ +function formatDuration(minutes) { + if (minutes >= 60) { + const h = Math.round(minutes / 60); + return `${h} heure${h > 1 ? 's' : ''}`; + } + return `${minutes} minute${minutes > 1 ? 's' : ''}`; +} + +/** + * Version courte : "12h" ou "45min" + */ +function formatDurationShort(minutes) { + if (minutes >= 60) { + return `${Math.round(minutes / 60)}h`; + } + return `${minutes}min`; +} + +/** + * Génère les slides du Wrapped avec des templates "à trous" + * Écrit comme un copywriter Spotify le ferait + */ +function generateSlides(data) { + const { + totalMinutes, totalHours, totalDays, totalDurationLabel, uniqueTitles, + topShowTitle, topShowHours, topShowMinutes, topShowDurationLabel, topShowType, + secondShowTitle, secondShow, + dominantType, dominantPercent, + peakMonth, lowestMonth, monthNames, + animePercent, moviePercent, tvPercent, + isExplorer, isLoyal, isBinger, + enrichedTopContent, typeStats, persona, + year, + // New data + percentile, peakHour, isNightOwl, isEarlyBird, + longestStreak, totalActiveDays, + firstWatchData, lastWatchData, + topGenres, avgSessionMinutes + } = data; + + const slides = []; + + // === SLIDE 1: INTRO / HOOK === + const introTemplates = [ + { + condition: totalHours > 200, + title: `${year}, c'était intense.`, + subtitle: 'Genre, vraiment intense.', + text: `Tu as passé ${totalDurationLabel} sur Movix. C'est ${totalDays} jours complets. On espère que t'avais des snacks.`, + highlight: `${totalDays} jours` + }, + { + condition: totalHours > 100, + title: `${year} ? Tu l'as bien remplie.`, + subtitle: 'Et ton historique aussi.', + text: `${totalDurationLabel} de contenu. C'est plus que certains jobs à temps partiel.`, + highlight: `${formatDurationShort(totalMinutes)}` + }, + { + condition: totalHours > 50, + title: `Pas mal, ${year}.`, + subtitle: 'Pas mal du tout.', + text: `${totalDurationLabel} de streaming. Tu sais ce que tu veux.`, + highlight: `${formatDurationShort(totalMinutes)}` + }, + { + condition: true, + title: `${year} s'est bien passée.`, + subtitle: 'On a les preuves.', + text: `${totalDurationLabel} ensemble cette année. C'est un bon début.`, + highlight: `${formatDurationShort(totalMinutes)}` + } + ]; + slides.push({ type: 'intro', ...introTemplates.find(t => t.condition) }); + + // === SLIDE 2: TOP 1 === + if (topShowTitle) { + const top1Templates = [ + { + condition: topShowHours > 100, + title: `"${topShowTitle}"`, + subtitle: 'Ton obsession de l\'année', + text: `${topShowDurationLabel} dessus. À ce stade, tu pourrais écrire la suite toi-même.`, + highlight: `#1`, + subtext: 'C\'est un peu gênant, mais on adore.' + }, + { + condition: topShowHours > 50, + title: `"${topShowTitle}"`, + subtitle: 'Ton coup de cœur absolu', + text: `${topShowDurationLabel}. Tu l'as regardé, rerererereregardé, et tu recommencerais.`, + highlight: `#1`, + subtext: 'Fan numéro 1 ? C\'est toi.' + }, + { + condition: topShowHours > 20, + title: `"${topShowTitle}"`, + subtitle: 'Ta grande histoire d\'amour', + text: `${topShowDurationLabel} ensemble. C'est plus que certaines relations.`, + highlight: `#1`, + subtext: 'Et on ne juge pas.' + }, + { + condition: true, + title: `"${topShowTitle}"`, + subtitle: 'Ton préféré de l\'année', + text: `${topShowDurationLabel} passées dessus. Un classique dans ton cœur.`, + highlight: `#1`, + subtext: '' + } + ]; + slides.push({ type: 'top1', ...top1Templates.find(t => t.condition) }); + } + + // === SLIDE 3: TOP 5 === + if (enrichedTopContent.length >= 3) { + const top5Text = enrichedTopContent.slice(0, 5).map((c, i) => + `${i + 1}. ${c.content_title}` + ).join('\n'); + + slides.push({ + type: 'top5', + title: 'Ton Top 5', + subtitle: 'Ceux qui ont marqué ton année', + text: top5Text, + highlight: `${uniqueTitles} titres au total`, + subtext: uniqueTitles > 50 ? 'Tu es incollable.' : '' + }); + } + + // === SLIDE 4: PERSONNALITÉ / VIBE === + const typeLabel = { + 'anime': 'les animes', + 'movie': 'les films', + 'tv': 'les séries', + 'live-tv': 'la TV en direct' + }; + + const vibeTemplates = [ + { + condition: dominantPercent > 80, + title: persona.title, + subtitle: persona.subtitle, + text: `${dominantPercent}% de ton temps sur ${typeLabel[dominantType.content_type]}. Tu sais ce que tu aimes, et tu assumes.`, + highlight: persona.emoji, + subtext: persona.description + }, + { + condition: dominantPercent > 50, + title: persona.title, + subtitle: persona.subtitle, + text: `Ta vibe ? Principalement ${typeLabel[dominantType.content_type]}, avec une touche de variété.`, + highlight: persona.emoji, + subtext: persona.description + }, + { + condition: true, + title: persona.title, + subtitle: persona.subtitle, + text: `Tu es éclectique. Un peu de tout, c'est ton style.`, + highlight: persona.emoji, + subtext: persona.description + } + ]; + slides.push({ type: 'persona', ...vibeTemplates.find(t => t.condition) }); + + // === SLIDE 5: MOIS LE PLUS ACTIF === + const peakMonthMinutes = parseInt(peakMonth.duration); + const peakMonthHours = Math.round(peakMonthMinutes / 60); + const peakMonthDurationLabel = formatDuration(peakMonthMinutes); + + const monthTemplates = [ + { + condition: peakMonthHours > 50, + title: monthNames[peakMonth.month], + subtitle: 'Ton mois de folie', + text: `${peakMonthDurationLabel} en un seul mois. Il s'est passé quoi ? Rupture ? Vacances ? Les deux ?`, + highlight: `🔥`, + subtext: 'On ne juge pas, on constate.' + }, + { + condition: peakMonthHours > 20, + title: monthNames[peakMonth.month], + subtitle: 'Ton mois le plus actif', + text: `${peakMonthDurationLabel}. Tu étais dans ta bulle, et c'était bien.`, + highlight: `📅`, + subtext: '' + }, + { + condition: true, + title: monthNames[peakMonth.month], + subtitle: 'Là où tout s\'est joué', + text: `Ton pic de l'année. ${peakMonthDurationLabel} de pur bonheur.`, + highlight: `✨`, + subtext: '' + } + ]; + slides.push({ type: 'peak-month', ...monthTemplates.find(t => t.condition) }); + + // === SLIDE 6: TOP GENRES === + if (topGenres && topGenres.length >= 2) { + const topGenreNames = topGenres.slice(0, 3).map(g => g.name).join(', '); + slides.push({ + type: 'top-genres', + title: 'Tes genres préférés', + subtitle: topGenreNames, + text: topGenres.length >= 3 + ? `${topGenres[0].name} domine avec ${topGenres[0].percent}% de ton temps. Suivi par ${topGenres[1].name} et ${topGenres[2].name}.` + : `${topGenres[0].name} domine avec ${topGenres[0].percent}% de ton temps.`, + highlight: '🎭', + subtext: topGenres.length > 5 ? `Et aussi : ${topGenres.slice(5).map(g => g.name).join(', ')}` : '' + }); + } + + // === SLIDE 7: LISTENING CLOCK (Quand tu regardes) === + const hourLabel = (h) => `${h}h`; + const clockTemplates = [ + { + condition: isNightOwl, + title: 'Le mode nocturne', + subtitle: `Tu es le plus actif vers ${hourLabel(peakHour)}`, + text: 'Pendant que le monde dort, toi tu mates. Tes yeux rouges ne mentent pas.', + highlight: '🌙', + subtext: 'Les meilleures sessions, c\'est la nuit.' + }, + { + condition: isEarlyBird, + title: 'Lève-tôt, regarde tôt', + subtitle: `Ton pic d'activité : ${hourLabel(peakHour)}`, + text: 'Tu lances un épisode avant même que le café soit prêt. Respect.', + highlight: '🌅', + subtext: '' + }, + { + condition: true, + title: `${hourLabel(peakHour)}, ton heure de pointe`, + subtitle: 'Ton horloge de visionnage', + text: `C'est à ${hourLabel(peakHour)} que tu lances le plus souvent Movix. On connaît tes habitudes maintenant.`, + highlight: '⏰', + subtext: '' + } + ]; + slides.push({ type: 'listening-clock', ...clockTemplates.find(t => t.condition) }); + + // === SLIDE 8: STREAK === + if (longestStreak >= 3) { + const streakTemplates = [ + { + condition: longestStreak >= 30, + title: `${longestStreak} jours de suite`, + subtitle: 'Un mois complet non-stop', + text: `Ta plus longue série de visionnage : ${longestStreak} jours consécutifs. On appelle ça de la détermination.`, + highlight: '🔥', + subtext: `Sur ${totalActiveDays} jours actifs cette année.` + }, + { + condition: longestStreak >= 14, + title: `${longestStreak} jours d'affilée`, + subtitle: 'Streak impressionnant', + text: `Deux semaines sans lâcher Movix. Tu as une discipline de fer (pour le streaming en tout cas).`, + highlight: '⚡', + subtext: `${totalActiveDays} jours d'activité au total.` + }, + { + condition: longestStreak >= 7, + title: `${longestStreak} jours non-stop`, + subtitle: 'Une semaine de dédi', + text: `Ta meilleure série : ${longestStreak} jours sans interruption. C'est de la constance.`, + highlight: '💪', + subtext: '' + }, + { + condition: true, + title: `${longestStreak} jours de streak`, + subtitle: 'Ta meilleure série', + text: `${longestStreak} jours de visionnage consécutifs. Pas mal comme streak.`, + highlight: '🎯', + subtext: '' + } + ]; + slides.push({ type: 'streak', ...streakTemplates.find(t => t.condition) }); + } + + // === SLIDE 9: FUN FACT === + const funFacts = []; + + if (totalHours > 24) { + const equivalent = Math.floor(totalHours / 2); // Un film moyen = 2h + funFacts.push({ + title: 'En d\'autres termes...', + subtitle: '', + text: `Tu aurais pu regarder ${equivalent} films de suite. Ou dormir ${totalDays} jours. Tu as fait un choix.`, + highlight: '🤔', + subtext: 'Le bon choix.' + }); + } else if (totalMinutes > 30) { + funFacts.push({ + title: 'En d\'autres termes...', + subtitle: '', + text: `${totalDurationLabel} de streaming. C'est déjà un bon début pour cette année.`, + highlight: '🤔', + subtext: 'Et ce n\'est que le début.' + }); + } + + if (isExplorer && uniqueTitles > 30) { + funFacts.push({ + title: 'L\'algorithme t\'adore', + subtitle: '', + text: `${uniqueTitles} titres différents. Tu rends notre job de recommandation vraiment difficile (et intéressant).`, + highlight: '🧠', + subtext: '' + }); + } + + if (isBinger && topShowTitle) { + const percentOfTotal = totalMinutes > 0 ? Math.round((topShowMinutes / totalMinutes) * 100) : 0; + funFacts.push({ + title: 'Confession time', + subtitle: '', + text: `"${topShowTitle}" représente ${percentOfTotal}% de ton temps total. C'est de l'engagement.`, + highlight: '💍', + subtext: 'Ou de l\'obsession. Mais qui compte ?' + }); + } + + // Percentile fun fact + if (percentile >= 90) { + funFacts.push({ + title: `Top ${100 - percentile}% des viewers`, + subtitle: 'Tu es dans l\'élite', + text: `Tu regardes plus que ${percentile}% des utilisateurs Movix. On devrait te donner un badge.`, + highlight: '🏆', + subtext: '' + }); + } + + // Session length fun fact + if (avgSessionMinutes > 90) { + funFacts.push({ + title: 'Sessions marathon', + subtitle: '', + text: `En moyenne, tes sessions durent ${avgSessionMinutes} minutes. Tu ne fais pas les choses à moitié.`, + highlight: '🍿', + subtext: 'Netflix and actually chill.' + }); + } + + // First watch of the year fun fact + if (firstWatchData) { + const firstDate = new Date(firstWatchData.created_at); + const dayOfYear = Math.ceil((firstDate - new Date(firstDate.getFullYear(), 0, 1)) / (1000 * 60 * 60 * 24)); + if (dayOfYear <= 3) { + funFacts.push({ + title: 'Pas de temps à perdre', + subtitle: '', + text: `Ton premier visionnage de ${year} ? "${firstWatchData.content_title}", dès le ${dayOfYear === 1 ? '1er' : dayOfYear + 'ème'} janvier. Tu n'as pas attendu longtemps.`, + highlight: '🎆', + subtext: '' + }); + } + } + + if (funFacts.length > 0) { + // Pick 1-2 fun facts + const shuffled = funFacts.sort(() => 0.5 - Math.random()); + slides.push({ type: 'fun-fact', ...shuffled[0] }); + if (shuffled.length > 1 && totalHours > 50) { + slides.push({ type: 'fun-fact', ...shuffled[1] }); + } + } + + // === SLIDE 10: DETAILED STATS === + slides.push({ + type: 'detailed-stats', + title: 'Tes Statistiques', + subtitle: 'En détail', + text: 'Le résumé complet de ton année.', + highlight: '📊', + subtext: '' + }); + + // === SLIDE 8: CLOSING === + slides.push({ + type: 'closing', + title: `C'était ${year}.`, + subtitle: 'Avec toi.', + text: `${totalDurationLabel}. ${uniqueTitles} titres. 1 seul toi. Merci d'avoir passé cette année sur Movix.`, + highlight: '💜', + subtext: 'À l\'année prochaine ?' + }); + + return slides; +} + +module.exports = { router, initWrappedRoutes, initTables }; diff --git a/API/Mainapi/wrapped_tables.sql b/API/Mainapi/wrapped_tables.sql new file mode 100644 index 0000000..e6ab362 --- /dev/null +++ b/API/Mainapi/wrapped_tables.sql @@ -0,0 +1,67 @@ +-- ============================================ +-- Movix Wrapped 2026 - Database Tables +-- ============================================ +-- Run this SQL file to create the required tables for Movix Wrapped data collection. +-- These tables store viewing data and page visit statistics for the annual Wrapped summary. +-- ============================================ + +-- --------------------------------------------- +-- Table: wrapped_viewing_data +-- Stores viewing time for movies, TV shows, anime, and live TV +-- --------------------------------------------- +CREATE TABLE IF NOT EXISTS wrapped_viewing_data ( + id INT AUTO_INCREMENT PRIMARY KEY, + user_id VARCHAR(255) NOT NULL, + profile_id VARCHAR(255), + content_type ENUM('movie', 'tv', 'anime', 'live-tv') NOT NULL, + content_id VARCHAR(255) NOT NULL, + content_title VARCHAR(255), + season_number INT DEFAULT NULL, + episode_number INT DEFAULT NULL, + watch_duration INT NOT NULL DEFAULT 0, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + hour_of_day TINYINT DEFAULT NULL, + month INT NOT NULL, + year INT NOT NULL, + INDEX idx_user_year (user_id, year), + INDEX idx_content (content_type, content_id), + INDEX idx_user_profile (user_id, profile_id), + INDEX idx_hour (user_id, year, hour_of_day) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- --------------------------------------------- +-- Table: wrapped_pages_data +-- Stores page visit duration and statistics +-- --------------------------------------------- +CREATE TABLE IF NOT EXISTS wrapped_pages_data ( + id INT AUTO_INCREMENT PRIMARY KEY, + user_id VARCHAR(255) NOT NULL, + profile_id VARCHAR(255), + page_name VARCHAR(100) NOT NULL, + content_id VARCHAR(255) DEFAULT NULL, -- TMDB ID for detail pages (movie-details, tv-details) + duration INT DEFAULT 0, + meta_data JSON, + month INT NOT NULL, + year INT NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + INDEX idx_page_stats (user_id, page_name, year), + INDEX idx_user_profile (user_id, profile_id), + INDEX idx_content_page (page_name, content_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- ============================================ +-- Summary of tracked data: +-- ============================================ +-- +-- wrapped_viewing_data: +-- - Viewing time for movies, TV shows, anime, live TV +-- - Tracks: content_id, content_type, season/episode for TV/anime +-- - Used to calculate: most watched content, total watch time, genre preferences +-- +-- wrapped_pages_data: +-- - Page visit duration +-- - content_id for detail pages (movie-details, tv-details) +-- - Tracks: home, movies, tv-shows, movie-details, tv-details, watchparty, live-tv, wishboard +-- - Used to calculate: browsing habits, feature usage, engagement metrics +-- +-- ============================================ diff --git a/API/README.md b/API/README.md new file mode 100644 index 0000000..f4ffec8 --- /dev/null +++ b/API/README.md @@ -0,0 +1,74 @@ +# Services backend Movix + +Le dossier `API/` regroupe les services serveurs du projet. Le point clé à retenir : le backend applicatif actif est `API/Mainapi/`. Le vieux backend directement posé sous `API/` n'est plus la référence. + +Movix ne tourne pas sur un seul serveur monolithique. Selon la feature, le frontend peut parler au backend principal, à la WatchParty, à un proxy Python, à un worker Cloudflare ou à un outil navigateur. + +## Carte rapide + +| Dossier | Rôle | Lancement | Documentation | +| --- | --- | --- | --- | +| `API/Mainapi/` | Cœur applicatif : auth, sync, scraping, social, VIP, Live TV | `cd API/Mainapi && npm run dev` | [README](Mainapi/README.md) | +| `API/watchpartyAPI/` | Service temps réel WatchParty | `node API/watchpartyAPI/watchparty.js` | [README](watchpartyAPI/README.md) | +| `API/proxiesembed/` | Proxy aiohttp pour embeds, flux et DRM | `cd API/proxiesembed && python server.py` | [README](proxiesembed/README.md) | +| `API/miscs/` | Micro-service Flask pour certains 403 | `cd API/miscs && python bypass403.py` | [README](miscs/README.md) | + +## Setup minimal + +Commandes utiles pour préparer le dossier `API/` : + +```bash +# Backend principal +cd API/Mainapi +npm install +``` + +```bash +# Services Python +cd API/proxiesembed +pip install -r requirements.txt + +cd ../miscs +pip install flask requests python-dotenv +``` + +### Configurer les `.env` + +Avant de lancer les services backend, crée et renseigne leurs fichiers de configuration : + +```bash +cp API/Mainapi/.env.example API/Mainapi/.env +cp API/watchpartyAPI/.env.example API/watchpartyAPI/.env +cp API/proxiesembed/.env.example API/proxiesembed/.env +cp API/miscs/.env.example API/miscs/.env +``` + +Note utile : + +- `API/watchpartyAPI/` n'a pas son propre `package.json` ; il utilise les dépendances racine. +- `API/Mainapi/` garde ses dépendances Node. +- Il n'y a pas de workspace tooling pour tout orchestrer d'un coup. + +## Comment lire cette partie du repo + +- Si tu touches auth, profils ou persistance utilisateur, commence par `API/Mainapi/app.js` et `API/Mainapi/routes/`. +- Si tu touches la lecture en groupe, regarde `API/watchpartyAPI/watchparty.js` en miroir du frontend WatchParty. +- Si tu touches la lecture vidéo ou les hosters, il faut souvent croiser `API/Mainapi/`, `API/proxiesembed/`, `API/miscs/` et parfois `cloudflareproxy/`. + +## Stockage et dépendances + +Selon les services, le backend Movix s'appuie sur : + +- MySQL +- Redis +- caches JSON sur disque +- stockage local en mémoire pour certains services temps réel +- SQLite et fichiers de data sur quelques briques annexes + +## Lire ensuite + +- [README principal](../README.md) +- [Main API](Mainapi/README.md) +- [WatchParty API](watchpartyAPI/README.md) +- [Proxies Embed](proxiesembed/README.md) +- [bypass403](miscs/README.md) diff --git a/API/miscs/.env.example b/API/miscs/.env.example new file mode 100644 index 0000000..8329003 --- /dev/null +++ b/API/miscs/.env.example @@ -0,0 +1 @@ +BYPASS403_SOCKS5_PROXY_URL=YOUR_BYPASS403_SOCKS5_PROXY_URL # Exemple: socks5://user:pass@127.0.0.1:1080 diff --git a/API/miscs/README.md b/API/miscs/README.md new file mode 100644 index 0000000..073a253 --- /dev/null +++ b/API/miscs/README.md @@ -0,0 +1,43 @@ +# bypass403 + +`bypass403.py` est un micro-service Flask très ciblé. Il sert de relais quand certaines sources renvoient un `403` ou imposent des conditions réseau que le reste du stack ne passe pas facilement. + +Ce service est volontairement minimal : un healthcheck, un endpoint proxy, un peu de cache mémoire et quelques ajustements de headers selon le domaine demandé. + +## Démarrage + +```bash +cd API/miscs +cp .env.example .env +pip install flask requests python-dotenv +python bypass403.py +``` + +Le service écoute actuellement sur `http://localhost:25568`. + +## Configuration + +Le seul paramètre exposé dans `API/miscs/.env.example` est : + +- `BYPASS403_SOCKS5_PROXY_URL` + +## Endpoints + +| Route | Rôle | +| --- | --- | +| `GET /health` | Retourne l'état du service et la taille du cache | +| `GET/POST/HEAD/OPTIONS /proxy/<target>` | Relaie la requête vers la cible demandée | + +## Ce que le service fait en pratique + +- reconstruit l'URL cible à partir du path et de la query string +- peut activer un proxy SOCKS5 pour certains domaines ou si `proxy=true` est passé dans l'URL +- injecte quelques headers métier pour des domaines connus +- met en cache certaines réponses `GET` de petite taille pendant 10 minutes +- ré-expose la réponse avec des headers CORS permissifs + +## Quand l'utiliser + +- quand une source précise casse avec un `403` +- quand le backend principal ou le frontend ne doivent pas gérer ce cas eux-mêmes +- quand tu veux un relais léger plutôt que mobiliser `API/proxiesembed/` diff --git a/API/miscs/bypass403.py b/API/miscs/bypass403.py new file mode 100644 index 0000000..e00f649 --- /dev/null +++ b/API/miscs/bypass403.py @@ -0,0 +1,187 @@ +import logging +import time +import os +import requests +from flask import Flask, request, Response, jsonify +from urllib.parse import unquote, urlparse, parse_qs, urlencode, urlunparse +from dotenv import load_dotenv + +load_dotenv(os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env')) + +# Disable extensive logging +log = logging.getLogger('werkzeug') +log.setLevel(logging.ERROR) + +app = Flask(__name__) + +# --- Configuration --- +PORT = 25568 +# SOCKS5 Proxy definition +PROXY_SOCKS = os.environ.get("BYPASS403_SOCKS5_PROXY_URL", "") + +# --- In-Memory Cache (Simple & Light) --- +# Stores: { url: {'content': bytes, 'ts': timestamp, 'headers': list, 'status': int} } +CACHE = {} +CACHE_TTL = 600 # 10 minutes cache +MAX_CACHE_ITEMS = 200 # Keep memory low +MAX_BODY_SIZE = 1 * 1024 * 1024 # Only cache responses < 1MB + +def get_cached(url): + """Retrieve item from cache if valid.""" + if url in CACHE: + item = CACHE[url] + if time.time() - item['ts'] < CACHE_TTL: + return item + else: + del CACHE[url] # Expired + return None + +def set_cached(url, content, headers, status): + """Add item to cache, evicting old ones if full.""" + if len(CACHE) >= MAX_CACHE_ITEMS: + # Remove a random item (first available key) + CACHE.pop(next(iter(CACHE)), None) + + CACHE[url] = { + 'content': content, + 'ts': time.time(), + 'headers': headers, + 'status': status + } + +# --- HTTP Session --- +session = requests.Session() +# High pool size for concurrency +adapter = requests.adapters.HTTPAdapter(pool_connections=200, pool_maxsize=200) +session.mount('http://', adapter) +session.mount('https://', adapter) + +@app.after_request +def add_cors(response): + response.headers["Access-Control-Allow-Origin"] = "*" + response.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS, HEAD" + response.headers["Access-Control-Allow-Headers"] = "*" + return response + +@app.route("/health") +def health(): + return jsonify({"status": "ok", "cache_size": len(CACHE)}) + +@app.route("/proxy/<path:target>", methods=["GET", "POST", "HEAD", "OPTIONS"]) +def proxy(target): + # 1. Reconstruct Target URL + query_string = request.query_string.decode('utf-8') if request.query_string else "" + target_url = f"{target}?{query_string}" if query_string else target + + try: + target_url = unquote(target_url) + except: + pass + + if not target_url.startswith("http"): + target_url = f"https://{target_url}" + + # 2. Check Cache (Only for GET and likely static content) + if request.method == "GET": + cached = get_cached(target_url) + if cached: + return Response(cached['content'], status=cached['status'], headers=cached['headers']) + + # 3. Detect & Handle Proxy Params + use_proxy = False + parsed = urlparse(target_url) + domain_lower = parsed.netloc.lower() + + # logic to enable proxy for specific sites or if requested + if "coflix" in domain_lower: + use_proxy = True + + # Check query params for 'proxy=true' + params = parse_qs(parsed.query) + if 'proxy' in params and params['proxy'][0].lower() == 'true': + use_proxy = True + + # Remove strict 'proxy' param from upstream url if it exists + if 'proxy' in params: + del params['proxy'] + new_query = urlencode(params, doseq=True) + target_url = urlunparse(( + parsed.scheme, parsed.netloc, parsed.path, parsed.params, + new_query, parsed.fragment + )) + + # 4. Prepare Headers + # Forward most headers but clean duplicates/hop-by-hop + req_headers = {k: v for k, v in request.headers.items() if k.lower() not in ['host', 'content-length', 'content-encoding']} + + req_headers["Accept-Encoding"] = "identity" # Avoid auto-gzip by requests + req_headers["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" + + # Domain specific headers + if "coflix" in domain_lower: + req_headers["Origin"] = "https://movix.embedseek.com" + req_headers["Referer"] = "https://movix.embedseek.com/" + elif "cinetacos" in domain_lower: + req_headers["Origin"] = "https://cinepulse.to" + req_headers["Referer"] = "https://cinepulse.to/" + elif "fsvid" in domain_lower: + req_headers["Referer"] = "https://fs-miroir6.lol/" + elif "top-stream" in domain_lower: + req_headers["Origin"] = "https://top-stream.plus" + req_headers["Referer"] = "https://top-stream.plus/" + + # 5. Execute Request + try: + proxies = {'http': PROXY_SOCKS, 'https': PROXY_SOCKS} if use_proxy else None + + resp = session.request( + method=request.method, + url=target_url, + headers=req_headers, + data=request.get_data(), + cookies=request.cookies, + stream=True, # Stream content + timeout=20, # Fast timeout + verify=False, # Ignore SSL errors for speed/compat + proxies=proxies + ) + + # 6. Stream & Cache Response + excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection'] + resp_headers = [(k, v) for k, v in resp.headers.items() if k.lower() not in excluded_headers] + + # Logic to decide if we cache this response + should_cache = (request.method == "GET" and resp.status_code == 200) + cache_data = [] + current_size = 0 + + def generate(): + nonlocal should_cache, current_size + try: + for chunk in resp.iter_content(chunk_size=4096): + if chunk: + if should_cache: + current_size += len(chunk) + if current_size <= MAX_BODY_SIZE: + cache_data.append(chunk) + else: + should_cache = False # Exceeded limit + yield chunk + finally: + resp.close() + # On stream end, save to cache if eligible + if should_cache and current_size > 0: + full_body = b"".join(cache_data) + set_cached(target_url, full_body, resp_headers, resp.status_code) + + return Response(generate(), status=resp.status_code, headers=resp_headers) + + except Exception as e: + # Quiet error handling + return jsonify({"error": str(e)}), 500 + +if __name__ == "__main__": + import urllib3 + urllib3.disable_warnings() + # Threaded for concurrency + app.run(host="0.0.0.0", port=PORT, threaded=True, debug=False) diff --git a/API/proxiesembed/.env.example b/API/proxiesembed/.env.example new file mode 100644 index 0000000..7042e07 --- /dev/null +++ b/API/proxiesembed/.env.example @@ -0,0 +1,12 @@ +PORT=YOUR_PROXIESEMBED_PORT # Exemple: 8080 +DB_HOST=YOUR_DB_HOST # Exemple: localhost +DB_PORT=YOUR_DB_PORT # Exemple: 3306 +DB_USER=YOUR_DB_USER # Exemple: root +DB_PASSWORD=YOUR_DB_PASSWORD # Exemple: motdepassefort +DB_NAME=YOUR_DB_NAME # Exemple: movix +PROXY_BASE=YOUR_PROXY_BASE # Exemple: https://proxy.movix.rodeo +PROXIES_SOCKS5_JSON=YOUR_PROXIES_SOCKS5_JSON # Exemple: [{"url":"socks5://user:pass@127.0.0.1:1080"}] +SIBNET_PROXY_SOCKS5_JSON=YOUR_SIBNET_PROXY_SOCKS5_JSON # Exemple: [{"url":"socks5://user:pass@127.0.0.1:1081"}] +FRANCETV_EMAIL=YOUR_FRANCETV_EMAIL +FRANCETV_PASSWORD=YOUR_FRANCETV_PASSWORD +DEEPBRID_API_KEY=YOUR_DEEPBRID_API_KEY diff --git a/API/proxiesembed/README.md b/API/proxiesembed/README.md new file mode 100644 index 0000000..c0dbf52 --- /dev/null +++ b/API/proxiesembed/README.md @@ -0,0 +1,79 @@ +# Proxies Embed + +`API/proxiesembed/` est le gros proxy Python du projet. Il sert à la fois de proxy de streaming, de boîte à outils pour certains extracteurs d'hosters, de passerelle DRM et de couche de contournement pour des cas où le frontend ou le backend Node ne suffisent plus. + +Le service est écrit avec `aiohttp` et pensé pour la charge : connexions concurrentes, caches mémoire, coalescing de requêtes, pools proxy et endpoints spécialisés par hoster. + +## Ce que le service fait + +- proxy générique de flux via `/proxy` +- extracteurs dédiés pour plusieurs hosters embed +- endpoints proxy spécialisés par source +- debrid unlock via API +- surface DRM avec extraction de manifestes et réécriture de ressources +- vérification d'accès VIP via MySQL +- support de pools SOCKS5 et de sessions dédiées pour certains cas comme france.tv + +## Démarrage + +```bash +cd API/proxiesembed +cp .env.example .env +pip install -r requirements.txt +python server.py +``` + +Notes utiles : + +- le code bind actuellement sur `http://localhost:25569` +- le fichier `.env.example` contient `PORT`, mais `server.py` écoute aujourd'hui `25569` en dur +- certaines routes DRM s'appuient sur des utilitaires additionnels dans `drmproxy/` ; si ces utilitaires sont absents, le serveur démarre quand même mais la partie DRM avancée reste limitée + +## Variables d'environnement utiles + +Le fichier `API/proxiesembed/.env.example` couvre les besoins principaux : + +- base de données : `DB_HOST`, `DB_PORT`, `DB_USER`, `DB_PASSWORD`, `DB_NAME` +- exposition publique : `PROXY_BASE` +- pools proxies : `PROXIES_SOCKS5_JSON`, `SIBNET_PROXY_SOCKS5_JSON` +- france.tv : `FRANCETV_EMAIL`, `FRANCETV_PASSWORD` +- debrid : `DEEPBRID_API_KEY` + +## Endpoints à connaître + +| Route | Rôle | +| --- | --- | +| `GET /proxy` et `GET /proxy/{path}` | Proxy streaming générique | +| `GET /health` | Healthcheck | +| `GET /stats` | Stats runtime | +| `GET /api/extract-fsvid` | Extraction FSVid | +| `GET /api/extract-vidzy` | Extraction Vidzy | +| `GET /api/extract-vidmoly` | Extraction Vidmoly | +| `GET /api/extract-sibnet` | Extraction Sibnet | +| `GET /api/extract-uqload` | Extraction Uqload | +| `GET /api/extract-doodstream` | Extraction Doodstream | +| `GET /api/extract-seekstreaming` | Extraction SeekStreaming | +| `GET /voe-proxy`, `/fsvid-proxy`, `/vidzy-proxy`, `/vidmoly-proxy`, `/sibnet-proxy`, `/uqload-proxy`, `/doodstream-proxy`, `/seekstreaming-proxy`, `/cinep-proxy` | Proxies dédiés par source | +| `GET/POST /drm/extract` | Extraction de manifeste DRM | +| `GET /drm/manifest` | Réécriture de manifeste HLS ou DASH | +| `GET /drm/resource` | Proxy de ressources DRM | +| `GET /drm/b/{base_b64}/{subpath}` | Proxy path-based pour DASH | +| `POST /api/debrid/unlock` | Unlock de liens debrid | + +## Notes d'architecture + +- le serveur initialise plusieurs sessions HTTP spécialisées +- certaines ressources lourdes sont cachées en mémoire avec eviction TTL +- la partie france.tv peut utiliser une session SOCKS5H distincte pour l'extraction +- la partie DRM tente de charger les utilitaires WideFrog au démarrage, mais reste optionnelle +- la vérification VIP s'appuie sur MySQL avant d'autoriser certaines surfaces + +## Quand regarder aussi ailleurs + +Si tu touches ce dossier, il faut souvent vérifier en miroir : + +- `API/Mainapi/liveTvRoutes.js` +- `API/Mainapi/routes/debrid.js` +- `src/pages/Watch/` +- `src/components/*Player*` +- `cloudflareproxy/` ou `RivestreamCloudflareProxy/` selon les flux concernés diff --git a/API/proxiesembed/app_files/config.json b/API/proxiesembed/app_files/config.json new file mode 100644 index 0000000..eb29e48 --- /dev/null +++ b/API/proxiesembed/app_files/config.json @@ -0,0 +1,102 @@ +{ + "CDM_WVD_FILE_PATH": "gift_from_karoolus.wvd", + "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 Edg/123.0.0.0", + "NUMBER_OF_THREADS": { + "DATA_SCRAPER": 5, + "MEDIA_DOWNLOADER": 3 + }, + "DOWNLOAD_COMMANDS": { + "OUTPUT_MEDIA_PATH": "media", + "WAIT_BEFORE_DOWNLOADING": true, + "ADDITIONAL_SUBS": true, + "TOOL_PARAMETERS": { + "VOD": "-sv best -sa best -da id=audio_div -ss all -mt --check-segments-count false --no-log", + "LIVESTREAM": "--live-pipe-mux --live-record-limit 00:02:00" + } + }, + "SERVICE_CREDENTIALS": { + "app.nzrplus.com": { + "EMAIL": "YOUR_EMAIL", + "PASSWORD": "YOUR_PASSWORD" + }, + "auvio.rtbf.be": { + "EMAIL": "YOUR_EMAIL", + "PASSWORD": "YOUR_PASSWORD" + }, + "cineverse.com": { + "OPTIONAL": true, + "FIREFOX_COOKIES": true + }, + "eurovisionsport.com": { + "EMAIL": "YOUR_EMAIL", + "PASSWORD": "YOUR_PASSWORD" + }, + "joyn.de": { + "OPTIONAL": true, + "EMAIL": "", + "PASSWORD": "YOUR_PASSWORD (leave at least one login field empty if you don't want to use an account)", + "PIN": "YOUR_PIN (this field is ignored if it's not a 4 digit text or if you don't use an account)" + }, + "kanopy.com": { + "FIREFOX_COOKIES": true + }, + "m6.fr": { + "EMAIL": "YOUR_EMAIL", + "PASSWORD": "YOUR_PASSWORD" + }, + "midnightpulp.com": { + "OPTIONAL": true, + "FIREFOX_COOKIES": true + }, + "mtv.fi": { + "FIREFOX_COOKIES": true + }, + "nba.com": { + "OPTIONAL": true, + "FIREFOX_COOKIES": true + }, + "npo.nl": { + "OPTIONAL": true, + "FIREFOX_COOKIES": true + }, + "plus.rtl.de": { + "OPTIONAL": true, + "EMAIL": "", + "PASSWORD": "YOUR_PASSWORD (leave at least one field empty if you don't want to use an account)" + }, + "ptvflix.org": { + "EMAIL": "YOUR_EMAIL", + "PASSWORD": "YOUR_PASSWORD" + }, + "rmcbfmplay.com": { + "EMAIL": "YOUR_EMAIL", + "PASSWORD": "YOUR_PASSWORD" + }, + "rtlplay.be": { + "FIREFOX_COOKIES": true + }, + "rugbypass.tv": { + "EMAIL": "YOUR_EMAIL", + "PASSWORD": "YOUR_PASSWORD" + }, + "tf1.fr": { + "EMAIL": "YOUR_EMAIL", + "PASSWORD": "YOUR_PASSWORD" + }, + "uefa.tv": { + "FIREFOX_COOKIES": true + }, + "viki.com": { + "OPTIONAL": true, + "FIREFOX_COOKIES": true + }, + "vtmgo.be": { + "FIREFOX_COOKIES": true + }, + "watch.shortly.film": { + "EMAIL": "YOUR_EMAIL", + "PASSWORD": "YOUR_PASSWORD" + } + }, + "WARN_EXTERNAL_TOOLS": true +} \ No newline at end of file diff --git a/API/proxiesembed/drmproxy/gift_from_karoolus.wvd b/API/proxiesembed/drmproxy/gift_from_karoolus.wvd new file mode 100644 index 0000000..bb4e78a Binary files /dev/null and b/API/proxiesembed/drmproxy/gift_from_karoolus.wvd differ diff --git a/API/proxiesembed/drmproxy/proxy_server.py b/API/proxiesembed/drmproxy/proxy_server.py new file mode 100644 index 0000000..a5fb94d --- /dev/null +++ b/API/proxiesembed/drmproxy/proxy_server.py @@ -0,0 +1,1133 @@ +""" +Proxy server that wraps widefrog services to extract and play +m3u8/mpd manifests directly in the browser. + +Usage: + python proxy_server.py [--port PORT] [--host HOST] + +Then open http://localhost:5000 in your browser. +""" + +import base64 +import builtins +import json +import os +import re +import sys +import traceback +from urllib.parse import urlencode, urlparse, urljoin, quote, unquote, parse_qs, urlunparse + +from flask import Flask, request, Response, render_template_string, jsonify, redirect +import requests as http_requests + +from utils.constants.macros import CONFIG_FILE, DEFAULT_DEBUG_MODE +from utils.structs import BaseElement +from utils.tools.args import get_config +from utils.tools.cdm import init_cdm, close_cdm +from utils.tools.common import get_base_url +from utils.tools.service import get_service, get_all_services + +# --------------------------------------------------------------------------- +# Flask app +# --------------------------------------------------------------------------- +app = Flask(__name__) + +# Cache extracted data so we don't re-extract on every segment request +_manifest_cache: dict = {} # url -> {manifest_url, manifest_type, keys, headers, additional} + +# Default headers used when proxying requests +_PROXY_HEADERS = { + "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", + "Accept": "*/*", + "Accept-Language": "en-US,en;q=0.9", + "Origin": None, + "Referer": None, +} + + +# --------------------------------------------------------------------------- +# Initialise widefrog config (once) +# --------------------------------------------------------------------------- +def _init_widefrog(): + """Perform the same first-time setup as widefrog.py.""" + if hasattr(builtins, "CONFIG"): + return + args = [] + builtins.CONFIG = get_config(args) + builtins.CONFIG["QUERY"] = { + "MIN": {"COLLECTION": None, "ELEMENT": None}, + "MAX": {"COLLECTION": None, "ELEMENT": None}, + } + builtins.CONFIG["DEBUG_MODE"] = DEFAULT_DEBUG_MODE + builtins.SERVICES = get_all_services() + # Override to skip downloads + builtins.CONFIG["DOWNLOAD_COMMANDS"]["WAIT_BEFORE_DOWNLOADING"] = None + + +# --------------------------------------------------------------------------- +# Extraction helpers +# --------------------------------------------------------------------------- +def _extract_manifest(content_url: str) -> dict: + """Use the widefrog service layer to get manifest + keys for *content_url*.""" + if content_url in _manifest_cache: + return _manifest_cache[content_url] + + _init_widefrog() + + service = get_service(content_url) + if service is None: + raise ValueError(f"No service found for URL: {content_url}") + + service_instance = service + source_element = BaseElement(url=content_url) + + # --- get_video_data returns (manifest, pssh, additional) --- + manifest, pssh, additional = service_instance.get_video_data(source_element) + + # Normalise manifest to list of (url, name) + if not isinstance(manifest, list): + manifest = [(manifest, None)] + if len(manifest) == 0: + manifest = [(None, None)] + + # Normalise pssh + if not isinstance(pssh, list): + pssh = [pssh] + + # Determine manifest type + manifest_url = None + for m_url, m_name in manifest: + if m_url: + manifest_url = m_url + break + + if manifest_url is None: + raise ValueError("No manifest URL could be extracted") + + manifest_type = "unknown" + if ".m3u8" in manifest_url.split("?")[0].lower() or "m3u8" in manifest_url.lower(): + manifest_type = "hls" + elif ".mpd" in manifest_url.split("?")[0].lower() or "mpd" in manifest_url.lower(): + manifest_type = "dash" + elif ".ism" in manifest_url.split("?")[0].lower(): + manifest_type = "smooth" + else: + # Try to sniff from content + try: + resp = http_requests.get(manifest_url, timeout=10) + ct = resp.headers.get("Content-Type", "").lower() + body = resp.text[:500].lower() + if "#extm3u" in body: + manifest_type = "hls" + elif "<mpd" in body or "dash" in body: + manifest_type = "dash" + except: + pass + + # Get decryption keys (for informational purposes / ClearKey) + is_hls_aes = additional.get("AES", None) is not None if isinstance(additional, dict) else False + keys = [] + if not is_hls_aes: + for p in pssh: + if p is None: + continue + try: + cdm, cdm_session_id, challenge = init_cdm(p) + if cdm is None: + continue + keys += close_cdm( + cdm, cdm_session_id, + service_instance.get_keys(challenge, additional.get(p, additional) if isinstance(additional, dict) else additional) + ) + except Exception: + pass + keys = list(set(keys)) + + result = { + "manifest_url": manifest_url, + "all_manifests": [(m, n) for m, n in manifest if m], + "manifest_type": manifest_type, + "keys": keys, + "is_hls_aes": is_hls_aes, + "aes_info": additional.get("AES", None) if isinstance(additional, dict) else None, + "additional": additional if isinstance(additional, dict) else {}, + "title": source_element.element or "video", + } + _manifest_cache[content_url] = result + return result + + +# --------------------------------------------------------------------------- +# URL rewriting helpers +# --------------------------------------------------------------------------- +def _proxy_url(target_url: str, route: str = "/proxy/resource") -> str: + """Build a proxy URL pointing to our server.""" + return f"{route}?url={quote(target_url, safe='')}" + + +def _resolve_url(base_url: str, relative: str) -> str: + """Resolve a possibly-relative URL against a base.""" + if relative.startswith("http://") or relative.startswith("https://"): + return relative + return urljoin(base_url, relative) + + +def _rewrite_m3u8(content: str, base_url: str) -> str: + """Rewrite all URLs in an HLS manifest so they go through our proxy.""" + lines = content.split("\n") + result = [] + for line in lines: + stripped = line.strip() + if not stripped: + result.append(line) + continue + + # Rewrite URI="..." in tags like #EXT-X-KEY, #EXT-X-MAP, etc. + if stripped.startswith("#"): + def _rewrite_uri(m): + uri = m.group(1) + absolute = _resolve_url(base_url, uri) + return f'URI="{_proxy_url(absolute)}"' + rewritten = re.sub(r'URI="([^"]*)"', _rewrite_uri, stripped, flags=re.IGNORECASE) + result.append(rewritten) + else: + # This is a URL line (segment or sub-playlist) + absolute = _resolve_url(base_url, stripped) + result.append(_proxy_url(absolute)) + return "\n".join(result) + + +def _make_base_proxy_url(original_base_url: str) -> str: + """Encode a base URL into a path-based proxy prefix. + + Shaka-player resolves relative segment URLs against the manifest URL. + By injecting a <BaseURL> that uses a path-based route like + /proxy/b/<encoded_base>/, relative URLs naturally resolve to + /proxy/b/<encoded_base>/segment.dash which our handler proxies + to original_base + segment.dash. + """ + b = base64.urlsafe_b64encode(original_base_url.encode()).decode().rstrip("=") + return f"/proxy/b/{b}/" + + +def _rewrite_mpd(content: str, base_url: str) -> str: + """Rewrite URLs in a DASH MPD manifest to go through our proxy. + + Strategy: + - Replace / inject <BaseURL> so that *relative* segment URLs + resolve through our path-based proxy (/proxy/b/<base64>/). + - Rewrite any *absolute* URLs in media/initialization attributes + of SegmentTemplate. + """ + has_base_url = bool(re.search(r"<BaseURL[^>]*>", content, re.IGNORECASE)) + + if has_base_url: + # Rewrite existing <BaseURL> elements + def _rewrite_baseurl(m): + url = m.group(1).strip() + if url and (url.startswith("http://") or url.startswith("https://")): + resolved = url if url.endswith("/") else url + "/" + return f"<BaseURL>{_make_base_proxy_url(resolved)}</BaseURL>" + elif url: + absolute = _resolve_url(base_url, url) + if not absolute.endswith("/"): + absolute += "/" + return f"<BaseURL>{_make_base_proxy_url(absolute)}</BaseURL>" + return m.group(0) + content = re.sub(r"<BaseURL>(.*?)</BaseURL>", _rewrite_baseurl, content, flags=re.DOTALL) + else: + # No BaseURL exists — inject one right after <MPD ...> + proxy_base = _make_base_proxy_url(base_url) + content = re.sub( + r'(<MPD[^>]*>)', + rf'\1\n <BaseURL>{proxy_base}</BaseURL>', + content, + count=1, + ) + + # Rewrite absolute URLs in SegmentTemplate media/initialization attributes + for attr in ["media", "initialization"]: + def _rewrite_attr(m, attr_name=attr): + url = m.group(1) + if url.startswith("http://") or url.startswith("https://"): + return f'{attr_name}="{_proxy_url(url)}"' + return m.group(0) + content = re.sub( + rf'{attr}="(https?://[^"]*)"', + _rewrite_attr, + content, + flags=re.IGNORECASE, + ) + + return content + + +# --------------------------------------------------------------------------- +# API Routes +# --------------------------------------------------------------------------- +@app.route("/") +def index(): + """Home page with URL input form.""" + return render_template_string(HOME_PAGE_HTML) + + +@app.route("/api/extract", methods=["GET", "POST"]) +def api_extract(): + """Extract manifest info from a content URL (JSON API).""" + if request.method == "POST": + content_url = request.json.get("url", "").strip() + else: + content_url = request.args.get("url", "").strip() + + if not content_url: + return jsonify({"error": "Missing 'url' parameter"}), 400 + + try: + info = _extract_manifest(content_url) + return jsonify({ + "manifest_url": info["manifest_url"], + "proxied_manifest_url": _proxy_url(info["manifest_url"], "/proxy/manifest"), + "manifest_type": info["manifest_type"], + "keys": info["keys"], + "is_hls_aes": info["is_hls_aes"], + "title": info["title"], + }) + except Exception as e: + traceback.print_exc() + return jsonify({"error": str(e)}), 500 + + +@app.route("/play") +def play(): + """Player page — extracts manifest and renders an HTML5 video player.""" + content_url = request.args.get("url", "").strip() + if not content_url: + return redirect("/") + + try: + info = _extract_manifest(content_url) + except Exception as e: + traceback.print_exc() + return render_template_string(ERROR_PAGE_HTML, error=str(e), url=content_url), 500 + + proxied_manifest = request.host_url.rstrip("/") + _proxy_url(info["manifest_url"], "/proxy/manifest") + + return render_template_string( + PLAYER_PAGE_HTML, + manifest_url=proxied_manifest, + original_manifest_url=info["manifest_url"], + manifest_type=info["manifest_type"], + keys=info["keys"], + title=info["title"], + content_url=content_url, + is_hls_aes=info["is_hls_aes"], + ) + + +@app.route("/proxy/manifest") +def proxy_manifest(): + """Fetch a manifest, rewrite its URLs, and return it.""" + target_url = request.args.get("url", "") + if not target_url: + return "Missing url parameter", 400 + + target_url = unquote(target_url) + headers = {k: v for k, v in _PROXY_HEADERS.items() if v is not None} + headers["User-Agent"] = builtins.CONFIG.get("USER_AGENT", headers["User-Agent"]) if hasattr(builtins, "CONFIG") else headers["User-Agent"] + + try: + resp = http_requests.get(target_url, headers=headers, timeout=30) + except Exception as e: + return f"Failed to fetch manifest: {e}", 502 + + content_type = resp.headers.get("Content-Type", "") + body = resp.text + + # Determine base URL for relative resolution + base_url = target_url.rsplit("/", 1)[0] + "/" + + # Detect type and rewrite + if "#EXTM3U" in body or "m3u8" in target_url.lower() or "mpegurl" in content_type.lower(): + body = _rewrite_m3u8(body, base_url) + content_type = "application/vnd.apple.mpegurl" + elif "<MPD" in body or "mpd" in target_url.lower() or "dash" in content_type.lower(): + body = _rewrite_mpd(body, base_url) + content_type = "application/dash+xml" + + return Response( + body, + content_type=content_type, + headers={ + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": "GET, OPTIONS", + "Access-Control-Allow-Headers": "*", + "Cache-Control": "no-cache", + }, + ) + + +@app.route("/proxy/resource") +def proxy_resource(): + """Generic proxy for segments, keys, init data, sub-playlists, etc.""" + target_url = request.args.get("url", "") + if not target_url: + return "Missing url parameter", 400 + + target_url = unquote(target_url) + headers = {k: v for k, v in _PROXY_HEADERS.items() if v is not None} + headers["User-Agent"] = builtins.CONFIG.get("USER_AGENT", headers["User-Agent"]) if hasattr(builtins, "CONFIG") else headers["User-Agent"] + + # Forward range headers for segment requests + if "Range" in request.headers: + headers["Range"] = request.headers["Range"] + + try: + resp = http_requests.get(target_url, headers=headers, timeout=60, stream=True) + except Exception as e: + return f"Failed to fetch resource: {e}", 502 + + content_type = resp.headers.get("Content-Type", "application/octet-stream") + resp_body = resp.content + + # If this is a sub-playlist (m3u8 inside m3u8), rewrite it too + is_m3u8 = ( + "mpegurl" in content_type.lower() + or target_url.lower().split("?")[0].endswith(".m3u8") + ) + try: + if is_m3u8 or (resp_body[:7] == b"#EXTM3U"): + text = resp_body.decode("utf-8", errors="replace") + base_url = target_url.rsplit("/", 1)[0] + "/" + text = _rewrite_m3u8(text, base_url) + resp_body = text.encode("utf-8") + content_type = "application/vnd.apple.mpegurl" + except: + pass + + # If this is a DASH sub-manifest + is_mpd = "dash" in content_type.lower() or target_url.lower().split("?")[0].endswith(".mpd") + try: + if is_mpd: + text = resp_body.decode("utf-8", errors="replace") + if "<MPD" in text: + base_url = target_url.rsplit("/", 1)[0] + "/" + text = _rewrite_mpd(text, base_url) + resp_body = text.encode("utf-8") + content_type = "application/dash+xml" + except: + pass + + resp_headers = { + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": "GET, OPTIONS", + "Access-Control-Allow-Headers": "*", + } + if "Content-Range" in resp.headers: + resp_headers["Content-Range"] = resp.headers["Content-Range"] + + return Response( + resp_body, + status=resp.status_code, + content_type=content_type, + headers=resp_headers, + ) + + +@app.route("/proxy/b/<base_b64>/<path:subpath>") +def proxy_base_resource(base_b64, subpath): + """Path-based proxy: resolves *subpath* relative to the decoded base URL. + + This is used by DASH manifests where <BaseURL> is set to + /proxy/b/<encoded_base>/ so that relative segment URLs like + "segment-video=400000.dash" naturally resolve here. + """ + # Decode the base URL + padding = 4 - len(base_b64) % 4 + if padding != 4: + base_b64 += "=" * padding + try: + decoded_base = base64.urlsafe_b64decode(base_b64).decode() + except Exception: + return "Invalid base encoding", 400 + + target_url = decoded_base + subpath + + # Preserve query string from the original request + if request.query_string: + target_url += "?" + request.query_string.decode() + + headers = {k: v for k, v in _PROXY_HEADERS.items() if v is not None} + if hasattr(builtins, "CONFIG"): + headers["User-Agent"] = builtins.CONFIG.get("USER_AGENT", headers["User-Agent"]) + + if "Range" in request.headers: + headers["Range"] = request.headers["Range"] + + try: + resp = http_requests.get(target_url, headers=headers, timeout=60, stream=True) + except Exception as e: + return f"Failed to fetch: {e}", 502 + + content_type = resp.headers.get("Content-Type", "application/octet-stream") + resp_body = resp.content + + # If the response is a sub-manifest (m3u8 or mpd), rewrite it + try: + if b"#EXTM3U" in resp_body[:20]: + text = resp_body.decode("utf-8", errors="replace") + text_base = target_url.rsplit("/", 1)[0] + "/" + text = _rewrite_m3u8(text, text_base) + resp_body = text.encode("utf-8") + content_type = "application/vnd.apple.mpegurl" + elif b"<MPD" in resp_body[:500]: + text = resp_body.decode("utf-8", errors="replace") + text_base = target_url.rsplit("/", 1)[0] + "/" + text = _rewrite_mpd(text, text_base) + resp_body = text.encode("utf-8") + content_type = "application/dash+xml" + except Exception: + pass + + resp_headers = { + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": "GET, OPTIONS", + "Access-Control-Allow-Headers": "*", + } + if "Content-Range" in resp.headers: + resp_headers["Content-Range"] = resp.headers["Content-Range"] + + return Response( + resp_body, + status=resp.status_code, + content_type=content_type, + headers=resp_headers, + ) + + +@app.after_request +def add_cors(response): + """Add CORS headers to all responses.""" + response.headers["Access-Control-Allow-Origin"] = "*" + response.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS" + response.headers["Access-Control-Allow-Headers"] = "*" + return response + + +# --------------------------------------------------------------------------- +# HTML Templates +# --------------------------------------------------------------------------- +HOME_PAGE_HTML = r""" +<!DOCTYPE html> +<html lang="en"> +<head> +<meta charset="UTF-8"> +<meta name="viewport" content="width=device-width, initial-scale=1.0"> +<title>WideFrog Proxy Player + + + +
+

WideFrog Proxy

+

Paste a video URL from a supported service to play it in your browser.

+
+ + +
+
Extracting manifest… this may take a moment.
+
+

You can also use the API directly:

+

GET /api/extract?url=CONTENT_URL

+

GET /proxy/manifest?url=MANIFEST_URL

+
+
+ + + +""" + +PLAYER_PAGE_HTML = r""" + + + + + +{{ title }} — WideFrog Player + + + + + +
+ ← WideFrog Proxy + {{ title }} +
+ +
+ + + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
Initializing player…
+ +
+
Type: {{ manifest_type | upper }}
+
Original manifest: {{ original_manifest_url[:120] }}{% if original_manifest_url|length > 120 %}…{% endif %}
+
Proxied manifest: {{ manifest_url[:120] }}{% if manifest_url|length > 120 %}…{% endif %}
+ {% if keys %} +
Decryption keys: + {% for k in keys %} +
  {{ k }}
+ {% endfor %} +
+ {% endif %} +
+
+ + + + +""" + +ERROR_PAGE_HTML = r""" + + + + +Error — WideFrog Proxy + + + +
+

Extraction Failed

+

{{ url }}

+
{{ error }}
+

← Back

+
+ + +""" + +# --------------------------------------------------------------------------- +# Main +# --------------------------------------------------------------------------- +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="WideFrog Proxy Player") + parser.add_argument("--host", default="127.0.0.1", help="Host to bind (default: 127.0.0.1)") + parser.add_argument("--port", type=int, default=5000, help="Port to bind (default: 5000)") + parser.add_argument("--debug", action="store_true", help="Enable Flask debug mode") + cli_args = parser.parse_args() + + # Pre-init widefrog + _init_widefrog() + + print(f"\n WideFrog Proxy Player") + print(f" Open http://{cli_args.host}:{cli_args.port} in your browser\n") + + app.run(host=cli_args.host, port=cli_args.port, debug=cli_args.debug, threaded=True) diff --git a/API/proxiesembed/drmproxy/requirements.txt b/API/proxiesembed/drmproxy/requirements.txt new file mode 100644 index 0000000..6a7d303 --- /dev/null +++ b/API/proxiesembed/drmproxy/requirements.txt @@ -0,0 +1,19 @@ +beautifulsoup4 +html5lib +browser_cookie3 +numpy +pycountry +Requests +Unidecode +xmltodict +curl_cffi +chompjs +isodate +slugify +cryptography +m3u8 +cf_clearance +playwright +pywidevine +protobuf +flask \ No newline at end of file diff --git a/API/proxiesembed/drmproxy/services/_35mm_online.py b/API/proxiesembed/drmproxy/services/_35mm_online.py new file mode 100644 index 0000000..5e130ae --- /dev/null +++ b/API/proxiesembed/drmproxy/services/_35mm_online.py @@ -0,0 +1,358 @@ +import builtins +import json +from os.path import join +from urllib.parse import unquote + +import requests +import xmltodict + +import utils.tools.cdm as cdm_tools +from utils.constants.macros import ERR_MSG, USER_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename, get_ext_from_url, update_url_params, rand_str, clean_url + + +class _35mm_online(BaseService): + DEMO_URLS = [ + "https://35mm.online/search?page=3&search_tag.2=tag_3441&__NodeTypeAlias.2=asset%2Cseries&__productionYear.4=1972%2C2001", + "https://35mm.online/search?page=1&searchPhrase.3=test&__NodeTypeAlias.2=asset%2Cseries&__productionYear.4=1940%2C2024", + "https://35mm.online/vod/animacja/fobia", + "https://35mm.online/vod/dla-dzieci/reksio/reksio/reksio-reksio-czyscioch", + "https://35mm.online/vod/dokument/prom", + "https://35mm.online/vod/fabula/zycie-raz-jeszcze", + "https://35mm.online/fonoteka/muzyka/muzyka-ludowa/karnawalowa-polka", + "https://35mm.online/vod/dla-dzieci/reksio", + "https://35mm.online/vod/dla-dzieci/pampalini", + ] + + CONTENT_URL = 'https://cms.35mm.online/umbraco/api/content' + PLAYLIST_URL = 'https://cms.35mm.online/umbraco/api/products/{content_id}/videos/playlist' + SEARCH_URL = 'https://cms.35mm.online/umbraco/api/search' + BASE_URL = "https://35mm.online" + + PAGE_SIZE = 48 + LANGUAGE = 'pl-pl' + + @staticmethod + def test_service(): + main_service.run_service(_35mm_online) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def initialize_service(): + return _35mm_online + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post(additional["license_url"], data=challenge) + if licence.status_code == 500: + message = json.loads(licence.content.decode()).get("message", "").lower() + if "error" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=additional["URL"], + reason="Cannot download paid content", + solution="Do not attempt to download paid content" + )) + + licence.raise_for_status() + return licence.content + + @staticmethod + def get_init_from_mpd(mpd_url): + mpd_content = requests.get(mpd_url).content.decode() + mpd_content = xmltodict.parse(mpd_content)["MPD"] + base_url = mpd_content["BaseURL"] + mpd_content = mpd_content["Period"] + + if type(mpd_content["AdaptationSet"]) is not list: + mpd_content["AdaptationSet"] = [mpd_content["AdaptationSet"]] + + best_content = None + best_height = None + best_bandwidth = None + for content in mpd_content["AdaptationSet"]: + if content["@contentType"] != "video": + continue + update_content = False + + height = content.get("@maxHeight", content.get("@height", None)) + if height is None: + continue + height = int(height) + bandwidth = content.get("@maxBandwidth", content.get("@bandwidth", None)) + + if best_content is None: + update_content = True + else: + if height > best_height: + update_content = True + elif height == best_height: + if bandwidth is not None: + if best_bandwidth is None: + update_content = True + elif int(bandwidth) > int(best_bandwidth): + update_content = True + + if update_content: + best_content = content + best_height = height + best_bandwidth = bandwidth + + mpd_content = best_content + init_url = mpd_content["SegmentTemplate"]["@initialization"] + if type(mpd_content["Representation"]) is not list: + mpd_content["Representation"] = [mpd_content["Representation"]] + + best_content = None + for content in mpd_content["Representation"]: + if best_content is None: + best_content = content + continue + if int(content["@height"]) > int(best_content["@height"]): + best_content = content + continue + elif int(content["@height"]) == int(best_content["@height"]): + if int(content["@bandwidth"]) > int(best_content["@bandwidth"]): + best_content = content + continue + + init_url = init_url.replace("$RepresentationID$", best_content["@id"]) + init_url = init_url.replace("$Bandwidth$", best_content["@bandwidth"]) + init_url = base_url + init_url + return init_url + + @staticmethod + def get_pssh_from_manifest(manifest): + return cdm_tools.get_pssh_from_init(_35mm_online.get_init_from_mpd(manifest)) + + @staticmethod + def get_video_data(source_element): + if source_element.additional is None: + source_element.additional = {} + if source_element.additional.get("CACHE_RESULT", None) is not None: + return source_element.additional["CACHE_RESULT"] + + response = json.loads(requests.get(_35mm_online.CONTENT_URL, headers={ + 'x-origin-url': source_element.url, + 'x-language': 'x-language' + }).content.decode()) + content = response["content"] + content_id = content.get("atdId", None) + + if content_id is None: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + if source_element.element is None: + element_name = content.get("title", None) + if element_name is None: + element_name = source_element.url.split(_35mm_online.BASE_URL)[1] + source_element.element = get_valid_filename(element_name) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + _35mm_online.__name__[1:] + ) + + response = requests.get( + _35mm_online.PLAYLIST_URL.format(content_id=content_id), + params={'platform': 'BROWSER', 'videoType': 'MOVIE'} + ) + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + + err_msg = response.get("code", "").lower() + if status_code == 404 and "not_exists" in err_msg: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + additional = {"URL": source_element.url} + for d in response["drm"]: + if "widevine" not in d.lower(): + continue + additional["license_url"] = response["drm"][d]["src"] + break + + manifest = None + for s in response["sources"]: + if "dash" not in s.lower(): + continue + manifest = response["sources"][s][0]["src"] + if "https:" not in manifest: + manifest = manifest.replace("//", "https://") + break + + subtitles = [] + index = 0 + for subtitle in response.get("subtitles", []): + index += 1 + url = subtitle["url"] + if "https:" not in url: + url = url.replace("//", "https://") + srt_ext = get_ext_from_url(url) + + subtitles.append((False, BaseElement( + url=url, + collection=join(source_element.collection, source_element.element), + element=f'subtitle_{index}_{subtitle["language"]}{srt_ext}' + ))) + additional["SUBTITLES"] = subtitles + + pssh_value = _35mm_online.get_pssh_from_manifest(manifest) + return manifest, pssh_value, additional + + @staticmethod + def get_collection_elements(collection_url): + collection_url = collection_url.rstrip("#").rstrip("/") + if "/vod/" in collection_url or "/fonoteka/" in collection_url: + collection_url = clean_url(collection_url) + response = requests.get( + _35mm_online.CONTENT_URL, + headers={ + 'x-origin-url': collection_url, + 'x-language': _35mm_online.LANGUAGE + } + ) + + response = response.content.decode() + response = json.loads(response) + response = response.get("content", None) + if response in ["", None, {}]: + return [BaseElement(url=collection_url)] + + try: + seasons = response["seasonsModel"]["seasons"] + assert type(seasons) is list and len(seasons) > 0 + except: + seasons = [] + if len(seasons) == 0: + return [BaseElement(url=collection_url)] + + try: + check_element = BaseElement(url=collection_url) + check_result = _35mm_online.get_video_data(check_element) + check_element.additional = {"CACHE_RESULT": check_result} + return [check_element] + except CustomException as e: + if "Reason: The content isn't available" not in str(e): + raise e + + collection_title = response.get("title", None) + if collection_title in ["", None]: + collection_title = collection_url.split("/")[-1] + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + _35mm_online.__name__[1:] + ), + get_valid_filename(collection_title) + ) + + season_index = 0 + collection = [] + for season in seasons: + season_index += 1 + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + season_title = season.get("title", "") + season_title = get_valid_filename(f'Rail {season_index} {season_title}') + episode_index = 0 + + for episode in season.get("episodes", []): + episode_index += 1 + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + episode_title = episode.get("title", "") + episode_title = get_valid_filename(f'Episode_{episode_index} {episode_title}') + episode_url = _35mm_online.BASE_URL + episode["url"] + + collection.append(BaseElement( + url=episode_url, + collection=join(collection_title, season_title), + element=get_valid_filename(episode_title) + )) + + return collection + + if "/search?" in collection_url: + collection_title = unquote(collection_url).split("?")[1] + collection_title = get_valid_filename(collection_title) + collection_title = "Filters_" + collection_title[0:40] + "_" + rand_str(5) + collection_title = join(join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + _35mm_online.__name__[1:]), collection_title + ) + + collection = [] + param_url = collection_url + page = 0 + + while True: + page += 1 + check = check_range(True, page, None) + if check is True: + continue + elif check is False: + return collection + + param_url = update_url_params(param_url, { + "page": page, "limit": _35mm_online.PAGE_SIZE + }) + page_url = _35mm_online.SEARCH_URL + "?" + param_url.split("?")[1] + page_url = unquote(page_url) + + response = json.loads(requests.get( + page_url, headers={ + 'x-origin-url': collection_url, + 'x-language': _35mm_online.LANGUAGE + } + ).content.decode()) + if len(response.get("records", [])) == 0: + break + + record_index = 0 + for record in response["records"]: + record_index += 1 + check = check_range(False, page, record_index) + if check is True: + continue + elif check is False: + return collection + + record_url = record["url"] + record_title = get_valid_filename(record["title"]) + + if not record_url.startswith(_35mm_online.BASE_URL): + record_url = _35mm_online.BASE_URL + record_url + + collection.append(BaseElement( + url=record_url, + collection=join(collection_title, f'Page_{page}'), + element=f"Video_{record_index}_{record_title}" + )) + + return collection + return None diff --git a/API/proxiesembed/drmproxy/services/__init__.py b/API/proxiesembed/drmproxy/services/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/API/proxiesembed/drmproxy/services/adtv_ae.py b/API/proxiesembed/drmproxy/services/adtv_ae.py new file mode 100644 index 0000000..5e9b3d3 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/adtv_ae.py @@ -0,0 +1,235 @@ +import builtins +import json +import re +import time +from os.path import join +from urllib.parse import urlparse, urlunparse, parse_qs + +import requests + +from utils.constants.macros import USER_ERROR, ERR_MSG +from utils.main_service import main_service +from utils.structs import BaseElement, CustomException, BaseService +from utils.tools.args import check_range + + +class adtv_ae(BaseService): + DEMO_URLS = [ + "https://adtv.ae/en/shows?media=%D8%A7%D9%84%D8%AC%D8%A7%D8%B1-%D9%84%D9%84%D8%AC%D8%A7%D8%B1&video_external_id=228029_page&externalContentId=228029_page&externalSeriesId=228029&type=Series", + "https://adtv.ae/en/shows?media=%D8%A7%D9%84%D8%A5%D8%AE%D8%AA%D9%8A%D8%A7%D8%B1&video_external_id=27799990&externalContentId=216885&externalSeriesId=216884&type=Series&externalSeasonId=216885", + "https://adtv.ae/en/shows?media=%D8%A7%D9%84%D9%86%D9%85%D8%B1&video_external_id=220820_page&externalContentId=220820_page&externalSeriesId=220820&type=Series", + "https://adtv.ae/en/sports?media=%D8%B9%D8%A7%D9%84%D9%85-%D8%A7%D9%84%D8%AC%D9%8A%D9%88%D8%AC%D9%8A%D8%AA%D8%B3%D9%88&video_external_id=%D8%B9%D8%A7%D9%84%D9%85+%D8%A7%D9%84%D8%AC%D9%8A%D9%88%D8%AC%D9%8A%D8%AA%D8%B3%D9%88&externalContentId=%D8%B9%D8%A7%D9%84%D9%85+%D8%A7%D9%84%D8%AC%D9%8A%D9%88%D8%AC%D9%8A%D8%AA%D8%B3%D9%88&externalSeriesId=229231&type=Series", + "https://adtv.ae/en/shows/216884/Al%20Ekhteyar/season-2/episode-28", + "https://adtv.ae/en/sports?media=%D8%A7%D9%84%D8%B3%D8%B9%D9%8A-%D9%84%D8%AA%D8%AD%D9%82%D9%8A%D9%82-%D8%A7%D9%84%D8%AD%D9%84%D9%85&video_external_id=229450_page&externalContentId=229450_page&externalSeriesId=229450&type=Series", + "https://adtv.ae/en/shows/wasaya%20al%20sabbar-series/Wasaya%20Al-Sabbar/season-1/episode-2", + "https://adtv.ae/ar/shows/216884/%D8%A7%D9%84%D8%A5%D8%AE%D8%AA%D9%8A%D8%A7%D8%B1/season-2/episode-26", + "https://adtv.ae/ar/watch?video_external_id=LP00050096&assetExternalId=LP00050096&externalContentId=LP00050096&type=Movie&media=%D8%A3%D8%B7%D9%84%D8%A7%D9%84-%D9%88%D8%AD%D8%B6%D8%A7%D8%B1%D8%A9", + "https://adtv.ae/en/watch?video_external_id=27884199&assetExternalId=27884199&externalContentId=27884199&type=Movie&media=%D8%B5%D8%B1%D8%A7%D8%B9-%D9%81%D9%89-%D8%A7%D9%84%D9%86%D9%8A%D9%84", + "https://adtv.ae/en/shows/229775/follow%20the%20wind/season-1/episode-14777", + "https://adtv.ae/en/shows/HeadCoachSeries/HeadCoachSeries/season-1/episode-11", + "https://adtv.ae/en/sports/FinalScoreSeries/Final%20Score/season-1/episode-5", + ] + + CONFIG_URL = 'https://adtv.ae/api/biz/config/v1/config' + INFO_URL = 'https://adtv.ae/api/biz/video{path}/playinfo' + DETAIL_URL = 'https://adtv.ae/api/biz/video/aggregate/detail' + EPISODE_URL = '{base_url}/season-{season_index}/episode-{episode_index}' + + USER_AGENT = None + LICENSE_RETRIES = 3 + + @staticmethod + def test_service(): + main_service.run_service(adtv_ae) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def initialize_service(): + if adtv_ae.USER_AGENT is None: + adtv_ae.USER_AGENT = builtins.CONFIG["USER_AGENT"] + return adtv_ae + + @staticmethod + def get_keys(challenge, additional): + licence = None + for i in range(1, adtv_ae.LICENSE_RETRIES + 1): + try: + licence = requests.post( + additional["license_url"], data=challenge, + params={"token": additional["token"]}, + headers={'User-Agent': adtv_ae.USER_AGENT} + ) + licence.raise_for_status() + break + except Exception as e: + response = e.response + if response.status_code == 403: + if i < adtv_ae.LICENSE_RETRIES: + time.sleep(1) + continue + raise e + + return licence.content + + @staticmethod + def get_content_info(source_element): + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + adtv_ae.__name__ + ) + + if "/shows/" in source_element.url or "/sports" in source_element.url: + if "/shows" in source_element.url: + ext_id = re.findall(r'/shows/([^/]*)/', source_element.url)[0] + else: + ext_id = re.findall(r'/sports/([^/]*)/', source_element.url)[0] + season_id = re.findall(r'/season-(\d+)', source_element.url)[0] + + response = json.loads(requests.get( + adtv_ae.DETAIL_URL, headers={'User-Agent': adtv_ae.USER_AGENT}, + params={ + 'type': 'Series', 'client': 'json', + 'externalSeriesId': ext_id + } + ).content.decode())["response"]["tvShowSeasons"] + + for season in response: + if season["seasonNumber"] == int(season_id): + ext_id = season["externalId"] + + ep_id = re.findall(r'/episode-(\d+)', source_element.url)[0] + path, url_params = "/episode", { + 'season_external_id': ext_id, + 'episode_number': ep_id, + 'client': 'json' + } + + if source_element.element is None: + name = ext_id + if not name.isnumeric(): + name = "".join([str(ord(c)) for c in name])[0:10] + source_element.element = f"SeasonId_{name}_Episode_{ep_id}" + elif "/watch?" in source_element.url: + query_params = parse_qs(urlparse(source_element.url).query) + for p in ["assetExternalId", "externalContentId"]: + ext_id = query_params.get(p, []) + if len(ext_id) > 0: + ext_id = ext_id[0] + break + path, url_params = "", {'asset_external_id': ext_id} + if source_element.element is None: + source_element.element = f"VideoId_{ext_id}" + else: + raise + return path, url_params + + @staticmethod + def get_video_data(source_element): + try: + app_locale = [re.findall(r'/([a-zA-Z]{2})/', source_element.url)[0]] + except: + app_locale = ["en", "ae"] + + license_url = json.loads(requests.get( + adtv_ae.CONFIG_URL, headers={'User-Agent': adtv_ae.USER_AGENT} + ).content.decode())["response"]["widevine_licenser_vod"] + license_url = urlparse(license_url) + license_url = urlunparse(( + license_url.scheme, license_url.netloc, + license_url.path, '', '', '' + )) + + path, url_params = adtv_ae.get_content_info(source_element) + manifest, token = None, None + + for locale in app_locale: + try: + response = json.loads(requests.get( + adtv_ae.INFO_URL.format(path=path), headers={ + 'User-Agent': adtv_ae.USER_AGENT, + 'App-Locale': locale + }, + params=url_params + ).content.decode())["response"] + manifest, token = response["url"], response["token"] + break + except: + continue + + if manifest is None: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + try: + pssh_value = str(min(re.findall( + r']*>(.*?)', + requests.get(manifest).content.decode() + ), key=len)) + except: + return manifest, None, {} + return manifest, pssh_value, { + "token": token, "license_url": license_url + } + + @staticmethod + def get_collection_elements(collection_url): + if (("/shows/" in collection_url or "/sports" in collection_url) + and "/season-" in collection_url and "/episode-" in collection_url): + return [BaseElement(url=collection_url)] + if "/watch?" in collection_url: + return [BaseElement(url=collection_url)] + + if ("/shows?" in collection_url or "/sports?" in collection_url) and "externalSeriesId=" in collection_url: + collection = [] + external_series_id = parse_qs(urlparse(collection_url).query)["externalSeriesId"][0] + + seasons = json.loads(requests.get( + adtv_ae.DETAIL_URL, headers={'User-Agent': adtv_ae.USER_AGENT}, + params={ + 'type': 'Series', 'contentType': 'Series', + 'client': 'json', 'externalSeriesId': external_series_id + } + ).content.decode())["response"]["tvShowSeasons"] + + seasons = sorted(seasons, key=lambda s: s["seasonNumber"]) + seasons = [s for s in seasons if s["seasonNumber"] > 0] + + for season in seasons: + check = check_range(True, season["seasonNumber"], None) + if check is True: + continue + elif check is False: + return collection + + for ep_index in range(1, season["numberOfEpisodes"] + 1): + check = check_range(False, season["seasonNumber"], ep_index) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=adtv_ae.EPISODE_URL.format( + base_url=season["shareLink"], + season_index=str(season["seasonNumber"]), + episode_index=str(ep_index) + ), + collection=join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + adtv_ae.__name__ + ), + join(f"Series_{external_series_id}", f"Season_{season['seasonNumber']}") + ), + element=f"Episode_{ep_index}" + )) + return collection + return None diff --git a/API/proxiesembed/drmproxy/services/adultswim_com.py b/API/proxiesembed/drmproxy/services/adultswim_com.py new file mode 100644 index 0000000..8d72354 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/adultswim_com.py @@ -0,0 +1,888 @@ +import builtins +import json +import os +import re +from copy import deepcopy +from os.path import join + +import m3u8 +import requests +from bs4 import BeautifulSoup + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename, clean_url, get_public_ip + + +class adultswim_com(BaseService): + DEMO_URLS = [ + "https://www.adultswim.com/videos/specials/mother-may-i-dance-with-mary-janes-fist-a-lifetone-original-movie", + "https://www.adultswim.com/videos/12-oz-mouse/corndog-chronicles", + "https://www.adultswim.com/videos/common-side-effects/pilot", + "https://www.adultswim.com/videos/apollo-gauntlet/eros", + "https://www.adultswim.com/videos/dragon-ball-z-kai/a-boundary-pushing-brawl-goku-frieza-and-ginyu-again", + "https://www.adultswim.com/videos/toonami/toonami-music-video-koko-v", + + "https://www.adultswim.com/videos/aqua-teen-hunger-force", + "https://www.adultswim.com/videos/rick-and-morty", + "https://www.adultswim.com/videos/12-oz-mouse", + "https://www.adultswim.com/videos/music-videos", + "https://www.adultswim.com/videos/promos", + ] + + VIDEO_API_URL = 'https://www.adultswim.com/api/shows/v1/videos/{video_id}' + MEDIA_URL = 'https://medium.ngtv.io/v2/media/{media_id}/desktop' + LICENSE_URL = "https://widevine.license.istreamplanet.com/widevine/api/license/e1b9076f-e876-436d-ba0a-d0fac24ff03e" + DRM_TOKEN_URL = 'https://token.ngtv.io/token/token_isp' + GRAPHQL_URL = 'https://api.adultswim.com/v1' + APP_ID_URL = 'https://www.adultswim.com/videos/smalls' + + APP_ID = None + PUBLIC_IP = None + SHA256 = { + "ShowPage": "bd4268978154f8418a63abb1571627cb322078e30d1ba2409b93d1e45d5648ed", + "ShowExtras": "73ef922a385ce12855326cde2523273fed37347ea39e9549977247aa1a40eec0", + "ShowClips": "f960692d22ecbd51f90be300cc61e30ac3ec847a54e833d196b2c1101b79ca91" + } + + @staticmethod + def test_service(): + main_service.run_service(adultswim_com) + + @staticmethod + def get_additional_params(additional): + additional_params = BaseService.get_additional_params(additional) + if additional.get("FORWARD_IP", False) is True: + additional_params = [( + ("HEADER", lambda s: s.format(key="X-Forwarded-For", value=adultswim_com.PUBLIC_IP)) + )] + additional_params + return additional_params + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def get_app_id(): + response = requests.get(adultswim_com.APP_ID_URL).text + response = re.findall(r'[\'"](http[^\'"]*auth[^\'"]*\.js)[\'"]', response, re.IGNORECASE) + response = requests.get(response[0]).text + response = re.findall(r'withServiceAppId\([\'"]([^\'"]+)[\'"]', response) + return response[0] + + @staticmethod + def initialize_service(): + if adultswim_com.APP_ID is None: + adultswim_com.APP_ID = adultswim_com.get_app_id() + + if adultswim_com.PUBLIC_IP is None: + if builtins.CONFIG.get("BASIC", False) is True: + adultswim_com.PUBLIC_IP = "" + else: + adultswim_com.PUBLIC_IP = get_public_ip() + + if adultswim_com.PUBLIC_IP is None: + raise CustomException(ERR_MSG.format( + type=f'{APP_ERROR}', + url=f'from the {adultswim_com.__name__} service', + reason="Failed to obtain the public IP", + solution="Fix the code responsible for obtaining the IP" + )) + return adultswim_com + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + adultswim_com.LICENSE_URL, data=challenge, + headers={"x-isp-token": additional["drm_token"]} + ) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_best_res_from_m3u8(m3u8_object): + best_res = 0 + for segment in m3u8_object.playlists + m3u8_object.media: + try: + res = int(segment.stream_info.resolution[1]) + if res > best_res: + best_res = res + except: + pass + return best_res + + @staticmethod + def get_free_stream(free_streams, min_height): + free_streams = free_streams["assets"] + assert type(free_streams) is list and len(free_streams) > 0 + + best_streams = [] + for free_stream in free_streams: + try: + assert free_stream["mime_type"].lower() in ["application/x-mpegurl"] + assert clean_url(free_stream["url"]).endswith(".m3u8") + bitrate = int(free_stream["bitrate"]) + assert bitrate > 0 + + height = adultswim_com.get_best_res_from_m3u8( + m3u8.loads(requests.get(free_stream["url"]).text) + ) + assert height >= min_height > 0 + best_streams.append((free_stream["url"], height, bitrate)) + break + except: + pass + + best_streams = sorted(best_streams, key=lambda st: (-st[1], -st[2])) + return best_streams[0][0] + + @staticmethod + def fix_relative_url(relative_url, absolute_url): + dots = relative_url.count("../") + temp_base_url = absolute_url.split("/") + temp_base_url = temp_base_url[0:len(temp_base_url) - dots] + temp_base_url = "/".join(temp_base_url) + + relative_url = relative_url.replace("../", "") + if not relative_url.startswith("/"): + relative_url = "/" + relative_url + relative_url = temp_base_url + relative_url + return relative_url + + @staticmethod + def split_manifest(manifest_object, manifest_url, source_element): + manifest_content = manifest_object.dumps() + try: + pssh_value = re.search(r'base64,([^"]+)"', manifest_content).group(1) + assert len(pssh_value) > 0 + if builtins.CONFIG.get("BASIC", False) is True: + return manifest_url, pssh_value + except: + pssh_value = None + + manifest_segments = {} + parts_counter = None + track_index = 0 + + base_url = clean_url(manifest_url).split("/") + del base_url[-1] + base_url = "/".join(base_url) + + for segment in manifest_object.playlists + manifest_object.media: + segment_url = segment.uri + if segment_url is None: + continue + if manifest_segments.get(segment_url, None) is not None: + continue + if not segment_url.startswith("http"): + segment_url = adultswim_com.fix_relative_url(segment_url, base_url) + + track_content = requests.get(segment_url).text + if pssh_value is None: + try: + pssh_value = re.search(r'base64,([^"]+)"', track_content).group(1) + assert len(pssh_value) > 0 + if builtins.CONFIG.get("BASIC", False) is True: + return manifest_url, pssh_value + except: + pssh_value = None + + current_parts = track_content.count("#EXT-X-MAP:") + if parts_counter is None: + parts_counter = current_parts + else: + assert parts_counter == current_parts + init_m3u8 = track_content.split("#EXT-X-MAP:")[0] + end_m3u8 = "#EXT-X-ENDLIST" + m3u8_maps = [ + f'#EXT-X-MAP:{m.strip()}' + for m in track_content.split('#EXT-X-MAP:')[1:] if m.strip() + ] + + segment_base_url = clean_url(segment_url).split("/") + del segment_base_url[-1] + segment_base_url = "/".join(segment_base_url) + part_m3u8s = [] + + for m in m3u8_maps: + part_m3u8 = list(reversed(m.splitlines())) + ext_index = 0 + while "#ext-x-" in part_m3u8[ext_index].lower(): + ext_index += 1 + part_m3u8 = "\n".join(list(reversed(part_m3u8[ext_index:]))) + part_m3u8 = f'{init_m3u8}\n{part_m3u8}\n{end_m3u8}' + + part_m3u8 = m3u8.loads(part_m3u8) + for part_segment in part_m3u8.media + part_m3u8.segments: + if part_segment.uri is None: + continue + if not part_segment.uri.startswith("http"): + part_segment.uri = adultswim_com.fix_relative_url(part_segment.uri, segment_base_url) + try: + if not part_segment.init_section.uri.startswith("http"): + part_segment.init_section.uri = adultswim_com.fix_relative_url( + part_segment.init_section.uri, segment_base_url + ) + except: + pass + + part_m3u8 = part_m3u8.dumps() + part_m3u8s.append(part_m3u8) + track_index += 1 + manifest_segments[segment.uri] = {"url": segment_url, "parts": part_m3u8s, "index": track_index} + + assert pssh_value is not None + if parts_counter == 1: + return manifest_url, pssh_value + output_path = join(source_element.collection, source_element.element) + + visited = [] + master_paths = [] + z_width = len(str(parts_counter)) + for part_index in range(0, parts_counter): + master_name = f"Part_{str(part_index + 1).zfill(z_width)}" + master_path = join(str(output_path), master_name) + if not os.path.exists(master_path): + os.makedirs(master_path) + + temp_manifest_object = deepcopy(manifest_object) + for segment in temp_manifest_object.playlists + temp_manifest_object.media: + segment_url = segment.uri + if segment_url is None: + continue + segment_dict = manifest_segments.get(segment_url, None) + if segment_dict is None: + continue + + segment_url = f"track_{segment_dict['index']}_part_{part_index + 1}.m3u8" + if segment_url not in visited: + visited.append(segment_url) + with open(join(master_path, segment_url), "w") as f: + f.write(segment_dict["parts"][part_index]) + segment.uri = segment_url + + master_path = join(master_path, f'master.m3u8') + with open(master_path, "w") as f: + f.write(temp_manifest_object.dumps()) + master_paths.append((master_path, master_name)) + return master_paths, pssh_value + + @staticmethod + def get_apollo_state(page_text): + try: + soup = BeautifulSoup(page_text, 'html5lib') + script = soup.find_all('script', {'type': 'application/json'}) + script = [s for s in script if s.get("id", None) == "__NEXT_DATA__"][0] + + script = json.loads(script.string) + page_content = script["props"]["pageProps"]["__APOLLO_STATE__"] + assert type(page_content) is dict + except: + page_content = {} + return page_content + + @staticmethod + def get_video_data(source_element): + if source_element.additional is None: + source_element.additional = {} + video_slug = source_element.url.split("/")[-1] + video_id, video_content = source_element.additional.get("id", None), None + + if video_id in ["", None]: + response = requests.get(source_element.url) + if response.status_code < 200 or response.status_code >= 300: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Don't attempt to download it" + )) + page_content = adultswim_com.get_apollo_state(response.text) + + for page_k, page_v in page_content.items(): + if type(page_v) is not dict: + continue + + if "videocollection" in page_k.lower(): + for col_k, col_v in page_v.items(): + try: + check = re.search(fr'[\'"]slug[\'"]:[\'"]{video_slug}[\'"]', col_k) + assert check is not None + + assert ":" in col_v["id"] + video_id = col_v["id"].split(":")[1] + assert len(video_id) > 0 + video_content = col_v + break + except: + video_id, video_content = None, None + + if video_id is not None: + break + try: + assert ":" in page_k + assert page_v["slug"] == video_slug + + video_id = page_k.split(":")[1] + assert len(video_id) > 0 + video_content = page_v + break + except: + video_id, video_content = None, None + + if video_content is None: + video_content = {} + if video_id in ["", None]: + show_slug = source_element.url.split("/")[-2] + response = requests.get( + adultswim_com.GRAPHQL_URL, + params={ + "operationName": "ShowPage", + "variables": json.dumps({"show": show_slug, "video": video_slug}), + "extensions": json.dumps({ + "persistedQuery": {"version": 1, "sha256Hash": adultswim_com.SHA256["ShowPage"]} + }) + } + ) + response = json.loads(response.content.decode())["data"]["show"]["collection"]["video"] + video_id = response["id"] + video_content = response + + assert video_id not in ["", None] + if source_element.element is None: + title = video_content.get("title", None) + if title not in ["", None]: + for f in ["seasonNumber", "episodeNumber"]: + try: + i = int(video_content[f]) + assert i > 0 + title += " " + f[0] + str(i) + except: + pass + + source_element.element = get_valid_filename(title) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + adultswim_com.__name__ + ) + + response = requests.get( + adultswim_com.VIDEO_API_URL.format(video_id=video_id), + params={ + "fields": ",".join([ + "title", "type", "duration", "collection_title", "stream", + "title_id", "auth", "media_id", "season_number", "episode_number" + ]) + }) + status_code = response.status_code + response = response.content.decode() + + response = json.loads(response) + error_code = response.get("errorCode", None) + if status_code in [404] or error_code in [404]: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Don't attempt to download it" + )) + + response = response["data"]["video"] + if source_element.element is None: + title = video_content.get("title", None) + if title in ["", None]: + title = video_slug + if response.get("collection_title", None) not in ["", None]: + title = response["collection_title"] + " " + title + + for f in ["season_number", "episode_number"]: + try: + i = int(response[f]) + assert i > 0 + title += " " + f[0] + str(i) + except: + pass + source_element.element = get_valid_filename(title) + + free_streams = response.get("stream", None) + media_id = response["media_id"] + if media_id in ["", None]: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Don't attempt to download it" + )) + + response = requests.get( + adultswim_com.MEDIA_URL.format(media_id=media_id), + params={"appId": adultswim_com.APP_ID} + ) + response = response.content.decode() + response = json.loads(response) + try: + error = response["error"]["error"].lower() + assert len(error) > 0 and type(error) is str + except: + error = "" + + if "does not exist" in error and "mediaid" in error: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Don't attempt to download it" + )) + + response = response["media"]["desktop"] + try: + manifest_url = response["unprotected"]["unencrypted"]["url"] + assert type(manifest_url) is str and len(manifest_url) > 0 + except: + manifest_url = None + + if manifest_url is not None: + status_code = requests.head(manifest_url, allow_redirects=False).status_code + if status_code < 200 or 300 <= status_code: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need American IP to access content", + solution="Use a VPN" + )) + return manifest_url, None, {"FORWARD_IP": True} + + try: + response = response["widevine"]["cenc"] + manifest_url = response["url"] + assert type(manifest_url) is str and len(manifest_url) > 0 + except: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine wasn't found", + solution="Do not attempt to download it" + )) + + check_url = clean_url(manifest_url) + if not check_url.endswith(".m3u8"): + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {check_url}", + solution=f"Extend the {adultswim_com.__name__} service" + )) + asset_id = response["assetId"] + assert asset_id not in ["", None] + + response = requests.get( + adultswim_com.DRM_TOKEN_URL, + params={ + 'appId': adultswim_com.APP_ID, 'format': 'json', + 'assetId': asset_id, 'mediaId': media_id + } + ) + response = response.content.decode() + response = json.loads(response) + try: + err_msg = response["auth"]["error"] + err_msg = err_msg.get("msg", err_msg.get("message", "")).lower() + assert len(err_msg) > 0 and type(err_msg) is str + except: + err_msg = "" + + if "invalid asset id" in err_msg or "invalid media asset" in err_msg: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Don't attempt to download it" + )) + if "content blocked" in err_msg and "location" in err_msg: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need American IP to access content", + solution="Use a VPN" + )) + if "authentication token" in err_msg: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available without a TV provider account", + solution="Do not attempt to download it" + )) + + manifest_object = m3u8.loads(requests.get(manifest_url).text) + min_res = adultswim_com.get_best_res_from_m3u8(manifest_object) + if min_res == 0: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need American IP to access content", + solution="Use a VPN (that is not detected)" + )) + try: + return adultswim_com.get_free_stream(free_streams, min_res), None, {"FORWARD_IP": True} + except: + pass + + additional = {"drm_token": response["jwt"]} + try: + manifest_url, pssh_value = adultswim_com.split_manifest(manifest_object, manifest_url, source_element) + except: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {check_url}", + solution=f"Extend the {adultswim_com.__name__} service" + )) + return manifest_url, pssh_value, additional + + @staticmethod + def handle_seasons_episodes(collection_url, page_content, collection_title): + videos = [] + season_max = None + extra_cursor = None + extra_contents = [] + past_urls = [] + + for page_k, page_v in page_content.items(): + if extra_cursor is None: + try: + assert "VideoCollection" in page_k and page_k.split(".")[-1] == "pageInfo" + assert len(page_v["endCursor"]) > 0 and type(page_v["endCursor"]) is str + assert page_v["hasNextPage"] is True + extra_cursor = page_v["endCursor"] + except: + extra_cursor = None + + try: + season_index = int(page_v["seasonNumber"]) + if season_max is None or season_index > season_max: + season_max = season_index + except: + season_index = None + try: + episode_index = int(page_v["episodeNumber"]) + except: + episode_index = None + + try: + video_id = page_v.get("id", None) + if video_id in ["", None]: + video_id = page_k.split(":")[1] + assert video_id not in ["", None] + + for f in [":", ".", "{", "}"]: + assert f not in video_id + except: + continue + if season_index is None and episode_index is None: + try: + assert "VideoCollection" not in page_k + for f in ["seasonNumber", "episodeNumber"]: + assert page_v[f] is None + extra_contents.append(page_v) + except: + pass + continue + videos.append((season_index, episode_index, video_id, page_v)) + + if season_max is None: + season_max = 1 + else: + season_max += 1 + temp_videos = [] + season_dict = {} + + for season_index, episode_index, video_id, video_info in videos: + if season_index is None: + season_index = season_max + + if episode_index is not None: + if season_dict.get(season_index, None) is None: + season_dict[season_index] = episode_index + elif episode_index > season_dict[season_index]: + season_dict[season_index] = episode_index + temp_videos.append((season_index, episode_index, video_id, video_info)) + videos = temp_videos + + temp_videos = [] + for season_index, episode_index, video_id, video_info in videos: + if episode_index is None: + episode_index = season_dict.get(season_index, 0) + 1 + season_dict[season_index] = episode_index + temp_videos.append((season_index, episode_index, video_id, video_info)) + videos = temp_videos + + videos = sorted(videos, key=lambda e: (e[0], e[1])) + collection = [] + visited = [] + rail_index = 0 + rail_extras_index = 1 + + for season_index, episode_index, video_id, video_info in videos: + if season_index not in visited: + visited.append(season_index) + rail_index += 1 + rail_extras_index += 1 + + video_url = collection_url + "/" + video_info["slug"] + if video_url in past_urls: + continue + else: + past_urls.append(video_url) + + check = check_range(True, rail_index, None) + if check is True: + continue + elif check is False: + return collection, True, None + + check = check_range(False, rail_index, episode_index) + if check is True: + continue + elif check is False: + return collection, True, None + + video_title = video_info.get("title", None) + if video_title in ["", None]: + video_title = video_info["slug"] + + collection.append(BaseElement( + url=video_url, + collection=join(collection_title, f'Rail_{rail_index}'), + element=get_valid_filename(f"Video_{episode_index} {video_title}"), + additional={"id": video_id} + )) + + return collection, False, (rail_extras_index, extra_contents, extra_cursor) + + @staticmethod + def handle_extras(collection, show_slug, collection_url, collection_title, extra_tuple): + rail_extras_index, extra_contents, extra_cursor = extra_tuple + check = check_range(True, rail_extras_index, None) + if check is True: + return collection, False + elif check is False: + return collection, True + + past_urls = [c.url for c in collection] + extra_index = 0 + while True: + response = None + if extra_cursor is not None: + response = requests.get( + adultswim_com.GRAPHQL_URL, + params={ + "operationName": "ShowExtras", + "variables": json.dumps({"show": show_slug, "cursor": extra_cursor}), + "extensions": json.dumps({ + "persistedQuery": {"version": 1, "sha256Hash": adultswim_com.SHA256["ShowExtras"]} + }) + } + ) + + try: + response = json.loads(response.content.decode()) + response = response["data"]["show"]["collection"]["videos"] + extras = response["nodes"] + assert len(extras) > 0 and type(extras) is list + except: + extras = [] + extras = extra_contents + extras + extra_contents = [] + if len(extras) == 0: + break + + for extra in extras: + extra_url = collection_url + "/" + extra["slug"] + if extra_url in past_urls: + continue + else: + past_urls.append(extra_url) + + extra_index += 1 + check = check_range(False, rail_extras_index, extra_index) + if check is True: + continue + elif check is False: + return collection, True + + extra_title = extra.get("title", None) + if extra_title in ["", None]: + extra_title = extra["slug"] + + collection.append(BaseElement( + url=extra_url, + collection=join(collection_title, f'Rail_{rail_extras_index}_Extras'), + element=get_valid_filename(f"Extra_{extra_index} {extra_title}"), + additional={"id": extra['id']} + )) + + try: + response = response["pageInfo"] + assert response["hasNextPage"] is True + extra_cursor = response["endCursor"] + assert len(extra_cursor) > 0 and type(extra_cursor) is str + except: + extra_cursor = None + if extra_cursor is None: + break + return collection, False + + @staticmethod + def handle_clips(collection, show_slug, collection_url, collection_title, rail_clips_index): + past_urls = [c.url for c in collection] + + try: + response = requests.get( + adultswim_com.GRAPHQL_URL, + params={ + "operationName": "ShowClips", + "variables": json.dumps({ + "show": show_slug, + "sort": ["seasonNumber:desc", "episodeNumber:desc", "launchDate:desc", "clipOrder"] + }), + "extensions": json.dumps({ + "persistedQuery": {"version": 1, "sha256Hash": adultswim_com.SHA256["ShowClips"]}} + ) + } + ) + response = json.loads(response.content.decode()) + rail_clips = response["data"]["show"]["collection"]["seasons"]["nodes"] + assert len(rail_clips) > 0 and type(rail_clips) is list + except: + rail_clips = [] + + rail_clips_index -= 1 + for rail_clip in rail_clips: + rail_clips_index += 1 + check = check_range(True, rail_clips_index, None) + if check is True: + continue + elif check is False: + return collection + + season_number = rail_clip["number"] + clips_index = 0 + clips_cursor = None + while True: + variables = { + "season": season_number, "show": show_slug, + "sort": ["seasonNumber:desc", "episodeNumber:desc", "launchDate:desc", "clipOrder"] + } + if clips_cursor is not None: + variables["cursor"] = clips_cursor + + response = requests.get( + adultswim_com.GRAPHQL_URL, + params={ + "operationName": "ShowClips", + "variables": json.dumps(variables), + "extensions": json.dumps({ + "persistedQuery": {"version": 1, "sha256Hash": adultswim_com.SHA256["ShowClips"]} + }) + } + ) + try: + response = json.loads(response.content.decode()) + response = response["data"]["show"]["collection"]["clips"] + except: + break + + try: + clips = response["nodes"] + assert len(clips) > 0 and type(clips) is list + except: + clips = [] + + for clip in clips: + clip_url = collection_url + "/" + clip["slug"] + if clip_url in past_urls: + continue + else: + past_urls.append(clip_url) + + clips_index += 1 + check = check_range(False, rail_clips_index, clips_index) + if check is True: + continue + elif check is False: + return collection + + clips_title = clip.get("title", None) + if clips_title in ["", None]: + clips_title = clip["slug"] + + collection.append(BaseElement( + url=clip_url, + collection=join(collection_title, f'Rail_{rail_clips_index}_Clips_{season_number}'), + element=get_valid_filename(f"Clip_{clips_index} {clips_title}"), + additional={"id": clip['id']} + )) + try: + response = response["pageInfo"] + assert response["hasNextPage"] is True + clips_cursor = response["endCursor"] + assert len(clips_cursor) > 0 and type(clips_cursor) is str + except: + clips_cursor = None + if clips_cursor is None: + break + return collection + + @staticmethod + def get_collection_elements(collection_url): + collection_url = clean_url(collection_url).rstrip("/") + if "/videos/" not in collection_url: + return None + + slash_count = collection_url.split("/videos/")[1].count("/") + if slash_count == 1: + return [BaseElement(url=collection_url)] + if slash_count > 0: + return None + + response = requests.get(collection_url) + if response.status_code < 200 or response.status_code >= 300: + return [] + page_content = adultswim_com.get_apollo_state(response.text) + show_slug = collection_url.split("/")[-1] + try: + collection_title = page_content[show_slug]["title"] + except: + collection_title = show_slug + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + adultswim_com.__name__ + ), + get_valid_filename(collection_title) + ) + + collection, return_flag, extra_tuple = adultswim_com.handle_seasons_episodes( + collection_url, page_content, collection_title + ) + if return_flag: + return collection + + rail_extras_index, extra_contents, extra_cursor = extra_tuple + rail_clips_index = rail_extras_index + if len(extra_contents) > 0 or extra_cursor is not None: + rail_clips_index += 1 + + collection, return_flag = adultswim_com.handle_extras( + collection, show_slug, collection_url, collection_title, extra_tuple + ) + if return_flag: + return collection + + collection = adultswim_com.handle_clips( + collection, show_slug, collection_url, collection_title, rail_clips_index + ) + return collection diff --git a/API/proxiesembed/drmproxy/services/aloula_sa.py b/API/proxiesembed/drmproxy/services/aloula_sa.py new file mode 100644 index 0000000..1b9c4e6 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/aloula_sa.py @@ -0,0 +1,161 @@ +import builtins +import json +import re +from os.path import join + +import requests + +from utils.constants.macros import ERR_MSG, USER_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range + + +class aloula_sa(BaseService): + DEMO_URLS = [ + "https://www.aloula.sa/en/title/1090", + "https://www.aloula.sa/title/1129", + "https://www.aloula.sa/episode/24387", + "https://www.aloula.sa/episode/11164", + ] + + PLAYER_URL = 'https://aloula.faulio.com/api/v1/video/{video_id}/player' + PROJECT_URL = "https://aloula.faulio.com/api/v1.1/project/{title_id}" + PAGE_URL = 'https://aloula.faulio.com/api/v1/video?page={page}&season={season}' + EPISODE_URL = "https://www.aloula.sa/episode/{episode}" + + ORIGIN = "https://www.aloula.sa" + + @staticmethod + def test_service(): + main_service.run_service(aloula_sa) + + @staticmethod + def get_additional_params(additional): + return [ + ("HEADER", lambda s: s.format(key="Origin", value=aloula_sa.ORIGIN)) + ] + BaseService.get_additional_params(additional) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def initialize_service(): + return aloula_sa + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + additional["license_url"], data=challenge, + headers={"Origin": aloula_sa.ORIGIN} + ) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_video_data(source_element): + video_id = re.search(r"/episode/([^/]+)", source_element.url).group(1) + if source_element.element is None: + source_element.element = f"EpisodeId_{video_id}" + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + aloula_sa.__name__ + ) + + response = json.loads(requests.get( + aloula_sa.PLAYER_URL.format(video_id=video_id), + headers={'Origin': aloula_sa.ORIGIN} + ).content.decode())["settings"] + if response is None: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available anymore", + solution="Do not attempt to download it" + )) + + manifest = response["protocols"]["dash"] + try: + license_url = response["drm"]["license"] + + pssh_value = str(min(re.findall( + r']*>(.*?)', + requests.get(manifest, headers={"Origin": aloula_sa.ORIGIN}).content.decode() + ), key=len)) + except: + return manifest, None, {} + return manifest, pssh_value, {"license_url": license_url} + + @staticmethod + def get_collection_elements(collection_url): + if "/episode/" in collection_url: + return [BaseElement(url=collection_url)] + + if "/title/" in collection_url: + title_id = re.search(r"/title/([^/]+)", collection_url).group(1) + collection = [] + response = json.loads(requests.get( + aloula_sa.PROJECT_URL.format(title_id=title_id), + collection_url + ).content.decode()) + + if "not_found" in response.get("message", "") or "not_found" in response.get("cms_error", ""): + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="The content isn't available anymore", + solution="Do not attempt to download it" + )) + + visited = [] + for block in response["blocks"]: + if block.get("seasons", None) is None: + continue + + block["seasons"] = sorted(block["seasons"], key=lambda s: s['order']) + for season in block["seasons"]: + check = check_range(True, season["order"], None) + if check is True: + continue + elif check is False: + return collection + + last_page = json.loads(requests.get( + aloula_sa.PAGE_URL.format(page=0, season=season["id"]), + ).content.decode())["blocks"][0]["paging"]["last_page"] + page = last_page + 1 + + while True: + page -= 1 + episodes = json.loads(requests.get( + aloula_sa.PAGE_URL.format(page=page, season=season["id"]), + ).content.decode())["blocks"][0] + + episodes["projects"] = sorted(episodes["projects"], key=lambda e: e["episode"]) + for episode in episodes["projects"]: + check = check_range(False, season["order"], episode['episode']) + if check is True: + continue + elif check is False: + return collection + + if episode["id"] in visited: + continue + visited.append(episode["id"]) + collection.append(BaseElement( + url=aloula_sa.EPISODE_URL.format(episode=episode["id"]), + collection=join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + aloula_sa.__name__ + ), + join(f"Title_{title_id}", f"Season_{season['order']}") + ), + element=f"Episode_{episode['episode']}" + )) + if page <= 0: + break + return collection + return None diff --git a/API/proxiesembed/drmproxy/services/app_nzrplus_com.py b/API/proxiesembed/drmproxy/services/app_nzrplus_com.py new file mode 100644 index 0000000..5b2ead0 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/app_nzrplus_com.py @@ -0,0 +1,581 @@ +import builtins +import json +import os +import re +import threading +from os.path import join + +import m3u8 +import requests + +from utils.constants.macros import ERR_MSG, USER_ERROR, CACHE_DIR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.cdm import get_pssh_from_default_kid +from utils.tools.common import clean_url, get_valid_filename, dict_to_file, file_to_dict + + +class app_nzrplus_com(BaseService): + DEMO_URLS = [ + "https://app.nzrplus.com/video/642249", + "https://app.nzrplus.com/video/526149?playlistId=25137", + "https://app.nzrplus.com/playlist/25137", + "https://app.nzrplus.com/playlist/17076", + "https://app.nzrplus.com/section/BlackFerns", + "https://app.nzrplus.com/section/AllBlacks", + ] + + BUCKETS_URL = 'https://dce-frontoffice.imggaming.com/api/v4/content/{section_id}' + BUCKET_VODS_URL = 'https://dce-frontoffice.imggaming.com/api/v4/content/{section_id}/bucket/{bucket_id}' + PLAYLIST_URL = 'https://dce-frontoffice.imggaming.com/api/v4/playlist/{playlist_id}' + REALM_URL = 'https://dce-frontoffice.imggaming.com/api/v1/init/' + LOGIN_URL = 'https://dce-frontoffice.imggaming.com/api/v2/login' + REFRESH_URL = 'https://dce-frontoffice.imggaming.com/api/v2/token/refresh' + VOD_URL = 'https://dce-frontoffice.imggaming.com/api/v4/vod/{vod_id}' + BASE_URL = "https://app.nzrplus.com" + VIDEO_URL = BASE_URL + "/video/{vod_id}" + + EMAIL = "YOUR_EMAIL" + PASSWORD = "YOUR_PASSWORD" + SITE_DICT = None + CACHE_FILE = None + LOCK = None + DRM_INFO = "eyJzeXN0ZW0iOiJjb20ud2lkZXZpbmUuYWxwaGEifQ==" + PAGE_SIZE = 25 + BUCKET_SIZE = 10 + + @staticmethod + def test_service(): + main_service.run_service(app_nzrplus_com) + + @staticmethod + def get_additional_params(additional): + add_params = BaseService.get_additional_params(additional) + if additional.get("USE_BASE_URL", False) is True: + add_params += [("BASE_URL", lambda s: s.format(value=additional["MANIFEST_URL"]))] + return add_params + + @staticmethod + def credentials_needed(): + return { + "EMAIL": app_nzrplus_com.EMAIL, + "PASSWORD": app_nzrplus_com.PASSWORD + } + + @staticmethod + def set_site_dict(): + try: + file_dict = file_to_dict(app_nzrplus_com.CACHE_FILE) + assert len(file_dict.keys()) == 4 + app_nzrplus_com.SITE_DICT = file_dict + return True + except: + pass + + class_name = app_nzrplus_com.__name__.replace("_", ".") + credentials = builtins.CONFIG["SERVICE_CREDENTIALS"][class_name] + try: + assert type(credentials["EMAIL"]) is str + assert type(credentials["PASSWORD"]) is str + except: + return None + + response = requests.get(app_nzrplus_com.BASE_URL).content.decode() + app_js = re.findall(r'src="([^"]*app\.js)"', response)[0] + if app_js[0] != "/": + app_js = "/" + app_js + app_js = app_nzrplus_com.BASE_URL + app_js + response = requests.get(app_js).content.decode() + realm_api_key = re.findall(r'API_KEY:"([^"]+)"', response)[0] + + response = requests.get( + app_nzrplus_com.REALM_URL, + headers={ + 'x-api-key': realm_api_key, + 'Origin': app_nzrplus_com.BASE_URL + } + ) + response = response.content.decode() + response = json.loads(response) + realm_id = response["settings"]["realm"] + + response = requests.post( + app_nzrplus_com.LOGIN_URL, + headers={ + 'x-api-key': realm_api_key, 'Realm': realm_id, + 'Authorization': f'Bearer {response["authentication"]["authorisationToken"]}' + }, + json={ + 'id': credentials["EMAIL"], + 'secret': credentials["PASSWORD"] + } + ) + response = response.content.decode() + response = json.loads(response) + message = str(response.get("messages", [])).lower() + if response.get("status", "") in [404] and response.get("code", "").lower() in ["not_found"]: + if "failedauthentication" in message: + return None + + site_dict = { + "REALM_ID": realm_id, + "REALM_API_KEY": realm_api_key, + "AUTH_TOKEN": response["authorisationToken"], + "REFRESH_TOKEN": response["refreshToken"] + } + dict_to_file(app_nzrplus_com.CACHE_FILE, site_dict) + app_nzrplus_com.SITE_DICT = site_dict + return True + + @staticmethod + def initialize_service(): + if app_nzrplus_com.CACHE_FILE is None: + app_nzrplus_com.CACHE_FILE = join(CACHE_DIR, f'{app_nzrplus_com.__name__}.json') + if builtins.CONFIG.get("FRESH", False) is True: + dict_to_file(app_nzrplus_com.CACHE_FILE, {}) + + if app_nzrplus_com.SITE_DICT is None: + flag = app_nzrplus_com.set_site_dict() + if flag is None: + return flag + if app_nzrplus_com.LOCK is None: + app_nzrplus_com.LOCK = threading.Lock() + return app_nzrplus_com + + @staticmethod + def refresh_account_tokens(source_url): + old_auth_token = app_nzrplus_com.SITE_DICT["AUTH_TOKEN"] + with app_nzrplus_com.LOCK: + if old_auth_token == app_nzrplus_com.SITE_DICT["AUTH_TOKEN"]: + response = requests.post( + app_nzrplus_com.REFRESH_URL, + headers={ + 'realm': app_nzrplus_com.SITE_DICT["REALM_ID"], + 'x-api-key': app_nzrplus_com.SITE_DICT["REALM_API_KEY"], + 'Authorization': f'Bearer {app_nzrplus_com.SITE_DICT["AUTH_TOKEN"]}' + }, + json={'refreshToken': app_nzrplus_com.SITE_DICT["REFRESH_TOKEN"]} + ) + response = response.content.decode() + response = json.loads(response) + + if response.get("authorisationToken", None) in ["", None]: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_url, + reason="Can't access the video content because the cached information expired", + solution=f'Delete the {app_nzrplus_com.CACHE_FILE} cache manually or add the parameter --fresh to your command' + )) + + app_nzrplus_com.SITE_DICT["AUTH_TOKEN"] = response["authorisationToken"] + dict_to_file(app_nzrplus_com.CACHE_FILE, app_nzrplus_com.SITE_DICT) + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + additional["license_url"], + headers={ + 'Authorization': f'Bearer {additional["drm_token"]}', + 'X-DRM-INFO': app_nzrplus_com.DRM_INFO + }, + data=challenge + ) + licence.raise_for_status() + return licence.content + + @staticmethod + def generate_master_file(output_path, manifest, manifest_type, manifest_content): + if not os.path.exists(output_path): + os.makedirs(output_path) + + if manifest_type not in ["hls"]: + output_path = join(output_path, "master.mpd") + with open(output_path, "w") as f: + f.write(manifest_content) + return output_path + + base_url = clean_url(manifest).split("/") + del base_url[-1] + base_url = "/".join(base_url) + + manifest_content = m3u8.loads(manifest_content) + for segment in manifest_content.playlists + manifest_content.media + manifest_content.segments: + if not segment.uri.startswith("http"): + if segment.uri.startswith("/"): + segment.uri = ".." + segment.uri + + dots = segment.uri.count("../") + temp_base_url = base_url.split("/") + temp_base_url = temp_base_url[0:len(temp_base_url) - dots] + temp_base_url = "/".join(temp_base_url) + + segment.uri = segment.uri.replace("../", "") + if not segment.uri.startswith("/"): + segment.uri = "/" + segment.uri + segment.uri = temp_base_url + segment.uri + + output_path = join(output_path, "master.m3u8") + with open(output_path, "w") as f: + f.write(manifest_content.dumps()) + return output_path + + @staticmethod + def get_video_data(source_element): + vod_id = re.search(r"/video/([^/?]*)", source_element.url).group(1) + response = {} + + for i in range(0, 2): + response = requests.get( + app_nzrplus_com.VOD_URL.format(vod_id=vod_id), + params={'includePlaybackDetails': 'URL'}, + headers={ + 'realm': app_nzrplus_com.SITE_DICT["REALM_ID"], + 'x-api-key': app_nzrplus_com.SITE_DICT["REALM_API_KEY"], + 'Authorization': f'Bearer {app_nzrplus_com.SITE_DICT["AUTH_TOKEN"]}' + } + ) + response = response.content.decode() + response = json.loads(response) + + message = str(response.get("messages", [])).lower() + if 400 <= response.get("status", 200) < 500 and " not found" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + if response.get("playerUrlCallback", None) in ["", None]: + if i == 1: + break + app_nzrplus_com.refresh_account_tokens(source_element.url) + continue + break + + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + app_nzrplus_com.__name__ + ) + if source_element.element is None: + title = response.get("title", f'Video_{vod_id}') + info = response.get("episodeInformation", {}) + for f in ["seasonNumber", "episodeNumber"]: + try: + assert info[f] not in ["", None] + title += " " + f[0].upper() + str(info[f]) + except: + pass + source_element.element = get_valid_filename(title) + + response = requests.get(response["playerUrlCallback"]) + response = response.content.decode() + response = json.loads(response) + + manifests = [] + for f in ["hls", "dash"]: + try: + m = response[f] + assert len(m) > 0 + for mt in m: + manifests.append((mt, f)) + except: + pass + + non_drm_manifests = [] + drm_manifests = [] + for m, t in manifests: + m_drm = m.get("drm", None) + if m_drm is None or type(m_drm) is not dict: + non_drm_manifests.append((m, t)) + continue + if m_drm.get("jwtToken", None) is None: + non_drm_manifests.append((m, t)) + continue + + systems = m_drm.get("keySystems", []) + if systems is None or type(systems) is not list: + continue + systems = [s.lower() for s in systems] + if "widevine" in systems: + drm_manifests.append((m, t)) + + additional = {} + pssh_value = None + is_drm = False + if len(non_drm_manifests) > 0: + manifest, manifest_type = non_drm_manifests[0] + else: + if len(drm_manifests) == 0: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine wasn't found", + solution="Do not attempt to download it" + )) + manifest, manifest_type = drm_manifests[0] + additional["license_url"] = manifest["drm"]["url"] + additional["drm_token"] = manifest["drm"]["jwtToken"] + is_drm = True + + manifest = manifest["url"] + manifest_content = requests.get(manifest).content.decode() + if is_drm: + try: + pssh_value = get_pssh_from_default_kid(manifest_content) + except: + pass + + if pssh_value is None: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}", + solution=f"Extend the {app_nzrplus_com.__name__} service" + )) + + additional["USE_BASE_URL"] = manifest_type in ["dash"] + additional["MANIFEST_URL"] = clean_url(manifest) + manifest = app_nzrplus_com.generate_master_file( + join(source_element.collection, source_element.element), + manifest, manifest_type, manifest_content + ) + return manifest, pssh_value, additional + + @staticmethod + def get_playlist(collection_url): + playlist_id = re.search(r"/playlist/([^/?]*)", collection_url).group(1) + response = {} + last_seen = None + collection_title = None + + collection = [] + vod_index = 0 + while True: + playlist_params = {'rpp': app_nzrplus_com.PAGE_SIZE} + if last_seen is not None: + playlist_params["lastSeen"] = last_seen + + for i in range(0, 2): + response = requests.get( + app_nzrplus_com.PLAYLIST_URL.format(playlist_id=playlist_id), + params=playlist_params, + headers={ + 'realm': app_nzrplus_com.SITE_DICT["REALM_ID"], + 'x-api-key': app_nzrplus_com.SITE_DICT["REALM_API_KEY"], + 'Authorization': f'Bearer {app_nzrplus_com.SITE_DICT["AUTH_TOKEN"]}' + } + ) + response = response.content.decode() + response = json.loads(response) + + if response.get("code", None) in ["UNAUTHORIZED"]: + if i == 1: + break + app_nzrplus_com.refresh_account_tokens(collection_url) + continue + break + + vods = response.get("vods", []) + if len(vods) == 0: + break + + if collection_title is None: + collection_title = response.get("title", f'Playlist_{playlist_id}') + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + app_nzrplus_com.__name__ + ), + get_valid_filename(collection_title) + ) + + for vod in vods: + vod_index += 1 + check = check_range(False, None, vod_index) + if check is True: + continue + elif check is False: + return collection + + if vod.get("type", "").lower() not in ["vod"]: + continue + vod_url = app_nzrplus_com.VIDEO_URL.format(vod_id=vod["id"]) + vod_title = vod.get("title", vod["id"]) + vod_title = f'Vod_{vod_index}_{vod_title}' + + collection.append(BaseElement( + url=vod_url, + collection=collection_title, + element=get_valid_filename(vod_title) + )) + + paging = response.get("paging", {}) + if paging in ["", None]: + break + if paging.get("moreDataAvailable", False) in [None, False]: + break + last_seen = paging.get("lastSeen", None) + if last_seen is None: + break + + return collection + + @staticmethod + def get_section(collection_url): + section_id = collection_url.split("/")[-1] + buckets_response = {} + buckets_last_seen = None + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + app_nzrplus_com.__name__ + ), + get_valid_filename(f"Section {section_id}") + ) + + collection = [] + bucket_index = 0 + while True: + buckets_params = { + 'bpp': app_nzrplus_com.BUCKET_SIZE, + 'rpp': app_nzrplus_com.PAGE_SIZE, + 'displaySectionLinkBuckets': 'SHOW', + 'displayEpgBuckets': 'HIDE', + 'displayEmptyBucketShortcuts': 'SHOW', + 'displayContentAvailableOnSignIn': 'SHOW', + 'displayGeoblocked': 'SHOW', + 'bspp': app_nzrplus_com.BUCKET_SIZE + } + if buckets_last_seen is not None: + buckets_params["lastSeen"] = buckets_last_seen + + for i in range(0, 2): + buckets_response = requests.get( + app_nzrplus_com.BUCKETS_URL.format(section_id=section_id), + params=buckets_params, + headers={ + 'realm': app_nzrplus_com.SITE_DICT["REALM_ID"], + 'x-api-key': app_nzrplus_com.SITE_DICT["REALM_API_KEY"], + 'Authorization': f'Bearer {app_nzrplus_com.SITE_DICT["AUTH_TOKEN"]}' + } + ) + buckets_response = buckets_response.content.decode() + buckets_response = json.loads(buckets_response) + + if buckets_response.get("code", None) in ["UNAUTHORIZED"]: + if i == 1: + break + app_nzrplus_com.refresh_account_tokens(collection_url) + continue + break + + buckets = buckets_response.get("buckets", []) + if len(buckets) == 0: + break + + for bucket in buckets: + bucket_index += 1 + check = check_range(True, bucket_index, None) + if check is True: + continue + elif check is False: + return collection + + bucket_type = bucket.get("type", "").lower() + if "vod" not in bucket_type and "video" not in bucket_type: + continue + + bucket_title = bucket.get("name", bucket.get("rowTypeData", {}).get("title", "")) + bucket_title = get_valid_filename(f'Rail {bucket_index} {bucket_title}') + bucket_id = bucket["exid"] + + vods_response = {} + vods_last_seen = None + vod_index = 0 + while True: + vods_params = { + 'rpp': app_nzrplus_com.PAGE_SIZE, + 'displayContentAvailableOnSignIn': 'SHOW', + 'displayGeoblocked': 'SHOW' + } + if vods_last_seen is not None: + vods_params["lastSeen"] = vods_last_seen + + for i in range(0, 2): + vods_response = requests.get( + app_nzrplus_com.BUCKET_VODS_URL.format(section_id=section_id, bucket_id=bucket_id), + params=vods_params, + headers={ + 'realm': app_nzrplus_com.SITE_DICT["REALM_ID"], + 'x-api-key': app_nzrplus_com.SITE_DICT["REALM_API_KEY"], + 'Authorization': f'Bearer {app_nzrplus_com.SITE_DICT["AUTH_TOKEN"]}' + } + ) + vods_response = vods_response.content.decode() + vods_response = json.loads(vods_response) + + if vods_response.get("code", None) in ["UNAUTHORIZED"]: + if i == 1: + break + app_nzrplus_com.refresh_account_tokens(collection_url) + continue + break + + vods = vods_response.get("contentList", []) + if len(vods) == 0: + break + + for vod in vods: + vod_index += 1 + check = check_range(False, bucket_index, vod_index) + if check is True: + continue + elif check is False: + return collection + + if vod.get("type", "").lower() not in ["vod"]: + continue + vod_url = app_nzrplus_com.VIDEO_URL.format(vod_id=vod["id"]) + vod_title = vod.get("title", vod["id"]) + vod_title = f'Vod_{vod_index}_{vod_title}' + + collection.append(BaseElement( + url=vod_url, + collection=join(collection_title, bucket_title), + element=get_valid_filename(vod_title) + )) + + vods_paging = vods_response.get("paging", {}) + if vods_paging in ["", None]: + break + if vods_paging.get("moreDataAvailable", False) in [None, False]: + break + vods_last_seen = vods_paging.get("lastSeen", None) + if vods_last_seen is None: + break + + buckets_paging = buckets_response.get("paging", {}) + if buckets_paging in ["", None]: + break + if buckets_paging.get("moreDataAvailable", False) in [None, False]: + break + buckets_last_seen = buckets_paging.get("lastSeen", None) + if buckets_last_seen is None: + break + + return collection + + @staticmethod + def get_collection_elements(collection_url): + collection_url = clean_url(collection_url) + if "/video/" in collection_url: + return [BaseElement(url=collection_url)] + + if "/playlist/" in collection_url: + return app_nzrplus_com.get_playlist(collection_url) + if "/section/" in collection_url: + return app_nzrplus_com.get_section(collection_url) + return None diff --git a/API/proxiesembed/drmproxy/services/auvio_rtbf_be.py b/API/proxiesembed/drmproxy/services/auvio_rtbf_be.py new file mode 100644 index 0000000..3a3bb19 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/auvio_rtbf_be.py @@ -0,0 +1,554 @@ +import builtins +import json +import os +import re +from os.path import join + +import requests +from unidecode import unidecode + +from utils.constants.macros import USER_ERROR, ERR_MSG, APP_ERROR, CACHE_DIR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename, dict_to_file, file_to_dict, update_url_params + + +class auvio_rtbf_be(BaseService): + DEMO_URLS = [ + "https://auvio.rtbf.be/chaine/musiq3-7", + "https://auvio.rtbf.be/emission/deter-27162", + "https://auvio.rtbf.be/emission/la-theorie-du-y-11043/bonus", + "https://auvio.rtbf.be/widget/22508?context%5BprogramId%5D=8340", + "https://auvio.rtbf.be/widget/19164", + "https://auvio.rtbf.be/emission/le-cactus-4043", + "https://auvio.rtbf.be/emission/l-art-du-crime-27164", + "https://auvio.rtbf.be/media/les-grandes-vacances-de-cowboy-et-indien-les-grandes-vacances-3017947", + "https://auvio.rtbf.be/emission/little-girl-blue-27421", + "https://auvio.rtbf.be/media/l-heure-h-l-heure-h-3198029", + "https://auvio.rtbf.be/live/tipikvision-515396", + ] + + ENTITLEMENT_URL = 'https://exposure.api.redbee.live/v2/customer/RTBF/businessunit/Auvio/entitlement/{content_id}/play' + EMBED_URL = "https://bff-service.rtbf.be/auvio/v1.23/embed/{content_type}/{content_id}" + BOOTSTRAP_URL = 'https://login.auvio.rtbf.be/accounts.webSdkBootstrap' + LOGIN_URL = 'https://login.auvio.rtbf.be/accounts.login' + JWT_URL = 'https://login.auvio.rtbf.be/accounts.getJWT' + GIGYA_URL = 'https://exposure.api.redbee.live/v2/customer/RTBF/businessunit/Auvio/auth/gigyaLogin' + BASE_URL = 'https://auvio.rtbf.be' + + EMAIL = "YOUR_EMAIL" + PASSWORD = "YOUR_PASSWORD" + BEARER_TOKEN = None + CACHE_FILE = None + PAGE_SIZE = 50 + FORMAT_PRIORITY = {"": 0, "mss": 1, "aac": 2, "mp3": 3, "smoothstreaming": 4, "hls": 5, "dash": 6} + + @staticmethod + def test_service(): + main_service.run_service(auvio_rtbf_be) + + @staticmethod + def is_content_livestream(content, additional): + return "/live/" in content or "/chaine/" in content + + @staticmethod + def credentials_needed(): + return { + "EMAIL": auvio_rtbf_be.EMAIL, + "PASSWORD": auvio_rtbf_be.PASSWORD + } + + @staticmethod + def get_api_key(): + app_js = re.findall( + r'src="([^\"]*/[^\"/]app[^\"/]*\.js)"', + requests.get(auvio_rtbf_be.BASE_URL).content.decode() + )[0] + if not app_js.startswith("/"): + app_js = "/" + app_js + app_js = requests.get(auvio_rtbf_be.BASE_URL + app_js).content.decode() + + api_key = re.findall(r'apiKey:"([^\-\"]*)"', app_js)[0] + return api_key + + @staticmethod + def get_bearer_token(): + try: + return file_to_dict(auvio_rtbf_be.CACHE_FILE)["bearer_token"] + except: + pass + + class_name = auvio_rtbf_be.__name__.replace("_", ".") + credentials = builtins.CONFIG["SERVICE_CREDENTIALS"][class_name] + try: + assert type(credentials["EMAIL"]) is str + assert type(credentials["PASSWORD"]) is str + except: + return None + + api_key = auvio_rtbf_be.get_api_key() + response = requests.get( + auvio_rtbf_be.BOOTSTRAP_URL, + params={'apiKey': api_key, 'sdk': 'js_latest', 'format': 'json'} + ) + + gmid = None + response = response.headers["set-cookie"] + for h in response.split(";"): + if h.startswith("gmid="): + gmid = h[5:] + break + assert gmid is not None + + response = requests.post( + auvio_rtbf_be.LOGIN_URL, + cookies={'gmid': gmid}, + data={ + "loginID": credentials["EMAIL"], + "password": credentials["PASSWORD"], + "sessionExpiration": "-2", "targetEnv": "jssdk", "APIKey": api_key, + "sdk": "js_latest", "authMode": "cookie", "format": "json" + } + ).content.decode() + response = json.loads(response) + + status_code = response.get("statusCode", None) + status_reason = response.get("statusReason", "").lower() + message = response.get("errorMessage", "").lower() + if status_code == 403 or "forbidden" in status_reason: + if "locked" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=f'from the {auvio_rtbf_be.__name__} service', + reason="Account is temporarily locked because of too many failed login attempts", + solution="Wait 15 minutes or use another burner account" + )) + if "invalid" in message: + return None + + response = requests.post( + auvio_rtbf_be.JWT_URL, + cookies={'gmid': gmid}, + data={ + 'fields': 'email, firstName, lastName', + 'APIKey': api_key, 'sdk': 'js_latest', + 'login_token': response["sessionInfo"]["login_token"], + 'authMode': 'cookie', 'format': 'json' + } + ).content.decode() + + response = json.loads(response) + response = requests.post( + auvio_rtbf_be.GIGYA_URL, + json={ + 'device': {'deviceId': 'deviceId', 'name': 'Browser', 'type': 'WEB'}, + 'jwt': response["id_token"] + } + ).content.decode() + + bearer_token = json.loads(response)["sessionToken"] + dict_to_file(auvio_rtbf_be.CACHE_FILE, {"bearer_token": bearer_token}) + return bearer_token + + @staticmethod + def initialize_service(): + if auvio_rtbf_be.CACHE_FILE is None: + auvio_rtbf_be.CACHE_FILE = join(CACHE_DIR, f'{auvio_rtbf_be.__name__}.json') + if builtins.CONFIG.get("FRESH", False) is True: + dict_to_file(auvio_rtbf_be.CACHE_FILE, {}) + + if auvio_rtbf_be.BEARER_TOKEN is None: + auvio_rtbf_be.BEARER_TOKEN = auvio_rtbf_be.get_bearer_token() + if auvio_rtbf_be.BEARER_TOKEN is None: + return None + return auvio_rtbf_be + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post(additional["license_url"], data=challenge) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_content_title(content): + try: + data = content["data"] + title = f'{data.get("title", "")}_{data.get("subtitle", "")}' + assert len(title) > 1 + return title + except: + pass + + try: + return content["data"]["program"]["title"] + except: + pass + try: + return content["meta"]["seo"]["title"] + except: + pass + return None + + @staticmethod + def get_collection_info(content): + state = content["props"]["pageProps"]["initialState"] + asset_url = None + + for query in state["api"]["queries"]: + if not query.startswith("page"): + continue + q = state["api"]["queries"][query] + + try: + asset_url = q["data"]["data"]["content"]["media"]["path"] + if not asset_url.startswith("/"): + asset_url = '/' + asset_url + asset_url = auvio_rtbf_be.BASE_URL + asset_url + except: + pass + try: + return q["data"]["data"]["content"]["title"], asset_url + except: + pass + try: + return q["data"]["meta"]["seo"]["title"], asset_url + except: + pass + return None, asset_url + + @staticmethod + def generate_video_m3u8(output_path, manifest_info, content_info): + m3u8_content = "#EXTM3U\n#EXT-X-VERSION:3\n\n" + m3u8_content += f'#EXTINF:{content_info.get("data", {}).get("duration", 1)},\n' + m3u8_content += f'{manifest_info[0]}\n' + + m3u8_content += "#EXT-X-ENDLIST\n" + with open(output_path, "w") as f: + f.write(m3u8_content) + + @staticmethod + def generate_master_m3u8(source_element, manifest_info, content_info): + output_path = str(join(source_element.collection, source_element.element)) + if not os.path.exists(output_path): + os.makedirs(output_path) + m3u8_content = "#EXTM3U\n#EXT-X-VERSION:3\n\n" + + title = f'audio.m3u8' + auvio_rtbf_be.generate_video_m3u8(join(output_path, title), manifest_info, content_info) + m3u8_content += f"#EXT-X-STREAM-INF:BANDWIDTH=1000,TYPE=AUDIO,MIME-TYPE=\"audio/{manifest_info[1]}\"\n" + m3u8_content += f'{title}\n' + + output_path = join(output_path, "master.m3u8") + with open(output_path, "w") as f: + f.write(m3u8_content) + return output_path + + @staticmethod + def get_video_data(source_element): + if '/custom_dict://' in source_element.url: + content_id = source_element.url.split("/custom_dict://")[1].split("_https://")[0] + content_id = json.loads(content_id)["stream_asset_id"] + content_info = {} + + else: + content_id = source_element.url.split("-")[-1] + response = json.loads(requests.get( + auvio_rtbf_be.EMBED_URL.format( + content_type="live" if "/live/" in source_element.url else "media", + content_id=content_id + ), + params={"userAgent": "Chrome-web"} + ).content.decode()) + + content_info = response + if response.get("status", None) == 404 or "not_found" in response.get("code", "").lower(): + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Don't attempt to download it" + )) + + content_id = response["data"]["assetId"] + if source_element.element is None: + title = auvio_rtbf_be.get_content_title(response) + if title is None: + title = source_element.url.split("/")[-1] + source_element.element = get_valid_filename(title) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + auvio_rtbf_be.__name__ + ) + + response = json.loads(requests.get( + auvio_rtbf_be.ENTITLEMENT_URL.format(content_id=content_id), + params={ + 'supportedFormats': 'dash,hls,mss,mp3,aac', + 'supportedDrms': 'widevine' + }, + headers={'Authorization': f'Bearer {auvio_rtbf_be.BEARER_TOKEN}'} + ).content.decode()) + + message = response.get("message", "").lower() + if "not_published" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Don't attempt to download it" + )) + if "not_entitled" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need Belgian IP to access content or the content isn't available yet", + solution="Use a VPN or don't attempt to download it" + )) + if "invalid" in message and "token" in message: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Can't access the video content because the cached token expired", + solution=f'Delete the {auvio_rtbf_be.CACHE_FILE} cache manually or add the parameter --fresh to your command' + )) + + if len(message) > 0: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Unknown error encountered: {str(response)}", + solution=f"Debug the {auvio_rtbf_be.__name__} service" + )) + + license_url = manifest = None + formats = sorted( + response["formats"], reverse=True, + key=lambda f: auvio_rtbf_be.FORMAT_PRIORITY.get(f.get("format", "").lower(), 0) + ) + + for current_format in formats: + if len(current_format.get("format", "")) == 0: + continue + + manifest = (current_format["mediaLocator"], current_format["format"].lower()) + if len(current_format.get("drm", {}).keys()) == 0: + break + + license_url = None + for k, v in current_format["drm"].items(): + if "widevine" not in k.lower(): + continue + + license_url = v["licenseServerUrl"] + break + + if license_url is not None: + break + manifest = None + + if manifest is None: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine wasn't found", + solution="Do not attempt to download it" + )) + + if manifest[1] in ["mss"] or (manifest[1] in ["hls"] and license_url is not None): + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {str(manifest)}", + solution=f"Extend the {auvio_rtbf_be.__name__} service" + )) + + if manifest[1] in ["aac", "mp3"]: + manifest = auvio_rtbf_be.generate_master_m3u8(source_element, manifest, content_info) + pssh_value = None + else: + manifest = manifest[0] + + try: + pssh_value = str(min(re.findall( + r']*>(.*?)', + requests.get(manifest).content.decode() + ), key=len)) + except: + return manifest, None, {} + return manifest, pssh_value, {"license_url": license_url} + + @staticmethod + def get_page_json(url): + response = json.loads(re.findall( + r'type="application/json"[^<>]*>({.*?})', + requests.get(url).content.decode() + )[0]) + + r = response["props"]["pageProps"] + if r["initialState"].startswith("{"): + r["initialState"] = json.loads(r["initialState"]) + + response["props"]["pageProps"] = r + return response + + @staticmethod + def get_label_index(label): + if label is None or len(label) == 0: + return None + label = unidecode(label.lower()) + label = re.sub(r'\s+', ' ', label) + label = label.replace(' ', "_") + for s in ["saison_", "annee_"]: + try: + return int(re.findall(fr'{s}(\d+)', label)[0]) + except: + pass + return None + + @staticmethod + def handle_list(collection_name, season_index, content_url, collection_url): + if season_index is not None: + collection_name = join(collection_name, f'Season_{season_index}') + + content_url = update_url_params(content_url, {"_limit": auvio_rtbf_be.PAGE_SIZE}) + episode_index = 0 + collection = [] + + while True: + response = json.loads(requests.get(content_url).content.decode()) + if "/mosaic/" in content_url: + contents = response.get("data", []) + else: + contents = response.get("data", {}).get("content", []) + + for content in contents: + episode_index += 1 + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + if content.get('resourceType', "").lower() in ["radio_live"]: + episode_title = ( + f'{content["channel"].get("label", "")}' + f'_' + f'{content.get("title", "")}' + f'_' + f'{content.get("subtitle", "")}' + ) + + episode_url = ( + f'{auvio_rtbf_be.BASE_URL}/custom_dict://' + f'{json.dumps({"stream_asset_id": content["channel"]["streamAssetId"]})}' + f'_{collection_url}' + ) + else: + episode_url = content["path"] + if not episode_url.startswith("/"): + episode_url = "/" + episode_url + episode_url = auvio_rtbf_be.BASE_URL + episode_url + episode_title = f'{content.get("title", "")}_{content.get("subtitle", "")}' + + name_prefix = str(episode_index) + if season_index is not None: + name_prefix = f'Episode_{name_prefix}' + + collection.append(BaseElement( + url=episode_url, + collection=collection_name, + element=f'{name_prefix}' + f'_' + f'{get_valid_filename(episode_title)}' + )) + + if response["links"].get("next", None) is None: + break + content_url = response["links"]["next"] + + return collection + + @staticmethod + def get_collection_elements(collection_url): + collection_url = collection_url.rstrip("/") + if "/media/" in collection_url or "/live/" in collection_url: + return [BaseElement(url=collection_url)] + + if "/emission/" in collection_url or "/widget/" in collection_url or "/chaine/" in collection_url: + collection = [] + page_json = auvio_rtbf_be.get_page_json(collection_url) + + collection_name, asset_url = auvio_rtbf_be.get_collection_info(page_json) + if collection_name is None: + collection_name = collection_url.split("/")[-1] + collection_name = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + auvio_rtbf_be.__name__ + ), + get_valid_filename(collection_name) + ) + + queries = page_json["props"]["pageProps"]["initialState"]["api"]["queries"] + collection_content = None + for query in queries: + if "/widget/" in collection_url or collection_url.endswith("/bonus"): + if not query.startswith("mosaic"): + continue + else: + if not query.startswith("widget"): + continue + collection_content = queries[query] + break + + collection_content = collection_content["data"] + if "/widget/" in collection_url or collection_url.endswith("/bonus") or "/chaine/" in collection_url: + collection = auvio_rtbf_be.handle_list( + collection_name, None, + collection_content["links"]["first"], collection_url + ) + return collection + + collection_content = collection_content["data"] + if collection_content["type"].lower() not in ["tab_list"]: + if asset_url is None: + return None + return [BaseElement(url=asset_url)] + + collection_content = collection_content["content"] + collection_content = [ + (auvio_rtbf_be.get_label_index(c["title"]), c) + for c in collection_content + ] + other_content = [(i, c) for i, c in collection_content if i is None] + collection_content = sorted([ + (i, c) for i, c in collection_content + if i is not None + ], key=lambda m: m[0]) + + if len(collection_content) == 0: + for _, c in other_content: + if c["title"].lower().startswith("tous les "): + collection = auvio_rtbf_be.handle_list( + collection_name, None, + c["contentPath"], collection_url + ) + return collection + return None + + for season_index, c in collection_content: + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + collection += auvio_rtbf_be.handle_list( + collection_name, season_index, + c["contentPath"], collection_url + ) + + return collection + return None diff --git a/API/proxiesembed/drmproxy/services/canalplus_com.py b/API/proxiesembed/drmproxy/services/canalplus_com.py new file mode 100644 index 0000000..8297fa9 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/canalplus_com.py @@ -0,0 +1,928 @@ +import base64 +import builtins +import json +import re +import threading +from os.path import join +from urllib.parse import parse_qs, urlparse + +import requests +import xmltodict +from curl_cffi import requests as requests_cf + +from utils.constants.macros import WIDEVINE_SCHEME_ID, ERR_MSG, USER_ERROR, PLAYREADY_SCHEME_ID, CACHE_DIR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename, update_url_params, dict_to_file, file_to_dict + + +class canalplus_com(BaseService): + DEMO_URLS = [ + "https://www.canalplus.com/divertissement/hot-ones-jerome-niel-vrille-completement/h/21582462_50001", + "https://www.canalplus.com/divertissement/pierre-niney-veritable-justicier-masque-dans-le-comte-de-monte-christo-canal/h/25788986_50001", + "https://www.canalplus.com/divertissement/hot-ones/h/18582832_50001", + "https://www.canalplus.com/series/bref/h/4603293_50001", + "https://www.canalplus.com/series/d-argent-et-de-sang/h/22860111_50001/bonus/", + "https://www.canalplus.com/live/?channel=450", + "https://www.canalplus.com/pl/seria/the-office-pl/h/11800604_70026/explorer/bonus/", + "https://www.canalplus.com/pl/seriale/za-kulisami-serialu-powrot-belfra/h/14153942_70033", + "https://www.canalplus.com/pl/seriale/powrot-sezon-1/h/12397026_70033", + ] + + CONFIG_URL = 'https://player.canalplus.com/one/configs/v2/11' + MAP_URL = CONFIG_URL + '/mapping/mapping.json' + PROD_URL = CONFIG_URL + '/{zone_value}/prod.json' + ENDPOINT_URLS = None + BASE_URL = "https://www.canalplus.com" + VIDEO_URL = BASE_URL + "{language}/h/{video_id}" + + DIST_MODES = 'catchup,live,svod,tvod,posttvod' + DEVICE_ID = 3 + DRM_ID = 31 + ECK = "pc" + DEVICE = "pc" + DEFAULT_GROUP_TYPE = "1" + DEFAULT_LOCATION = "fr" + LIVE_MODE = 'MKPL' + PROFILE_ID = "undefined" + QUALITY_PRIORITY = {"hd": 1, "sd": 0} + DRM_PRIORITY = { + "unprotected": 3, + "drm_mkpc_widevine_dash": 2, + "drm_mkpc_widevine_dash_download": 1, + "drm_widevine": 0 + } + IMPERSONATOR = "chrome110" + LOCK = None + CACHE_FILE = None + USER_AGENT = None + + @staticmethod + def test_service(): + main_service.run_service(canalplus_com) + + @staticmethod + def is_content_livestream(content, additional): + return additional["IS_LIVE"] + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def get_endpoints(): + try: + endpoints_dict = file_to_dict(canalplus_com.CACHE_FILE) + assert len(endpoints_dict.keys()) > 0 + return endpoints_dict + except: + endpoints_dict = {} + + response = requests.get(canalplus_com.MAP_URL) + response = json.loads(response.content.decode()) + for zone, zone_value in response["mycanal"].items(): + if zone.lower() in ["default"]: + continue + + response = requests.get(canalplus_com.PROD_URL.format(zone_value=zone_value)) + response = json.loads(response.content.decode()) + + license_base_url = response["hapi"]["licenceBaseUrl"] + if license_base_url.startswith("//"): + license_base_url = f'https:{license_base_url}' + + view_url = response["hapi"]["view"] + if view_url.startswith("//"): + view_url = f'https:{view_url}' + + playset_url = response["hapi"]["playset"] + if playset_url.startswith("//"): + playset_url = f'https:{playset_url}' + + spyro_url = response["hapi"]["spyro"] + if spyro_url.startswith("//"): + spyro_url = f'https:{spyro_url}' + + service = response["hapi"]["service"] + spyro_version = response["hapi"]["spyroVersion"] + + try: + group_types = response["live"]["liveTvGroupType"][zone] + except: + group_types = canalplus_com.DEFAULT_GROUP_TYPE + init_live_url = response["live"]["init"] + license_live_url = response["live"]["licence"] + + pass_url = response["pass"]["url"] + pass_media = response["pass"]["media"] + pass_portail_id = response["pass"]["portailId"] + pass_vect = response["pass"]["vect"] + + endpoints_dict[zone] = { + "LICENSE_BASE_URL": license_base_url, + "VIEW_URL": view_url, + "PLAYSET_URL": playset_url, + "SPYRO_URL": spyro_url, + "SERVICE": service, + "SPYRO_VERSION": spyro_version, + "GROUP_TYPES": group_types, + "INIT_LIVE_URL": init_live_url, + "LICENSE_LIVE_URL": license_live_url, + "PASS_URL": pass_url, + "PASS_MEDIA": pass_media, + "PASS_PORTAIL_ID": pass_portail_id, + "PASS_VECT": pass_vect + } + for k, u in endpoints_dict[zone].items(): + u = u.replace("{offerZone}", zone) + u = u.replace("{drmId}", str(canalplus_com.DRM_ID)) + u = u.replace("{deviceId}", str(canalplus_com.DEVICE_ID)) + endpoints_dict[zone][k] = u + + dict_to_file(canalplus_com.CACHE_FILE, endpoints_dict) + return endpoints_dict + + @staticmethod + def initialize_service(): + if canalplus_com.USER_AGENT is None: + canalplus_com.USER_AGENT = builtins.CONFIG["USER_AGENT"] + + if canalplus_com.CACHE_FILE is None: + canalplus_com.CACHE_FILE = join(CACHE_DIR, f'{canalplus_com.__name__}.json') + if builtins.CONFIG.get("FRESH", False) is True: + dict_to_file(canalplus_com.CACHE_FILE, {}) + + if canalplus_com.ENDPOINT_URLS is None: + canalplus_com.ENDPOINT_URLS = canalplus_com.get_endpoints() + assert len(canalplus_com.ENDPOINT_URLS.keys()) > 0 + + if canalplus_com.LOCK is None: + canalplus_com.LOCK = threading.Lock() + return canalplus_com + + @staticmethod + def get_best_decryptable_video(manifest, keys): + mpd_content_raw = requests.get(manifest).content.decode() + mpd_content = xmltodict.parse(mpd_content_raw) + if mpd_content.get("MPD", None) is None: + if WIDEVINE_SCHEME_ID not in mpd_content_raw and PLAYREADY_SCHEME_ID in mpd_content_raw: + return None + raise + + mpd_content = mpd_content["MPD"]["Period"] + if type(mpd_content["AdaptationSet"]) is not list: + mpd_content["AdaptationSet"] = [mpd_content["AdaptationSet"]] + + best_content = None + best_height = None + best_width = None + for content in mpd_content["AdaptationSet"]: + if content["@contentType"] != "video": + continue + + default_kid = None + for protection in content["ContentProtection"]: + if protection.get("@cenc:default_KID", None) is None: + continue + default_kid = protection["@cenc:default_KID"].lower().replace("-", "") + + if default_kid is None: + continue + is_decryptable = False + for k in keys: + k1 = k.split(":")[1] + if k1 == "0" * len(k1): + continue + + if default_kid == k.split(":")[0]: + is_decryptable = True + break + if not is_decryptable: + continue + + for representation in content["Representation"]: + update_content = False + height = int(representation.get("@height", content.get("@height", None))) + if height is None: + continue + height = int(height) + + width = int(representation.get("@width", content.get("@width", None))) + if width is None: + continue + width = int(width) + + if best_content is None: + update_content = True + else: + if height > best_height: + update_content = True + + if update_content: + best_content = content + best_height = height + best_width = width + + assert best_content is not None + return best_width, best_height + + @staticmethod + def get_keys(challenge, additional): + if not additional["IS_LIVE"]: + pass_token = additional["pass_token"] + licence = requests.post( + additional["license_url"], + headers={ + 'Content-Type': 'text/plain', + 'XX-OZ': additional["offer_zone"], + 'XX-SERVICE': additional["service"], + 'XX-OPERATOR': canalplus_com.ECK, + 'Authorization': f'PASS Token="{pass_token}"', + 'XX-Profile-Id': canalplus_com.PROFILE_ID, + 'XX-DEVICE': f'{canalplus_com.DEVICE} device-device' + }, + data=base64.b64encode(challenge).decode() + ) + licence.raise_for_status() + licence = xmltodict.parse(licence.content.decode()) + return licence["licenseresponse"]["clientresponse"]["license"]["#text"] + + else: + licence = requests.post( + additional["license_url"], + json={ + 'ServiceRequest': { + 'InData': { + 'EpgId': additional["epg_id"], + 'LiveToken': additional["live_token"], + 'ChallengeInfo': base64.b64encode(challenge).decode(), + 'Mode': canalplus_com.LIVE_MODE + } + } + } + ) + licence.raise_for_status() + return json.loads(licence.content.decode())["ServiceResponse"]["OutData"]["LicenseInfo"] + + @staticmethod + def sort_drm_quality(obj): + quality_score = canalplus_com.QUALITY_PRIORITY[obj["quality"].lower()] + drm_score = canalplus_com.DRM_PRIORITY[obj["drmType"].lower()] + return -quality_score, -drm_score + + @staticmethod + def get_pssh_from_manifest(manifest_content): + psshs = re.findall( + fr'"]*"[^<>"]*{WIDEVINE_SCHEME_ID}[^<>"]*"[^<>]*>(.*?)', + manifest_content, + re.DOTALL | re.IGNORECASE + ) + pssh = [] + + for p in psshs: + try: + pssh.append(str(min(re.findall( + r'<[^<>]*cenc:pssh[^<>]*>(.*?)]*cenc:pssh[^<>]*>', p + ), key=len))) + except: + pass + + if len(psshs) > 0: + return str(min(pssh, key=len)) + + if PLAYREADY_SCHEME_ID not in manifest_content: + return None + + psshs = re.findall( + fr'"]*"[^<>"]*{PLAYREADY_SCHEME_ID}[^<>"]*"[^<>]*>(.*?)', + manifest_content, + re.DOTALL | re.IGNORECASE + ) + return str(min(psshs, key=len)) + + @staticmethod + def get_video_data(source_element): + response = requests.get(source_element.url).content.decode() + offer_zone = re.search( + r'"offerZone":"(.+?)"', + response + ).group(1) + + page_json = re.findall( + r'__data\s*=\s*({.+?})\s*;', + response + ) + if len(page_json) == 0: + raise + page_json = page_json[0].replace("undefined", "null") + page_json = json.loads(page_json) + + offer_location = page_json.get("application", {}).get("zoneInfo", {}).get( + "offerLocation", canalplus_com.DEFAULT_LOCATION + ) + pass_token = canalplus_com.ENDPOINT_URLS[offer_zone].get("PASS_TOKEN", None) + + if pass_token is None: + with canalplus_com.LOCK: + pass_token = canalplus_com.ENDPOINT_URLS[offer_zone].get("PASS_TOKEN", None) + + if pass_token is None: + response = requests_cf.post( + canalplus_com.ENDPOINT_URLS[offer_zone]["PASS_URL"].format( + offerLocation=offer_location + ), + headers={'User-Agent': canalplus_com.USER_AGENT}, + data='&'.join(f'{k}={v}' for k, v in { + 'media': canalplus_com.ENDPOINT_URLS[offer_zone]["PASS_MEDIA"], + 'portailId': canalplus_com.ENDPOINT_URLS[offer_zone]["PASS_PORTAIL_ID"], + 'vect': canalplus_com.ENDPOINT_URLS[offer_zone]["PASS_VECT"] + }.items()), + impersonate=canalplus_com.IMPERSONATOR + ) + response = json.loads(response.content.decode()) + + pass_token = response["response"]["passToken"] + canalplus_com.ENDPOINT_URLS[offer_zone]["PASS_TOKEN"] = pass_token + + epg_id = None + if "/h/" in source_element.url: + content_id = re.search(r"/h/([^/?]*)", source_element.url).group(1) + else: + content_id = None + params_dict = parse_qs(urlparse(source_element.url).query) + epg_id = params_dict["channel"][0] + + if content_id is not None: + response = requests.get( + canalplus_com.ENDPOINT_URLS[offer_zone]["PLAYSET_URL"].format(id=content_id), + headers={ + 'XX-DISTMODES': canalplus_com.DIST_MODES, + 'XX-OZ': offer_zone, + 'XX-SERVICE': canalplus_com.ENDPOINT_URLS[offer_zone]["SERVICE"], + 'XX-OPERATOR': canalplus_com.ECK, + 'Authorization': f'PASS Token="{pass_token}"', + 'XX-Profile-Id': canalplus_com.PROFILE_ID, + 'XX-DEVICE': f'{canalplus_com.DEVICE} device-device' + } + ) + status_code = response.status_code + response = json.loads(response.content.decode()) + + if status_code < 200 or status_code >= 300: + page_json = re.findall( + r'REACT_QUERY_STATE\s*=\s*({.+?})\s*;', + requests.get(source_element.url).content.decode() + ) + if len(page_json) > 0: + page_json = page_json[0].replace("undefined", "null") + page_json = json.loads(page_json) + + for q in page_json.get("queries", []): + d = q.get("state", {}).get("data", {}) + p = d.get("currentPage", {}).get("path", None) + + if p is None: + continue + if not source_element.url.endswith(p.rstrip("/")): + continue + + for a in d.get("actionLayout", {}).get("primaryActions", []): + if a.get("type", "").lower() not in ["play"]: + continue + epg_id = a.get("onClick", {}).get("epgID", None) + + if epg_id is None: + for o in a.get("onClick", {}).get("options", []): + epg_id = o.get("onClick", {}).get("epgID", None) + + if epg_id is not None: + break + if epg_id is not None: + break + if epg_id is not None: + break + else: + status_code = 500 + response = {} + + if epg_id is None: + if status_code == 404 or response.get("code", "").lower() == "conso-404-0": + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + if status_code in [500, 403] or response.get("code", "").lower() in ["tec-500-1", "conso-403-3"]: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Can't download paid content", + solution='Do not attempt to download it' + )) + + live_token = None + if epg_id is not None: + has_drm = True + + response = requests.post( + canalplus_com.ENDPOINT_URLS[offer_zone]["INIT_LIVE_URL"].replace("{offerLocation}", offer_location), + json={ + 'ServiceRequest': {'InData': { + 'PassData': {'Token': pass_token}, + 'PDSData': {'GroupTypes': canalplus_com.ENDPOINT_URLS[offer_zone]["GROUP_TYPES"]} + }} + } + ) + response = json.loads(response.content.decode()) + response = response["ServiceResponse"]["OutData"] + live_token = response["LiveToken"] + + manifest = None + for group in response.get("PDS", {}).get("ChannelsGroups", {}).get("ChannelsGroup", []): + for channel in group.get("Channels", []): + if str(epg_id) != str(channel.get("EpgId", None)): + continue + manifest = channel.get("WSXUrl", None) + + if channel.get("NoEncrypt", None) not in ["", None]: + has_drm = str(channel["NoEncrypt"]).lower() != "true" + if manifest is not None: + break + if manifest is not None: + break + + manifest = requests.get(manifest).content.decode() + manifest = json.loads(manifest) + manifest = manifest["primary"]["src"] + license_url = canalplus_com.ENDPOINT_URLS[offer_zone]["LICENSE_LIVE_URL"].format( + offerZone=offer_zone, + drmId=canalplus_com.DRM_ID + ) + + else: + response = response.get("available", []) + if len(response) == 0: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Can't download paid content", + solution='Do not attempt to download it' + )) + + response = list(filter( + lambda r: "widevine" in r.get("drmType", "").lower() or + "unprotected" in r.get("drmType", "").lower(), + response + )) + response = sorted(response, key=canalplus_com.sort_drm_quality) + if len(response) == 0: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine wasn't found", + solution="Do not attempt to download it" + )) + + response = response[0] + has_drm = "widevine" in response["drmType"].lower() + response = response["hash"] + + response = requests.put( + canalplus_com.ENDPOINT_URLS[offer_zone]["VIEW_URL"], + headers={ + 'XX-DISTMODES': canalplus_com.DIST_MODES, + 'XX-OZ': offer_zone, + 'XX-SERVICE': canalplus_com.ENDPOINT_URLS[offer_zone]["SERVICE"], + 'XX-OPERATOR': canalplus_com.ECK, + 'Authorization': f'PASS Token="{pass_token}"', + 'XX-Profile-Id': canalplus_com.PROFILE_ID, + 'XX-DEVICE': f'{canalplus_com.DEVICE} device-device' + }, + params={"include": "medias"}, + json={'hash': response} + ) + + response = json.loads(response.content.decode()) + licence_path = None + if has_drm: + licence_path = response["@licence"] + manifest = None + license_url = None + + for media in response.get("medias", []): + try: + if has_drm: + if licence_path not in media["@licence"] and media["@licence"] not in licence_path: + continue + + for file in media.get("files", []): + if "video" != file.get("type", "").lower(): + continue + + manifest = file.get("distribURL", None) + try: + redirect = requests.get(manifest, allow_redirects=False).headers + location = dict(redirect)["Location"] + assert len(location) > 0 + manifest = location + except: + pass + + if manifest is None: + try: + manifest = file["routemeup"] + manifest = requests.get(manifest) + manifest = json.loads(manifest.content.decode()) + manifest = manifest["primary"]["src"] + except: + manifest = None + + if manifest is not None: + if has_drm: + license_url = f'{canalplus_com.ENDPOINT_URLS[offer_zone]["LICENSE_BASE_URL"]}{media["@licence"]}' + break + + if manifest is not None: + break + except: + manifest = None + + if manifest is None: + raise + if manifest.endswith(".ism"): + manifest += "/manifest" + + if has_drm and "drmConfig=" not in license_url: + license_url = update_url_params(license_url, { + "drmConfig": "mkpl::true|persistent::false" + }) + + manifest_content = requests.get(manifest) + if manifest_content.status_code < 200 or 300 <= manifest_content.status_code: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Can't download paid content or the VPN was detected", + solution='Do not attempt to download it or use a better VPN' + )) + + try: + if not has_drm: + raise + pssh_value = canalplus_com.get_pssh_from_manifest(manifest_content.content.decode()) + except: + pssh_value = None + + if has_drm and pssh_value is None: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine wasn't found", + solution="Do not attempt to download it" + )) + + if source_element.element is None: + if content_id is not None: + response = requests.post( + canalplus_com.ENDPOINT_URLS[offer_zone]["SPYRO_URL"], + headers={ + 'XX-OZ': offer_zone, + 'XX-SERVICE': canalplus_com.ENDPOINT_URLS[offer_zone]["SERVICE"], + 'XX-OPERATOR': canalplus_com.ECK, + 'Authorization': f'PASS Token="{pass_token}"', + 'XX-Profile-Id': canalplus_com.PROFILE_ID, + 'XX-DEVICE': f'{canalplus_com.DEVICE} device-device', + 'XX-SPYRO-VERSION': canalplus_com.ENDPOINT_URLS[offer_zone]["SPYRO_VERSION"] + }, + json={ + 'operationName': 'content', + 'variables': {'id': content_id}, + 'query': ''' + query content($id: String!) { + catalog { unit(id: $id) { + id titles { + title originalTitle + subtitle + } + }} + } + ''' + } + ) + response = json.loads(response.content.decode()) + + response = response["data"]["catalog"]["unit"].get("titles", {}) + title = response.get("title", response.get("originalTitle", "")) + if title is None: + title = "" + + if len(title) > 0 and response.get("subtitle", "") not in ["", None]: + title = title + "_" + response["subtitle"] + + if len(title) == 0: + title = content_id + else: + if epg_id is not None: + title = f"Live_{epg_id}" + else: + title = source_element.url.split(canalplus_com.BASE_URL)[1] + source_element.element = get_valid_filename(title) + + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + canalplus_com.__name__ + ) + + return manifest, pssh_value, { + "license_url": license_url, + "live_token": live_token, + "epg_id": epg_id, + "IS_LIVE": epg_id is not None, + "USE_SHAKA": False, + "pass_token": pass_token, + "offer_zone": offer_zone, + "service": canalplus_com.ENDPOINT_URLS[offer_zone]["SERVICE"], + } + + @staticmethod + def extra_sections_handler(collection_url, collection_page_content, extra_section, language): + page_json = re.findall( + r'REACT_QUERY_STATE\s*=\s*({.+?})\s*;', + collection_page_content + ) + if len(page_json) == 0: + return None + page_json = page_json[0].replace("undefined", "null") + page_json = json.loads(page_json) + + content_id = re.search(r"/h/([^/?]*)", collection_url).group(1) + collection_title = re.findall(r"/([^/]*)/h/", collection_url) + if len(collection_title) == 0: + collection_title = content_id + else: + collection_title = collection_title[0] + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + canalplus_com.__name__ + ), + get_valid_filename(collection_title + "_" + extra_section) + ) + + tabs = [] + for query in page_json.get("queries", []): + query = query.get("state", {}).get("data", {}) + for k, v in query.items(): + if k not in ["pages", "tabs"]: + continue + if type(v) is not list: + continue + + if k == "tabs": + for tab in v: + if tab.get("path", "") in [None, ""]: + continue + + if collection_url.endswith(tab["path"].rstrip("/")): + tabs.append(tab["URLPage"]) + else: + pages = [] + for page in v: + page_path = page.get("currentPage", {}).get("path", "") + if page_path in [None, ""]: + continue + + if collection_url.endswith(page_path.rstrip("/")): + pages.append(page) + tabs.append({"strates": pages}) + + rail_index = 0 + collection = [] + for tab in tabs: + if type(tab) is not dict: + response = requests.get(tab).content.decode() + response = json.loads(response) + is_tab = True + else: + response = tab + is_tab = False + + for rail in response.get("strates", []): + if type(rail) is not dict: + continue + rail_index += 1 + + check = check_range(True, rail_index, None) + if check is True: + continue + elif check is False: + return collection + + list_title = None + if is_tab: + list_title = rail.get("title", rail.get("context", {}).get("context_list_title", None)) + rail_title = f"Rail_{rail_index}" + if list_title is not None: + rail_title = f'{rail_title}_{list_title}' + rail_title = get_valid_filename(rail_title) + + video_index = 0 + while True: + for content in rail.get("contents", []): + video_index += 1 + if content.get("type", "").lower() not in ["vod", "detailpage"]: + continue + + check = check_range(False, rail_index, video_index) + if check is True: + continue + elif check is False: + return collection + + video_title = f"Video_{video_index}" + for f in ["title", "subtitle"]: + if content.get(f, None) not in ["", None]: + video_title = video_title + "_" + content[f] + + collection.append(BaseElement( + url=canalplus_com.VIDEO_URL.format( + video_id=content["contentID"], + language=language + ), + collection=join(collection_title, rail_title), + element=get_valid_filename(video_title) + )) + + paging = rail.get("paging", {}) + if paging is None: + break + if paging.get("hasNextPage", False) is False: + break + + rail = requests.get(paging["URLPage"]) + rail = json.loads(rail.content.decode()) + + return collection + + @staticmethod + def get_collection_elements(collection_url): + if "/live" in collection_url and "channel=" in collection_url: + return [BaseElement(url=collection_url)] + + collection_url = collection_url.split("#")[0].split("?")[0].rstrip("/") + if "/h/" not in collection_url: + return None + + extra_section = re.findall(r"/h/[^/]*/(.+)", collection_url) + if len(extra_section) == 0: + extra_section = None + else: + extra_section = extra_section[0] + if extra_section in ["saisons", "sezony"]: + return None + + collection_page_content = requests.get(collection_url) + if collection_page_content.status_code == 403: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="The VPN was detected", + solution="Use a better VPN" + )) + + collection_page_content = collection_page_content.content.decode() + language = re.findall(fr'{canalplus_com.BASE_URL}/([^/?]*)/', collection_url) + if len(language) == 0: + language = "" + else: + language = language[0] + if len(language) != 2: + language = "" + else: + language = f"/{language}" + + if extra_section is not None: + return canalplus_com.extra_sections_handler( + collection_url, collection_page_content, + extra_section, language + ) + + content_id = re.search(r"/h/([^/?]*)", collection_url).group(1) + page_json = re.findall( + r'REACT_QUERY_STATE\s*=\s*({.+?})\s*;', + collection_page_content + ) + if len(page_json) == 0: + return None + page_json = page_json[0].replace("undefined", "null") + page_json = json.loads(page_json) + + episodes_url = None + for query in page_json.get("queries", []): + query = query.get("state", {}).get("data", {}) + for k, v in query.items(): + if k not in ["tabs"]: + continue + if type(v) is not list: + continue + + for tab in v: + if tab.get("displayTemplate", "").lower() not in ["episodeslist"]: + continue + if tab.get("path", "") in [None, ""]: + continue + + episodes_url = tab["URLPage"] + break + if episodes_url is not None: + break + if episodes_url is not None: + break + + if episodes_url is None: + return [BaseElement(url=collection_url)] + + response = json.loads(requests.get(episodes_url).content.decode()) + collection_title = response.get("meta", {}).get("title", None) + if collection_title is None: + collection_title = re.findall(r"/([^/]*)/h/", collection_url) + if len(collection_title) == 0: + collection_title = None + if collection_title is None: + collection_title = content_id + + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + canalplus_com.__name__ + ), + get_valid_filename(collection_title) + ) + + seasons = [] + for season in response.get("selector", []): + if season.get("seasonNumber", None) is None: + continue + seasons.append((season["seasonNumber"], season["contentID"])) + seasons = sorted(seasons, key=lambda s: s[0]) + + collection = [] + for season_index, season_id in seasons: + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + response = requests.get(update_url_params( + episodes_url, {'seasonID': season_id} + )) + response = json.loads(response.content.decode()) + has_episode_index = None + episode_counter = 0 + + while True: + episodes = response.get("episodes", {}) + + for episode in episodes.get("contents", []): + if has_episode_index is None: + has_episode_index = episode.get("episodeNumber", None) is not None + + episode_counter += 1 + if not has_episode_index: + episode_index = episode_counter + else: + episode_index = episode["episodeNumber"] + + check = check_range(False, season_index, episode_index) + if check in [True, False]: + continue + + video_title = f"E{episode_index}" + for f in ["title", "editorialTitle"]: + if episode.get(f, None) not in ["", None]: + video_title = video_title + "_" + episode[f] + + collection.append(BaseElement( + url=canalplus_com.VIDEO_URL.format( + language=language, + video_id=episode["contentID"] + ), + collection=join(collection_title, f'Season_{season_index}'), + element=get_valid_filename(video_title) + )) + + paging = episodes.get("paging", {}) + if paging is None: + break + if paging.get("hasNextPage", False) is False: + break + + response = requests.get(paging["URLPage"]) + response = json.loads(response.content.decode()) + + return collection diff --git a/API/proxiesembed/drmproxy/services/cda_pl.py b/API/proxiesembed/drmproxy/services/cda_pl.py new file mode 100644 index 0000000..10bc897 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/cda_pl.py @@ -0,0 +1,378 @@ +import builtins +import html +import json +import os +import re +import time +import urllib.parse +from os.path import join + +import browser_cookie3 +import requests +from bs4 import BeautifulSoup +from cf_clearance import sync_cf_retry, sync_stealth +from playwright.sync_api import sync_playwright + +from utils.constants.macros import ERR_MSG, APP_ERROR, USER_ERROR, WARN_MSG +from utils.main_service import main_service +from utils.structs import BaseElement, CustomException, BaseService +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename, get_width_res_from_height + + +class cda_pl(BaseService): + DEMO_URLS = [ + "https://www.cda.pl/Bajki123/folder/19713517/vfilm", + "https://www.cda.pl/STOPCHAM/folder/22765636/vfilm", + "https://www.cda.pl/WojnaIdei/folder-glowny/vfilm", + "https://www.cda.pl/video/lifestyle-kobieta", + "https://www.cda.pl/video/75382667f", + "https://www.cda.pl/video/4456700e0", + "https://www.cda.pl/video/17625912bf/vfilm", + "https://www.cda.pl/video/5809406b/vfilm", + "https://www.cda.pl/video/504842386/vfilm", + "https://www.cda.pl/video/153780264/vfilm", + ] + + BASE_URL = "https://www.cda.pl" + CLOUDFLARE = None + SITE_COOKIES = None + USER_AGENT = None + CF_RETRIES = 8 + TIMEOUT_RETRIES = 8 + TIMEOUT = 30 + + @staticmethod + def bypass_cloudflare(): + user_agent, cf_clearance = cda_pl.USER_AGENT, None + retry = 0 + failure = False + + with sync_playwright() as spw: + browser = spw.firefox.launch(headless=True) + page = browser.new_page() + + sync_stealth(page) + page.goto(cda_pl.BASE_URL) + while True: + if sync_cf_retry(page): + for cookie in page.context.cookies(): + if cookie.get('name') == 'cf_clearance': + cf_clearance = cookie.get('value') + break + user_agent = page.evaluate('() => {return navigator.userAgent}') + + if cf_clearance is not None: + break + else: + retry = cda_pl.CF_RETRIES + + retry += 1 + if retry >= cda_pl.CF_RETRIES: + failure = True + break + browser.close() + + if failure: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}/{APP_ERROR}', + url=f"from {cda_pl.__name__}", + reason="Failed to bypass Cloudflare", + solution=f"Try again and if it persists, then debug the {cda_pl.__name__} service" + )) + return user_agent, cf_clearance + + @staticmethod + def check_cloudflare(): + if cda_pl.USER_AGENT is None: + cda_pl.USER_AGENT = builtins.CONFIG["USER_AGENT"] + + if "Just a moment..." in requests.get(cda_pl.BASE_URL).content.decode(): + user_agent, cf_clearance = cda_pl.bypass_cloudflare() + return {"User-Agent": user_agent, "cf_clearance": cf_clearance} + return {"User-Agent": cda_pl.USER_AGENT, "cf_clearance": None} + + @staticmethod + def test_service(): + main_service.run_service(cda_pl) + + @staticmethod + def credentials_needed(): + return { + "OPTIONAL": True, + "FIREFOX_COOKIES": True + } + + @staticmethod + def set_site_cookies(): + cda_pl_cookies = {} + try: + for c in browser_cookie3.firefox(domain_name='cda.pl'): + cda_pl_cookies[c.name] = c.value + except browser_cookie3.BrowserCookieError: + pass + cda_pl_cookies["cf_clearance"] = cda_pl.CLOUDFLARE["cf_clearance"] + cda_pl.SITE_COOKIES = cda_pl_cookies + + @staticmethod + def initialize_service(): + if cda_pl.CLOUDFLARE is None: + cda_pl.CLOUDFLARE = cda_pl.check_cloudflare() + if cda_pl.SITE_COOKIES is None: + cda_pl.set_site_cookies() + return cda_pl + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + additional["license_url"], data=challenge, + headers={'x-dt-custom-data': additional["custom_data"]} + ) + licence.raise_for_status() + return licence.content + + # Taken from: https://github.com/divadsn/cda-video-extractor/blob/master/server.py#L37 + @staticmethod + def decrypt_file(file_str: str): + words = ["_XDDD", "_CDA", "_ADC", "_CXD", "_QWE", "_Q5", "_IKSDE"] + for w in words: + file_str = file_str.replace(w, "") + file_str = urllib.parse.unquote(file_str) + + decrypted_chars = [] + for char in range(len(file_str)): + char_ord = ord(file_str[char]) + decrypted_chars.append( + chr(33 + (char_ord + 14) % 94) if 33 <= char_ord <= 126 + else chr(char_ord) + ) + + file_str = "".join(decrypted_chars) + file_str = file_str.replace(".cda.mp4", "") + file_str = file_str.replace(".2cda.pl", ".cda.pl") + file_str = file_str.replace(".3cda.pl", ".cda.pl") + return f"https://{file_str}.mp4" + + @staticmethod + def generate_video_m3u8(output_path, content): + m3u8_content = "#EXTM3U\n#EXT-X-VERSION:3\n\n" + m3u8_content += f'#EXTINF:{content["duration"]},\n' + m3u8_content += f'{cda_pl.decrypt_file(content["file"])}\n' + + m3u8_content += "#EXT-X-ENDLIST\n" + with open(output_path, "w") as f: + f.write(m3u8_content) + + @staticmethod + def generate_master_m3u8(source_element, content): + output_path = str(join(source_element.collection, source_element.element)) + if not os.path.exists(output_path): + os.makedirs(output_path) + m3u8_content = "#EXTM3U\n#EXT-X-VERSION:3\n\n" + + index = 0 + for quality in content.get("qualities", {}): + index += 1 + if content["quality"] != content["qualities"][quality]: + c = cda_pl.get_video_content(f'{source_element.url}?wersja={quality}') + else: + c = content + + q = int(quality.split("p")[0]) + q = f'{get_width_res_from_height(q)}x{q}' + title = f'video_{quality}.m3u8' + + cda_pl.generate_video_m3u8(join(output_path, title), c) + m3u8_content += f"#EXT-X-STREAM-INF:BANDWIDTH={index * 1000},RESOLUTION={q},TYPE=VIDEO,MIME-TYPE=\"video/mp4\"\n" + m3u8_content += f'{title}\n' + + output_path = join(output_path, "master.m3u8") + with open(output_path, "w") as f: + f.write(m3u8_content) + return output_path + + @staticmethod + def handle_cloudflare_timeout(url, lambda_request): + for i in range(1, cda_pl.TIMEOUT_RETRIES + 1): + response = lambda_request(url) + if "Just a moment..." in response: + print(WARN_MSG.format( + msg=f"Cloudflare timeout: ({i}/{cda_pl.TIMEOUT_RETRIES}). " + f"Duration (seconds): {cda_pl.TIMEOUT}") + ) + + if i == cda_pl.TIMEOUT_RETRIES: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=url, + reason='You requested too much content recently', + solution="Wait 1 minute" + )) + + time.sleep(cda_pl.TIMEOUT) + continue + return response + + @staticmethod + def get_video_content(url): + response = cda_pl.handle_cloudflare_timeout( + url, + lambda u: requests.post( + u, cookies=cda_pl.SITE_COOKIES, + headers={'User-Agent': cda_pl.CLOUDFLARE['User-Agent']}, + files={'age_confirm': (None, '')} + ).content.decode() + ) + + if "player_data" not in response: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=url, + reason="Need Polish IP to access content or it is paid premium", + solution="Use a VPN or don't attempt to download it" + )) + + player_match = re.findall(r'player_data="([^"]*)"', response) + if len(player_match) == 0: + player_match = re.findall(r"player_data='([^']*)'", response) + return json.loads(html.unescape(player_match[0]))["video"] + + @staticmethod + def get_video_data(source_element): + content = cda_pl.get_video_content(source_element.url) + if source_element.element is None: + element_name = content.get("title", "") + if "%" in element_name: + element_name = urllib.parse.unquote(element_name) + element_name = get_valid_filename(element_name) + if element_name is None: + element_name = re.search(r"/video/([^/?]*)", source_element.url).group(1) + + source_element.element = element_name + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + cda_pl.__name__ + ) + + manifest = content.get("manifest", None) + if manifest is None: + return cda_pl.generate_master_m3u8(source_element, content), None, {} + + license_url = content["manifest_drm_proxy"] + custom_data = content["manifest_drm_header"] + try: + pssh_value = str(min(re.findall( + r']*>(.*?)', + requests.get(manifest).content.decode() + ), key=len)) + except: + return manifest, None, {} + return manifest, pssh_value, { + "license_url": license_url, + "custom_data": custom_data, + "FORCE_SHAKA": "vp9/" in manifest + } + + @staticmethod + def get_collection_elements(collection_url): + collection_url = collection_url.split("?")[0] + content_id = None + if "/video/" in collection_url: + content_id = re.search(r"/video/([^/?]*)", collection_url).group(1) + if content_id[0].isdigit(): + return [BaseElement(url=collection_url)] + content_id = get_valid_filename(content_id) + + for p in ["/kolekcje/", "/premium", "/tv", "/powtorki-z-telewizji/"]: + if p in collection_url: + return None + + if "/video/" in collection_url or "/folder" in collection_url: + if content_id is None: + content_id = re.search(r"/([^/?]*)/folder", collection_url).group(1) + is_folder = True + else: + is_folder = False + + if not collection_url.endswith("/"): + collection_url += "/" + collection = [] + + page = builtins.CONFIG["QUERY"]["MIN"]["COLLECTION"] + if page is None: + page = 1 + else: + page = int(page) + + while True: + response = cda_pl.handle_cloudflare_timeout( + f'{collection_url}{page}', + lambda u: requests.get( + u, cookies=cda_pl.SITE_COOKIES, + headers={'User-Agent': cda_pl.CLOUDFLARE['User-Agent']} + ).content.decode() + ) + + soup = BeautifulSoup(response, 'html5lib') + + try: + pag_div = soup.find('div', class_='paginationControl') + if not is_folder: + disabled_page = pag_div.find('span', class_='disabledPage').text + else: + disabled_page = pag_div.find('li', class_='active').find('a').text + + if disabled_page != str(page): + break + except: + if page > 1: + break + + check = check_range(True, page, None) + if check is True: + continue + elif check is False: + return collection + + a_elements = soup.find_all( + 'a', + class_="video-clip-link" if not is_folder else "link-title-visit" + ) + a_elements = [ + a for a in a_elements + if "/video/" in a["href"] and a["href"].split("/video/")[1][0].isdigit() + ] + + index = 0 + for link in a_elements: + index += 1 + check = check_range(False, page, index) + if check is True: + continue + elif check is False: + return collection + + if not is_folder: + title = soup.find('a', href=link["href"], title=True)["title"] + else: + title = link.text + + collection.append(BaseElement( + url=f'{cda_pl.BASE_URL}{link["href"]}', + collection=join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + cda_pl.__name__ + ), + join(content_id, f'Page_{page}') + ), + element=f"Video_{index}" + f'_' + f"{get_valid_filename(title)}" + )) + + page += 1 + + return collection + return None diff --git a/API/proxiesembed/drmproxy/services/channel4_com.py b/API/proxiesembed/drmproxy/services/channel4_com.py new file mode 100644 index 0000000..ff9f0ab --- /dev/null +++ b/API/proxiesembed/drmproxy/services/channel4_com.py @@ -0,0 +1,485 @@ +import base64 +import builtins +import json +import re +from os.path import join + +import requests +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes +from cryptography.hazmat.primitives.padding import PKCS7 + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR, CACHE_DIR +from utils.main_service import main_service +from utils.structs import BaseElement, CustomException, BaseService +from utils.tools.args import check_range +from utils.tools.cdm import get_pssh_from_default_kid, get_pssh_from_cenc_pssh +from utils.tools.common import get_valid_filename, dict_to_file, file_to_dict, get_ext_from_url + + +class channel4_com(BaseService): + DEMO_URLS = [ + "https://www.channel4.com/programmes/honest-thief/on-demand/74015-001", + "https://www.channel4.com/programmes/dance-moms/on-demand/76149-003", + "https://www.channel4.com/now/M4", + "https://www.channel4.com/now/4S", + "https://www.channel4.com/programmes/ugly-betty", + "https://www.channel4.com/programmes/8-out-of-10-cats-does-countdown", + "https://www.channel4.com/programmes/first-dates", + ] + + BUNDLE_JS_URL = "https://static.c4assets.com/all4-player/latest/bundle.app.js" + STREAM_URL = 'https://www.channel4.com/vod/stream/{stream_id}' + CHANNEL_URL = 'https://www.channel4.com/simulcast/channels/{channel_id}' + VIDEO_URL = "https://www.channel4.com/programmes/{program_title}/on-demand/{program_id}" + ASSET_URL = 'https://www.channel4.com/player/{programme_title}/asset/{asset_id}' + BASE_URL = "https://www.channel4.com" + + CACHE_FILE = None + AES_INFO = None + USER_AGENT = None + + @staticmethod + def test_service(): + main_service.run_service(channel4_com) + + @staticmethod + def is_content_livestream(content, additional): + return "/now/" in content and "/on-demand/" not in content + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def get_aes_info(): + try: + file_dict = file_to_dict(channel4_com.CACHE_FILE) + assert len(file_dict.keys()) == 2 + return file_dict + except: + pass + + response = requests.get(channel4_com.BUNDLE_JS_URL).content.decode() + aes_info = { + "KEY": re.findall(r'"bytes1":"([^"]+)"', response)[0], + "IV": re.findall(r'"bytes2":"([^"]+)"', response)[0] + } + dict_to_file(channel4_com.CACHE_FILE, aes_info) + return aes_info + + @staticmethod + def initialize_service(): + if channel4_com.USER_AGENT is None: + channel4_com.USER_AGENT = builtins.CONFIG["USER_AGENT"] + if channel4_com.CACHE_FILE is None: + channel4_com.CACHE_FILE = join(CACHE_DIR, f'{channel4_com.__name__}.json') + if builtins.CONFIG.get("FRESH", False) is True: + dict_to_file(channel4_com.CACHE_FILE, {}) + + if channel4_com.AES_INFO is None: + channel4_com.AES_INFO = channel4_com.get_aes_info() + return channel4_com + + @staticmethod + def get_keys(challenge, additional): + additional["json_data"]["message"] = base64.b64encode(challenge).decode() + licence = requests.post( + additional["license_url"], + json=additional["json_data"], + ) + licence.raise_for_status() + return json.loads(licence.content.decode())["license"] + + @staticmethod + def decrypt_message(message): + cipher = Cipher( + algorithms.AES(channel4_com.AES_INFO["KEY"].encode()), + modes.CBC(channel4_com.AES_INFO["IV"].encode()), + backend=default_backend() + ).decryptor() + unpadder = PKCS7(algorithms.AES.block_size).unpadder() + + message = cipher.update(base64.b64decode(message)) + cipher.finalize() + message = (unpadder.update(message) + unpadder.finalize()).decode() + return message + + @staticmethod + def get_js_dict_from_page(page): + try: + pattern = re.compile(r'', re.DOTALL) + js_dict = re.findall(pattern, page)[0] + for f1 in ",]}": + for f2, v2 in [("undefined", "null")]: + js_dict = js_dict.replace(f":{f2}{f1}", f":{v2}{f1}") + + return json.loads(js_dict) + except: + return {} + + @staticmethod + def get_title_from_js_dict(js_dict, is_collection): + init_data = js_dict.get("initialData", {}) + brand = init_data.get("brand", {}) + page_data = init_data.get("pageData", {}) + select_ep = init_data.get("selectedEpisode", {}) + og_tags = init_data.get("ogTags", {}) + + video_title = "" + if og_tags.get("title", None) not in ["", None]: + video_title = og_tags["title"] + if video_title not in ["", None]: + return video_title + + brand_title = "" + for f in ["title", "websafeTitle"]: + if brand_title in ["", None] and brand.get(f, None) not in ["", None]: + brand_title = brand[f] + if brand_title not in ["", None]: + break + if brand_title in ["", None] and page_data.get("title", None) not in ["", None]: + brand_title = page_data["title"] + brand_title = brand_title.strip() + + if len(brand_title) == 0: + return None + if is_collection: + return brand_title + + ep_title = "" + for f in ["title", "fullTitle", "originalTitle", "secondaryTitle"]: + if ep_title in ["", None] and select_ep.get(f, None) not in ["", None]: + ep_title = select_ep[f] + if ep_title not in ["", None]: + break + ep_title = ep_title.strip() + + if len(ep_title) == 0: + return None + + video_title = "" + if brand_title != ep_title: + video_title = brand_title + " " + ep_title + + video_title = video_title.strip() + if len(video_title) is None: + video_title = None + return video_title + + @staticmethod + def process_video_profiles(profiles, source_url, is_live=False): + profiles = list(filter(lambda p: p["name"].lower().split("-")[0].endswith("wv"), profiles)) + if len(profiles) == 0: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_url, + reason=f"DRM not supported. Widevine wasn't found", + solution="Do not attempt to download it" + )) + + manifest_url = None + manifest_token = None + for profile in profiles: + streams = profile.get("streams", []) + streams = sorted(streams, key=lambda s: s.get("bitRate", 0), reverse=True) + if len(streams) == 0: + continue + + stream = streams[0] + manifest_url, manifest_token = stream["uri"], stream["token"] + if manifest_url is not None and manifest_token is not None: + break + + assert manifest_url is not None + additional = {} + pssh = None + + if manifest_token not in ["", None]: + try: + message = channel4_com.decrypt_message(manifest_token) + except: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_url, + reason="Can't access the video content because the AES key/iv was changed", + solution=f'Delete the {channel4_com.CACHE_FILE} cache manually or add the parameter --fresh to your command' + )) + + if not is_live: + message = message.split("|") + additional["license_url"] = message[0] + token = message[1] + content_type = "ondemand" + else: + message = message.split("t=") + additional["license_url"] = message[0].split("?")[0] + token = message[1].split("&")[0] + content_type = "simulcast" + + additional["json_data"] = { + "video": {"type": content_type, "url": manifest_url}, + "token": token + } + + manifest_content = requests.get( + manifest_url, headers={'User-Agent': channel4_com.USER_AGENT} + ).content.decode() + try: + pssh = get_pssh_from_default_kid(manifest_content) + except: + pssh = None + + if pssh is None: + try: + pssh = get_pssh_from_cenc_pssh(manifest_content) + except: + pssh = None + + if pssh is None: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_url, + reason=f"Manifest format not supported: {manifest_url}. Can't extract pssh", + solution=f"Extend the {channel4_com.__name__} service" + )) + + if builtins.CONFIG.get("BASIC", False) is True: + manifest_url = manifest_url.split("?")[0] + "?" + return manifest_url, pssh, additional + + @staticmethod + def get_live_data(source_element): + channel_id = re.search(r"/now/([^/?]+)", source_element.url).group(1) + channel_id = channel_id.upper() + response = requests.get(channel4_com.CHANNEL_URL.format(channel_id=channel_id)) + + status = response.status_code + response = json.loads(response.content.decode()) + message = response.get("error", {}).get("message", "").lower() + + if status == 403 or "failed to fetch" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need British IP to access content", + solution="Use a VPN" + )) + + if source_element.element is None: + video_title = f"Livestream_{channel_id}" + video_title += " " + response.get("slotInfo", {}).get("episodeTitle", "") + source_element.element = get_valid_filename(video_title) + + profiles = response.get("channelInfo", {}).get("videoProfiles", []) + return channel4_com.process_video_profiles(profiles, source_element.url, is_live=True) + + @staticmethod + def get_video_data(source_element): + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + channel4_com.__name__ + ) + if "/now/" in source_element.url and "/on-demand/" not in source_element.url: + return channel4_com.get_live_data(source_element) + + stream_id = re.search(r"/on-demand/([^/?]+)", source_element.url).group(1) + response = requests.get(channel4_com.STREAM_URL.format(stream_id=stream_id)) + + status = response.status_code + try: + response = json.loads(response.content.decode()) + except: + response = {} + message = response.get("message", "").lower() + + if status in [404, 500]: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available or is paid", + solution="Do not attempt to download it" + )) + if status == 403 or "playback blocked" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need British IP to access content", + solution="Use a VPN" + )) + + if source_element.element is None: + video_title = response.get("brandTitle", None) + + if video_title in ["", None]: + video_title = response.get("webSafeBrandTitle", None) + if video_title in ["", None]: + video_title = re.findall(r"/([^/?]+)/on-demand/", source_element.url) + if len(video_title) == 0: + video_title = "" + else: + video_title = video_title[0] + "_" + video_title += stream_id + + episode_title = response.get("episodeTitle", None) + if episode_title not in ["", None] and video_title != episode_title: + video_title += "_" + str(episode_title) + + source_element.element = get_valid_filename(video_title) + + profiles = response.get("videoProfiles", []) + manifest, pssh, additional = channel4_com.process_video_profiles(profiles, source_element.url) + + srt_assets = response.get("subtitlesAssets", []) + if srt_assets is None: + srt_assets = [] + + srt_index = 0 + subtitles = [] + srt_path = join(source_element.collection, source_element.element) + for srt_asset in srt_assets: + if srt_asset.get("url", None) in ["", None]: + continue + + srt_url = srt_asset["url"] + srt_ext = get_ext_from_url(srt_url) + if srt_ext not in [".srt", ".vtt"]: + continue + + srt_index += 1 + subtitles.append((False, BaseElement( + url=srt_url, + collection=srt_path, + element=f'subtitle_{srt_index}{srt_ext}' + ))) + + additional["SUBTITLES"] = subtitles + return manifest, pssh, additional + + @staticmethod + def get_collection_elements(collection_url): + collection_url = collection_url.split("?")[0].split("#")[0].rstrip("/") + if "/programmes/" not in collection_url: + if "/now/" in collection_url: + return [BaseElement(url=collection_url)] + return None + if "/on-demand/" in collection_url: + return [BaseElement(url=collection_url)] + + programme_title = re.search(r"/programmes/([^/?]+)", collection_url).group(1) + response = requests.get(collection_url) + if response.status_code == 404: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + response = response.content.decode() + js_dict = channel4_com.get_js_dict_from_page(response) + + collection_title = channel4_com.get_title_from_js_dict(js_dict, True) + if collection_title is None: + collection_title = programme_title + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + channel4_com.__name__ + ), + get_valid_filename(collection_title) + ) + + contents = [] + try: + episodes = js_dict.get("initialData", {}).get("brand", {}).get("episodes", []) + assert type(episodes) is list and len(episodes) > 0 + except: + episodes = [] + + if len(episodes) == 0: + asset_id = js_dict["initialData"]["selectedEpisode"]["assetId"] + response = requests.get( + channel4_com.ASSET_URL.format( + programme_title=programme_title, + asset_id=asset_id + ) + ) + + response = json.loads(response.content.decode()) + seasons = response.get("series", {}) + if seasons is None: + seasons = {} + + for _, e in seasons.items(): + episodes.extend(e) + + for episode in episodes: + season_index = None + episode_index = None + for f in ["title", "fullTitle", "originalTitle", "secondaryTitle", "episodeSecondaryTitle", "episodeTitle"]: + try: + indexes = re.findall(r"series (\d+) episode (\d+)", episode[f].lower())[0] + season_index, episode_index = int(indexes[0]), int(indexes[1]) + break + except: + pass + + if season_index is None or episode_index is None: + season_index = episode["seriesNumber"] + episode_index = episode["episodeNumber"] + + found = False + for c_s, c_e in contents: + if c_s == season_index: + c_e.append((episode_index, episode)) + found = True + break + + if not found: + contents.append((season_index, [(episode_index, episode)])) + + collection = [] + contents = sorted(contents, key=lambda ct: ct[0]) + for season_index, episodes in contents: + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + episodes = sorted(episodes, key=lambda ep: ep[0]) + for episode_index, episode in episodes: + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + episode_title = "" + for f in ["originalTitle", "secondaryTitle", "episodeSecondaryTitle", "episodeTitle", "title", + "fullTitle"]: + if episode_title in ["", None] and episode.get(f, None) not in ["", None]: + episode_title = episode[f] + if episode_title not in ["", None]: + break + + if episode.get("programmeId", None) in ["", None]: + episode_url = channel4_com.BASE_URL + episode["hrefLink"] + programme_id = episode["hrefLink"].split("/")[-1] + else: + programme_id = episode["programmeId"] + episode_url = channel4_com.VIDEO_URL.format( + program_title=programme_title, + program_id=programme_id + ) + + if episode_title in ["", None]: + episode_title = programme_id + collection.append(BaseElement( + url=episode_url, + collection=join(collection_title, f'Season_{season_index}'), + element=f'E{episode_index}_{get_valid_filename(episode_title)}' + )) + + return collection diff --git a/API/proxiesembed/drmproxy/services/cineverse_com.py b/API/proxiesembed/drmproxy/services/cineverse_com.py new file mode 100644 index 0000000..2f6da99 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/cineverse_com.py @@ -0,0 +1,345 @@ +import builtins +import json +import re +from os.path import join +from urllib.parse import parse_qs, urlparse + +import browser_cookie3 +import requests +from bs4 import BeautifulSoup +from slugify import slugify + +from utils.constants.macros import APP_ERROR, ERR_MSG, USER_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename, get_ext_from_url, update_url_params + + +class cineverse_com(BaseService): + DEMO_URLS = [ + "https://www.cineverse.com/watch/1000000022997/On-Fire?vod_type=", + "https://www.cineverse.com/watch/1000000025139/Big-Freaking-Snake?vod_type=trailer", + "https://www.cineverse.com/watch/DMR00005120/FBI-Files:-Hired-Gun&vod_type=", + "https://www.cineverse.com/livetv?q=ComedyDynamics", + "https://www.cineverse.com/livetv?q=realmadrid", + "https://www.cineverse.com/details/1000000029521/Dog-Whisperer-with-Cesar-Millan", + "https://www.cineverse.com/details/BOOGIEPOPPHANTOM/Boogiepop-Phantom", + ] + + BASE_URL = "https://www.cineverse.com" + VIDEO_URL = BASE_URL + "/watch/{video_id}/{video_title}" + + AUTH_TOKEN = None + LOGIN_COOKIES = None + + @staticmethod + def test_service(): + main_service.run_service(cineverse_com) + + @staticmethod + def is_content_livestream(content, additional): + return "/livetv?" in content + + @staticmethod + def credentials_needed(): + return { + "OPTIONAL": True, + "FIREFOX_COOKIES": True + } + + @staticmethod + def get_auth_token(): + response = requests.get(cineverse_com.BASE_URL).content.decode() + response = re.findall(r']*src="([^"]*app-[^"]*.js)"[^<>]*>', response) + response = response[0] + if not response.startswith("http"): + response = f'{cineverse_com.BASE_URL}{response}' + + response = requests.get(response).content.decode() + response = re.findall(r'Authorization:"Basic ([^"]+)"', response) + return response[0] + + @staticmethod + def get_login_cookies(): + cookie_dict = {} + try: + for c in browser_cookie3.firefox(domain_name='cineverse.com'): + cookie_dict[c.name] = c.value + except browser_cookie3.BrowserCookieError: + pass + + try: + assert len(cookie_dict.keys()) > 0 + return cookie_dict + except: + return {} + + @staticmethod + def initialize_service(): + if cineverse_com.LOGIN_COOKIES is None: + cineverse_com.LOGIN_COOKIES = cineverse_com.get_login_cookies() + if cineverse_com.AUTH_TOKEN is None: + cineverse_com.AUTH_TOKEN = cineverse_com.get_auth_token() + return cineverse_com + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + additional["license_url"], + data=challenge + ) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_video_data(source_element): + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + cineverse_com.__name__ + ) + + response = requests.get( + source_element.url, + cookies=cineverse_com.LOGIN_COOKIES + ).content.decode() + + soup = BeautifulSoup(response, 'html5lib') + script = soup.find_all('script', {'type': 'application/json'}) + script = [s for s in script if s.get("id", None) == "__NEXT_DATA__"][0] + script = json.loads(script.string) + + if "/livetv?" in source_element.url: + params_dict = parse_qs(urlparse(source_element.url).query) + channel_query = params_dict["q"][0] + + live_channel = script["props"]["pageProps"].get("liveChannelListURL", None) + if live_channel in ["", None]: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need American IP to access content", + solution="Use a VPN" + )) + + live_feeds = [] + for _ in range(0, 2): + response = json.loads(requests.get( + live_channel, + headers={"Authorization": f"Basic {cineverse_com.AUTH_TOKEN}"} + ).content.decode()) + + live_feeds = response.get("liveFeeds", []) + if len(live_feeds) > 0: + break + if "jloc=us" in live_channel: + break + live_channel = update_url_params(live_channel, {"jloc": "us"}) + + live_feeds = list(filter(lambda lf: lf.get("item_id", None) == channel_query, live_feeds)) + if len(live_feeds) == 0: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content wasn't found or you need a VPN", + solution="Do not attempt to download it or use a VPN that lets you see the livestream in your browser" + )) + + live_feed = live_feeds[0] + if source_element.element is None: + title = live_feed.get("title", channel_query) + source_element.element = get_valid_filename(f"Live_{title}") + + manifest = live_feed["content"]["hls_url"] + return manifest, None, {} + + page_props = script["props"]["pageProps"] + details = page_props["idetails"] + dms_data = page_props.get("dmsData", {}) + err_code = dms_data.get("code", None) + err_msg = page_props.get("dmsMsg", dms_data.get("message", "")).lower() + + if err_code in [0, None]: + err_code = details.get("err_code", None) + if err_msg in ["", None]: + err_msg = details.get("err_msg", "").lower() + + if err_code == 1002 or "access" in err_msg: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason='Need account for this content, it is paid or it is not available', + solution="Sign into your account using Firefox or don't attempt to download it" + )) + if err_code == 1400 or ("available" in err_msg and "location" in err_msg): + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need American IP to access content", + solution="Use a VPN" + )) + + is_trailer = details.get("trailer", False) + if not is_trailer: + is_trailer = "trailer" in script.get("query", {}).get("vod_type", "").lower() + if not is_trailer: + is_trailer = "vod_type=trailer" in source_element.url + + if source_element.element is None: + title = details.get("title", None) + if title is None: + title = details.get("details", {}).get("title", None) + if title is None: + title = script.get("query", {}).get("play-asset-title", None) + if title is None: + title = source_element.url.split("/watch/")[1] + + if is_trailer: + title = f"Trailer_{title}" + source_element.element = get_valid_filename(title) + + has_drm = details.get("is_drm_encrypted", False) is True + additional = {} + + if has_drm: + drm_info = details["drm_info"] + manifest = drm_info.get("wv_dash_url", None) + if manifest is None: + manifest = drm_info["wv_hls_url"] + + license_url = drm_info.get("wv_drm_server", None) + if license_url is None: + license_url = drm_info["drm_server"] + additional["license_url"] = license_url + + else: + manifest = details.get("url", None) + if manifest is None and is_trailer: + manifest = details["details"]["media_trailer_url"] + + subtitles = [] + srt_url = details.get("subtitle_url", None) + if srt_url in [None, ""]: + srt_url = details.get("cc_url_vtt", None) + + if srt_url not in [None, ""]: + srt_ext = get_ext_from_url(srt_url) + subtitles.append((False, BaseElement( + url=srt_url, + collection=join(source_element.collection, source_element.element), + element=f'subtitle{srt_ext}' + ))) + + additional["SUBTITLES"] = subtitles + try: + if not has_drm: + raise + + pssh_value = str(min(re.findall( + r'<[^<>]*cenc:pssh[^<>]*>(.*?)]*cenc:pssh[^<>]*>', + requests.get(manifest).content.decode() + ), key=len)) + except: + pssh_value = None + + if has_drm and pssh_value is None: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}. Can't extract pssh", + solution=f"Extend the {cineverse_com.__name__} service" + )) + + return manifest, pssh_value, additional + + @staticmethod + def get_collection_elements(collection_url): + collection_url = collection_url.rstrip("/") + if "/watch/" in collection_url: + return [BaseElement(url=collection_url)] + if "/livetv?" in collection_url and "q=" in collection_url: + return [BaseElement(url=collection_url)] + + if "/details/" not in collection_url: + return None + collection_url = collection_url.split("?")[0].split("#")[0].rstrip("/") + response = requests.get( + collection_url, + cookies=cineverse_com.LOGIN_COOKIES + ).content.decode() + + soup = BeautifulSoup(response, 'html5lib') + script = soup.find_all('script', {'type': 'application/json'}) + script = [s for s in script if s.get("id", None) == "__NEXT_DATA__"][0] + script = json.loads(script.string) + + if script["props"]["pageProps"].get("locationAllowed", True) is False: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="Need American IP to access content", + solution="Use a VPN" + )) + + item_details = script["props"]["pageProps"]["itemDetailsData"] + err_code = item_details.get("code", None) + err_msg = item_details.get("message", "").lower() + if err_code == 1001 or "not available" in err_msg: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=collection_url, + reason="This content isn't available", + solution='Do not attempt to download it' + )) + + collection_title = item_details.get("title", None) + if collection_title is None: + collection_title = script.get("query", {}).get("item-title", None) + if collection_title is None: + collection_title = collection_url.split("/")[-1] + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + cineverse_com.__name__ + ), + get_valid_filename(collection_title) + ) + + seasons = script["props"]["pageProps"].get("seasonEpisodes", []) + seasons = sorted(seasons, key=lambda s: s["season"]) + collection = [] + + for season in seasons: + season_index = season["season"] + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + episodes = season.get("episodes", []) + episodes = sorted(episodes, key=lambda e: e["episode"]) + + for episode in episodes: + episode_index = episode["episode"] + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + episode_title = f'Episode_{episode_index} {episode.get("title", "")}' + episode_title = get_valid_filename(episode_title) + episode_url = cineverse_com.VIDEO_URL.format( + video_id=episode["item_id"], + video_title=slugify(episode.get("title", "title")) + ) + + collection.append(BaseElement( + url=episode_url, + collection=join(collection_title, f'Season_{season_index}'), + element=episode_title + )) + + return collection diff --git a/API/proxiesembed/drmproxy/services/docplus_com.py b/API/proxiesembed/drmproxy/services/docplus_com.py new file mode 100644 index 0000000..92bb812 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/docplus_com.py @@ -0,0 +1,166 @@ +import builtins +import json +from os.path import join + +import requests + +from utils.constants.macros import ERR_MSG, USER_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename, clean_url + + +class docplus_com(BaseService): + DEMO_URLS = [ + "https://www.docplus.com/details/we-are-oscar-mike/JPyypQpb/", + "https://www.docplus.com/details/kobe-bryant-a-tribute/dGgz7pVK/", + "https://www.docplus.com/category/films/o8VaZNFs/", + "https://www.docplus.com/category/the-royals/qVyLLHgs/", + ] + + MEDIA_URL = "https://cdn.jwplayer.com/v2/media/{media_id}" + PLAYLIST_URL = "https://cdn.jwplayer.com/v2/playlists/{playlist_id}" + CONTENT_URL = "https://www.docplus.com/details/content/{content_id}" + + PAGE_LIMIT = 500 + + @staticmethod + def test_service(): + main_service.run_service(docplus_com) + + @staticmethod + def get_additional_params(additional): + return [("MUXER", lambda s: s.format(args="mkv:muxer=mkvmerge"))] + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def initialize_service(): + return docplus_com + + @staticmethod + def get_keys(challenge, additional): + raise Exception( + f'{BaseService.get_keys.__name__} must not be called ' + f'for the {docplus_com.__name__} service' + ) + + @staticmethod + def get_video_data(source_element): + media_id = source_element.url.split("/")[-1] + response = requests.get(docplus_com.MEDIA_URL.format(media_id=media_id)) + if 400 <= response.status_code < 500: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + response = response.content.decode() + response = json.loads(response) + playlist = response.get("playlist", []) + playlist = filter(lambda p: p.get("mediaid", "") == media_id, playlist) + playlist = list(playlist)[0] + + if source_element.element is None: + title = response.get("title", playlist.get("title", "")) + if title in ["", None]: + title = source_element.url.split("/")[-2] + source_element.element = get_valid_filename(title) + + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + docplus_com.__name__ + ) + + sources = playlist.get("sources", []) + sources = filter(lambda s: "mpeg" in s.get("type", ""), sources) + sources = list(sources)[0] + manifest = sources["file"] + + return manifest, None, {} + + @staticmethod + def get_collection_elements(collection_url): + collection_url = clean_url(collection_url) + if "/details/" in collection_url: + return [BaseElement(url=collection_url)] + if "/category/" not in collection_url: + return None + + category_id = collection_url.split("/")[-1] + response = requests.get( + docplus_com.PLAYLIST_URL.format(playlist_id=category_id), + params={"page_limit": docplus_com.PAGE_LIMIT} + ) + if 400 <= response.status_code < 500: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + response = response.content.decode() + response = json.loads(response) + collection_title = response.get("title", None) + if collection_title in ["", None]: + collection_title = collection_url.split("/")[-2] + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + docplus_com.__name__ + ), + get_valid_filename(f'Category_{collection_title}') + ) + + collection = [] + visited = [] + media_index = 0 + prev_url = None + while True: + links = response.get("links", {}) + if links is None: + links = {} + + playlist = response.get("playlist", []) + for media in playlist: + media_index += 1 + check = check_range(False, None, media_index) + if check is True: + continue + elif check is False: + return collection + + media_id = media["mediaid"] + if media_id in visited: + continue + visited.append(media_id) + + media_title = media.get("title", media_id) + media_title = f'Media_{media_index}_{media_title}' + media_url = docplus_com.CONTENT_URL.format(content_id=media_id) + + collection.append(BaseElement( + url=media_url, + collection=collection_title, + element=get_valid_filename(media_title) + )) + + next_url = links.get("next", None) + if next_url in ["", None] or len(playlist) == 0: + break + if prev_url == next_url: + break + prev_url = next_url + + response = requests.get(str(next_url)) + response = response.content.decode() + response = json.loads(response) + + return collection diff --git a/API/proxiesembed/drmproxy/services/eurovisionsport_com.py b/API/proxiesembed/drmproxy/services/eurovisionsport_com.py new file mode 100644 index 0000000..92011c4 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/eurovisionsport_com.py @@ -0,0 +1,360 @@ +import builtins +import json +import re +from datetime import datetime +from os.path import join +from urllib.parse import parse_qs, urlparse, quote + +import requests + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename, clean_url + + +class eurovisionsport_com(BaseService): + DEMO_URLS = [ + "https://eurovisionsport.com/explore/competition?id=Generic-Schedule-Landing-Page&cId=20240614ECASzeged", + "https://eurovisionsport.com/explore/competition?id=Generic-Schedule-Landing-Page&cId=20240601IFMAPatras", + "https://eurovisionsport.com/explore/sport?id=EBU-Home-Racket", + "https://eurovisionsport.com/explore/sport?id=EBU-Home-Football", + "https://eurovisionsport.com/explore/federation?id=LandingPage-ESF", + "https://eurovisionsport.com/explore/federation?id=LandingPage-FIG", + "https://eurovisionsport.com/mediacard/EVS_OBE_240308_M_24-10262", + "https://eurovisionsport.com/mediacard/EVS_XEJ_240217_MX_24-3261A", + "https://eurovisionsport.com/mediacard/EVS_2023-10-08_FEED_FIG_1_DEF_F_TIME_12_50_ID_23-7614", + "https://eurovisionsport.com/mediacard/EVS_240204_EDD_25128_", + ] + + LOGIN_URL = "https://api.evsports.opentv.com/ias/v2/token?grant_type=password&username={email}&password={password}" + EDITORIALS_URL = 'https://api.evsports.opentv.com/metadata/delivery/v2/GLOBAL/vod/editorials' + TEMPLATE_URl = 'https://api.evsports.opentv.com/contentdelivery/v2/templateviews/{content_id}' + TOKEN_URL = 'https://api.evsports.opentv.com/ias/v2/content_token' + VIDEO_URL = "https://eurovisionsport.com/mediacard/{content_id}" + LICENSE_URL = "https://evsp4wab.anycast.nagra.com/EVSP4WAB/wvls/contentlicenseservice/v1/licenses" + + EMAIL = "YOUR_EMAIL" + PASSWORD = "YOUR_PASSWORD" + BEARER_TOKEN = None + PAGE_LIMIT = 9999 + + @staticmethod + def test_service(): + main_service.run_service(eurovisionsport_com) + + @staticmethod + def get_additional_params(additional): + params = [] + if builtins.CONFIG.get("BASIC", False) is True: + params.append(("ARGUMENT", lambda s: s.format(value="--check-segments-count false"))) + return params + BaseService.get_additional_params(additional) + + @staticmethod + def credentials_needed(): + return { + "EMAIL": eurovisionsport_com.EMAIL, + "PASSWORD": eurovisionsport_com.PASSWORD + } + + @staticmethod + def get_bearer_token(): + class_name = eurovisionsport_com.__name__.replace("_", ".") + credentials = builtins.CONFIG["SERVICE_CREDENTIALS"][class_name] + try: + assert type(credentials["EMAIL"]) is str + assert type(credentials["PASSWORD"]) is str + except: + return None, None + + response = json.loads(requests.post( + eurovisionsport_com.LOGIN_URL.format( + email=quote(credentials["EMAIL"]), + password=quote(credentials["PASSWORD"]) + ), json={}, headers={ + 'host': 'api.evsports.opentv.com', + 'tenantid': 'nagra' + } + ).content.decode()) + + message = response.get("message", "").lower() + if response.get("access_token", None) is None and len(message) > 0: + if "unauthorized" in message: + return None + raise CustomException(ERR_MSG.format( + type=f'{APP_ERROR}', + url=f"from the {eurovisionsport_com.__name__} service", + reason=f"Unknown error encountered: {str(response)}", + solution="Debug the service" + )) + return response["access_token"] + + @staticmethod + def initialize_service(): + if eurovisionsport_com.BEARER_TOKEN is None: + eurovisionsport_com.BEARER_TOKEN = eurovisionsport_com.get_bearer_token() + if eurovisionsport_com.BEARER_TOKEN is None: + return None + + return eurovisionsport_com + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + eurovisionsport_com.LICENSE_URL, data=challenge, + headers={'nv-authorizations': additional["content_token"]} + ) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_video_data(source_element): + video_id = source_element.url.split("/")[-1] + response = json.loads(requests.get( + eurovisionsport_com.EDITORIALS_URL, + headers={'Authorization': f'Bearer {eurovisionsport_com.BEARER_TOKEN}'}, + params={ + "filter": json.dumps({ + "editorial.id": {"$in": [video_id]}, + "locale": "en_US", "isValid": True, + "isVisible": True + }), + "limit": 9999, + "sort": json.dumps([["Title", 1]]) + } + ).content.decode()) + + video_data = [] + video_name = video_id + for e in response.get("editorials", []): + if e["id"] != video_id: + continue + + video_name = e["title"] + for t in e["technicals"]: + av = t["media"]["AV_PlaylistName"] + video_data += [(av["uri"], av["drmId"])] + + content = [v for v in video_data if ".mpd" in v[0]] + if len(content) == 0: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + if source_element.element is None: + source_element.element = get_valid_filename(video_name) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + eurovisionsport_com.__name__ + ) + + manifest, drm_id = content[0] + response = requests.get(manifest).content.decode() + try: + pssh_value = re.search(r']*>(.*?)', response).group(1) + except: + return manifest, None, {} + + response = json.loads(requests.post( + eurovisionsport_com.TOKEN_URL, + params={'content_id': drm_id, 'type': 'device'}, + headers={ + 'Nv-Tenant-Id': 'nagra', + 'Authorization': f'Bearer {eurovisionsport_com.BEARER_TOKEN}' + } + ).content.decode()) + return manifest, pssh_value, {"content_token": response["content_token"]} + + @staticmethod + def get_valid_contents(section): + return [ + c for c in section.get("contents", []) + if c is not None and type(c) is dict and + c.get("title", c.get("Title", None)) is not None and + c.get("id", None) is not None + ] + + @staticmethod + def get_template_content(content_id): + return json.loads(requests.get( + eurovisionsport_com.TEMPLATE_URl.format(content_id=content_id), + headers={ + 'Authorization': f'Bearer {eurovisionsport_com.BEARER_TOKEN}', + 'Accept-Language': 'en_US', + 'Nagra-Device-Type': 'Android,IOS', + 'Nagra-Target': 'everything' + } + ).content.decode()) + + @staticmethod + def get_competition_handler(collection_url): + params_dict = parse_qs(urlparse(collection_url).query) + competition_id = params_dict["cId"][0] + collection_name = None + + page = 0 + season_index = 0 + episode_index = 1 + current_date = None + collection = [] + + while True: + page += 1 + videos = json.loads(requests.get( + eurovisionsport_com.EDITORIALS_URL, + headers={'Authorization': f'Bearer {eurovisionsport_com.BEARER_TOKEN}'}, + params={ + "filter": json.dumps({ + "editorial.isLive": "true", "locale": "en_US", + "isValid": True, "isVisible": True, + "technical.deviceType": {"$in": ["Android"]}, + "technical.media": {"$exists": True}, + "editorial.tournament_name": competition_id + }), + "limit": eurovisionsport_com.PAGE_LIMIT, + "page": page, + "sort": json.dumps([["technical.ProgrammeStartDate", 1]]) + } + ).content.decode()).get("editorials", []) + + if len(videos) == 0: + break + if collection_name is None: + for category in videos[0].get("Categories", []): + if category.startswith("Competition"): + collection_name = category.split(":")[-1] + if collection_name is None: + collection_name = "Competition_" + competition_id + collection_name = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + eurovisionsport_com.__name__ + ), + get_valid_filename(collection_name) + ) + + for video in videos: + technicals = [t for t in video.get("technicals", []) if t.get("tournament_name", "") == competition_id] + if len(technicals) == 0: + start_date = datetime.fromtimestamp(video["CUStartDate"]).strftime("%d-%m-%Y") + else: + start_date = datetime.strptime( + technicals[0]["ProgrammeStartDate"], + "%Y-%m-%dT%H:%M:%SZ" + ).strftime("%d-%m-%Y") + + if current_date != start_date: + season_index += 1 + episode_index = 1 + current_date = start_date + else: + episode_index += 1 + + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=eurovisionsport_com.VIDEO_URL.format(content_id=video["id"]), + collection=join(collection_name, f"Schedule_{season_index}_{current_date}"), + element=f'Video_{episode_index}' + f'_' + f'{get_valid_filename(video.get("title", video["Title"]))}' + )) + + return collection + + @staticmethod + def get_collection_elements(collection_url): + if "/mediacard/" in collection_url: + return [BaseElement(url=clean_url(collection_url))] + + if "/explore/competition" in collection_url and "cId=" in collection_url: + return eurovisionsport_com.get_competition_handler(collection_url) + + if "/explore/" in collection_url and "id=" in collection_url: + if "/sport" not in collection_url and "/federation" not in collection_url: + return None + + content_id = parse_qs(urlparse(collection_url).query)["id"][0] + collection = [] + + response = eurovisionsport_com.get_template_content(content_id) + if "/federation" in collection_url: + content_id = None + for rail in response.get("rails", []): + if rail["name"] != "RenderTemplate": + continue + + for section in rail.get("sections", []): + properties = section.get("properties", {}) + content_id = properties.get( + "userSignedOnTemplate", + properties.get("anonymousSignedOnTemplate", None) + ) + if content_id is not None: + break + + if content_id is not None: + break + + assert content_id is not None + response = eurovisionsport_com.get_template_content(content_id) + content_id = get_valid_filename(content_id) + + rail_index = 0 + for rail in response.get("rails", []): + if rail["title"].lower() == "carrousel": + continue + if len(rail.get("sections", [])) == 0: + continue + if 0 in [len(eurovisionsport_com.get_valid_contents(s)) for s in rail["sections"]]: + continue + + rail_index += 1 + check = check_range(True, rail_index, None) + if check is True: + continue + elif check is False: + return collection + + video_index = 0 + rail_title = get_valid_filename(rail['title']) + for section in rail["sections"]: + for content in eurovisionsport_com.get_valid_contents(section): + video_index += 1 + check = check_range(False, rail_index, video_index) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=eurovisionsport_com.VIDEO_URL.format(content_id=content["id"]), + collection=join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + eurovisionsport_com.__name__ + ), + join(content_id, f"Rail_{rail_index}_{rail_title}") + ), + element=f'Video_{video_index}' + f'_' + f'{get_valid_filename(content.get("title", content["Title"]))}' + )) + + return collection + return None diff --git a/API/proxiesembed/drmproxy/services/fifa_com.py b/API/proxiesembed/drmproxy/services/fifa_com.py new file mode 100644 index 0000000..2736668 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/fifa_com.py @@ -0,0 +1,597 @@ +import base64 +import builtins +import json +import os +import re +import threading +from os.path import join +from urllib.parse import quote, parse_qs, urlparse + +import isodate +import requests +import xmltodict +from pywidevine import PSSH + +from utils.constants.macros import USER_ERROR, ERR_MSG +from utils.main_service import main_service +from utils.pssh_box.pssh_box import _parse_boxes, _generate_widevine_data, widevine_pssh_data_pb2 +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename + + +class fifa_com(BaseService): + DEMO_URLS = [ + "https://www.fifa.com/en/search?q=football+future&source=FIFA&ftype=video%2CvideoEpisode%2Cmovie&fdateFrom=2023-8-13&fsortBy=dateDesc&fpage=2", + "https://www.fifa.com/en/watch/series/1Iu4eLzBYq5IB3Vmo0p1Iv/2IRouvwslVX67tzEWkKKQO/4yqqJewWMqxizXYpuRu7ER", + "https://www.fifa.com/en/watch/series/3to1B8QAwfphSKO7TO5fz/243cTtTU0bNJcnRzHXhWuu/p4cFrSmlPcV2Eq9QHEHTH", + "https://www.fifa.com/en/watch/movie/3lFf41pUt0hft8FPnqGgxf", + "https://www.fifa.com/en/watch/movie/5U5nbmAEMkCR2NsL3yeKkM", + "https://www.fifa.com/en/watch/1lCxgqjZaH0CNHkVzpl0za", + "https://www.fifa.com/en/watch/f4fca463-7321-4019-b0ca-96a221608c28", + "https://www.fifa.com/en/watch/7wST4MTAbpXRAAmufEpCbx", + "https://www.fifa.com/en/watch/2PPgztGTe9gXubqGkHaDoT", + "https://www.fifa.com/en/watch/1mTRUzxa860cV3SUfs2xXC", + ] + + VIDEO_PLAYER_URL = 'https://cxm-api.fifa.com/fifaplusweb/api/videoPlayerData/{video_id}' + PREPLAY_URL = 'https://content.uplynk.com/preplay/{content_id}/multiple.json' + LICENSE_URL = 'https://content-aeui1.uplynk.com/wv' + EPISODES_URL = 'https://cxm-api.fifa.com/fifaplusweb/api/sections/videoEpisodeDetails' + MOVIE_URL = 'https://cxm-api.fifa.com/fifaplusweb/api/sections/movieDetails/{movie_id}' + SEARCH_URL = 'https://cxm-api.fifa.com/fifacxmsearch/api/results' + REDIRECT_URL = 'https://cxm-api.fifa.com/fifaplusweb/api/pages/{page}' + BASE_URL = "https://www.fifa.com" + + SEARCH_KEY = None + PAGE_SIZE = 25 + USER_AGENT = None + PLUS_SERVICE = None + LOCALE = 'en' + INTRO_DURATION = 5 + LOCK = None + IS_VALID_MANIFEST = None + + @staticmethod + def test_service(): + main_service.run_service(fifa_com) + + @staticmethod + def get_additional_params(additional): + if additional.get("PLUS_SERVICE", False) is True and fifa_com.PLUS_SERVICE is not None: + return fifa_com.PLUS_SERVICE.get_additional_params(additional) + return [] + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def get_search_key(): + return re.search( + r'"SEARCH_KEY":"(.+?)"', + requests.get( + fifa_com.BASE_URL, + headers={'User-Agent': fifa_com.USER_AGENT} + ).content.decode() + ).group(1) + + @staticmethod + def initialize_service(): + if fifa_com.USER_AGENT is None: + fifa_com.USER_AGENT = builtins.CONFIG["USER_AGENT"] + + try: + # raise + from services.plus_fifa_com import plus_fifa_com + fifa_com.PLUS_SERVICE = plus_fifa_com.initialize_service() + except: + fifa_com.PLUS_SERVICE = None + + if fifa_com.LOCK is None: + fifa_com.LOCK = threading.Lock() + if fifa_com.SEARCH_KEY is None: + fifa_com.SEARCH_KEY = fifa_com.get_search_key() + return fifa_com + + @staticmethod + def get_keys(challenge, additional): + if additional.get("PLUS_SERVICE", False) is True: + if fifa_com.PLUS_SERVICE is None: + raise Exception( + f'{BaseService.get_keys.__name__} must not be called ' + f'for the {fifa_com.__name__} service' + ) + return fifa_com.PLUS_SERVICE.get_keys(challenge, additional) + + licence = requests.post(additional["license_url"], data=challenge) + licence.raise_for_status() + return licence.content + + @staticmethod + def search_m3u8(m3u8): + try: + response = requests.get(m3u8).content.decode() + response = re.findall(r'https://[^\s]+', response) + + for u in response: + if ".ts?" in u: + response = requests.get(u).status_code + return 200 <= response < 300 + return None + except: + pass + return False + + @staticmethod + def is_valid_manifest(manifest): + # return False + try: + response = requests.get(manifest).content.decode() + response = re.findall(r'https://[^\s]+', response) + + for u in response: + if ".m3u8?" in u: + is_valid = fifa_com.search_m3u8(u) + if is_valid is not None: + return is_valid + + except: + pass + return False + + @staticmethod + def get_mpd_video_data(manifest, source_element): + manifest = manifest.replace(".m3u8?", ".mpd?") + response = requests.get(manifest).content.decode() + response = xmltodict.parse(response) + + kids_psshs = [] + periods = response["MPD"].get("Period", []) + if type(periods) is not list: + periods = [periods] + + filtered_periods = [] + for period in periods: + if period.get("@duration", None) is None: + continue + duration = isodate.parse_duration(period["@duration"]) + duration = duration.total_seconds() + if duration < fifa_com.INTRO_DURATION: + continue + + filtered_periods.append(period) + adaptations = period.get("AdaptationSet", []) + if type(adaptations) is not list: + adaptations = [adaptations] + + for adaptation in adaptations: + protections = adaptation.get("ContentProtection", []) + if type(protections) is not list: + protections = [protections] + + current_kid, current_pssh, license_url = None, None, None + for protection in protections: + if protection.get("@cenc:default_KID", None) is not None: + current_kid = protection["@cenc:default_KID"] + if PSSH.SystemId.Widevine.__str__() in protection.get("@schemeIdUri", ""): + current_pssh = protection["cenc:pssh"]["#text"] + license_url = protection.get("ms:laurl", {}).get("@licenseUrl", None) + + if current_kid is not None and current_pssh is not None: + break + + if current_kid is None or current_pssh is None: + continue + kids_psshs.append((current_kid.replace("-", ""), current_pssh, license_url)) + + content_id_dict = {} + pssh_data_dict = {} + for k, p, l in kids_psshs: + pssh_box = _parse_boxes(base64.b64decode(p))[0] + pssh_data = widevine_pssh_data_pb2.WidevinePsshData() + pssh_data.ParseFromString(pssh_box.pssh_data) + + if not pssh_data.HasField('content_id'): + continue + content_id = str(base64.b16encode(pssh_data.content_id).decode()) + + if l is None: + try: + license_args = pssh_data.content_id.decode().split("_") + l = ( + f'https://content-{license_args[1]}.uplynk.com/wv' + f'?b={license_args[0]}' + f'&v={license_args[0]}' + f'&pbs={license_args[2]}' + ) + except: + l = fifa_com.LICENSE_URL + + provider = None + if pssh_data.HasField('provider'): + provider = pssh_data.provider + protection_scheme = None + if pssh_data.HasField('protection_scheme'): + protection_scheme = pssh_data.protection_scheme + + content_id_dict[content_id] = content_id_dict.get(content_id, []) + [(k, l)] + if pssh_data_dict.get(content_id, None) is None: + pssh_data_dict[content_id] = (provider, protection_scheme, pssh_data.content_id) + + merged_psshs = [] + for cid, kid_license in content_id_dict.items(): + kids = [kid.encode() for kid, _ in kid_license] + provider, protection_scheme, raw_cid = pssh_data_dict[cid] + + pssh_data = _generate_widevine_data( + key_ids=kids, + content_id=raw_cid, + provider=provider, + protection_scheme=protection_scheme + ) + merged_pssh = PSSH.new(init_data=pssh_data, system_id=PSSH.SystemId.Widevine) + merged_psshs.append((merged_pssh.__str__(), kid_license[0][1])) + + additional = {} + psshs = [] + for pssh, license_url in merged_psshs: + psshs.append(pssh) + additional[pssh] = {"license_url": license_url} + + response["MPD"]["Period"] = filtered_periods + manifest = xmltodict.unparse(response, pretty=True) + + output_path = join(source_element.collection, source_element.element) + if not os.path.exists(output_path): + os.makedirs(output_path) + output_path = join(str(output_path), "master.mpd") + + with open(output_path, "w") as f: + f.write(manifest) + return output_path, psshs, additional + + @staticmethod + def get_video_data(source_element): + if fifa_com.PLUS_SERVICE is not None and "/watch/series/" not in source_element.url: + response = requests.get( + source_element.url, allow_redirects=False, + headers={"User-Agent": fifa_com.USER_AGENT} + ) + if response.headers.get("Location", None) is not None: + temp_element = BaseElement() + temp_element.copy(source_element) + source_element.url = response.headers["Location"].rstrip("/") + + try: + return fifa_com.PLUS_SERVICE.get_video_data(source_element) + except Exception as e: + source_element.copy(temp_element) + if type(e) is not CustomException: + raise e + + video_id = re.search(r"/watch/([^/?]*)", source_element.url).group(1) + category_type = video_id + if category_type == "series": + video_id = source_element.url.split("/watch/")[1].split("/")[1:] + + response = requests.get( + fifa_com.EPISODES_URL, params={ + 'locale': fifa_com.LOCALE, 'seriesId': video_id[0], + 'seasonId': video_id[1], 'episodeId': video_id[2] + } + ) + + if response.status_code == 404: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="This content isn't available", + solution='Do not attempt to download it' + )) + + response = json.loads(response.content.decode()) + if source_element.element is None: + for f in ["title", "internalTitle", "episodeInternalTitle"]: + if response.get(f, None) in ["", None]: + continue + + source_element.element = get_valid_filename(response[f]) + break + + if source_element.element is None: + source_element.element = get_valid_filename(f"Episode_{video_id[2]}") + video_id = response["videoEntryId"] + + elif category_type == "movie": + video_id = re.search(r"/watch/[^/]*/([^/?]*)", source_element.url).group(1) + + response = requests.get( + fifa_com.MOVIE_URL.format(movie_id=video_id), + params={'locale': fifa_com.LOCALE} + ) + + if response.status_code == 404: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="This content isn't available", + solution='Do not attempt to download it' + )) + + response = json.loads(response.content.decode()) + metadata = response.get("video", {}) + if source_element.element is None: + + for f in ["title", "internalTitle"]: + if metadata.get(f, None) in ["", None]: + continue + + source_element.element = get_valid_filename(metadata[f]) + break + + if source_element.element is None: + source_element.element = get_valid_filename(f"Movie_{video_id}") + video_id = metadata["videoEntryId"] + + response = requests.get( + fifa_com.VIDEO_PLAYER_URL.format(video_id=video_id), + params={'locale': fifa_com.LOCALE} + ) + + status_code = response.status_code + if status_code == 404: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="This content isn't available", + solution='Do not attempt to download it' + )) + + response = json.loads(response.content.decode()) + if source_element.element is None: + source_element.element = get_valid_filename(response.get('title', video_id)) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + fifa_com.__name__ + ) + + response = response["preplayParameters"] + preplay_url = fifa_com.PREPLAY_URL.format(content_id=response["contentId"]) + if response.get("queryStr", None) is not None: + preplay_url += "?" + response["queryStr"] + if response.get("signature", None) is not None: + if "?" not in preplay_url: + preplay_url += "?" + else: + preplay_url += "&" + preplay_url += "sig=" + quote(response["signature"]) + + response = json.loads(requests.get(preplay_url).content.decode()) + manifest = response["playURL"] + + if fifa_com.IS_VALID_MANIFEST is None: + with fifa_com.LOCK: + if fifa_com.IS_VALID_MANIFEST is None: + fifa_com.IS_VALID_MANIFEST = fifa_com.is_valid_manifest(manifest) + + if fifa_com.IS_VALID_MANIFEST: + return manifest, None, {} + return fifa_com.get_mpd_video_data(manifest, source_element) + + @staticmethod + def get_collection_elements(collection_url): + if "/watch/" in collection_url and "/series/" not in collection_url: + return [BaseElement(url=collection_url)] + + if "/watch/series/" in collection_url: + if fifa_com.PLUS_SERVICE is not None: + redirect_url = fifa_com.REDIRECT_URL.format( + page=collection_url.split(fifa_com.BASE_URL)[1][1:] + ) + response = requests.get(redirect_url, headers={"User-Agent": fifa_com.USER_AGENT}) + response = json.loads(response.content.decode()).get("redirectUrl", None) + + if response is not None: + temp_url = str(collection_url) + collection_url = response + + try: + return fifa_com.PLUS_SERVICE.get_collection_elements(collection_url) + except Exception as e: + collection_url = temp_url + if type(e) is not CustomException: + raise e + + video_id = collection_url.split("/watch/series/")[1].split("/") + if len(video_id) < 3: + return None + + series_season_id = video_id[1] + series_episode_id = video_id[2] + response = requests.get( + fifa_com.EPISODES_URL, params={ + 'locale': fifa_com.LOCALE, 'seriesId': video_id[0], + 'seasonId': series_season_id, 'episodeId': series_episode_id + } + ) + if response.status_code == 404: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=collection_url, + reason="This content isn't available", + solution='Do not attempt to download it' + )) + response = json.loads(response.content.decode()) + + collection_title = None + for f in ["seriesTitle", "seriesInternalTitle"]: + if response.get(f, None) in ["", None]: + continue + + collection_title = response[f] + break + if collection_title is None: + collection_title = f'Series_{video_id[0]}' + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + fifa_com.__name__ + ), + get_valid_filename(collection_title) + ) + + collection = [] + seasons = response.get("seasons", []) + seasons = sorted(seasons, key=lambda s: int(s["seasonNumber"])) + for season in seasons: + check = check_range(True, season["seasonNumber"], None) + if check is True: + continue + elif check is False: + return collection + + episodes = season.get("episodes", []) + episodes = sorted(episodes, key=lambda e: int(e["episodeNumber"])) + for episode in episodes: + check = check_range(False, season["seasonNumber"], episode["episodeNumber"]) + if check is True: + continue + elif check is False: + return collection + + episode_title = None + for f1 in [None, "video", "videoPlayerdata"]: + if f1 is None: + metadata = episode + else: + metadata = episode.get(f1, {}) + if metadata in [{}, None, ""]: + continue + if type(metadata) is not dict: + continue + + for f2 in ["title", "internalTitle", "slug"]: + if metadata.get(f2, None) in ["", None]: + continue + + episode_title = metadata[f2] + break + + if episode_title is not None: + break + + if episode_title is None: + episode_title = episode["episodeId"] + episode_title = get_valid_filename(f'Episode_{episode["episodeNumber"]}_{episode_title}') + + collection.append(BaseElement( + url=collection_url.replace( + series_episode_id, episode["episodeId"] + ).replace(series_season_id, season["seasonId"]), + collection=join(collection_title, f'Season_{season["seasonNumber"]}'), + element=episode_title + )) + return collection + + if "/search?" in collection_url and "source=" in collection_url: + params_dict = parse_qs(urlparse(collection_url).query) + if params_dict["source"][0].lower() not in ["fifa"]: + return None + for k, v in params_dict.items(): + params_dict[k] = v[0] + + collection_name = f'Filters_{collection_url.split("?")[1]}' + collection_name = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + fifa_com.__name__ + ), + get_valid_filename(collection_name)[0:50] + ) + + search_query = { + 'locale': fifa_com.LOCALE, 'clientType': 'fifaplus', + 'type': 'search', 'context': 'default', + 'size': fifa_com.PAGE_SIZE, 'dateFrom': '1900-01-01' + } + for k, v in params_dict.items(): + if k == 'q': + search_query['searchString'] = v + continue + if k == 'ftype': + if v == 'all': + v = 'article,document,video,movie,videoEpisode' + search_query["contentType"] = v + continue + if k == 'fsortBy': + search_query["sort"] = v + continue + if k == 'fdateFrom': + search_query['dateFrom'] = v + continue + if k in ["source", "fpage"]: + continue + search_query[k] = v + collection = [] + + content_index = -fifa_com.PAGE_SIZE + page_index = 0 + while True: + page_index += 1 + content_index += fifa_com.PAGE_SIZE + + check = check_range(True, page_index, None) + if check is True: + continue + elif check is False: + return collection + + search_query['from'] = content_index + response = json.loads(requests.get( + fifa_com.SEARCH_URL, + headers={'X-Functions-Key': fifa_com.SEARCH_KEY}, + params=search_query + ).content.decode()) + + hit_index = 0 + hits = response.get("hits", {}).get("hits", []) + if len(hits) == 0: + break + + for hit in hits: + hit_index += 1 + check = check_range(False, page_index, hit_index) + if check is True: + continue + elif check is False: + return collection + + information = json.loads(hit["_source"]["additionalInformation"]) + if information["ArticleId"] is not None: + continue + content_id = None + for f in ["VideoEntryId", "MovieId", "VideoEpisodeId", "VideoSeasonId", "VideoSeriesId"]: + if information[f] is not None: + content_id = information[f] + break + if content_id is None: + continue + + hit_title = hit.get("title", None) + if hit_title is None: + hit_title = information.get("InternalTitle", None) + if hit_title is None: + hit_title = content_id + hit_title = get_valid_filename(f'V{hit_index}_{hit_title}') + hit_url = hit["_source"]["url"] + + collection.append(BaseElement( + url=hit_url, + collection=join(collection_name, f'Page_{page_index}'), + element=hit_title + )) + + return collection + return None diff --git a/API/proxiesembed/drmproxy/services/filmzie_com.py b/API/proxiesembed/drmproxy/services/filmzie_com.py new file mode 100644 index 0000000..237f73d --- /dev/null +++ b/API/proxiesembed/drmproxy/services/filmzie_com.py @@ -0,0 +1,150 @@ +import builtins +import json +import re +from os.path import join + +import requests + +from utils.constants.macros import USER_ERROR, ERR_MSG +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename, clean_url + + +class filmzie_com(BaseService): + DEMO_URLS = [ + "https://filmzie.com/content/before-the-dawn-2019?sourceId=613744175971e8001d714ce6", + "https://filmzie.com/content/trump-the-art-of-the-insult", + "https://filmzie.com/content/3-athletes-4-seasons-slovak-compilation-2018", + "https://filmzie.com/content/vegan-mashup-2012", + "https://filmzie.com/content/tough-rides-2013", + "https://filmzie.com/content/inner-worlds-the-series-2012", + ] + + STREAM_URL = 'https://filmzie.com/api/v1/video/stream/{stream_id}' + + @staticmethod + def test_service(): + main_service.run_service(filmzie_com) + + @staticmethod + def get_additional_params(additional): + return [("MUXER", lambda s: s.format(args="mkv:muxer=mkvmerge"))] + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def initialize_service(): + return filmzie_com + + @staticmethod + def get_keys(challenge, additional): + raise Exception( + f'{BaseService.get_keys.__name__} must not be called ' + f'for the {filmzie_com.__name__} service' + ) + + @staticmethod + def get_video_data(source_element): + stream_id = source_element.additional["stream_id"] + response = requests.get(filmzie_com.STREAM_URL.format(stream_id=stream_id)) + response = response.content.decode() + response = json.loads(response) + response = response["data"]["source"] + + manifest = None + for s in response.get("sources", []): + if s.get("file", None) not in ["", None]: + manifest = s["file"] + break + if manifest is None: + manifest = response["hlsV2"] + + return manifest, None, {} + + @staticmethod + def get_collection_elements(collection_url): + collection_url = clean_url(collection_url) + response = requests.get(collection_url).content.decode() + response = re.findall(r"window\['APP_STATE'][^=]*=[^{]({.*});", response) + response = json.loads(response[0]) + + response = response.get("contentPage", {}) + if response in [{}, None, ""]: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + metadata = response.get("content", {}) + seo_tags = metadata.get("seoTags", {}) + if seo_tags is None: + seo_tags = {} + + collection_title = metadata.get("title", seo_tags.get("title", None)) + if collection_title in ["", None]: + collection_title = collection_url.split("/")[-1] + collection_title = get_valid_filename(collection_title) + + if metadata.get("type", "").lower() not in ["tv_show"]: + stream_id = metadata["videos"] + stream_id = filter(lambda v: v["type"] not in ["TRAILER"], stream_id) + stream_id = list(stream_id)[0]["id"] + + return [BaseElement( + url=collection_url, + element=collection_title, + collection=join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + filmzie_com.__name__ + ), + additional={"stream_id": stream_id} + )] + + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + filmzie_com.__name__ + ), + collection_title + ) + collection = [] + + seasons = response.get("seasons", []) + seasons = sorted(seasons, key=lambda s: s["seasonNumber"]) + for season in seasons: + season_index = season["seasonNumber"] + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + season_title = f'S{season_index}_{season.get("title", "")}' + season_title = get_valid_filename(season_title) + episodes = season.get("episodes", []) + episode_index = 0 + + for episode in episodes: + episode_index += 1 + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + stream_id = episode["videoId"] + episode_title = episode.get("title", stream_id) + collection.append(BaseElement( + url=collection_url + f"/s{season_index}_e{episode_index}", + collection=join(collection_title, season_title), + element=get_valid_filename(f'Episode_{episode_index}_{episode_title}'), + additional={"stream_id": stream_id} + )) + + return collection diff --git a/API/proxiesembed/drmproxy/services/france_tv.py b/API/proxiesembed/drmproxy/services/france_tv.py new file mode 100644 index 0000000..782e3aa --- /dev/null +++ b/API/proxiesembed/drmproxy/services/france_tv.py @@ -0,0 +1,668 @@ +import builtins +import json +import re +import os +import random +import logging +from os.path import join +from typing import Optional + +import requests +from bs4 import BeautifulSoup + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.cdm import get_pssh_from_cenc_pssh +from utils.tools.common import get_valid_filename, clean_url, update_url_params + + +def _ftv_cookies() -> dict: + """Return france.tv auth cookies from builtins (set by server.py auth flow). + Returns an empty dict if not authenticated.""" + cookies = getattr(builtins, 'FRANCETV_COOKIES', None) + if cookies is None: + return {} + # Filter out internal keys + return {k: v for k, v in cookies.items() if not k.startswith('_')} + + +def _ftv_proxy_session(): + """Return the SOCKS5H-proxied requests.Session from server.py, or None.""" + return getattr(builtins, 'FTV_PROXY_SESSION', None) + + +def _ftv_is_socks_session(sess: object) -> bool: + try: + proxies = getattr(sess, 'proxies', None) or {} + if not isinstance(proxies, dict) or not proxies: + return False + for v in proxies.values(): + if isinstance(v, str) and v.lower().startswith('socks'): + return True + return False + except Exception: + return False + + +FTV_DEFAULT_HEADERS = { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36', + 'Accept': '*/*', + 'Accept-Language': 'fr-FR,fr;q=0.9,en;q=0.6', +} + + +_FTV_PROXY_POOL = None +_FTV_PROXY_SESSION: Optional[requests.Session] = None +_FTV_PROXY_URL: Optional[str] = None + + +def _ftv_redact_proxy_url(proxy_url: Optional[str]) -> str: + if not proxy_url: + return 'none' + try: + # socks5h://user:pass@host:port -> socks5h://***@host:port + if '@' in proxy_url: + scheme, rest = proxy_url.split('://', 1) if '://' in proxy_url else ('proxy', proxy_url) + creds, hostpart = rest.split('@', 1) + return f"{scheme}://***@{hostpart}" + return proxy_url + except Exception: + return 'proxy' + + +def _ftv_build_proxy_url(proxy: dict) -> Optional[str]: + host = proxy.get('host') + port = proxy.get('port') + if not host or not port: + return None + ptype = proxy.get('type') or 'socks5h' + auth = proxy.get('auth') + if auth: + return f"{ptype}://{auth}@{host}:{port}" + return f"{ptype}://{host}:{port}" + + +def _ftv_local_proxy_pool(): + global _FTV_PROXY_POOL + if _FTV_PROXY_POOL is not None: + return _FTV_PROXY_POOL + try: + _FTV_PROXY_POOL = json.loads(os.environ.get('PROXIES_SOCKS5_JSON', '[]')) + except Exception: + _FTV_PROXY_POOL = [] + # Keep only valid entries + _FTV_PROXY_POOL = [p for p in _FTV_PROXY_POOL if isinstance(p, dict) and p.get('host') and p.get('port')] + return _FTV_PROXY_POOL + + +def _ftv_local_proxy_session(force_rotate: bool = False) -> Optional[requests.Session]: + """Create/return a local requests.Session using a SOCKS5H proxy from env. + Used as fallback when server.py didn't create builtins.FTV_PROXY_SESSION. + """ + global _FTV_PROXY_SESSION, _FTV_PROXY_URL + + if _FTV_PROXY_SESSION is not None and not force_rotate: + return _FTV_PROXY_SESSION + + pool = _ftv_local_proxy_pool() + if not pool: + _FTV_PROXY_SESSION = None + _FTV_PROXY_URL = None + return None + + # Pick a different proxy when rotating + candidates = pool + if _FTV_PROXY_URL: + candidates = [p for p in pool if _ftv_build_proxy_url(p) != _FTV_PROXY_URL] or pool + + proxy = random.choice(candidates) + proxy_url = _ftv_build_proxy_url(proxy) + if not proxy_url: + return None + + sess = requests.Session() + sess.proxies = { + 'http': proxy_url, + 'https': proxy_url, + } + sess.headers.update({ + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36', + 'Accept': '*/*', + 'Accept-Language': 'fr-FR,fr;q=0.9,en;q=0.6', + }) + + _FTV_PROXY_SESSION = sess + _FTV_PROXY_URL = proxy_url + return _FTV_PROXY_SESSION + + +def _ftv_request(method: str, url: str, **kwargs): + """HTTP request helper for france.tv extraction. + + Priority: + 1) builtins.FTV_PROXY_SESSION if present + 2) local SOCKS5H proxy session from PROXIES_SOCKS5_JSON + + Retries on 403 / proxy issues by rotating the local proxy. + """ + cookies = kwargs.pop('cookies', {}) + cookies.update(_ftv_cookies()) + timeout = kwargs.pop('timeout', 15) + + # Ensure decent default headers (some endpoints are picky) + req_headers = kwargs.pop('headers', None) or {} + merged_headers = dict(FTV_DEFAULT_HEADERS) + merged_headers.update(req_headers) + kwargs['headers'] = merged_headers + + log = logging.getLogger(__name__) + + # Prefer server-provided session + sess = _ftv_proxy_session() + if sess and _ftv_is_socks_session(sess): + req = getattr(sess, method.lower()) + resp = req(url, cookies=cookies, timeout=timeout, **kwargs) + status = getattr(resp, 'status_code', None) + if status not in (403, 429): + return resp + builtins_proxy = None + try: + proxies = getattr(sess, 'proxies', None) or {} + builtins_proxy = proxies.get('https') or proxies.get('http') + except Exception: + builtins_proxy = None + log.warning(f"[france.tv] {status} via builtins proxy on URL: {url} (proxy={_ftv_redact_proxy_url(builtins_proxy)})") + # Fall through to local proxy rotation if available + + # Fallback: local proxy rotation + pool = _ftv_local_proxy_pool() + if not pool: + log.warning(f"[france.tv] No PROXIES_SOCKS5_JSON configured; requesting directly: {url}") + max_attempts = min(6, len(pool)) if pool else 1 + last_resp = None + last_exc = None + for attempt in range(max_attempts): + local_sess = _ftv_local_proxy_session(force_rotate=(attempt > 0)) + if local_sess is None: + # No proxy configured -> direct + req = getattr(requests, method.lower()) + return req(url, cookies=cookies, timeout=timeout, **kwargs) + try: + req = getattr(local_sess, method.lower()) + resp = req(url, cookies=cookies, timeout=timeout, **kwargs) + last_resp = resp + status = getattr(resp, 'status_code', None) + if status in (403, 429): + log.warning( + f"[france.tv] {status} on URL: {url} (attempt {attempt+1}/{max_attempts}, proxy={_ftv_redact_proxy_url(_FTV_PROXY_URL)})" + ) + if attempt < (max_attempts - 1): + continue + return resp + return resp + except requests.RequestException as e: + last_exc = e + continue + if last_exc: + raise last_exc + if last_resp is not None: + return last_resp + req = getattr(requests, method.lower()) + return req(url, cookies=cookies, timeout=timeout, **kwargs) + + +def _ftv_get(url, **kwargs): + """requests.get() wrapper that injects france.tv session cookies + SOCKS5H proxy.""" + return _ftv_request('get', url, **kwargs) + + +def _ftv_post(url, **kwargs): + """requests.post() wrapper that injects france.tv session cookies + SOCKS5H proxy.""" + return _ftv_request('post', url, **kwargs) + + +class france_tv(BaseService): + DEMO_URLS = [ + "https://www.france.tv/spectacles-et-culture/festival-rock-en-seine/6428750-gossip-en-concert-a-rock-en-seine-2024.html", + "https://www.france.tv/france-3/commissaire-dupin/commissaire-dupin-saison-1/6366821-une-famille-endeuillee.html", + "https://www.france.tv/enfants/six-huit-ans/tortues-ninja-les-chevaliers-d-ecaille/saison-1/6137135-a-la-recherche-du-technodrome.html", + "https://www.france.tv/films/films-drame/494223-monsieur-klein.html", + "https://www.france.tv/films/6096218-butch-cassidy-et-le-kid.html", + "https://www.france.tv/collection/6314801-ils-ont-vecu-les-jeux/", + "https://www.france.tv/collection/6250718-histoires-de-famille/", + "https://www.france.tv/france-2/un-si-grand-soleil/", + "https://www.france.tv/enfants/six-huit-ans/il-etait-une-fois-ces-droles-d-objets/", + "https://www.france.tv/enfants/six-huit-ans/tortues-ninja-les-chevaliers-d-ecaille/", + "https://www.france.tv/france-3/ouija-un-ete-meurtrier/toutes-les-videos/", + ] + + VIDEOS_URL = None + LICENSE_URL = None + BASE_URL = 'https://www.france.tv' + COLLECTION_URL = "https://www.france.tv/api/collections/" + + MAIN_JS = "https://static.francetv.fr/magnetoscope/main.magnetoscope.js" + PAGE_SIZE = 50 + + @staticmethod + def test_service(): + main_service.run_service(france_tv) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def set_endpoints(): + response = _ftv_get(france_tv.MAIN_JS).content.decode() + france_tv.LICENSE_URL = "https://api-drm.ftven.fr/v1/wvls/contentlicenseservice/v1/licenses" + + france_tv.VIDEOS_URL = re.findall(r'gateway:\{url:"([^"]+)"', response)[0] + france_tv.VIDEOS_URL += "{video_id}" + + @staticmethod + def initialize_service(): + if france_tv.LICENSE_URL is None: + france_tv.set_endpoints() + return france_tv + + @staticmethod + def get_keys(challenge, additional): + licence = _ftv_post( + france_tv.LICENSE_URL, + headers={'nv-authorizations': additional["video_token"]}, + data=challenge + ) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_video_id(source_url, source_text): + content_id = source_url.split("/")[-1].split("-")[0] + + lists = [] + for r in [ + r'[\'"]content_id[\'\\"][^:]*:([^\\"\',]+)[,\\"\']', + r'[\'"]video_factory_id[\'\\"][^:]*:[\\"\']*([^\\"\',]+)[\\"\']' + ]: + temp_ids = re.findall(r, source_text, flags=re.DOTALL) + current_ids = [] + for i in temp_ids: + if i not in current_ids: + current_ids.append(i) + + lists.append(current_ids) + + size = min(len(lists[0]), len(lists[1])) + for i in range(size): + if content_id == lists[0][i]: + return lists[1][i] + return None + + @staticmethod + def get_video_data(source_element): + if source_element.additional is None: + source_element.additional = {} + video_id = source_element.additional.get("video_id", None) + + if video_id is None: + source_text = _ftv_get( + source_element.url, + headers={ + 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', + }, + ).content.decode() + video_id = france_tv.get_video_id(source_element.url, source_text) + + if video_id is None: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content wasn't found / is a text article, or isn't available yet", + solution="Do not attempt to download it or wait until you can play it on your browser" + )) + + response = _ftv_get( + france_tv.VIDEOS_URL.format(video_id=video_id), + params={'domain': 'domain', 'browser': 'browser', 'capabilities': 'drm'}, + headers={ + 'Referer': source_element.url, + 'Origin': france_tv.BASE_URL, + }, + ) + if response.status_code == 404: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + response = response.content.decode() + response = json.loads(response) + + if source_element.element is None: + meta = response.get("meta", None) + if meta is None: + meta = {} + + video_title = meta.get("title", None) + if video_title not in [None, ""]: + for f in ["pre_title", "additional_title"]: + if meta.get(f, None) not in ["", None]: + video_title += " " + meta[f] + + if video_title is None: + video_title = "" + video_title = video_title.strip() + + if len(video_title) == 0: + video_title = source_element.url.split("/")[-1].split(".html")[0] + source_element.element = get_valid_filename(video_title) + + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + france_tv.__name__ + ) + + video_info = response["video"] + is_drm = video_info.get("drm", False) is True + token_dict = video_info["token"] + if is_drm: + token_url = token_dict["drm"] + else: + token_url = token_dict["akamai"] + + manifest = video_info["url"] + additional = {} + pssh = None + if not is_drm: + manifest = json.loads(_ftv_get( + update_url_params(token_url, {"url": manifest}) + ).content.decode())["url"] + else: + manifest_content = _ftv_get( + manifest, + headers={ + 'Referer': source_element.url, + 'Origin': france_tv.BASE_URL, + 'Accept': 'application/dash+xml,application/xml;q=0.9,*/*;q=0.8', + }, + ) + if manifest_content.status_code == 403: + logging.getLogger(__name__).warning( + f"[france.tv] 403 fetching manifest URL: {manifest} (page={source_element.url}, proxy={_ftv_redact_proxy_url(_FTV_PROXY_URL)})" + ) + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need French IP to access content (and in this case, even to download it) or your VPN was detected", + solution="Use a VPN or get a better one" + )) + manifest_content = manifest_content.content.decode() + + try: + pssh = get_pssh_from_cenc_pssh(manifest_content) + except: + pssh = None + + if pssh is None: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}. Can't extract pssh", + solution=f"Extend the {france_tv.__name__} service" + )) + + response = _ftv_post( + token_url, + headers={ + 'Referer': source_element.url, + 'Origin': france_tv.BASE_URL, + }, + json={ + "id": video_id, "drm_type": "widevine", + "license_type": "online" + }, + ) + + response = response.content.decode() + response = json.loads(response) + additional["video_token"] = response["token"] + + return manifest, pssh, additional + + @staticmethod + def get_collection_elements(collection_url): + collection_url = clean_url(collection_url) + content_id = collection_url.split("/")[-1].split("-")[0] + is_id_number = re.match(r"\d+$", content_id) is not None + + if collection_url.endswith(".html"): + if is_id_number: + return [BaseElement(url=collection_url)] + if collection_url.endswith("direct.html"): + return None + + response = _ftv_get(collection_url) + response = response.content.decode() + soup = BeautifulSoup(response, 'html5lib') + + try: + collection_title = soup.title.text + collection_title = collection_title.replace("- Les épisodes en replay - France TV", "") + collection_title = collection_title.replace("- Toutes les vidéos en streaming - France TV", "") + assert len(collection_title) > 0 + except: + collection_title = collection_url.split(france_tv.BASE_URL)[-1] + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + france_tv.__name__ + ), + get_valid_filename(collection_title) + ) + + collection = [] + collection_url += "/" + if ("/collection/" in collection_url and is_id_number) or collection_url.endswith("/toutes-les-videos/"): + page = -1 + video_index = 0 + param_name = "id" + param_value = content_id + + if not is_id_number: + param_name = "slug" + param_value = collection_url.split(france_tv.BASE_URL + "/")[1] + param_value = param_value.split("/toutes-les-videos")[0].replace("/", "_") + + while True: + page += 1 + page_response = _ftv_get( + france_tv.COLLECTION_URL, + params={param_name: param_value, "type": "collection", "page": page} + ) + page_response = json.loads(page_response.content.decode()) + + try: + contents = page_response["result"] + assert len(contents) > 0 + except: + contents = [] + + if len(contents) == 0: + break + + for video_info in contents: + video_index += 1 + check = check_range(False, None, video_index) + if check is True: + continue + elif check is False: + return collection + + video_url = video_info["content"]["url"] + if not video_url.startswith(france_tv.BASE_URL): + video_url = f'{france_tv.BASE_URL}{video_url}' + + video_title = f'Video_{video_index}' + video_title += " " + video_info["content"].get( + "title", + video_url.split("/")[-1].split(".html")[0] + ) + + if not video_url.endswith(".html"): + continue + if video_info["content"].get("type", "").lower() in ["article"]: + continue + label = video_info["content"].get("label", None) + if label is not None and type(label) is str: + if label.lower() in ["indisponible"]: + continue + + collection.append(BaseElement( + url=video_url, + collection=collection_title, + element=get_valid_filename(video_title), + additional={"video_id": video_info.get("tracking", {}).get("video_factory_id", None)} + )) + + return collection + + page_seasons = soup.find_all( + 'a', + attrs={ + 'href': lambda x: x and + ("/saison-" in x or "-saison-" in x) and + ".html" not in x and not x.endswith("/") + } + ) + + visited = [] + seasons = [] + for season in page_seasons: + season_url = season["href"] + try: + season_index = re.search(r'saison-(\d+)', season_url).group(1) + assert season_index.isdigit() + season_index = int(season_index) + except: + continue + + if season_index in visited: + continue + visited.append(season_index) + + season_name = season.getText() + seasons.append((season_url, season_index, season_name)) + + seasons = sorted(seasons, key=lambda s: s[1]) + for season_url, season_index, season_name in seasons: + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + if season_url[0] == "/": + season_url = season_url[1:] + if season_url[-1] == "/": + season_url = season_url[:-1] + + season_name = join(collection_title, get_valid_filename(f'S{season_index} {season_name}')) + page = -1 + slug_value = season_url.replace("/", "_") + + episodes = [] + extras = [] + stop_flags = [] + page_filters = ["only-replay", "only-extract"] + + while len(stop_flags) != len(page_filters): + page += 1 + for page_filter in page_filters: + if page_filter in stop_flags: + continue + + season_response = _ftv_get( + france_tv.COLLECTION_URL, + params={ + "slug": slug_value, "type": "season", "page": page, + "size": france_tv.PAGE_SIZE, "filter": page_filter + } + ) + season_response = json.loads(season_response.content.decode()) + + try: + contents = season_response["result"] + assert len(contents) > 0 + except: + contents = [] + + if len(contents) == 0: + stop_flags.append(page_filter) + continue + + for video_info in contents: + video_url = video_info["content"]["url"] + if not video_url.startswith(france_tv.BASE_URL): + video_url = f'{france_tv.BASE_URL}{video_url}' + + if not video_url.endswith(".html"): + continue + if video_info["content"].get("type", "").lower() in ["article"]: + continue + label = video_info["content"].get("label", None) + if label is not None and type(label) is str: + if label.lower() in ["indisponible"]: + continue + + try: + assert page_filter == "only-replay" + video_index = video_info["content"]["title"].lower() + video_index = re.search(r's\d+\s*e(\d+)', video_index).group(1) + assert video_index.isdigit() + video_index = int(video_index) + except: + video_index = None + + video_title = video_info["content"].get( + "title", + video_url.split("/")[-1].split(".html")[0] + ) + + if video_index is not None: + episodes.append((video_url, video_index, video_title, video_info)) + else: + extras.append((video_url, video_index, video_title, video_info)) + + episodes = sorted(episodes, key=lambda e: e[1]) + try: + last_index = episodes[-1][1] + 1 + except: + last_index = 1 + episodes += extras + + for episode_url, episode_index, episode_name, episode_info in episodes: + if episode_index is None: + episode_index = last_index + last_index += 1 + + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + episode_name = f'E{episode_index} {episode_name}' + collection.append(BaseElement( + url=episode_url, + collection=season_name, + element=get_valid_filename(episode_name), + additional={"video_id": episode_info.get("tracking", {}).get("video_factory_id", None)} + )) + + return collection diff --git a/API/proxiesembed/drmproxy/services/goplay_be.py b/API/proxiesembed/drmproxy/services/goplay_be.py new file mode 100644 index 0000000..c51a002 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/goplay_be.py @@ -0,0 +1,452 @@ +import base64 +import builtins +import json +import os +import re +from os.path import join + +import browser_cookie3 +import requests +import xmltodict + +from utils.constants.macros import USER_ERROR, ERR_MSG, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, CustomException, BaseService +from utils.tools.args import check_range +from utils.tools.cdm import get_pssh_from_cenc_pssh +from utils.tools.common import get_valid_filename, clean_url + + +class goplay_be(BaseService): + DEMO_URLS = [ + "https://www.goplay.be/video/nonkels/de", + "https://www.goplay.be/video/maxine/maxine/maxine-s1-aflevering-2", + "https://www.goplay.be/video/left-for-dead-the-ashley-reeves-story", + "https://www.goplay.be/video/jodi-arias-dirty-little-secret-1", + "https://www.goplay.be/vermist", + "https://www.goplay.be/de-spor", + "https://www.goplay.be/de-expeditie", + ] + + CONTENT_URL = "https://api.goplay.be/web/v1/videos/{content_type}/{uuid}" + STREAM_URL = 'https://dai.google.com/ondemand/dash/content/{content_id}/vid/{video_id}/streams' + LICENSE_URL = "https://widevine.keyos.com/api/v4/getLicense" + BASE_URL = "https://www.goplay.be" + + BEARER_TOKEN = None + AMZ_JSON = 'application/x-amz-json-1.1' + + @staticmethod + def test_service(): + main_service.run_service(goplay_be) + + @staticmethod + def get_additional_params(additional): + additional_params = BaseService.get_additional_params(additional) + manifest_url = additional.get("manifest_url", None) + if manifest_url is not None: + manifest_url = clean_url(manifest_url) + additional_params = [( + "BASE_URL", lambda s: s.format(value=manifest_url) + )] + additional_params + return additional_params + + @staticmethod + def credentials_needed(): + return {"FIREFOX_COOKIES": True} + + @staticmethod + def get_bearer(): + cookie_dict = {} + check_cookies = {} + check_list = ["accesstoken", "refreshtoken"] + + for c in browser_cookie3.firefox(domain_name='goplay.be'): + cookie_dict[c.name] = c.value + cookie_name = c.name.lower() + for f in check_list: + if f in cookie_name: + check_cookies[f] = True + if len(cookie_dict.keys()) == 0 or len(check_cookies.keys()) != len(check_list): + return None + + refresh_token = None + client_id = None + refresh_url = None + for c, v in cookie_dict.items(): + c_name = c.lower() + if "accesstoken" in c_name: + refresh_url = json.loads(base64.b64decode(v.split(".")[1] + "==").decode())["iss"] + refresh_url = "/".join(refresh_url.split("/")[:-1]) + "/" + + if "refreshtoken" in c_name: + refresh_token = v + client_id = c.split(".")[1] + + if refresh_url is not None and refresh_token is not None: + break + + assert len(refresh_token) > 0 + assert len(client_id) > 0 + assert len(refresh_url) > 0 + + response = requests.post( + refresh_url, + headers={ + 'content-type': goplay_be.AMZ_JSON, + 'x-amz-target': 'AWSCognitoIdentityProviderService.InitiateAuth' + }, + data=json.dumps({ + "ClientId": client_id, "AuthFlow": "REFRESH_TOKEN_AUTH", + "AuthParameters": {"REFRESH_TOKEN": refresh_token} + }) + ) + response = response.content.decode() + response = json.loads(response) + return response["AuthenticationResult"]["AccessToken"] + + @staticmethod + def initialize_service(): + if goplay_be.BEARER_TOKEN is None: + goplay_be.BEARER_TOKEN = goplay_be.get_bearer() + if goplay_be.BEARER_TOKEN is None: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=f'from {goplay_be.__name__}', + reason='Need account for this service', + solution='Sign into your account using Firefox' + )) + return goplay_be + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + goplay_be.LICENSE_URL, data=challenge, + headers={"customdata": additional["drm_token"]} + ) + licence.raise_for_status() + return licence.content + + @staticmethod + def extend_dict(input_dict, input_key, input_value): + old_value = input_dict.get(input_key, None) + if old_value is None: + input_dict[input_key] = input_value + return input_dict + + for k1, v1 in input_value.items(): + if v1 is None: + continue + if type(v1) is not list: + v1 = [v1] + + v2 = old_value.get(k1, None) + if v2 is None: + old_value[k1] = v1 + continue + if type(v2) is not list: + v2 = [v2] + + v2.extend(v1) + old_value[k1] = v2 + input_dict[input_key] = old_value + + @staticmethod + def generate_master_mpd(source_element, mpd_content): + xml_dict = xmltodict.parse(mpd_content) + xml_node = xml_dict["MPD"] + new_nodes = [] + + xml_periods = xml_node["Period"] + if type(xml_periods) is not list: + xml_periods = [xml_periods] + for period in xml_periods: + if "-ad-" in period["@id"]: + continue + new_nodes.append(period) + + segment_dict = {} + assert len(new_nodes) >= 1 + for loop in range(0, 2): + if loop == 1: + new_nodes = [new_nodes[0]] + + for node in new_nodes: + adaptations = node["AdaptationSet"] + if type(adaptations) is not list: + adaptations = [adaptations] + + for adaptation in adaptations: + representations = adaptation["Representation"] + if type(representations) is not list: + representations = [representations] + + for representation in representations: + segment_key = representation.get("@width", representation.get("@audioSamplingRate", None)) + if loop == 0: + goplay_be.extend_dict( + segment_dict, segment_key, + representation["SegmentTemplate"]["SegmentTimeline"] + ) + else: + representation["SegmentTemplate"]["SegmentTimeline"] = segment_dict[segment_key] + + xml_dict["MPD"]["Period"] = new_nodes + mpd_content = xmltodict.unparse(xml_dict, pretty=True) + output_path = join(source_element.collection, source_element.element) + if not os.path.exists(output_path): + os.makedirs(output_path) + output_path = join(str(output_path), "master.mpd") + + with open(output_path, "w") as f: + f.write(mpd_content) + return output_path + + @staticmethod + def get_video_data(source_element): + response = requests.get(source_element.url, headers={'Accept': 'application/json'}) + response = json.loads(response.content.decode()) + if response.get("uuid", None) in ["", None]: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + content_type = response["contentType"] + content_type = re.sub(r'([a-z])([A-Z])', r'\1-\2', content_type).lower() + response = requests.get( + goplay_be.CONTENT_URL.format(content_type=content_type, uuid=response["uuid"]), + headers={'Authorization': f'Bearer {goplay_be.BEARER_TOKEN}'}, + ) + status_code = response.status_code + response = json.loads(response.content.decode()) + message = response.get("message", "").lower() + + if 400 <= status_code < 500 and "locked" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need Belgian IP to access content", + solution="Use a VPN" + )) + + if source_element.element is None: + try: + program = response["tracking"]["cimName"] + assert len(program) > 0 + except: + program = "" + if program == "": + try: + program = response["tracking"]["piano"]["program"] + assert len(program) > 0 + except: + program = "" + else: + program = "" + + try: + title = response["title"] + except: + title = "" + if title.lower() == program.lower(): + title = "" + + if source_element.element is None: + source_element.element = "" + for f in ["seasonNumber", "episodeNumber"]: + try: + title += " " + f[0].upper() + str(int(response[f])) + except: + pass + + source_element.element = get_valid_filename(source_element.element + " " + program + " " + title) + if source_element.element in ["", None]: + source_element.element = source_element.url.split("/video/")[-1] + source_element.element = get_valid_filename(source_element.element) + + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + goplay_be.__name__ + ) + + drm_token = None + try: + is_drm = response["flags"]["isDrm"] + assert is_drm + drm_token = response["drmXml"] + assert len(drm_token) > 0 and type(drm_token) is str + is_drm = True + except: + is_drm = False + + try: + manifest = response["manifestUrls"]["dash"] + assert len(manifest) > 0 + except: + manifest = None + + if manifest is None: + response = response["ssai"] + response = requests.post(goplay_be.STREAM_URL.format( + content_id=response["contentSourceID"], + video_id=response["videoID"] + )) + + try: + assert 200 <= response.status_code < 300 + response = response.content.decode() + response = json.loads(response) + except: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}/{APP_ERROR}', + url=source_element.url, + reason=f"Dash manifest not found", + solution=f"If you can watch the video in browser, then extend the {goplay_be.__name__} service" + )) + + manifest = response["stream_manifest"] + if response.get("manifest_format", "dash").lower() not in ["dash", "mpd"]: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}", + solution=f"Extend the {goplay_be.__name__} service" + )) + + pssh_value = None + additional = {"drm_token": drm_token} + mpd_content = None + if is_drm or builtins.CONFIG.get("BASIC", False) is False: + mpd_content = requests.get(manifest).content.decode() + + if is_drm: + try: + pssh_value = get_pssh_from_cenc_pssh(mpd_content) + except: + pssh_value = None + if pssh_value is None: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}", + solution=f"Extend the {goplay_be.__name__} service" + )) + + if builtins.CONFIG.get("BASIC", False) is True: + return manifest, pssh_value, additional + + additional["manifest_url"] = manifest + try: + manifest = goplay_be.generate_master_mpd(source_element, mpd_content) + except: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}", + solution=f"Extend the {goplay_be.__name__} service" + )) + return manifest, pssh_value, additional + + @staticmethod + def get_label_index(label, label_regex): + if label is None or len(label) == 0: + return None + label = label.lower() + label = re.sub(r'\s+', ' ', label) + label = label.replace(' ', "_") + for r in label_regex: + try: + return int(re.findall(r, label)[0]) + except: + pass + return None + + @staticmethod + def get_collection_elements(collection_url): + collection_url = clean_url(collection_url) + if "/live-kijken" in collection_url: + return None + if "/video/" in collection_url: + return [BaseElement(url=collection_url)] + + response = requests.get(collection_url) + response = response.content.decode() + try: + collection_title = re.findall(r'([^<>]+)', response)[0] + collection_title = get_valid_filename(collection_title) + assert len(collection_title) > 0 + except: + collection_title = collection_url.split("/")[-1] + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + goplay_be.__name__ + ), + get_valid_filename(collection_title) + ) + + videos = [] + visited = [] + for video in re.findall( + fr'"([^"]*/video/{collection_url.split("/")[-1]}/[^\\"]+)[\\"]', + response + ): + if not video.startswith("http"): + video = goplay_be.BASE_URL + video + if video in visited: + continue + visited.append(video) + + paths = video.split("/")[-2:] + season_index = None + episode_index = goplay_be.get_label_index( + label=paths[-1], + label_regex=["aflevering-(\\d+)"] + ) + + if episode_index is not None: + for i in [-1, -2]: + season_index = goplay_be.get_label_index( + label=paths[i], + label_regex=["-s(\\d+)[-/]"] + ) + if season_index is not None: + break + if season_index is None: + episode_index = None + + videos.append((video, season_index, episode_index)) + + extras = [v for v in videos if v[1] is None] + videos = sorted([v for v in videos if v[1] is not None], key=lambda v: (v[1], v[2])) + try: + max_season = max(videos, key=lambda v: v[1])[1] + 1 + except: + max_season = 1 + extras = [(v[0], max_season, i + 1) for i, v in enumerate(extras)] + + collection = [] + for episode_url, season_index, episode_index in videos + extras: + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + season_title = "extras" if season_index == max_season else "" + collection.append(BaseElement( + url=episode_url, + collection=join(collection_title, get_valid_filename(f'Season_{season_index} {season_title}')), + element=f"Episode_{episode_index}" + )) + return collection diff --git a/API/proxiesembed/drmproxy/services/joyn_de.py b/API/proxiesembed/drmproxy/services/joyn_de.py new file mode 100644 index 0000000..5fbb3ec --- /dev/null +++ b/API/proxiesembed/drmproxy/services/joyn_de.py @@ -0,0 +1,1282 @@ +import builtins +import json +import re +from os.path import join +from urllib.parse import parse_qs, urlparse + +import requests +from bs4 import BeautifulSoup + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR, CACHE_DIR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.cdm import get_pssh_from_cenc_pssh +from utils.tools.common import get_valid_filename, clean_url, dict_to_file, file_to_dict + + +class joyn_de(BaseService): + DEMO_URLS = [ + # Without account + "https://www.joyn.de/play/live-tv?channel_id=1007", + "https://www.joyn.de/play/live-tv?channel_id=1298", + "https://www.joyn.de/play/serien/the-race/2-1-bts-folge-1-the-race-staffel-2-beginnt", + "https://www.joyn.de/play/serien/big-brother/2025-15-tageszusammenfassung-15-bluetenzauber-und-fleischeslust?from=%2F", + "https://www.joyn.de/play/highlight/serien/newstime/wie-reagiert-deutschland-auf-trump-zoelle?from=%2F", + "https://www.joyn.de/play/highlight/serien/newstime/supervulkan-neapel-plant-evakuierung?from=%2Fnews", + "https://www.joyn.de/play/compilation/nba-orlando-magic-at-cleveland-cavaliers-im-relive/nba-overtime-krimi-bei-pacers-und-timberwolves", + "https://www.joyn.de/play/compilation/ran-racing-dtm/dtm-kein-taxifahrer-mehr-timo-glock-ist-zurueck-in-der-dtm", + "https://www.joyn.de/play/trailer/compilation/spacetime/spacetime-staffel-4-trailer", + "https://www.joyn.de/play/filme/kung-fu-panda", + "https://www.joyn.de/play/filme/die-olsenbande-sieht-rot", + + # With (free) account and no PIN + "https://www.joyn.de/play/live-tv?channel_id=1132", + "https://www.joyn.de/play/live-tv?channel_id=1043", + "https://www.joyn.de/play/serien/detektiv-conan/1-198-das-haus-der-200-masken-1", + "https://www.joyn.de/play/serien/joko-klaas-gegen-prosieben/3-10-episode-10-bptn5pr23j41", + "https://www.joyn.de/play/compilation/ran-football-elf-live/elf-finale-rhein-fire-vs-vienna-vikings-in-voller-laenge", + "https://www.joyn.de/play/filme/detektiv-conan-die-azurblaue-flagge", + # With (free) account and PIN + "https://www.joyn.de/play/live-tv?channel_id=1105", + "https://www.joyn.de/play/serien/z-nation/2-1-der-murphy", + "https://www.joyn.de/play/serien/killers-on-camera-auf-frischer-tat-ertappt/1-4-moerderische-rache-bpijk7f7j76s", + "https://www.joyn.de/play/filme/the-demon-hunter", + "https://www.joyn.de/play/filme/the-sniper", + + "https://www.joyn.de/play/live-tv", + "https://www.joyn.de/serien/joko-klaas-gegen-prosieben", + "https://www.joyn.de/serien/navy-cis", + "https://www.joyn.de/serien/dragon-ball-z-kai", + "https://www.joyn.de/serien/one-piece", + "https://www.joyn.de/compilation/ran-football-elf-live", + "https://www.joyn.de/compilation/spacetime", + "https://www.joyn.de/play/playlist/639347?from=/sport", + "https://www.joyn.de/play/playlist/617143?from=/sport", + ] + + ENTITLEMENT_URL = None + PLAYLIST_URL = None + GRAPHQL_URL = None + ANONYMOUS_URL = None + REFRESH_URL = None + ENDPOINTS_URL = None + OAUTH_URL = 'https://www.joyn.de/oauth' + LIVESTREAM_URL = 'https://www.joyn.de/play/live-tv?channel_id={channel_id}' + BASE_URL = 'https://www.joyn.de' + + CACHE_FILE = None + BEARER_TOKEN = None + GRAPHQL_API_KEY = None + PLATFORM = 'web' + CLIENT_ID = 'client_id' + PAGE_COUNT = 50 + EMAIL = "" + PASSWORD = "YOUR_PASSWORD (leave at least one login field empty if you don't want to use an account)" + PIN = "YOUR_PIN (this field is ignored if it's not a 4 digit text or if you don't use an account)" + + @staticmethod + def test_service(): + main_service.run_service(joyn_de) + + @staticmethod + def is_content_livestream(content, additional): + return "/live-tv" in content and "channel_id=" in content + + @staticmethod + def credentials_needed(): + return { + "OPTIONAL": True, + "EMAIL": joyn_de.EMAIL, + "PASSWORD": joyn_de.PASSWORD, + "PIN": joyn_de.PIN + } + + @staticmethod + def get_anon_bearer_token(): + return json.loads(requests.post( + joyn_de.ANONYMOUS_URL, json={'client_id': joyn_de.CLIENT_ID, 'client_name': joyn_de.PLATFORM} + ).content.decode())["access_token"] + + @staticmethod + def login_flow(credentials): + response = requests.get(joyn_de.ENDPOINTS_URL, params={ + 'client_id': joyn_de.CLIENT_ID, 'client_name': joyn_de.PLATFORM + }) + response = json.loads(response.content.decode()) + token_url = response["redeem-token"] + + response = response["web-login"] + auth_url = clean_url(response) + login_url = urlparse(response) + login_url = f"{login_url.scheme}://{login_url.netloc}" + "/login-srv/login" + + response = parse_qs(urlparse(response).query) + client_id = response["client_id"][0] + + response = requests.get( + auth_url, allow_redirects=False, + params={'client_id': client_id, 'response_type': 'code'} + ) + response = response.headers["location"] + response = parse_qs(urlparse(response).query) + request_id = response["requestId"][0] + + response = requests.post(login_url, allow_redirects=False, data={ + 'username': credentials["EMAIL"], 'requestId': request_id, + 'password': credentials["PASSWORD"] + }) + + try: + response = response.headers["location"] + response = parse_qs(urlparse(response).query) + code = response["code"][0] + assert code not in ["", None] + except: + return None + + response = requests.post(token_url, json={ + 'code': code, 'client_id': client_id, + 'redirect_uri': joyn_de.OAUTH_URL, + 'tracking_name': joyn_de.PLATFORM + }) + return json.loads(response.content.decode()) + + @staticmethod + def refresh_flow(refresh_token): + response = requests.post( + joyn_de.REFRESH_URL, headers={'joyn-platform': joyn_de.PLATFORM}, + json={ + 'client_name': joyn_de.PLATFORM, 'client_id': joyn_de.CLIENT_ID, + 'grant_type': 'Bearer', 'refresh_token': refresh_token + } + ) + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + + joyn_de.check_expired_token(status_code, response, f'from the {joyn_de.__name__} service') + return response + + @staticmethod + def get_bearer_token(): + # return joyn_de.get_anon_bearer_token() + try: + refresh_token = file_to_dict(joyn_de.CACHE_FILE)["refresh_token"] + assert type(refresh_token) is str and len(refresh_token) > 0 + except: + refresh_token = None + + if refresh_token is not None: + response = joyn_de.refresh_flow(refresh_token) + else: + class_name = joyn_de.__name__.replace("_", ".") + credentials = builtins.CONFIG["SERVICE_CREDENTIALS"][class_name] + try: + assert type(credentials["EMAIL"]) is str + assert type(credentials["PASSWORD"]) is str + except: + return None + if credentials["EMAIL"].strip() == "" or credentials["PASSWORD"].strip() == "": + return joyn_de.get_anon_bearer_token() + + response = joyn_de.login_flow(credentials) + if response is None: + return None + + bearer_token = response["access_token"] + refresh_token = response["refresh_token"] + for f in [bearer_token, refresh_token]: + assert type(f) is str and len(f) > 0 + dict_to_file(joyn_de.CACHE_FILE, {"refresh_token": refresh_token}) + return bearer_token + + @staticmethod + def get_pin(): + class_name = joyn_de.__name__.replace("_", ".") + credentials = builtins.CONFIG["SERVICE_CREDENTIALS"][class_name] + try: + if credentials["EMAIL"].strip() == "" or credentials["PASSWORD"].strip() == "": + raise + pin = credentials["PIN"] + assert type(pin) is str and pin.isdigit() and len(pin) == 4 + return pin + except: + return "" + + @staticmethod + def endpoint_regex(regex_list, content): + value = None + for reg in regex_list: + try: + value = re.findall(reg + r"[^{}]*{([^{}]+)}", content)[0] + value = re.findall(r'value[^:]*:[^"\']*["\']([^"\']+)["\']', value)[0] + assert len(value) > 0 + break + except: + value = None + return value + + @staticmethod + def set_endpoints(): + try: + response = requests.get(joyn_de.BASE_URL).text + response = BeautifulSoup(response, "html5lib") + response = response.find_all("script", src=True) + response = [s["src"] for s in response if "app-" in s["src"] and ".js" in s["src"]][0] + if not response.startswith("http"): + response = joyn_de.BASE_URL + response + response = requests.get(response).text + except: + response = None + + api_key = joyn_de.endpoint_regex( + ["API_GW_API_KEY", "NEXT_PUBLIC_PLAYER_GRAPHQL_SERVICE_API_KEY"], + response + ) + if api_key in ["", None]: + api_key = "4f0fd9f18abbe3cf0e87fdb556bc39c8" + joyn_de.GRAPHQL_API_KEY = api_key + + entitlement = joyn_de.endpoint_regex( + ["NEXT_PUBLIC_PLAYER_ENTITLEMENT_BASE_URL"], + response + ) + if entitlement in ["", None]: + entitlement = 'https://entitlement.p7s1.io/api/user' + if "/entitlement-token" not in entitlement: + entitlement += "/entitlement-token" + joyn_de.ENTITLEMENT_URL = entitlement + + playback = joyn_de.endpoint_regex( + ["NEXT_PUBLIC_PLAYER_PLAYBACK_API_BASE_URL"], + response + ) + if playback in ["", None]: + playback = 'https://api.vod-prd.s.joyn.de/v1' + joyn_de.PLAYLIST_URL = playback + '/{asset_type}/{asset_id}/playlist' + + graphql = joyn_de.endpoint_regex( + ["GRAPHQL_ENDPOINT", "NEXT_PUBLIC_PLAYER_GRAPHQL_ENDPOINT"], + response + ) + if graphql in ["", None]: + graphql = 'https://api.joyn.de/graphql' + joyn_de.GRAPHQL_URL = graphql + + auth_url = joyn_de.endpoint_regex(["AUTH_ENDPOINT"], response) + if auth_url in ["", None]: + auth_url = 'https://auth.joyn.de' + joyn_de.ANONYMOUS_URL = auth_url + '/auth/anonymous' + joyn_de.REFRESH_URL = auth_url + '/auth/refresh' + joyn_de.ENDPOINTS_URL = auth_url + '/sso/endpoints' + + @staticmethod + def initialize_service(): + if joyn_de.GRAPHQL_API_KEY is None: + joyn_de.set_endpoints() + if joyn_de.CACHE_FILE is None: + joyn_de.CACHE_FILE = join(CACHE_DIR, f'{joyn_de.__name__}.json') + if builtins.CONFIG.get("FRESH", False) is True: + dict_to_file(joyn_de.CACHE_FILE, {}) + + if joyn_de.BEARER_TOKEN is None: + joyn_de.BEARER_TOKEN = joyn_de.get_bearer_token() + if joyn_de.BEARER_TOKEN is None: + return None + + joyn_de.PIN = joyn_de.get_pin() + if joyn_de.PIN is None: + joyn_de.PIN = "" + return joyn_de + + @staticmethod + def check_expired_token(status_code, response, url): + try: + error_code = response.get("code", "").lower() + assert len(error_code) > 0 + except: + error_code = "" + try: + error_data = response.get("data", "").lower() + assert len(error_data) > 0 + except: + error_data = "" + + if ( + status_code in [401] or "invalid_jwt" in error_code or + ("invalid refresh token" in error_data or "used refresh token" in error_data) + ): + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=url, + reason="Can't access the video content because the cached token expired", + solution=f'Delete the {joyn_de.CACHE_FILE} cache manually or add the parameter --fresh to your command' + )) + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post(additional["license_url"], data=challenge) + licence.raise_for_status() + return licence.content + + @staticmethod + def analyze_vod_format(url): + content_client_hash = None + content_client_path = None + content_client_field = None + content_query_lambda = None + + if "/filme/" in url: + content_client_hash = "a06da53f05ced9524e1694940d6ceb23e97d85cdb081d3c2ac44ffae5b3190a6" + content_client_field = "movie" + content_client_path = "/" + url.split("/play/")[1] + + content_query_lambda = lambda cid: requests.post( + joyn_de.GRAPHQL_URL, + json={ + 'query': '''query Movie($id: ID!) { movie(id: $id) { title video { id } } }''', + "variables": {"id": cid} + }, + headers={ + 'authorization': f'Bearer {joyn_de.BEARER_TOKEN}', + 'joyn-platform': joyn_de.PLATFORM, 'x-api-key': joyn_de.GRAPHQL_API_KEY + } + ) + elif "/serien/" in url: + series_type = re.search(r'/play/([^/]+)/serien/', url) + if series_type is None: + content_client_hash = "864e9acb09fed428ad277efef2351295e76518b6803e63d5831a4150b96f9051" + content_client_field = "episode" + series_type = "play" + + content_query_lambda = lambda cid: requests.get( + joyn_de.GRAPHQL_URL, + params={ + 'query': '''query PlayerSeriesEpisode { episode(id: "{{content_id}}") { + title number season { number } series { title } video { id } + } }'''.replace("{{content_id}}", cid) + }, + headers={ + 'authorization': f'Bearer {joyn_de.BEARER_TOKEN}', + 'joyn-platform': joyn_de.PLATFORM, 'x-api-key': joyn_de.GRAPHQL_API_KEY + } + ) + else: + content_client_field = "extra" + series_type = series_type.group(1).lower() + + if series_type == "highlight": + content_client_hash = "497626ae16c19df71d61147590e7eaa7e3b288f90a3e207c400daaf1651563de" + content_query_lambda = lambda cid: requests.post( + joyn_de.GRAPHQL_URL, + json={ + 'query': '''query Highlight($id: ID!) { extra(id: $id) { title video { id } } }''', + "variables": {"id": cid} + }, + headers={ + 'authorization': f'Bearer {joyn_de.BEARER_TOKEN}', + 'joyn-platform': joyn_de.PLATFORM, 'x-api-key': joyn_de.GRAPHQL_API_KEY + } + ) + content_client_path = "/" + url.split(f"/{series_type}/")[1] + elif "/compilation/" in url: + comp_type = re.search(r'/play/([^/]+)/compilation/', url) + if comp_type is None: + content_client_hash = "8025eaf32540f47be5a377ceef8ce718116159569ad1d7e32766abed97f87961" + content_client_field = "compilationItem" + comp_type = "play" + + content_query_lambda = lambda cid: requests.post( + joyn_de.GRAPHQL_URL, + json={ + 'variables': {'id': cid}, 'query': ''' + query CompilationItem($id: ID!) { compilationItem(id: $id) { title video { id } } } + ''' + }, + headers={ + 'authorization': f'Bearer {joyn_de.BEARER_TOKEN}', + 'joyn-platform': joyn_de.PLATFORM, 'x-api-key': joyn_de.GRAPHQL_API_KEY + } + ) + else: + content_client_field = "extra" + comp_type = comp_type.group(1).lower() + + if comp_type == "trailer": + content_client_hash = "81e7a9385cb87ae569178ceb96563c427b72efdf94183ae75952579b39226556" + content_query_lambda = lambda cid: requests.post( + joyn_de.GRAPHQL_URL, + json={ + 'query': '''query Extra($id: ID!) { extra(id: $id) { title video { id } } }''', + 'variables': {'id': cid} + }, + headers={ + 'authorization': f'Bearer {joyn_de.BEARER_TOKEN}', + 'joyn-platform': joyn_de.PLATFORM, 'x-api-key': joyn_de.GRAPHQL_API_KEY + } + ) + content_client_path = "/" + url.split(f"/{comp_type}/")[1] + + for var in [content_client_hash, content_client_path, content_client_field, content_query_lambda]: + if var in [None, ""]: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=url, + reason=f"URL format not supported: {url}", + solution=f"Extend the {joyn_de.__name__} service" + )) + return content_client_hash, content_client_path, content_client_field, content_query_lambda + + @staticmethod + def handle_vod(source_element): + (content_client_hash, content_client_path, + content_client_field, content_query_lambda + ) = joyn_de.analyze_vod_format(source_element.url) + + response = requests.get( + joyn_de.GRAPHQL_URL, + params={ + 'variables': json.dumps({"path": content_client_path}), + 'extensions': json.dumps({"persistedQuery": {"version": 1, "sha256Hash": content_client_hash}}) + }, + headers={ + 'authorization': f'Bearer {joyn_de.BEARER_TOKEN}', + 'joyn-platform': joyn_de.PLATFORM, 'x-api-key': joyn_de.GRAPHQL_API_KEY + } + ) + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + temp_response = response + + try: + content_id = response["data"]["page"][content_client_field]["id"] + assert type(content_id) is str and len(content_id) > 0 + except: + content_id = None + + if content_id is None: + joyn_de.check_expired_token(status_code, temp_response, source_element.url) + + try: + for error in response.get("errors", []): + if type(error) is not dict: + continue + error_code = error.get("extensions", {}).get("code", "").lower() + if error_code in ["not_found"]: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + except CustomException as e: + raise e + except: + pass + raise + + response = content_query_lambda(content_id) + response = response.content.decode() + response = json.loads(response) + + response = response["data"] + response = response[content_client_field] + asset_id = response["video"]["id"] + + if source_element.element is None: + try: + title = response["series"]["title"] + assert len(title) > 0 and type(title) is str + except: + title = "" + + try: + temp_title = response["season"]["number"] + assert type(temp_title) in [str, int] + title += " S" + str(temp_title) + except: + pass + try: + temp_title = response["number"] + assert type(temp_title) in [str, int] + title += " E" + str(temp_title) + except: + pass + + try: + temp_title = response["title"] + assert len(temp_title) > 0 and type(temp_title) is str + title += " " + temp_title + except: + title += " " + source_element.url.split("/")[-1] + + source_element.element = get_valid_filename(title) + return asset_id + + @staticmethod + def handle_live(source_element): + channel_id = parse_qs(urlparse(source_element.url).query)["channel_id"][0] + response = requests.get( + joyn_de.GRAPHQL_URL, + headers={ + 'authorization': f'Bearer {joyn_de.BEARER_TOKEN}', + 'joyn-platform': joyn_de.PLATFORM, 'x-api-key': joyn_de.GRAPHQL_API_KEY + }, + params={ + 'variables': json.dumps({"id": channel_id}), + 'extensions': json.dumps({"persistedQuery": { + "version": 1, + "sha256Hash": "6395983f3c004b2f9f42c0e9beee5efb1ca6d866fa0e637214220117ee411b15" + }}) + } + ) + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + temp_response = response + + try: + response = response["data"]["brand"] + assert response["id"] == channel_id + + live_id = response["livestream"]["id"] + assert type(live_id) is str and live_id != "" + except: + joyn_de.check_expired_token(status_code, temp_response, source_element.url) + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + if source_element.element is None: + title = f"Live {live_id} id {channel_id}" + source_element.element = get_valid_filename(title) + return live_id + + @staticmethod + def get_video_data(source_element): + if source_element.additional is None: + source_element.additional = {} + asset_id = source_element.additional.get("asset_id", None) + + if "/live-tv" in source_element.url: + if asset_id in ["", None]: + asset_id = joyn_de.handle_live(source_element) + content_type = "LIVE" + asset_type = "channel" + else: + if asset_id in ["", None]: + asset_id = joyn_de.handle_vod(source_element) + content_type = "VOD" + asset_type = "asset" + + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + joyn_de.__name__ + ) + + response = requests.post( + joyn_de.ENTITLEMENT_URL, + headers={ + 'authorization': f'Bearer {joyn_de.BEARER_TOKEN}', + 'joyn-platform': joyn_de.PLATFORM + }, + json={'content_id': asset_id, 'content_type': content_type, "pin": joyn_de.PIN} + ) + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + + if status_code < 200 or 300 <= status_code: + if type(response) is not list: + response = [response] + + for error in response: + error = error.get("code", "").lower() + if "vpn_detected" in error or "notavailableincountry" in error: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need German IP to access content", + solution="Use a VPN (a good one that is not detected)" + )) + if "ageverification" in error or "pinrequired" in error: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason='Need PIN and account for this content', + solution='Set the PIN and account in the config file' + )) + if "pininvalid" in error: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason='Wrong PIN value', + solution='Set the correct PIN in the config file' + )) + if "playback_restricted" in error: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason='Need account for this content', + solution='Set the account credentials in the config file' + )) + if "business_model" in error: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Can't download paid content", + solution='Do not attempt to download it' + )) + + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Unknown error encountered: {str(response)}", + solution=f"Debug the {joyn_de.__name__} service" + )) + + response = requests.post( + joyn_de.PLAYLIST_URL.format(asset_type=asset_type, asset_id=asset_id), + headers={'authorization': f'Bearer {response["entitlement_token"]}'}, + json={ + 'manufacturer': 'unknown', 'platform': 'browser', 'maxSecurityLevel': 1, + 'streamingFormat': 'dash', 'model': 'unknown', 'protectionSystem': 'widevine', + 'enableDolbyAudio': True, 'enableSubtitles': True, 'maxResolution': 1080, + 'variantName': 'default' + } + ) + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + + if status_code < 200 or 300 <= status_code: + message = response.get("message", "").lower() + + if "channel not found" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The channel isn't available or it isn't a real livestream", + solution="Do not attempt to download it or download using the original vods URLs" + )) + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Unknown error encountered: {str(message)}", + solution=f"Debug the {joyn_de.__name__} service" + )) + + additional = {} + manifest = response["manifestUrl"] + license_url = response.get("licenseUrl", None) + pssh_value = None + + if license_url not in ["", None]: + try: + pssh_value = get_pssh_from_cenc_pssh(requests.get(manifest).text) + except: + pssh_value = None + + if pssh_value is None: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}", + solution=f"Extend the {joyn_de.__name__} service" + )) + additional["license_url"] = license_url + + return manifest, pssh_value, additional + + @staticmethod + def handle_live_list(collection_url): + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + joyn_de.__name__ + ), + get_valid_filename(collection_url.split("/")[-1] + " livestreams") + ) + + response = requests.get( + joyn_de.GRAPHQL_URL, + params={ + 'extensions': json.dumps({"persistedQuery": { + "version": 1, + "sha256Hash": "52b37a3cf5bc75e56026aed7b0d234874eeabd2eccd369d0cd3d3a6ea15ef566" + }}) + }, + headers={ + 'authorization': f'Bearer {joyn_de.BEARER_TOKEN}', + 'joyn-platform': joyn_de.PLATFORM, 'x-api-key': joyn_de.GRAPHQL_API_KEY + } + ) + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + temp_response = response + + try: + livestreams = response["data"]["liveStreams"] + assert type(livestreams) is list + except: + joyn_de.check_expired_token(status_code, temp_response, collection_url) + livestreams = [] + + live_index = 0 + collection = [] + for livestream in livestreams: + live_index += 1 + check = check_range(False, None, live_index) + if check is True: + continue + elif check is False: + return collection + + try: + brand_id = livestream["brand"]["id"] + assert brand_id is not None + except: + continue + try: + live_id = livestream["id"] + assert live_id not in ["", None] + except: + continue + + collection.append(BaseElement( + url=joyn_de.LIVESTREAM_URL.format(channel_id=brand_id), + collection=collection_title, + element=get_valid_filename(f"Channel {live_index} Live {live_id} id {brand_id}"), + additional={"asset_id": live_id} + )) + return collection + + @staticmethod + def get_content_url(content): + content_url = joyn_de.BASE_URL + if "/play/" not in content["path"]: + content_url += "/play" + try: + assert type(content["type"]) is str and len(content["type"]) > 0 + content_type = content["type"].lower() + if content_type[-1] == "s": + content_type = content_type[0:len(content_type) - 1] + content_url += "/" + content_type + except: + pass + content_url += content["path"] + return content_url + + @staticmethod + def handle_clips(clips_index, collection, collection_title, clips_path): + check = check_range(True, clips_index, None) + if check in [True, False]: + return collection + + clip_index = 0 + clips_title = join(collection_title, f"Season_{clips_index}_Clips") + clips_offset = -joyn_de.PAGE_COUNT + while True: + clips_offset += joyn_de.PAGE_COUNT + + response = requests.get( + joyn_de.GRAPHQL_URL, + params={ + 'variables': json.dumps({ + "path": clips_path, "first": joyn_de.PAGE_COUNT, "offset": clips_offset + }), + 'extensions': json.dumps({"persistedQuery": { + "version": 1, + "sha256Hash": "a68817f5c13383b59aa93cf97bf9892b364f1ce38523b4a20609ff1619523a30" + }}) + }, + headers={ + 'authorization': f'Bearer {joyn_de.BEARER_TOKEN}', + 'joyn-platform': joyn_de.PLATFORM, 'x-api-key': joyn_de.GRAPHQL_API_KEY + } + ) + try: + response = response.content.decode() + response = json.loads(response) + clips = response["data"]["page"]["clipsAndTrailers"]["extras"] + assert type(clips) is list and len(clips) > 0 + except: + break + + for clip in clips: + clip_index += 1 + check = check_range(False, clips_index, clip_index) + if check is True: + continue + elif check is False: + return collection + + clip_url = joyn_de.get_content_url(clip) + try: + clip_id = clip["video"]["id"] + assert type(clip_id) is str and len(clip_id) > 0 + except: + continue + + try: + clip_title = clip["title"] + assert type(clip_title) is str and len(clip_title) > 0 + except: + clip_title = clip_url.split("/") + clip_title = get_valid_filename(f'Clip_{clip_index} {clip_title}') + + collection.append(BaseElement( + url=clip_url, + collection=clips_title, + element=clip_title, + additional={"asset_id": clip_id} + )) + return collection + + @staticmethod + def handle_serien(collection_url): + response = requests.get( + joyn_de.GRAPHQL_URL, + params={ + 'variables': json.dumps({"path": "/serien/" + collection_url.split("/serien/")[1]}), + 'extensions': json.dumps({"persistedQuery": { + "version": 1, + "sha256Hash": "43cad327eeae12e14dfb629d662ebc947d78b71ec91d972ea1ef46ccdb29eede" + }}) + }, + headers={ + 'authorization': f'Bearer {joyn_de.BEARER_TOKEN}', + 'joyn-platform': joyn_de.PLATFORM, 'x-api-key': joyn_de.GRAPHQL_API_KEY + } + ) + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + temp_response = response + + try: + page = response["data"]["page"] + except: + page = None + + if page is None: + joyn_de.check_expired_token(status_code, temp_response, collection_url) + try: + for error in response.get("errors", []): + if error.get("extensions", {}).get("code", "").lower() in ["not_found"]: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + except CustomException as e: + raise e + except: + pass + raise + + response = page + try: + collection_title = response["series"]["title"] + assert type(collection_title) is str and len(collection_title) > 0 + except: + collection_title = None + if collection_title in ["", None]: + try: + collection_title = response["tracking"]["payload"]["cms_title"] + assert type(collection_title) is str and len(collection_title) > 0 + except: + collection_title = None + + if collection_title in ["", None]: + collection_title = collection_url.split("/serien/")[1] + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + joyn_de.__name__ + ), + get_valid_filename(collection_title) + ) + + response = response["series"] + try: + seasons = response["allSeasons"] + except: + seasons = [] + seasons = sorted(seasons, key=lambda s: s["number"]) + + collection = [] + for season in seasons: + try: + season_id = season["id"] + assert len(season_id) > 0 and type(season_id) is str + except: + continue + + season_index = season["number"] + season_title = join(collection_title, f"Season_{season_index}") + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + episodes = [] + eps_offset = -joyn_de.PAGE_COUNT + while True: + eps_offset += joyn_de.PAGE_COUNT + + response = requests.get( + joyn_de.GRAPHQL_URL, + params={ + 'variables': json.dumps({ + "id": season_id, "first": joyn_de.PAGE_COUNT, "offset": eps_offset + }), + 'extensions': json.dumps({"persistedQuery": { + "version": 1, + "sha256Hash": "ee2396bb1b7c9f800e5cefd0b341271b7213fceb4ebe18d5a30dab41d703009f" + }}) + }, + headers={ + 'authorization': f'Bearer {joyn_de.BEARER_TOKEN}', + 'joyn-platform': joyn_de.PLATFORM, 'x-api-key': joyn_de.GRAPHQL_API_KEY + } + ) + try: + response = response.content.decode() + response = json.loads(response) + current_episodes = response["data"]["season"]["episodes"] + assert type(current_episodes) is list and len(current_episodes) > 0 + except: + break + episodes.extend(current_episodes) + + episodes = sorted(episodes, key=lambda ep: ep["number"]) + for episode in episodes: + episode_index = episode["number"] + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + episode_url = joyn_de.get_content_url(episode) + try: + episode_id = episode["video"]["id"] + assert type(episode_id) is str and len(episode_id) > 0 + except: + continue + + try: + episode_title = episode["title"] + assert type(episode_title) is str and len(episode_title) > 0 + except: + episode_title = episode_url.split("/") + episode_title = get_valid_filename(f'Episode_{episode_index} {episode_title}') + + collection.append(BaseElement( + url=episode_url, + collection=season_title, + element=episode_title, + additional={"asset_id": episode_id} + )) + + try: + clips_index = seasons[-1]["number"] + 1 + except: + clips_index = 1 + return joyn_de.handle_clips( + clips_index, collection, collection_title, + "/serien/" + collection_url.split("/serien/")[1] + ) + + @staticmethod + def handle_compilation(collection_url): + collection_title = None + collection = [] + item_index = 0 + + season_index = 1 + check = check_range(True, season_index, None) + skip_flag = check in [True, False] + + comp_offset = -joyn_de.PAGE_COUNT + while True: + comp_offset += joyn_de.PAGE_COUNT + response = requests.get( + joyn_de.GRAPHQL_URL, + params={ + 'variables': json.dumps({ + "path": "/compilation/" + collection_url.split("/compilation/")[1], + "first": joyn_de.PAGE_COUNT, "offset": comp_offset + }), + 'extensions': json.dumps({"persistedQuery": { + "version": 1, + "sha256Hash": "0672194d788614168fba6effad2cf3f3de8cd73d980efd8a41991a177ded4693" + }}) + }, + headers={ + 'authorization': f'Bearer {joyn_de.BEARER_TOKEN}', + 'joyn-platform': joyn_de.PLATFORM, 'x-api-key': joyn_de.GRAPHQL_API_KEY + } + ) + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + temp_response = response + + try: + page = response["data"]["page"] + except: + page = None + + if page is None: + joyn_de.check_expired_token(status_code, temp_response, collection_url) + try: + for error in response.get("errors", []): + if error.get("extensions", {}).get("code", "").lower() in ["not_found"]: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + except CustomException as e: + raise e + except: + pass + raise + + response = page + if collection_title is None: + try: + collection_title = response["compilation"]["title"] + assert type(collection_title) is str and len(collection_title) > 0 + except: + collection_title = None + if collection_title in ["", None]: + try: + collection_title = response["tracking"]["payload"]["cms_title"] + assert type(collection_title) is str and len(collection_title) > 0 + except: + collection_title = None + + if collection_title in ["", None]: + collection_title = collection_url.split("/compilation/")[1] + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + joyn_de.__name__ + ), + get_valid_filename(collection_title) + ) + + try: + assert skip_flag is False + items = response["compilation"]["compilationItems"] + assert type(items) is list and len(items) > 0 + except: + break + + for item in items: + item_index += 1 + check = check_range(False, season_index, item_index) + if check is True: + continue + elif check is False: + return collection + + item_url = joyn_de.get_content_url(item) + try: + item_id = item["video"]["id"] + assert type(item_id) is str and len(item_id) > 0 + except: + continue + + try: + item_title = item["title"] + assert type(item_title) is str and len(item_title) > 0 + except: + item_title = item_url.split("/") + item_title = get_valid_filename(f'Item_{item_index} {item_title}') + + collection.append(BaseElement( + url=item_url, + collection=join(collection_title, f"Season_{season_index}"), + element=item_title, + additional={"asset_id": item_id} + )) + + return joyn_de.handle_clips( + season_index + 1, collection, collection_title, + "/compilation/" + collection_url.split("/compilation/")[1] + ) + + @staticmethod + def handle_playlist(collection_url): + playlist_id = collection_url.split("/playlist/")[1].split("/")[0] + collection_title = None + collection = [] + + item_offset = 0 + item_index = 0 + visited = [] + current_item = None + while True: + response = requests.post( + joyn_de.GRAPHQL_URL, + headers={ + 'authorization': f'Bearer {joyn_de.BEARER_TOKEN}', + 'joyn-platform': joyn_de.PLATFORM, 'x-api-key': joyn_de.GRAPHQL_API_KEY + }, + json={ + 'query': '''query Playlist( + $playlistId: ID!, $playlistOffset: Int = 0, + $playlistItemTypes: [PlaylistItemType] = [EXTRA, COMPILATION_ITEM] + ) { playlist(playlistId: $playlistId) { + title currentPlaylistItem(playlistItemTypes: $playlistItemTypes) { asset { + ... on Extra { title video { id } } + ... on CompilationItem { title path video { id } } + } } + remainingPlaylistItems( + first: {{page_count}} offset: $playlistOffset playlistItemTypes: $playlistItemTypes + ) { asset { + ... on Extra { title video { id } } + ... on CompilationItem { title path video { id } } + } } + } + }'''.replace("{{page_count}}", str(joyn_de.PAGE_COUNT)), + 'variables': {'playlistId': playlist_id, 'playlistOffset': item_offset} + } + ) + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + temp_response = response + + try: + playlist = response["data"]["playlist"] + except: + playlist = None + + if playlist is None: + joyn_de.check_expired_token(status_code, temp_response, collection_url) + try: + for error in response.get("errors", []): + if error.get("extensions", {}).get("code", "").lower() in ["not_found"]: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + except CustomException as e: + raise e + except: + pass + raise + + response = playlist + if collection_title is None: + try: + collection_title = response["title"] + assert type(collection_title) is str and len(collection_title) > 0 + except: + collection_title = None + + if collection_title in ["", None]: + collection_title = f'Playlist_{playlist_id}' + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + joyn_de.__name__ + ), + get_valid_filename(collection_title) + ) + + playlist_items = [] + if current_item is None: + try: + current_item = response["currentPlaylistItem"] + assert type(current_item) is dict + playlist_items = [current_item] + except: + current_item = {} + playlist_items = [] + + try: + items = response["remainingPlaylistItems"] + assert type(items) is list and len(items) > 0 + playlist_items += items + skip_flag = False + except: + skip_flag = True + + for playlist_item in playlist_items: + item_index += 1 + check = check_range(False, None, item_index) + if check is True: + continue + elif check is False: + return collection + + playlist_item = playlist_item["asset"] + item_url = joyn_de.get_content_url(playlist_item) + if item_url in visited: + continue + visited.append(item_url) + + try: + item_id = playlist_item["video"]["id"] + assert type(item_id) is str and len(item_id) > 0 + except: + continue + + try: + item_title = playlist_item["title"] + assert type(item_title) is str and len(item_title) > 0 + except: + item_title = item_url.split("/") + clip_title = get_valid_filename(f'Item_{item_index} {item_title}') + + collection.append(BaseElement( + url=item_url, + collection=collection_title, + element=clip_title, + additional={"asset_id": item_id} + )) + + if skip_flag or len(playlist_items) == 0: + break + item_offset += len(playlist_items) + return collection + + @staticmethod + def get_collection_elements(collection_url): + if "/live-tv" not in collection_url: + collection_url = clean_url(collection_url).rstrip("/") + elif "channel_id=" not in collection_url: + return joyn_de.handle_live_list(clean_url(collection_url).rstrip("/")) + + if "/play/" in collection_url: + if "/playlist/" in collection_url: + return joyn_de.handle_playlist(collection_url) + return [BaseElement(url=collection_url)] + + if "/serien/" in collection_url: + return joyn_de.handle_serien(collection_url) + if "/compilation/" in collection_url: + return joyn_de.handle_compilation(collection_url) + return None diff --git a/API/proxiesembed/drmproxy/services/kanopy_com.py b/API/proxiesembed/drmproxy/services/kanopy_com.py new file mode 100644 index 0000000..b26346b --- /dev/null +++ b/API/proxiesembed/drmproxy/services/kanopy_com.py @@ -0,0 +1,515 @@ +import base64 +import builtins +import json +import time +from os.path import join + +import browser_cookie3 +import requests + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.cdm import get_pssh_from_cenc_pssh +from utils.tools.common import get_valid_filename, clean_url + + +class kanopy_com(BaseService): + DEMO_URLS = [ + "https://www.kanopy.com/en/alplibrary/watch/video/15161814", + "https://www.kanopy.com/en/alplibrary/video/113155", + "https://www.kanopy.com/en/alplibrary/watch/video/14994123/14994127", + "https://www.kanopy.com/en/alplibrary/video/14837778/15070509/15070524", + "https://www.kanopy.com/en/alplibrary/watch/video/2567156", + "https://www.kanopy.com/en/alplibrary/video/12489916", + "https://www.kanopy.com/en/alplibrary/watch/video/2962529/2962535", + "https://www.kanopy.com/en/alplibrary/video/14414459/14414465", + + "https://www.kanopy.com/en/alplibrary/video/14098194", + "https://www.kanopy.com/en/alplibrary/video/15118812", + "https://www.kanopy.com/en/alplibrary/video/14837931", + "https://www.kanopy.com/en/alplibrary/video/3034173", + ] + + MEMBERSHIPS_URL = 'https://www.kanopy.com/kapi/memberships' + PLAYS_URL = 'https://www.kanopy.com/kapi/plays' + LICENSE_URL = "https://www.kanopy.com/kapi/licenses/widevine/{drm_id}" + VIDEO_INFO_URL = 'https://www.kanopy.com/kapi/videos/{video_id}' + ITEMS_URL = 'https://www.kanopy.com/kapi/videos/{collection_id}/items' + MANIFEST_URL = 'https://www.kanopy.com/kapi/manifests/{manifest_type}/{video_id}.{manifest_ext}' + + BEARER_TOKEN = None + USER_ID = None + DOMAIN_ID = None + X_VERSION = "///" + RETRIES_TIMER = 5 + RETRIES_COUNT = 3 + SRT_PRIORITY = {"srt": 2, "webvtt": 1, '': 0} + + @staticmethod + def test_service(): + main_service.run_service(kanopy_com) + + @staticmethod + def credentials_needed(): + return {"FIREFOX_COOKIES": True} + + @staticmethod + def get_account_info(): + cookie_dict = {} + for c in browser_cookie3.firefox(domain_name='kanopy.com'): + cookie_dict[c.name] = c.value + + try: + bearer_token = cookie_dict["kapi_token"] + assert type(bearer_token) is str and len(bearer_token) > 0 + user_id = json.loads(base64.b64decode(bearer_token.split(".")[1] + "==").decode())["data"]["uid"] + + assert type(user_id) in [int, str] and user_id not in ["", None] + return bearer_token, int(user_id) + except: + return None, None + + @staticmethod + def get_domain_id(): + response = requests.get( + kanopy_com.MEMBERSHIPS_URL, + params={'userId': kanopy_com.USER_ID}, + headers={ + 'Authorization': f'Bearer {kanopy_com.BEARER_TOKEN}', + 'x-Version': kanopy_com.X_VERSION + } + ) + if response.status_code in [401, 403]: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}/{APP_ERROR}', + url=f'from {kanopy_com.__name__}', + reason='Refresh the site cookies', + solution='Sign into your account using Firefox. ' + 'If it persists then debug the service' + )) + + response = response.content.decode() + response = json.loads(response)["list"] + for domain in response: + if domain.get("isDefault", False) is True: + return int(domain["domainId"]) + return int(response[0]["domainId"]) + + @staticmethod + def initialize_service(): + if kanopy_com.BEARER_TOKEN is None or kanopy_com.USER_ID is None: + kanopy_com.BEARER_TOKEN, kanopy_com.USER_ID = kanopy_com.get_account_info() + if kanopy_com.BEARER_TOKEN is None or kanopy_com.USER_ID is None: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=f'from {kanopy_com.__name__}', + reason='Need account for this service', + solution='Sign into your account using Firefox' + )) + + if kanopy_com.DOMAIN_ID is None: + kanopy_com.DOMAIN_ID = kanopy_com.get_domain_id() + return kanopy_com + + @staticmethod + def get_keys(challenge, additional): + licence = None + for i in range(1, kanopy_com.RETRIES_COUNT + 1): + try: + licence = requests.post( + additional["license_url"], data=challenge, + headers={ + 'Authorization': f'Bearer {kanopy_com.BEARER_TOKEN}', + 'x-Version': kanopy_com.X_VERSION + } + ) + licence.raise_for_status() + break + except Exception as e: + response = e.response + if response.status_code >= 300 or response.status_code < 200: + if i < kanopy_com.RETRIES_COUNT: + time.sleep(kanopy_com.RETRIES_TIMER) + continue + raise e + return licence.content + + @staticmethod + def get_video_name(collection_id, video_id): + responses = [] + if collection_id is None: + response = requests.get( + kanopy_com.VIDEO_INFO_URL.format(video_id=video_id), + params={'domainId': kanopy_com.DOMAIN_ID}, + headers={ + 'Authorization': f'Bearer {kanopy_com.BEARER_TOKEN}', + 'x-Version': kanopy_com.X_VERSION + } + ) + response = response.content.decode() + try: + response = json.loads(response)["video"] + except: + response = {"DEFAULT_VALUE": f"Video_id_{video_id}"} + responses.append(response) + else: + response = requests.get( + kanopy_com.VIDEO_INFO_URL.format(video_id=collection_id), + params={'domainId': kanopy_com.DOMAIN_ID}, + headers={ + 'Authorization': f'Bearer {kanopy_com.BEARER_TOKEN}', + 'x-Version': kanopy_com.X_VERSION + } + ) + response = response.content.decode() + try: + response = json.loads(response) + response = response.get("playlist", response.get("collection", None)) + assert type(response) is dict + except: + response = {"DEFAULT_VALUE": f"Series_id_{collection_id}"} + responses.append(response) + + response = requests.get( + kanopy_com.ITEMS_URL.format(collection_id=collection_id), + params={'domainId': kanopy_com.DOMAIN_ID}, + headers={ + 'Authorization': f'Bearer {kanopy_com.BEARER_TOKEN}', + 'x-Version': kanopy_com.X_VERSION + } + ) + response = response.content.decode() + try: + response = json.loads(response).get("list", []) + if type(response) is not list: + response = [response] + + for v in response: + v = v["video"] + if v["videoId"] == video_id: + response = v + break + assert type(response) is dict + except: + response = {"DEFAULT_VALUE": f"Video_id_{video_id}"} + responses.append(response) + + title = "" + for r in responses: + for f in ["title", "alias", "DEFAULT_VALUE"]: + if r.get(f, None) not in ["", None]: + title += r[f] + " " + break + return title.split() + + @staticmethod + def get_video_data(source_element): + ids = source_element.url.split("/video/")[1].split("/") + assert len(ids) > 0 + if len(ids) == 1: + collection_id, video_id = None, int(ids[0]) + else: + collection_id, video_id = int(ids[-2]), int(ids[-1]) + + response = requests.post( + kanopy_com.PLAYS_URL, + headers={ + 'Authorization': f'Bearer {kanopy_com.BEARER_TOKEN}', + 'x-Version': kanopy_com.X_VERSION + }, + json={'videoId': video_id, 'userId': kanopy_com.USER_ID, 'domainId': kanopy_com.DOMAIN_ID} + ) + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + error = response.get("errorSubcode", "").lower() + + if status_code in [403] or "playregionrestricted" in error: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need specific country IP to access content", + solution="Use a VPN for the country that lets you watch the video" + )) + if status_code in [404]: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + manifests = response.get("manifests", []) + if type(manifests) is not list: + manifests = [manifests] + + license_url = None + manifest = None + for m in manifests: + drm_id = m.get("drmLicenseID", None) + drm_type = m.get("drmType", None) + if type(drm_type) is str: + drm_type = drm_type.lower() + + if drm_id not in ["", None] and drm_type not in [None, "", "none"]: + if m.get("manifestType", "").lower() not in ["dash"]: + continue + + manifest = m.get("url", None) + if manifest in ["", None]: + manifest = kanopy_com.MANIFEST_URL.format( + manifest_type="dash", video_id=video_id, manifest_ext="mpd" + ) + license_url = kanopy_com.LICENSE_URL.format(drm_id=m["drmLicenseID"]) + break + + manifest = m.get("url", None) + if manifest in ["", None]: + manifest = kanopy_com.MANIFEST_URL.format( + manifest_type="hls", video_id=video_id, manifest_ext="m3u8" + ) + break + + if manifest is None: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + pssh_value = None + additional = {} + if license_url not in ["", None]: + try: + pssh_value = get_pssh_from_cenc_pssh(requests.get(manifest).text) + except: + pssh_value = None + + if pssh_value is None: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}", + solution=f"Extend the {kanopy_com.__name__} service" + )) + additional["license_url"] = license_url + + if source_element.element is None: + title = kanopy_com.get_video_name(collection_id, video_id) + source_element.element = get_valid_filename(title) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + kanopy_com.__name__ + ) + + try: + captions = response["captions"] + assert captions not in ["", None] + if type(captions) is not list: + captions = [captions] + assert len(captions) > 0 + except: + captions = [] + + subtitle_index = 0 + subtitles = [] + subtitle_path = join(source_element.collection, source_element.element) + for caption in captions: + try: + files = caption["files"] + assert files not in ["", None] + if type(files) is not list: + files = [files] + assert len(files) > 0 + except: + continue + + try: + file = list(sorted( + files, reverse=True, + key=lambda f: kanopy_com.SRT_PRIORITY.get(f.get("type", "").lower(), 0) + ))[0] + subtitle_index += 1 + srt_title = caption.get("language", "") + srt_title = f'subtitle_{subtitle_index} {srt_title}' + + subtitles.append((False, BaseElement( + url=file["url"], + collection=subtitle_path, + element=f'{get_valid_filename(srt_title)}.{file["type"]}' + ))) + except: + pass + + additional["SUBTITLES"] = subtitles + return manifest, pssh_value, additional + + @staticmethod + def get_collection_elements(collection_url): + collection_url = clean_url(collection_url).rstrip("/") + if "/video/" not in collection_url: + return None + if "/watch/" in collection_url: + return [BaseElement(url=collection_url)] + if collection_url.split("/video/")[1].count("/") >= 1: + return [BaseElement(url=collection_url)] + + watch_url = collection_url.replace("/video/", "/watch/video/") + series_id = collection_url.split("/")[-1] + response = requests.get( + kanopy_com.VIDEO_INFO_URL.format(video_id=series_id), + params={'domainId': kanopy_com.DOMAIN_ID}, + headers={ + 'Authorization': f'Bearer {kanopy_com.BEARER_TOKEN}', + 'x-Version': kanopy_com.X_VERSION + } + ) + if response.status_code in [404]: + return [] + + response = response.content.decode() + temp_response = None + try: + response = json.loads(response) + temp_response = response + response = response.get("collection", response.get("playlist", None)) + assert type(response) is dict + except: + try: + temp_response = temp_response["video"] + assert type(temp_response) is dict + return [BaseElement(url=watch_url)] + except: + pass + response = {} + + collection_title = None + for f in ["title", "alias"]: + if response.get(f, None) not in ["", None]: + collection_title = response[f] + break + + if collection_title in ["", None]: + collection_title = f'Series_{series_id}' + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + kanopy_com.__name__ + ), + get_valid_filename(collection_title) + ) + + response = requests.get( + kanopy_com.ITEMS_URL.format(collection_id=series_id), + params={'domainId': kanopy_com.DOMAIN_ID}, + headers={ + 'Authorization': f'Bearer {kanopy_com.BEARER_TOKEN}', + 'x-Version': kanopy_com.X_VERSION + } + ) + response = response.content.decode() + response = json.loads(response) + try: + contents = response["list"] + assert contents not in ["", None] + if type(contents) is not list: + contents = [contents] + except: + contents = [] + + seasons = [] + episodes = [] + for content in contents: + content_type = content.get("type", "").lower() + if content_type in ["playlist", "collection"]: + seasons.append(content) + elif content_type == "video": + episodes.append(content) + + if len(episodes) >= 0: + seasons.append(episodes) + + season_index = 0 + collection = [] + for season in seasons: + season_index += 1 + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + episode_index = 0 + if type(season) is list: + season_title = f"Season_{season_index}" + season_id = None + else: + season = season.get("playlist", season.get("collection", None)) + season_id = season["videoId"] + + season_title = None + for f in ["title", "alias"]: + if season.get(f, None) not in ["", None]: + season_title = season[f] + break + if season_title in ["", None]: + season_title = f'Id_{season_id}' + season_title = get_valid_filename(f"Season_{season_index} {season_title}") + + response = requests.get( + kanopy_com.ITEMS_URL.format(collection_id=season_id), + params={'domainId': kanopy_com.DOMAIN_ID}, + headers={ + 'Authorization': f'Bearer {kanopy_com.BEARER_TOKEN}', + 'x-Version': kanopy_com.X_VERSION + } + ) + response = response.content.decode() + response = json.loads(response) + try: + season = response["list"] + assert season not in ["", None] + if type(season) is not list: + season = [season] + except: + season = [] + + for episode in season: + episode_index += 1 + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + try: + episode = episode["video"] + episode_id = episode["videoId"] + assert type(episode_id) in [int, str] and episode_id != "" + except: + continue + + if season_id is None: + episode_url = f'{watch_url}/{episode_id}' + else: + episode_url = f'{watch_url}/{season_id}/{episode_id}' + + title = None + for f in ["title", "alias"]: + if episode.get(f, None) not in ["", None]: + title = episode[f] + break + if title in ["", None]: + title = f'Id_{episode_id}' + + collection.append(BaseElement( + url=episode_url, + collection=join(collection_title, season_title), + element=get_valid_filename(f'Episode_{episode_index} {title}') + )) + + return collection diff --git a/API/proxiesembed/drmproxy/services/kijk_nl.py b/API/proxiesembed/drmproxy/services/kijk_nl.py new file mode 100644 index 0000000..63c2bc4 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/kijk_nl.py @@ -0,0 +1,343 @@ +import base64 +import builtins +import json +import re +from os.path import join +from urllib.parse import parse_qs, urlparse + +import requests + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import flatten_list, get_valid_filename, get_ext_from_url + + +class kijk_nl(BaseService): + DEMO_URLS = [ + "https://www.kijk.nl/programmas/lang-leve-de-liefde", + "https://www.kijk.nl/programmas/lingo", + "https://www.kijk.nl/programmas/vrienden-van-lingo", + "https://www.kijk.nl/programmas/het-jachtseizoen", + "https://www.kijk.nl/programmas/camping-de-wildernis/QBhATP8rokD", + "https://www.kijk.nl/programmas/10-voor-taal/BPSOLHDAwPp", + "https://www.kijk.nl/films/lock-stock-and-two-smoking-barrels/qw9q3GjAQu7", + "https://www.kijk.nl/films/venom/D3mFkhATspI", + "https://www.kijk.nl/programmas/vrienden-van-lingo/krnoeBgBKQrCbl", + ] + + GRAPHQL_URL = None + BASE_URL = "https://www.kijk.nl" + + DRM_TOKEN = None + MAN_PRIORITY = {"": 0, "m3u8": 1, "ism": 2, "dash": 3} + PAGE_SIZE = 50 + + @staticmethod + def test_service(): + main_service.run_service(kijk_nl) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def get_site_info(): + graphql_url = json.loads(re.findall( + r'type="application/json"[^<>]*>({.*?})', + requests.get(kijk_nl.BASE_URL).content.decode() + )[0])["props"]["pageProps"]["videoApiUrl"] + + drm_token = json.loads(requests.get( + graphql_url, params={'query': '{ drmToken { token } }'} + ).content.decode())["data"]["drmToken"]["token"] + return graphql_url, drm_token + + @staticmethod + def initialize_service(): + if kijk_nl.GRAPHQL_URL is None or kijk_nl.DRM_TOKEN is None: + kijk_nl.GRAPHQL_URL, kijk_nl.DRM_TOKEN = kijk_nl.get_site_info() + return kijk_nl + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + additional["license_url"], + headers={'authorization': f'Basic {kijk_nl.DRM_TOKEN}'}, + json={ + 'getRawWidevineLicense': { + 'releasePid': additional["release_pid"], + 'widevineChallenge': base64.b64encode(challenge).decode() + } + } + ) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_video_data(source_element): + guid = source_element.url.split("/")[-1] + page_dict = json.loads(re.findall( + r'type="application/json"[^<>]*>({.*?})', + requests.get(source_element.url).content.decode() + )[0]).get("props", {}) + + response = page_dict.get("pageProps", {}).get("formatDataInitial", {}).get("video", {}) + if response.get("guid", None) != guid: + response = page_dict.get("apolloState", {}) + + for k, v in response.items(): + if not k.startswith("Program:"): + continue + if v.get("guid", None) != guid: + continue + + response = v + break + + if source_element.element is None: + title = response.get("title", None) + if title in ["", None]: + title = response.get("slug", None) + title = get_valid_filename(title) + if title is None: + title = guid + source_element.element = title + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + kijk_nl.__name__ + ) + + subtitles = [] + index = 0 + output_path = join(source_element.collection, source_element.element) + + for track in response.get("tracks", []): + if track.get("kind", "").lower() not in ["captions"]: + continue + index += 1 + + srt_url = track["file"] + srt_ext = get_ext_from_url(srt_url) + srt_code = get_valid_filename(track["label"].lower()) + + subtitles.append((False, BaseElement( + url=srt_url, + collection=output_path, + element=f'subtitle_{index}_{srt_code}{srt_ext}' + ))) + + additional = {"SUBTITLES": subtitles} + response = json.loads(requests.get( + kijk_nl.GRAPHQL_URL, + params={ + 'operationName': 'sources', 'variables': json.dumps({"guid": guid}), + 'query': ''' + query sources($guid:[String]) { + programs(guid:$guid) { items { guid sources { type file drm } } } + } + ''' + } + ).content.decode())["data"]["programs"]["items"] + + response = [r["sources"] for r in response if r["guid"] == guid] + response = flatten_list(response) + if len(response) == 0: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + response = list(filter( + lambda r: len(parse_qs(urlparse(r["file"]).query).keys()) > 0, + response + )) + if len(response) == 0: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need Dutch IP to access content", + solution="Use a VPN" + )) + + response = list(filter( + lambda r: r.get("drm", {}) in [None, {}], response + )) + list(filter( + lambda r: len(list(filter( + lambda d: "widevine" in d.lower(), + list(r["drm"].keys()) + ))) > 0, + list(filter(lambda r: r.get("drm", {}) not in [None, {}], response)) + )) + if len(response) == 0: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine wasn't found", + solution="Do not attempt to download it" + )) + + response = sorted( + response, reverse=True, + key=lambda r: kijk_nl.MAN_PRIORITY.get(r["type"].lower(), "") + ) + if response[0]["type"].lower() not in ["dash", "ism"] and response[0].get("drm", {}) not in [{}, None]: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {str(response)}. Can't extract pssh", + solution=f"Extend the {kijk_nl.__name__} service" + )) + + response = response[0] + manifest = response["file"] + try: + if response.get("drm", {}) in [None, {}]: + raise + for k, v in response["drm"].items(): + if "widevine" in k.lower(): + additional["license_url"] = v["url"] + additional["release_pid"] = v["releasePid"] + break + + pssh_value = str(min(re.findall( + r']*>(.*?)', + requests.get(manifest).content.decode() + ), key=len)) + except: + pssh_value = None + + return manifest, pssh_value, additional + + @staticmethod + def get_collection_elements(collection_url): + collection_url = collection_url.rstrip("/") + if "/programmas/" in collection_url or "/films/" in collection_url: + if collection_url.split(kijk_nl.BASE_URL)[-1].count("/") > 2: + return [BaseElement(url=collection_url)] + if "/programmas/" not in collection_url: + return None + + slug = collection_url.split("/")[-1] + response = json.loads(re.findall( + r'type="application/json"[^<>]*>({.*?})', + requests.get(collection_url).content.decode() + )[0]).get("props", {}).get("pageProps", {}).get("formatDataInitial", {}).get("format", {}) + + if slug != response.get("slug", ""): + return [] + collection_name = get_valid_filename(response.get("title", slug)) + collection_name = join(join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + kijk_nl.__name__ + ), collection_name) + + seasons = [] + for s1 in ["seasonList", "seriesTvSeasons"]: + s2 = response.get(s1, []) + if len(s2) == 0: + continue + + for s3 in s2: + season_id = s3.get("value", "") + if len(season_id) == 0: + season_id = s3["id"].split("/")[-1] + + season_number = s3.get("seasonNumber", 0) + season_title = s3["guid"] + for st in ["title", 'label', 'ariaLabel']: + if s3.get(st, "") not in [None, ""]: + season_title = s3[st] + break + + season_title = get_valid_filename(f'Season_{season_number}_{season_title}') + seasons.append(( + season_id, season_number, season_title, + "tvSeasonId", "EPISODE" + )) + break + + seasons = sorted(seasons, key=lambda season: season[1]) + season_index = 0 + if len(seasons) > 0: + season_index = seasons[-1][1] + seasons.append(( + response["id"], season_index + 1, + f'Season_{season_index + 1}_Clips', + 'seriesId', 'CLIP' + )) + + content_query = """ + query programs( + $tvSeasonId: String, $programTypes: [ProgramType], $seriesId: String, + $skip: Int, $limit: Int, $sort: ProgramSortKey, $guid: [String] + ) { + programs( + tvSeasonId: $tvSeasonId, programTypes: $programTypes, seriesId: $seriesId, + skip: $skip, limit: $limit, sort: $sort, guid: $guid + ) { totalResults items { guid slug title } } + } + """ + + collection = [] + for season_id, season_number, season_title, id_type, program_type in seasons: + check = check_range(True, season_number, None) + if check is True: + continue + elif check is False: + return collection + + skip = 0 + episode_index = 0 + + while True: + request_params = { + 'query': content_query, + 'operationName': 'programs', + 'variables': { + "programTypes": program_type, + "skip": skip, + "limit": kijk_nl.PAGE_SIZE, + id_type: season_id + } + } + if program_type == "CLIP": + request_params["variables"]["sort"] = 'PUBLICATIONDATETIME' + request_params["variables"] = json.dumps(request_params["variables"]) + + response = json.loads(requests.get( + kijk_nl.GRAPHQL_URL, params=request_params + ).content.decode())["data"]["programs"].get("items", []) + + if len(response) == 0: + break + skip += kijk_nl.PAGE_SIZE + + for episode in response: + episode_index += 1 + check = check_range(False, season_number, episode_index) + if check is True: + continue + elif check is False: + return collection + + episode_title = episode["guid"] + for et in ["title", 'slug']: + if episode.get(et, "") not in [None, ""]: + episode_title = episode[et] + break + episode_title = get_valid_filename(episode_title) + + collection.append(BaseElement( + url=collection_url + "/" + episode["guid"], + collection=join(collection_name, season_title), + element=f"Episode_{episode_index}" + f"_" + f"{episode_title}" + )) + + return collection diff --git a/API/proxiesembed/drmproxy/services/m6_fr.py b/API/proxiesembed/drmproxy/services/m6_fr.py new file mode 100644 index 0000000..c326a85 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/m6_fr.py @@ -0,0 +1,570 @@ +import builtins +import json +import os +import re +from os.path import join +from urllib.parse import quote + +import requests +from requests.adapters import HTTPAdapter +from urllib3 import Retry + +from utils.constants.macros import CACHE_DIR, APP_ERROR, ERR_MSG, USER_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import dict_to_file, file_to_dict, get_valid_filename + + +class m6_fr(BaseService): + DEMO_URLS = [ + "https://www.m6.fr/6play/top-6play-6play-f_1393", + "https://www.m6.fr/les-animaux-p_25744", + "https://www.m6.fr/l-incroyable-famille-kardashian-p_10941", + "https://www.m6.fr/lois-et-clark-les-nouvelles-aventures-de-supe-p_25720/s1-e1-lois-et-clark-c_13064763", + "https://www.m6.fr/alvinnn-et-les-chipmunks-p_16251/le-deluge-de-collations-c_12962956", + "https://www.m6.fr/rtl-vous-regale-p_25746/la-recette-du-gratin-de-fraises-de-angele-ferreux-maeght-c_13070338", + ] + + LAYOUT_URL = 'https://layout.6cloud.fr/front/v1/m6web/m6group_web/main/token-web-4/{content_type}/{video_id}/layout' + PAGE_URL = 'https://layout.6cloud.fr/front/v1/m6web/m6group_web/main/token-web-4/{content_type}/{video_id}/block/{page_id}' + PROFILES_URL = 'https://6play-users.6play.fr/v2/platforms/m6group_web/users/{user_id}/profiles' + BOOTSTRAP_URL = 'https://login-gigya.6play.fr/accounts.webSdkBootstrap' + LOGIN_URL = 'https://login-gigya.6play.fr/accounts.login' + ACCOUNT_URL = 'https://accounts.eu1.gigya.com/accounts.getAccountInfo' + JWT_URL = 'https://front-auth.6cloud.fr/v2/platforms/m6group_web/getJwt' + TOKEN_URL = 'https://drm.6cloud.fr/v1/customers/m6web/platforms/m6group_web/services/6terreplay/users/-/videos/{video_id}/upfront-token' + LICENSE_URL = 'https://lic.drmtoday.com/license-proxy-widevine/cenc/' + BASE_URL = "https://www.m6.fr" + + API_KEY = '3_hH5KBv25qZTd_sURpixbQW6a4OsiIzIEF2Ei_2H7TXTGLJb_1Hr4THKZianCQhWK' + EMAIL = "YOUR_EMAIL" + PASSWORD = "YOUR_PASSWORD" + CACHE_FILE = None + BEARER_TOKEN = None + RES_PRIORITY = {"sd": 0, "hd": 1} + PAGE_SIZE = 10 + RETRIES_COUNT = 5 + RETRIES_TIMER = 5 + RETRIES_MAX = 10000 + + @staticmethod + def test_service(): + main_service.run_service(m6_fr) + + @staticmethod + def credentials_needed(): + return { + "EMAIL": m6_fr.EMAIL, + "PASSWORD": m6_fr.PASSWORD + } + + @staticmethod + def get_bearer_token(): + session_info_keys = ["profile_id", "UID", "UIDSignature", "signatureTimestamp"] + try: + session_info = file_to_dict(m6_fr.CACHE_FILE) + assert len(session_info.keys()) == len(session_info_keys) + + for k in session_info_keys: + assert session_info[k] is not None + except: + session_info = None + + if session_info is None: + class_name = m6_fr.__name__.replace("_", ".") + credentials = builtins.CONFIG["SERVICE_CREDENTIALS"][class_name] + try: + assert type(credentials["EMAIL"]) is str + assert type(credentials["PASSWORD"]) is str + except: + return None + + response = requests.get( + m6_fr.BOOTSTRAP_URL, params={'apiKey': m6_fr.API_KEY} + ).headers.get("set-cookie", None) + if response in ["", None]: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=f'from the {m6_fr.__name__} service', + reason="Can't obtain the session info because the API key was changed", + solution='Update the API key manually' + )) + + gmid = None + for h in response.split(";"): + if h.startswith("gmid="): + gmid = h[5:] + break + assert gmid is not None + + response = json.loads(requests.post( + m6_fr.LOGIN_URL, + cookies={'gmid': gmid}, + headers={'Content-Type': 'application/x-www-form-urlencoded'}, + data="&".join([f"{k}={quote(v)}" for k, v in { + 'loginID': credentials["EMAIL"], + 'password': credentials["PASSWORD"], + 'sessionExpiration': '-48', + 'targetEnv': 'jssdk', + 'APIKey': m6_fr.API_KEY + }.items()]) + ).content.decode()) + + message = response.get("errorDetails", "").lower() + status_code = response.get("statusCode", None) + if status_code == 403: + if "loginid" in message or "password" in message: + return None + if "locked" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=f'from the {m6_fr.__name__} service', + reason="Account is temporarily locked because of too many failed login attempts", + solution="Wait 15 minutes or use another burner account" + )) + if status_code != 200: + raise CustomException(ERR_MSG.format( + type=f'{APP_ERROR}', + url=f"from the {m6_fr.__name__} service", + reason=f"Unknown error encountered: {str(response)}", + solution="Debug the service" + )) + + session_info = {} + for k in session_info_keys: + if response.get(k, None) is None: + continue + session_info[k] = response[k] + + response = json.loads(requests.get( + m6_fr.JWT_URL, + headers={ + 'x-auth-device-id': 'x-auth-device-id', + 'X-Auth-gigya-uid': session_info["UID"], + 'X-Auth-gigya-signature': session_info["UIDSignature"], + 'X-Auth-gigya-signature-timestamp': str(session_info["signatureTimestamp"]) + } + ).content.decode()) + + bearer_token = response["token"] + response = json.loads(requests.get( + m6_fr.PROFILES_URL.format(user_id=session_info["UID"]), + headers={'Authorization': f'Bearer {bearer_token}'} + ).content.decode()) + if type(response) is not list: + response = [response] + + assert len(response) > 0 + profile_id = None + for profile in response: + if profile.get("profile_type", "").lower() == "adult": + profile_id = profile["uid"] + if profile_id is None: + profile_id = response[0]["uid"] + session_info["profile_id"] = profile_id + + response = requests.get( + m6_fr.JWT_URL, + headers={ + 'x-auth-device-id': 'x-auth-device-id', + 'X-Auth-profile-id': session_info["profile_id"], + 'X-Auth-gigya-uid': session_info["UID"], + 'X-Auth-gigya-signature': session_info["UIDSignature"], + 'X-Auth-gigya-signature-timestamp': str(session_info["signatureTimestamp"]) + } + ) + + status_code = response.status_code + response = json.loads(response.content.decode()) + message = response.get("message", response.get("error", {}).get("message", "")).lower() + if status_code == 498 or "invalid" in message or "token" in message or "expired" in message: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=f"from the {m6_fr.__name__} service", + reason="Can't access the video content because the session info expired", + solution=f'Delete the {m6_fr.CACHE_FILE} cache manually or add the parameter --fresh to your command' + )) + + bearer_token = response["token"] + dict_to_file(m6_fr.CACHE_FILE, session_info) + return bearer_token + + @staticmethod + def initialize_service(): + if m6_fr.CACHE_FILE is None: + m6_fr.CACHE_FILE = join(CACHE_DIR, f'{m6_fr.__name__}.json') + if builtins.CONFIG.get("FRESH", False) is True: + dict_to_file(m6_fr.CACHE_FILE, {}) + + if m6_fr.BEARER_TOKEN is None: + m6_fr.BEARER_TOKEN = m6_fr.get_bearer_token() + if m6_fr.BEARER_TOKEN is None: + return None + return m6_fr + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + m6_fr.LICENSE_URL, data=challenge, + headers={'x-dt-auth-token': additional["auth_token"]} + ) + licence.raise_for_status() + return json.loads(licence.content.decode())["license"] + + @staticmethod + def get_video_title(item_url, item_content): + video_title = item_content.get("title", None) + if video_title is None: + video_title = item_content.get("extraTitle", None) + elif item_content.get("extraTitle", None) is not None: + if item_content["extraTitle"] != item_content["title"]: + video_title = video_title + "_" + item_content["extraTitle"] + + if video_title is None: + video_title = item_url.split("/")[-1] + return get_valid_filename(video_title) + + @staticmethod + def generate_video_m3u8(output_path, asset_info, content_info): + m3u8_content = "#EXTM3U\n#EXT-X-VERSION:3\n\n" + m3u8_content += f'#EXTINF:{content_info.get("duration", 1)},\n' + m3u8_content += f'{asset_info["path"]}\n' + + m3u8_content += "#EXT-X-ENDLIST\n" + with open(output_path, "w") as f: + f.write(m3u8_content) + + @staticmethod + def generate_master_m3u8(source_element, asset_info, content_info): + output_path = str(join(source_element.collection, source_element.element)) + if not os.path.exists(output_path): + os.makedirs(output_path) + m3u8_content = "#EXTM3U\n#EXT-X-VERSION:3\n\n" + + title = f'audio.m3u8' + m6_fr.generate_video_m3u8(join(output_path, title), asset_info, content_info) + m3u8_content += f"#EXT-X-STREAM-INF:BANDWIDTH=1000,TYPE=AUDIO,MIME-TYPE=\"audio/{asset_info['video_container']}\"\n" + m3u8_content += f'{title}\n' + + output_path = join(output_path, "master.m3u8") + with open(output_path, "w") as f: + f.write(m3u8_content) + return output_path + + @staticmethod + def get_video_data(source_element): + with requests.Session() as session: + adapter = HTTPAdapter(max_retries=Retry( + connect=m6_fr.RETRIES_COUNT, + backoff_factor=m6_fr.RETRIES_MAX, + backoff_max=m6_fr.RETRIES_TIMER + )) + session.mount('http://', adapter) + session.mount('https://', adapter) + + content_id = re.search(r"-c_([^/?#]+)", source_element.url).group(1) + content_id = "clip_" + content_id + response = session.get( + m6_fr.LAYOUT_URL.format(content_type="video", video_id=content_id), + headers={'Authorization': f'Bearer {m6_fr.BEARER_TOKEN}'}, + params={"nbPages": m6_fr.PAGE_SIZE} + ) + + status_code = response.status_code + response = json.loads(response.content.decode()) + message = response.get("message", "").lower() + if status_code == 498 or "invalid" in message or "token" in message or "expired" in message: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Can't access the video content because the bearer token expired", + solution=f'Delete the {m6_fr.CACHE_FILE} cache manually or add the parameter --fresh to your command' + )) + + has_drm = False + manifest = None + + for block in response.get("blocks", []): + if block.get("content", {}) in ["", None, {}]: + continue + + for item in block["content"].get("items", []): + item_content = item.get("itemContent", {}) + video = item_content.get("video", {}) + if video.get("id", None) != content_id: + continue + + reason = item_content.get("action", {}).get("target", {}).get( + "value_lock", {} + ).get("reason", "").lower() + if "geoblock" in reason: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need French IP to access content or the VPN was detected", + solution="Use a VPN or get a better one" + )) + + video_title = m6_fr.get_video_title(source_element.url, item_content) + if source_element.element is None: + source_element.element = video_title + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + m6_fr.__name__ + ) + + assets = video.get("assets", []) + has_drm = len(list(filter( + lambda d: d not in ["", None, {}] and 'none' not in d.get("type", ""), + [a.get("drm", None) for a in assets] + ))) > 0 + + if has_drm: + assets = list(filter(lambda a: a['format'].lower().startswith("dash"), assets)) + if len(assets) == 0: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {str(video.get('assets', []))}", + solution=f"Extend the {m6_fr.__name__} service" + )) + + assets = sorted(assets, key=lambda a: m6_fr.RES_PRIORITY[a["quality"].lower()], reverse=True) + asset = assets[0] + + if asset['video_container'].lower() not in ["ism", "mpd", "m3u8"]: + if has_drm: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}. Can't extract pssh", + solution=f"Extend the {m6_fr.__name__} service" + )) + manifest = m6_fr.generate_master_m3u8(source_element, asset, video) + else: + manifest = asset["path"] + break + if manifest is not None: + break + + if manifest is None: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + pssh_value = None + additional = {} + if has_drm: + try: + pssh_value = str(min( + re.findall( + r']*>(.*?)', + session.get(manifest).content.decode() + ), key=len + )) + except: + pass + + if pssh_value is None: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}. Can't extract pssh", + solution=f"Extend the {m6_fr.__name__} service" + )) + + response = json.loads(session.get( + m6_fr.TOKEN_URL.format(video_id=content_id), + headers={'Authorization': f'Bearer {m6_fr.BEARER_TOKEN}'} + ).content.decode()) + additional["auth_token"] = response["token"] + + if builtins.CONFIG.get("BASIC", False) is True: + manifest = re.sub(r'=eyJ[^&]*', '=', manifest) + return manifest, pssh_value, additional + + @staticmethod + def get_series_handler(collection_url, content_type): + collection_url = collection_url.split("?")[0].split("#")[0].rstrip("/") + collection = [] + + with requests.Session() as session: + adapter = HTTPAdapter(max_retries=Retry( + connect=m6_fr.RETRIES_COUNT, + backoff_factor=m6_fr.RETRIES_MAX, + backoff_max=m6_fr.RETRIES_TIMER + )) + session.mount('http://', adapter) + session.mount('https://', adapter) + + content_id = re.search(fr"{content_type[0]}([^/?#]+)", collection_url).group(1) + layout_page = 1 + layout_response = session.get( + m6_fr.LAYOUT_URL.format(content_type=content_type[1], video_id=content_id), + headers={'Authorization': f'Bearer {m6_fr.BEARER_TOKEN}'}, + params={'page': str(layout_page), 'nbPages': str(m6_fr.PAGE_SIZE)} + ) + + status_code = layout_response.status_code + layout_response = json.loads(layout_response.content.decode()) + message = layout_response.get("message", "").lower() + if status_code == 498 or "invalid" in message or "token" in message or "expired" in message: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=collection_url, + reason="Can't access the video content because the bearer token expired", + solution=f'Delete the {m6_fr.CACHE_FILE} cache manually or add the parameter --fresh to your command' + )) + + collection_name = layout_response.get("entity", {}).get("metadata", {}).get("title", None) + if collection is None: + collection_name = layout_response.get("layout", {}).get("title", None) + if collection_name is None: + collection_name = layout_response.get("layout", {}).get("branding", {}).get("title", None) + if collection_name is None: + collection_name = layout_response.get("seo", {}).get("title", None) + if collection_name is None: + collection_name = collection_url.split("/")[-1] + collection_name = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + m6_fr.__name__ + ), + get_valid_filename(collection_name) + ) + + rail_index = 0 + while True: + if len(layout_response.get("blocks", [])) == 0: + break + + for rail_block in layout_response["blocks"]: + if rail_block.get("content", None) is None: + continue + if "jumbotron" in rail_block.get("templateId", "").lower(): + continue + + if len(list(filter( + lambda i: i.get("itemContent", {}).get("action", {}).get( + "target", {} + ).get("value_layout", {}).get("type", "").lower() in ["video", "audio"], + rail_block["content"].get("items", []) + ))) == 0: + continue + + rail_index += 1 + check = check_range(True, rail_index, None) + if check is True: + continue + elif check is False: + return collection + + rail_title = rail_block.get("title", {}) + if rail_title is not None: + if rail_title.get("long", None) is None: + rail_title = rail_title.get("short", None) + else: + rail_title = rail_title["long"] + if rail_title is None: + rail_title = f'Rail_{rail_index}' + else: + rail_title = f'Rail_{rail_index}_{rail_title}' + rail_title = join(collection_name, get_valid_filename(rail_title)) + + rail_page = 1 + loaded = [] + if rail_block["content"].get("pagination", None) not in ["", {}, None]: + if rail_block["content"]["pagination"].get("nextPage", None) not in ["", {}, None]: + if rail_block["content"]["pagination"]["nextPage"] > 0: + rail_page = rail_block["content"]["pagination"]["nextPage"] + loaded = rail_block["content"]["items"] + + content_index = 0 + while True: + grid_response = json.loads(session.get( + m6_fr.PAGE_URL.format( + content_type=content_type[1], video_id=content_id, page_id=rail_block["id"] + ), params={'page': str(rail_page), 'nbPages': str(m6_fr.PAGE_SIZE)}, + headers={'Authorization': f'Bearer {m6_fr.BEARER_TOKEN}'} + ).content.decode()).get("content", {}) + + if grid_response is None: + break + if grid_response.get("items", []) in [[], None]: + grid_response["items"] = [] + + page_items = loaded + grid_response["items"] + if len(page_items) == 0: + break + loaded = [] + + for page_item in page_items: + try: + value_layout = page_item["itemContent"]["action"]["target"]["value_layout"] + if value_layout["type"].lower() not in ["video", "audio"]: + continue + parent = value_layout["parent"] + + video_url = m6_fr.BASE_URL + "/" + parent["seo"] + video_url += "-" + parent["type"].lower()[0] + "_" + parent["id"] + video_url += "/" + value_layout["seo"] + video_url += "-" + value_layout["id"].split("_")[0].lower()[0] + "_" + video_url += value_layout["id"].split("_")[-1] + except: + continue + + content_index += 1 + check = check_range(False, rail_index, content_index) + if check is True: + continue + elif check is False: + return collection + + video_title = m6_fr.get_video_title(video_url, page_item["itemContent"]) + collection.append(BaseElement( + url=video_url, + collection=rail_title, + element=f'Content_{content_index}_{video_title}' + )) + + if grid_response.get("pagination", None) not in ["", {}, None]: + if grid_response["pagination"].get("nextPage", None) not in ["", {}, None]: + if grid_response["pagination"]["nextPage"] > 0: + rail_page = grid_response["pagination"]["nextPage"] + continue + break + + if layout_response.get("pagination", None) not in ["", {}, None]: + if layout_response["pagination"].get("nextPage", None) not in ["", {}, None]: + if layout_response["pagination"]["nextPage"] > 0: + layout_page = layout_response["pagination"]["nextPage"] + layout_response = session.get( + m6_fr.LAYOUT_URL.format(content_type=content_type[1], video_id=content_id), + headers={'Authorization': f'Bearer {m6_fr.BEARER_TOKEN}'}, + params={'page': str(layout_page), 'nbPages': str(m6_fr.PAGE_SIZE)} + ) + continue + break + + return collection + + @staticmethod + def get_collection_elements(collection_url): + collection_url = collection_url.rstrip("/") + nr_slash = collection_url.split(m6_fr.BASE_URL)[-1].count("/") + slash_splits = collection_url.split("/") + + if "direct" == slash_splits[-1] and nr_slash == 2: + return None + if "-c_" in slash_splits[-1] and nr_slash == 2: + return [BaseElement(url=collection_url)] + + for content_type in [("-f_", "folder"), ("-p_", "program")]: + if content_type[0] in slash_splits[-1]: + return m6_fr.get_series_handler(collection_url, content_type) + return None diff --git a/API/proxiesembed/drmproxy/services/maoriplus_co_nz.py b/API/proxiesembed/drmproxy/services/maoriplus_co_nz.py new file mode 100644 index 0000000..22dac89 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/maoriplus_co_nz.py @@ -0,0 +1,375 @@ +import builtins +import json +import re +from os.path import join + +import requests + +from utils.constants.macros import USER_ERROR, ERR_MSG, CACHE_DIR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import clean_url, get_valid_filename, dict_to_file, file_to_dict + + +class maoriplus_co_nz(BaseService): + DEMO_URLS = [ + "https://www.maoriplus.co.nz/movie/bernie-the-dolphin/play", + "https://www.maoriplus.co.nz/movie/a-son/play", + "https://www.maoriplus.co.nz/show/ariki/play/6353035454112", + "https://www.maoriplus.co.nz/show/frenemies/play/5830339283001", + "https://www.maoriplus.co.nz/live-tv/whakaata-maori", + "https://www.maoriplus.co.nz/live-tv/te-reo", + "https://www.maoriplus.co.nz/show/marae-diy", + "https://www.maoriplus.co.nz/show/matariki-awards-2019", + "https://www.maoriplus.co.nz/show/nga-manu-korero-2024", + "https://www.maoriplus.co.nz/show/school-of-training", + ] + + PLAYBACK_URL = 'https://edge.api.brightcove.com/playback/v1/accounts/{account_id}/videos/{video_id}' + SESSION_URL = 'https://api.one.accedo.tv/session' + METADATA_URL = 'https://api.one.accedo.tv/metadata' + ENTRY_URL = 'https://api.one.accedo.tv/content/entry/alias/{alias}' + ENTRIES_URL = 'https://api.one.accedo.tv/content/entries' + EPISODES_URL = 'https://cms.maoriplus.co.nz/playlists/{season_id}/videos' + BASE_URL = 'https://www.maoriplus.co.nz' + + API_DICT = None + CACHE_FILE = None + SESSION_KEY = None + PAGE_SIZE = 50 + MPD_PRIORITY = {"": 0, "application/dash+xml": 1, "application/x-mpegURL": 2} + + @staticmethod + def test_service(): + main_service.run_service(maoriplus_co_nz) + + @staticmethod + def is_content_livestream(content, additional): + return "/live-tv/" in content + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def get_session_key(app_key): + response = requests.get( + maoriplus_co_nz.SESSION_URL, + params={'uuid': 'uuid', 'appKey': app_key} + ) + response = response.content.decode() + response = json.loads(response) + return response["sessionKey"] + + @staticmethod + def get_api_dict(): + try: + api_dict = file_to_dict(maoriplus_co_nz.CACHE_FILE) + assert len(api_dict.keys()) == 3 + maoriplus_co_nz.SESSION_KEY = maoriplus_co_nz.get_session_key(api_dict["app_key"]) + return api_dict + except: + pass + + response = requests.get(maoriplus_co_nz.BASE_URL).content.decode() + response = re.findall(r'src="([^"]*index[^"]*\.js)"', response)[0] + if response[0] != "/": + response = "/" + response + response = maoriplus_co_nz.BASE_URL + response + + response = requests.get(response).content.decode() + response = re.findall(r'="https://api.one.accedo.tv"[^"]*="([^"]*)"', response) + response = sorted(response, key=len, reverse=True)[0] + + app_key = response + maoriplus_co_nz.SESSION_KEY = maoriplus_co_nz.get_session_key(app_key) + + response = requests.get( + maoriplus_co_nz.METADATA_URL, + headers={'X-Session': maoriplus_co_nz.SESSION_KEY} + ) + response = response.content.decode() + response = json.loads(response) + response = response["brightcovePlayer"] + + api_dict = { + "app_key": app_key, + "account_id": response["accountId"], + "policy_key": response["playerPolicyKey"] + } + dict_to_file(maoriplus_co_nz.CACHE_FILE, api_dict) + return api_dict + + @staticmethod + def initialize_service(): + if maoriplus_co_nz.CACHE_FILE is None: + maoriplus_co_nz.CACHE_FILE = join(CACHE_DIR, f'{maoriplus_co_nz.__name__}.json') + if builtins.CONFIG.get("FRESH", False) is True: + dict_to_file(maoriplus_co_nz.CACHE_FILE, {}) + + if maoriplus_co_nz.API_DICT is None: + maoriplus_co_nz.API_DICT = maoriplus_co_nz.get_api_dict() + return maoriplus_co_nz + + @staticmethod + def get_keys(challenge, additional): + raise Exception( + f'{BaseService.get_keys.__name__} must not be called ' + f'for the {maoriplus_co_nz.__name__} service' + ) + + @staticmethod + def get_video_data(source_element): + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + maoriplus_co_nz.__name__ + ) + + video_id = None + if "/live-tv/" in source_element.url: + alias = source_element.url.split("/")[-1] + "-live" + offset = -maoriplus_co_nz.PAGE_SIZE + while True: + offset += maoriplus_co_nz.PAGE_SIZE + + response = requests.get( + maoriplus_co_nz.ENTRIES_URL, + params={ + 'typeAlias': 'live-channels', + "size": maoriplus_co_nz.PAGE_SIZE, + "offset": offset + }, + headers={'X-Session': maoriplus_co_nz.SESSION_KEY} + ) + response = response.content.decode() + response = json.loads(response) + + entries = response.get("entries", []) + if len(entries) == 0: + break + + for entry in entries: + if entry.get("_meta", {}).get("entryAlias", "") == alias: + video_id = entry["bcChannelId"] + break + + if video_id is not None: + break + + if video_id is None: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Don't attempt to download it" + )) + else: + alias = re.findall(r'/([^/]+)/play[^/]*', source_element.url)[0] + if not source_element.url.endswith("/play"): + video_id = source_element.url.split("/")[-1] + + if video_id is None: + response = requests.get( + maoriplus_co_nz.ENTRY_URL.format(alias=alias), + headers={'X-Session': maoriplus_co_nz.SESSION_KEY} + ) + response = response.content.decode() + response = json.loads(response) + + if response.get("drmProtected", False) is True: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine was found", + solution=f"Extend the {maoriplus_co_nz.__name__} service" + )) + + if source_element.element is None: + title = response.get("title", alias) + source_element.element = get_valid_filename(title) + video_id = response.get("brightcoveId", None) + + if video_id is None: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Don't attempt to download it" + )) + + response = requests.get( + maoriplus_co_nz.PLAYBACK_URL.format( + account_id=maoriplus_co_nz.API_DICT["account_id"], + video_id=video_id + ), + headers={'Accept': f'pk={maoriplus_co_nz.API_DICT["policy_key"]}'} + ) + response = response.content.decode() + response = json.loads(response) + + message = str(response).lower() + if "client_geo" in message and "access_denied" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need New Zealander IP to access content", + solution="Use a VPN" + )) + if "video_not_found" in message or "resource_not_found" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Don't attempt to download it" + )) + + if "account_not_found" in message or "invalid_policy_key" in message: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Can't access the video content because the account id/policy key expired", + solution=f'Delete the {maoriplus_co_nz.CACHE_FILE} cache manually or add the parameter --fresh to your command' + )) + + if source_element.element is None: + title = response.get("name", None) + if title in ["", None]: + title = alias + fields = response.get("custom_fields", {}) + + for f in ["season_number", "episode_number"]: + try: + title += " " + f[0] + fields[f] + except: + pass + source_element.element = get_valid_filename(title) + + sources = response.get("sources", []) + sources = filter(lambda s: s.get("container", None) in ["", None], sources) + sources = sorted( + list(sources), + key=lambda s: maoriplus_co_nz.MPD_PRIORITY.get(s.get("type", ""), 0), + reverse=True + ) + + manifest = sources[0]["src"] + return manifest, None, {} + + @staticmethod + def has_episodes(season_id): + episodes = json.loads(requests.get( + maoriplus_co_nz.EPISODES_URL.format(season_id=season_id), + params={'limit': 1, 'offset': 0} + ).content.decode()) + return type(episodes) is list and len(episodes) > 0 + + @staticmethod + def get_collection_elements(collection_url): + collection_url = clean_url(collection_url) + if "/play/" in collection_url or collection_url.endswith("/play") or "/live-tv/" in collection_url: + return [BaseElement(url=collection_url)] + if "/show/" not in collection_url: + return None + + alias = collection_url.split("/")[-1] + response = requests.get( + maoriplus_co_nz.ENTRY_URL.format(alias=alias), + headers={'X-Session': maoriplus_co_nz.SESSION_KEY} + ) + response = response.content.decode() + response = json.loads(response) + + error = response.get("error", {}) + message = error.get("status", "").lower() + code = error.get("code", "") + if "not found" in message or code in ["404"]: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="The content isn't available", + solution="Don't attempt to download it" + )) + + collection_title = response.get("title", alias) + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + maoriplus_co_nz.__name__ + ), + get_valid_filename(collection_title) + ) + seasons_id = ",".join(response.get("seasons", [])) + + seasons_offset = -maoriplus_co_nz.PAGE_SIZE + season_index = 0 + collection = [] + while True: + seasons_offset += maoriplus_co_nz.PAGE_SIZE + + seasons = requests.get( + maoriplus_co_nz.ENTRIES_URL, + headers={'X-Session': maoriplus_co_nz.SESSION_KEY}, + params={ + 'id': seasons_id, + 'offset': seasons_offset, + 'size': maoriplus_co_nz.PAGE_SIZE + } + ) + seasons = seasons.content.decode() + seasons = json.loads(seasons) + seasons = seasons.get("entries", []) + if len(seasons) == 0: + break + + for season in seasons: + season_id = season["playlistId"] + if not maoriplus_co_nz.has_episodes(season_id): + continue + + season_index += 1 + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + season_title = season.get("title", season.get("seasonTitle", "")) + if season_title is None: + season_title = "" + season_title = get_valid_filename(f'S{season_index} {season_title}') + + episodes_offset = -maoriplus_co_nz.PAGE_SIZE + while True: + episodes_offset += maoriplus_co_nz.PAGE_SIZE + + episodes = requests.get( + maoriplus_co_nz.EPISODES_URL.format(season_id=season_id), + params={ + 'limit': maoriplus_co_nz.PAGE_SIZE, + 'offset': episodes_offset + } + ) + episodes = episodes.content.decode() + episodes = json.loads(episodes) + if len(episodes) == 0: + break + + for episode in episodes: + episode_index = int(episode["custom_fields"]["episode_number"]) + check = check_range(False, season_index, episode_index) + if check in [True, False]: + continue + + episode_title = episode.get("name", "") + episode_title = get_valid_filename(f'E{episode_index} {episode_title}') + episode_url = f'{collection_url}/play/{episode["id"]}' + + collection.append(BaseElement( + url=episode_url, + collection=join(collection_title, season_title), + element=episode_title + )) + + return collection diff --git a/API/proxiesembed/drmproxy/services/mediasetinfinity_mediaset_it.py b/API/proxiesembed/drmproxy/services/mediasetinfinity_mediaset_it.py new file mode 100644 index 0000000..db62b4b --- /dev/null +++ b/API/proxiesembed/drmproxy/services/mediasetinfinity_mediaset_it.py @@ -0,0 +1,341 @@ +import builtins +import json +import re +from os.path import join +from urllib.parse import urlencode, urlparse, urlunparse + +import requests + +from utils.constants.macros import USER_ERROR, ERR_MSG, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename + + +class mediasetinfinity_mediaset_it(BaseService): + DEMO_URLS = [ + "https://mediasetinfinity.mediaset.it/video/yogaradiobrunoestate/prima-puntata_F313369801000101", + "https://mediasetinfinity.mediaset.it/programmi-tv/studioaperto/edizioniintegrali_SE000000000053,ST000000000132,sb9890596", + "https://mediasetinfinity.mediaset.it/browse/regione-piemonte_e6538f0b2a0e845001909118d", + "https://mediasetinfinity.mediaset.it/video/ierieoggiintv/popcorn-1983_F308773901011401", + "https://mediasetinfinity.mediaset.it/video/bravo/siamo-gia-il-tuo-futuro-bravo-e-anche-il-tuo-mondo_FD00000000323805", + ] + + LOGIN_URL = "https://api-ott-prod-fe.mediaset.net/PROD/play/idm/anonymous/login/v2.0" + ACCOUNT_URL = "http://access.auth.theplatform.com/data/Account/{a_id}" + PLAYBACK_URL = 'https://api-ott-prod-fe.mediaset.net/PROD/play/playback/check/v2.0' + PROGRAM_URL = 'https://feed.entertainment.tv.theplatform.eu/f/-/mediaset-prod-ext-programs-v2/guid/-/{guid}' + BASE_URL = 'https://mediasetinfinity.mediaset.it' + SPACE_URL = 'https://cdn.contentful.com/spaces/{id}/environments/master/entries' + PROD_URL = 'https://feed.entertainment.tv.theplatform.eu/f/-/mediaset-prod-all-programs-v2?byCustomValue=%7BsubBrandId%7D%7B{sb}%7D&sort=:publishInfo_lastPublished%7Cdesc,tvSeasonEpisodeNumber%7Casc' + LICENSE_URL = 'https://widevine.entitlement.theplatform.eu/wv/web/ModularDrm/getRawWidevineLicense' + + USER_AGENT = None + BEARER_TOKEN = None + ACCESS_TOKEN = None + SPACE_ID = None + PAGE_SIZE = 90 + RES_PRIORITY = ["hd", "hr", "sd"] + + @staticmethod + def test_service(): + main_service.run_service(mediasetinfinity_mediaset_it) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def get_bearer_token(): + return json.loads(requests.post( + mediasetinfinity_mediaset_it.LOGIN_URL, + json={'client_id': 'client_id', 'appName': 'embed//mediasetplay-embed'} + ).content.decode())["response"]["beToken"] + + @staticmethod + def get_basic_info(): + vendor_js = requests.get(re.findall( + r'href="(http[^\"]*vendor[^\"]*\.js)"', + requests.get(mediasetinfinity_mediaset_it.BASE_URL).content.decode() + )[0]).content.decode() + + space_id = re.findall(r'space:"(.*?)"', vendor_js)[0] + access_token = re.findall(r'accessToken:"(.*?)"', vendor_js)[0] + return space_id, access_token + + @staticmethod + def initialize_service(): + if mediasetinfinity_mediaset_it.USER_AGENT is None: + mediasetinfinity_mediaset_it.USER_AGENT = builtins.CONFIG["USER_AGENT"] + if mediasetinfinity_mediaset_it.BEARER_TOKEN is None: + mediasetinfinity_mediaset_it.BEARER_TOKEN = mediasetinfinity_mediaset_it.get_bearer_token() + + if mediasetinfinity_mediaset_it.SPACE_ID is None or mediasetinfinity_mediaset_it.ACCESS_TOKEN is None: + mediasetinfinity_mediaset_it.SPACE_ID, mediasetinfinity_mediaset_it.ACCESS_TOKEN = \ + mediasetinfinity_mediaset_it.get_basic_info() + return mediasetinfinity_mediaset_it + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + mediasetinfinity_mediaset_it.LICENSE_URL, data=challenge, + params={ + 'releasePid': additional['release_pid'], + 'account': mediasetinfinity_mediaset_it.ACCOUNT_URL.format(a_id=additional["account"]), + 'schema': '1.0', 'token': mediasetinfinity_mediaset_it.BEARER_TOKEN + } + ) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_manifest_info(manifest, formats, manifest_info): + try: + raise + return manifest, str(min(re.findall( + r'(.+?)', + requests.get(f"{manifest}?formats={formats}").content.decode() + ), key=len)) + except: + pass + matches = re.findall(r'= 300: + raise + except: + continue + try: + return temp_url, str(min(re.findall( + r'(.+?)', response.content.decode() + ), key=len)) + except: + return temp_url, None + return None, None + + @staticmethod + def get_content_name(content_info, content_id): + title = content_info.get("title", None) + if title is None: + title = content_id + title = get_valid_filename(title) + + program = content_info.get("mediasetprogram$brandTitle", None) + if program is None: + program = content_info.get("mediasetprogram$auditelBrandName", None) + if program is None: + program = content_info.get("mediasetprogram$tvLinearSeasonTitle", None) + program = get_valid_filename(program) + if program is None: + program = "" + return f'{program}_{title}' + + @staticmethod + def get_video_data(source_element): + page_content = requests.get(source_element.url).content.decode() + try: + content_id = re.search( + r'[?&]programGuid=([^"&]+)["&]', + page_content + ).group(1) + except: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content wasn't found", + solution="Do not attempt to download it" + )) + + if source_element.element is None: + content_info = json.loads(requests.get( + mediasetinfinity_mediaset_it.PROGRAM_URL.format(guid=content_id), + headers={'User-Agent': mediasetinfinity_mediaset_it.USER_AGENT} + ).content.decode()) + + source_element.element = mediasetinfinity_mediaset_it.get_content_name(content_info, content_id) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + mediasetinfinity_mediaset_it.__name__ + ) + + response = json.loads(requests.post( + mediasetinfinity_mediaset_it.PLAYBACK_URL, json={'contentId': content_id, 'streamType': 'VOD'}, + headers={ + 'User-Agent': mediasetinfinity_mediaset_it.USER_AGENT, + 'Authorization': f'Bearer {mediasetinfinity_mediaset_it.BEARER_TOKEN}' + } + ).content.decode()) + message = response.get("error", {}).get("message", "").lower() + if "available" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need Italian IP to access content", + solution="Use a VPN" + )) + if "rights" in message: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Can't download paid content", + solution='Do not attempt to download it' + )) + if len(message) > 0: + raise CustomException(ERR_MSG.format( + type=f'{APP_ERROR}', + url=source_element.url, + reason=f"Unknown error encountered: {message}", + solution=f"Debug the {mediasetinfinity_mediaset_it.__name__} service" + )) + + response = response["response"]["mediaSelector"] + manifest = response.pop("url") + response["auth"] = mediasetinfinity_mediaset_it.BEARER_TOKEN + + manifest_info = f"{manifest}?{urlencode(response)}" + manifest_info = requests.get(manifest_info, headers={ + 'Accept': 'application/json, text/plain, */*', + 'Origin': mediasetinfinity_mediaset_it.BASE_URL, + 'Referer': mediasetinfinity_mediaset_it.BASE_URL, + 'User-Agent': mediasetinfinity_mediaset_it.USER_AGENT + }).content.decode() + + if "AnonymousProxyBlocked" in manifest_info: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The VPN was detected", + solution="Use a better VPN" + )) + + manifest, pssh_value = mediasetinfinity_mediaset_it.get_manifest_info( + manifest, response["formats"], manifest_info + ) + return manifest, pssh_value, { + "release_pid": re.search(r"\|pid=(.*?)\|", manifest_info).group(1), + "account": re.search(r"aid=(.*?)\|", manifest_info).group(1) + } + + @staticmethod + def get_feed_elements(collection_name, feed_url): + collection_name = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + mediasetinfinity_mediaset_it.__name__ + ), + get_valid_filename(collection_name) + ) + collection = [] + + current_index = 0 + content_index = 0 + urls = [] + + while True: + response = json.loads(requests.get( + f'{feed_url}&range={current_index}-{current_index + mediasetinfinity_mediaset_it.PAGE_SIZE}', + ).content.decode()) + if len(response.get("entries", [])) == 0: + break + + for entry in response["entries"]: + entry_url = entry["mediasetprogram$videoPageUrl"] + if not entry_url.startswith("https:"): + entry_url = "https:" + entry_url + if entry_url in urls: + continue + + content_index += 1 + check = check_range(False, None, content_index) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=entry_url, + collection=collection_name, + element=f'{content_index}' + f'_' + f'{mediasetinfinity_mediaset_it.get_content_name(entry, entry["guid"])}' + )) + urls.append(entry_url) + + current_index += mediasetinfinity_mediaset_it.PAGE_SIZE + 1 + return collection + + @staticmethod + def get_collection_elements(collection_url): + collection_url = collection_url.rstrip("/") + if "/browse/" in collection_url: + sys_id = collection_url.split("_")[-1][1:] + response = json.loads(requests.get( + mediasetinfinity_mediaset_it.SPACE_URL.format(id=mediasetinfinity_mediaset_it.SPACE_ID), + params={'include': '1', 'sys.id': sys_id}, + headers={'Authorization': f'Bearer {mediasetinfinity_mediaset_it.ACCESS_TOKEN}'} + ).content.decode())["items"] + + collection_name = collection_url.split("/")[-1].split("_")[0] + feed_url = None + for item in response: + try: + if ( + item["sys"]["id"] != sys_id or + item["sys"]["space"]["sys"]["id"] != mediasetinfinity_mediaset_it.SPACE_ID + ): + continue + + fields = item["fields"] + collection_name = fields.get("name", fields.get("title", collection_name)) + + for k in fields: + if k.startswith("feedurl"): + feed_url = fields[k] + break + assert feed_url is not None + break + except: + pass + + if feed_url is None: + return None + return mediasetinfinity_mediaset_it.get_feed_elements(collection_name, feed_url) + + if ",sb" in collection_url: + collection_name = collection_url.split("/")[-2] + sb = None + for p in collection_url.split(","): + if p.startswith("sb"): + sb = p[2:] + + if sb is None: + return None + return mediasetinfinity_mediaset_it.get_feed_elements( + collection_name, + mediasetinfinity_mediaset_it.PROD_URL.format(sb=sb) + ) + + if "/video/" in collection_url or "/movie/" in collection_url: + return [BaseElement(url=collection_url)] + return None diff --git a/API/proxiesembed/drmproxy/services/midnightpulp_com.py b/API/proxiesembed/drmproxy/services/midnightpulp_com.py new file mode 100644 index 0000000..78e71dd --- /dev/null +++ b/API/proxiesembed/drmproxy/services/midnightpulp_com.py @@ -0,0 +1,321 @@ +import builtins +import json +import re +from os.path import join +from urllib.parse import parse_qs, urlparse + +import browser_cookie3 +import requests +from bs4 import BeautifulSoup +from slugify import slugify + +from utils.constants.macros import USER_ERROR, ERR_MSG, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename, get_ext_from_url, update_url_params + + +class midnightpulp_com(BaseService): + DEMO_URLS = [ + "https://www.midnightpulp.com/details/HIGHLANDER/Highlander", + "https://www.midnightpulp.com/details/1000000047253/Jekyll", + 'https://www.midnightpulp.com/livetv?q=MidnightPulp', + "https://www.midnightpulp.com/livetv?q=cinedigm-bloody-disgusting", + "https://www.midnightpulp.com/watch/NNVG1260/The-Hunters?vod_type=", + "https://www.midnightpulp.com/watch/1000000029854/Quantum-Cowboys?vod_type=", + "https://www.midnightpulp.com/watch/1000000022496/Fighting?vod_type=trailer", + ] + + BASE_URL = "https://www.midnightpulp.com" + VIDEO_URL = BASE_URL + "/watch/{video_id}/{video_title}" + + LOGIN_COOKIES = None + AUTH_TOKEN = None + + @staticmethod + def test_service(): + main_service.run_service(midnightpulp_com) + + @staticmethod + def is_content_livestream(content, additional): + return "/livetv?" in content + + @staticmethod + def credentials_needed(): + return { + "OPTIONAL": True, + "FIREFOX_COOKIES": True + } + + @staticmethod + def get_login_cookies(): + cookie_dict = {} + try: + for c in browser_cookie3.firefox(domain_name='midnightpulp.com'): + cookie_dict[c.name] = c.value + except browser_cookie3.BrowserCookieError: + pass + + try: + assert len(cookie_dict.keys()) > 0 + return cookie_dict + except: + return {} + + @staticmethod + def get_auth_token(): + response = requests.get(midnightpulp_com.BASE_URL).content.decode() + response = re.findall(r']*src="([^"]*app-[^"]*.js)"[^<>]*>', response) + response = response[0] + if not response.startswith("http"): + response = f'{midnightpulp_com.BASE_URL}{response}' + + response = requests.get(response).content.decode() + response = re.findall(r'Authorization:"Basic ([^"]+)"', response) + return response[0] + + @staticmethod + def initialize_service(): + if midnightpulp_com.LOGIN_COOKIES is None: + midnightpulp_com.LOGIN_COOKIES = midnightpulp_com.get_login_cookies() + if midnightpulp_com.AUTH_TOKEN is None: + midnightpulp_com.AUTH_TOKEN = midnightpulp_com.get_auth_token() + return midnightpulp_com + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + additional["license_url"], + data=challenge + ) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_video_data(source_element): + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + midnightpulp_com.__name__ + ) + + response = requests.get( + source_element.url, + cookies=midnightpulp_com.LOGIN_COOKIES + ).content.decode() + + soup = BeautifulSoup(response, 'html5lib') + script = soup.find_all('script', {'type': 'application/json'}) + script = [s for s in script if s.get("id", None) == "__NEXT_DATA__"][0] + script = json.loads(script.string) + + if "/livetv?" in source_element.url: + params_dict = parse_qs(urlparse(source_element.url).query) + channel_query = params_dict["q"][0] + + live_channel = script["props"]["pageProps"]["liveChannelListURL"] + live_feeds = [] + for _ in range(0, 2): + response = json.loads(requests.get( + live_channel, + cookies=midnightpulp_com.LOGIN_COOKIES, + headers={"Authorization": f"Basic {midnightpulp_com.AUTH_TOKEN}"} + ).content.decode()) + + live_feeds = response.get("liveFeeds", []) + if len(live_feeds) > 0: + break + if "jloc=us" in live_channel: + break + live_channel = update_url_params(live_channel, {"jloc": "us"}) + + live_feeds = list(filter(lambda lf: lf.get("item_id", None) == channel_query, live_feeds)) + if len(live_feeds) == 0: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content wasn't found or you need a VPN", + solution="Do not attempt to download it or use a VPN that lets you see the livestream in your browser" + )) + + live_feed = live_feeds[0] + if source_element.element is None: + title = live_feed.get("title", channel_query) + source_element.element = get_valid_filename(f"Live_{title}") + + manifest = live_feed["content"]["hls_url"] + return manifest, None, {} + + details = script["props"]["pageProps"]["idetails"] + err_code = details.get("err_code", None) + err_msg = details.get("err_msg", "").lower() + if err_code == 1002 or "access" in err_msg: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason='Need account for this content, it is paid or it is not available', + solution="Sign into your account using Firefox or don't attempt to download it" + )) + if err_code == 1200 or ("available" in err_msg and "location" in err_msg): + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need American IP to access content", + solution="Use a VPN" + )) + + is_trailer = details.get("trailer", False) + if not is_trailer: + is_trailer = "trailer" in script.get("query", {}).get("vod_type", "").lower() + if not is_trailer: + is_trailer = "vod_type=trailer" in source_element.url + + if source_element.element is None: + title = details.get("title", None) + if title is None: + title = details.get("details", {}).get("title", None) + if title is None: + title = script.get("query", {}).get("play-asset-title", None) + if title is None: + title = source_element.url.split("/watch/")[1] + + if is_trailer: + title = f"Trailer_{title}" + source_element.element = get_valid_filename(title) + + has_drm = details.get("is_drm_encrypted", False) is True + additional = {} + + if has_drm: + drm_info = details["drm_info"] + manifest = drm_info.get("wv_dash_url", None) + if manifest is None: + manifest = drm_info["wv_hls_url"] + + license_url = drm_info.get("wv_drm_server", None) + if license_url is None: + license_url = drm_info["drm_server"] + additional["license_url"] = license_url + + else: + manifest = details.get("url", None) + if manifest is None and is_trailer: + manifest = details["details"]["media_trailer_url"] + + subtitles = [] + srt_url = details.get("subtitle_url", None) + if srt_url in [None, ""]: + srt_url = details.get("cc_url_vtt", None) + + if srt_url not in [None, ""]: + srt_ext = get_ext_from_url(srt_url) + subtitles.append((False, BaseElement( + url=srt_url, + collection=join(source_element.collection, source_element.element), + element=f'subtitle{srt_ext}' + ))) + + additional["SUBTITLES"] = subtitles + try: + if not has_drm: + raise + + pssh_value = str(min(re.findall( + r'<[^<>]*cenc:pssh[^<>]*>(.*?)]*cenc:pssh[^<>]*>', + requests.get(manifest).content.decode() + ), key=len)) + except: + pssh_value = None + + if has_drm and pssh_value is None: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}. Can't extract pssh", + solution=f"Extend the {midnightpulp_com.__name__} service" + )) + + return manifest, pssh_value, additional + + @staticmethod + def get_collection_elements(collection_url): + collection_url = collection_url.rstrip("/") + if "/watch/" in collection_url: + return [BaseElement(url=collection_url)] + if "/livetv?" in collection_url and "q=" in collection_url: + return [BaseElement(url=collection_url)] + + if "/details/" not in collection_url: + return None + collection_url = collection_url.split("?")[0].split("#")[0].rstrip("/") + response = requests.get( + collection_url, + cookies=midnightpulp_com.LOGIN_COOKIES + ).content.decode() + + soup = BeautifulSoup(response, 'html5lib') + script = soup.find_all('script', {'type': 'application/json'}) + script = [s for s in script if s.get("id", None) == "__NEXT_DATA__"][0] + script = json.loads(script.string) + + item_details = script["props"]["pageProps"]["itemDetailsData"] + err_code = item_details.get("code", None) + err_msg = item_details.get("message", "").lower() + if err_code == 1001 or "not available" in err_msg: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=collection_url, + reason="This content isn't available", + solution='Do not attempt to download it' + )) + + collection_title = item_details.get("title", None) + if collection_title is None: + collection_title = script.get("query", {}).get("item-title", None) + if collection_title is None: + collection_title = collection_url.split("/")[-1] + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + midnightpulp_com.__name__ + ), + get_valid_filename(collection_title) + ) + + seasons = script["props"]["pageProps"].get("seasonEpisodes", []) + seasons = sorted(seasons, key=lambda s: s["season"]) + collection = [] + + for season in seasons: + season_index = season["season"] + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + episodes = season.get("episodes", []) + episodes = sorted(episodes, key=lambda e: e["episode"]) + + for episode in episodes: + episode_index = episode["episode"] + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + episode_title = f'Episode_{episode_index} {episode.get("title", "")}' + episode_title = get_valid_filename(episode_title) + episode_url = midnightpulp_com.VIDEO_URL.format( + video_id=episode["item_id"], + video_title=slugify(episode.get("title", "title")) + ) + + collection.append(BaseElement( + url=episode_url, + collection=join(collection_title, f'Season_{season_index}'), + element=episode_title + )) + return collection diff --git a/API/proxiesembed/drmproxy/services/mtv_fi.py b/API/proxiesembed/drmproxy/services/mtv_fi.py new file mode 100644 index 0000000..25a5256 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/mtv_fi.py @@ -0,0 +1,413 @@ +import builtins +import json +import re +from os.path import join +from urllib.parse import unquote + +import browser_cookie3 +import requests +from bs4 import BeautifulSoup + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, CustomException, BaseService +from utils.tools.args import check_range +from utils.tools.cdm import get_pssh_from_cenc_pssh +from utils.tools.common import get_valid_filename, clean_url + + +class mtv_fi(BaseService): + DEMO_URLS = [ + "https://www.mtv.fi/video/34b759d7d68e32d863b6/samu-sirkan-joulutervehdys-2024", + "https://www.mtv.fi/video/14866e70feb4bb53d04c/cliffhanger-kuilun-partaalla", + "https://www.mtv.fi/video/62eba76d8b449b3bf6d0/jakso-4-porvoon-mitalla", + "https://www.mtv.fi/lyhyet/da2fce85b18a2b7e6235/video-tytar-saara-muistelee-kultainen-venla-elamantyopalkinnon-saanutta-isaansa-heikki-silvennoista?first=129d8e9702d4f67430c3&playlist=2e5SUdVLjYGe3DWt6gGO39&isAutoplay=false", + "https://www.mtv.fi/hae/finland%20europe", + "https://www.mtv.fi/ohjelma/970e8c6279e5cf05de1a/hautalehto", + ] + + BASE_URL = "https://www.mtv.fi" + PLAY_URL = None + AUTH_URL = None + GRAPHQL_URL = None + + BEARER_TOKEN = None + CLIENT_VERSION = '5.3.0' + PAGE_LIMIT = 50 + VIDEO_URL = BASE_URL + "/{video_type}/{video_id}/{video_slug}" + + @staticmethod + def test_service(): + main_service.run_service(mtv_fi) + + @staticmethod + def credentials_needed(): + return {"FIREFOX_COOKIES": True} + + @staticmethod + def set_api_endpoints(): + response = requests.get(mtv_fi.BASE_URL).content.decode() + soup = BeautifulSoup(response, 'html5lib') + script = soup.find_all('script', {'type': 'application/json'}) + script = [s for s in script if s.get("id", None) == "__NEXT_DATA__"][0] + script = json.loads(script.string) + + response = script["runtimeConfig"] + mtv_fi.PLAY_URL = response["PLAYBACK_API"] + "/play/{vod_id}" + mtv_fi.AUTH_URL = response["AUTH_API"] + "/oauth/refresh" + mtv_fi.GRAPHQL_URL = response["GRAPHQL_URL"] + "/graphql" + + @staticmethod + def set_bearer_token(): + cookie_dict = {} + for c in browser_cookie3.firefox(domain_name='mtv.fi'): + cookie_dict[c.name] = c.value + + refresh_token = cookie_dict.get("mtv-refresh-token", None) + if refresh_token in ["", None]: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=f'from {mtv_fi.__name__}', + reason='Need account for this service', + solution='Sign into your account using Firefox' + )) + + response = requests.post(mtv_fi.AUTH_URL, json={'refresh_token': refresh_token}) + response = response.content.decode() + response = json.loads(response) + mtv_fi.BEARER_TOKEN = response["access_token"] + + @staticmethod + def initialize_service(): + if mtv_fi.PLAY_URL is None: + mtv_fi.set_api_endpoints() + if mtv_fi.BEARER_TOKEN is None: + mtv_fi.set_bearer_token() + return mtv_fi + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + additional["license_url"], + headers={'x-dt-auth-token': additional["license_token"]}, + data=challenge + ) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_video_data(source_element): + vod_id = None + for f in ["/video/", "/lyhyet/"]: + if f in source_element.url: + vod_id = re.search(fr"{f}([^/?]*)", source_element.url).group(1) + break + + response = requests.get( + mtv_fi.PLAY_URL.format(vod_id=vod_id), + params={ + 'service': 'mtv', 'device': 'device', + 'protocol': 'hls,dash', 'drm': 'widevine' + }, + headers={'x-jwt': f'Bearer {mtv_fi.BEARER_TOKEN}'} + ) + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + error_code = response.get("errorCode", "").lower() + + if status_code in [403] or "missing_subscription" in error_code: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Can't download paid content", + solution='Do not attempt to download it' + )) + if status_code in [404] or "asset_not_found" in error_code: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + if status_code in [401] or "invalid_geo_location" in error_code or "proxy_blocked" in error_code: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need Finnish IP to access content", + solution="Use a VPN (a good one that is not detected)" + )) + + if source_element.element is None: + metadata = response["metadata"] + title = metadata.get("title", None) + if title in ["", None]: + title = metadata.get("seriesTitle", None) + if title in ["", None]: + title = source_element.url.split("/")[-1] + + temp_title = "" + for f in ["seasonNumber", "episodeNumber"]: + if metadata.get(f, None) in ["", None]: + temp_title = "" + break + temp_title += " " + f[0] + str(metadata[f]) + + title = title + temp_title + source_element.element = get_valid_filename(title) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + mtv_fi.__name__ + ) + + playback = response["playbackItem"] + manifest = playback["manifestUrl"] + license_url = None + license_token = None + pssh_value = None + + try: + license_url = playback["license"]["castlabsServer"] + license_token = playback["license"]["castlabsToken"] + except: + pass + + if license_url is not None: + manifest_content = requests.get(manifest).content.decode() + try: + pssh_value = re.search(r'base64,(AAAA[^"]+)"', manifest_content).group(1) + except: + pssh_value = None + + if pssh_value is None: + try: + pssh_value = get_pssh_from_cenc_pssh(manifest_content) + except: + pssh_value = None + + if pssh_value is None: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}", + solution=f"Extend the {mtv_fi.__name__} service" + )) + + return manifest, pssh_value, { + "license_url": license_url, + "license_token": license_token, + "FORCE_SHAKA": True + } + + @staticmethod + def get_collection_elements(collection_url): + collection_url = clean_url(collection_url) + if "/lyhyet/" in collection_url: + return [BaseElement(url=collection_url)] + if "/video/" in collection_url: + return [BaseElement(url=collection_url)] + + if "/hae/" in collection_url: + search_text = re.search(r"/hae/([^/?]*)", collection_url).group(1) + search_text = unquote(search_text) + collection_name = join(join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + mtv_fi.__name__ + ), get_valid_filename("Search clips " + search_text)) + collection = [] + + offset = -mtv_fi.PAGE_LIMIT + clip_index = 0 + while True: + offset += mtv_fi.PAGE_LIMIT + response = requests.get( + mtv_fi.GRAPHQL_URL, + params={ + 'operationName': 'ListSearch', + 'variables': json.dumps({"input": { + "limit": mtv_fi.PAGE_LIMIT, "offset": offset, + "includeUpsell": True, + "query": search_text, "types": ["CLIP", "SHORT"] + }}), + 'extensions': json.dumps({"persistedQuery": { + "version": 1, + "sha256Hash": "f3e6a09f1f4ccea89fb4d0c6af2e91fa898902db4b457223c509218d0ee25ca7" + }}) + }, + headers={ + 'client-name': 'client-name', + 'client-version': mtv_fi.CLIENT_VERSION, + 'authorization': f'Bearer {mtv_fi.BEARER_TOKEN}' + } + ) + response = response.content.decode() + response = json.loads(response) + + try: + clips = response["data"]["listSearch"]["items"] + except: + clips = [] + if len(clips) == 0: + break + + try: + has_next_page = response["data"]["listSearch"]["pageInfo"]["hasNextPage"] + assert type(has_next_page) is bool + except: + has_next_page = False + + for clip in clips: + clip_index += 1 + check = check_range(False, None, clip_index) + if check is True: + continue + elif check is False: + return collection + + clip_url = mtv_fi.VIDEO_URL.format( + video_type="lyhyet", + video_id=clip["id"], + video_slug=clip.get("slug", "clip") + ) + clip_title = clip.get("title", clip.get("slug", "")) + clip_title = get_valid_filename(f'Clip {clip_index} {clip_title}') + + collection.append(BaseElement( + url=clip_url, + collection=collection_name, + element=clip_title + )) + + if not has_next_page: + break + + return collection + + if "/ohjelma/" in collection_url: + series_id = re.search(r"/ohjelma/([^/?]*)", collection_url).group(1) + collection = [] + seasons_response = requests.get( + mtv_fi.GRAPHQL_URL, + params={ + 'operationName': 'ContentDetailsPage', + 'variables': json.dumps({"mediaId": series_id}), + 'extensions': json.dumps({"persistedQuery": { + "version": 1, + "sha256Hash": "5dac39a55f8ca745ab7e974260bc685c0de11349eb1df85023e90e3f6477f084" + }}) + }, + headers={ + 'client-name': 'client-name', + 'client-version': mtv_fi.CLIENT_VERSION, + 'authorization': f'Bearer {mtv_fi.BEARER_TOKEN}' + } + ) + seasons_response = seasons_response.content.decode() + seasons_response = json.loads(seasons_response) + seasons_response = seasons_response["data"]["media"] + + if seasons_response is None: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + collection_name = seasons_response.get("title", seasons_response.get("slug", "")) + if collection_name in ["", None]: + collection_name = collection_url.split("/")[-1] + collection_name = join(join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + mtv_fi.__name__ + ), collection_name) + + try: + seasons = seasons_response["allSeasonLinks"] + assert len(seasons) > 0 + except: + seasons = [] + + season_index = 0 + for season in seasons: + season_index += 1 + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + season_id = season["seasonId"] + season_title = season.get("title", "") + season_title = get_valid_filename(f'Season {season_index} {season_title}') + + episode_offset = -mtv_fi.PAGE_LIMIT + episode_index = 0 + while True: + episode_offset += mtv_fi.PAGE_LIMIT + episode_response = requests.get( + mtv_fi.GRAPHQL_URL, + params={ + 'operationName': 'SeasonEpisodes', + 'variables': json.dumps({ + "seasonId": season_id, + "input": { + "limit": mtv_fi.PAGE_LIMIT, + "offset": episode_offset + } + }), + 'extensions': json.dumps({"persistedQuery": { + "version": 1, + "sha256Hash": "f705d5420f2d1cf2331f18059313bd93a6ccaaf18c4e96b38efee220ea116413" + }}) + }, + headers={ + 'client-name': 'client-name', + 'client-version': mtv_fi.CLIENT_VERSION, + 'authorization': f'Bearer {mtv_fi.BEARER_TOKEN}' + } + ) + episode_response = episode_response.content.decode() + episode_response = json.loads(episode_response) + + try: + episodes = episode_response["data"]["season"]["episodes"]["items"] + except: + episodes = [] + if len(episodes) == 0: + break + + try: + has_next_page = episode_response["data"]["season"]["episodes"]["pageInfo"]["hasNextPage"] + assert type(has_next_page) is bool + except: + has_next_page = False + + for episode in episodes: + episode_index += 1 + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + episode_url = mtv_fi.VIDEO_URL.format( + video_type="video", + video_id=episode["id"], + video_slug=episode.get("slug", "episode") + ) + episode_title = episode.get("title", episode.get("slug", "")) + episode_title = get_valid_filename(f'Episode {episode_index} {episode_title}') + + collection.append(BaseElement( + url=episode_url, + collection=join(collection_name, season_title), + element=episode_title + )) + + if not has_next_page: + break + + return collection + return None diff --git a/API/proxiesembed/drmproxy/services/nba_com.py b/API/proxiesembed/drmproxy/services/nba_com.py new file mode 100644 index 0000000..e9463e2 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/nba_com.py @@ -0,0 +1,216 @@ +import builtins +import json +import re +from os.path import join + +import browser_cookie3 +import requests + +import utils.tools.common as common_tools +from utils.constants.macros import ERR_MSG, USER_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, CustomException, BaseService +from utils.tools.args import check_range + + +class nba_com(BaseService): + DEMO_URLS = [ + "https://www.nba.com/watch/list/collection/skills-drills", + "https://www.nba.com/watch/list/collection/coaches-corner", + # Without account + "https://www.nba.com/watch/video/game-recap-lakers-120-timberwolves-109", + "https://www.nba.com/watch/video/the-fast-break-mar-10-2", + "https://www.nba.com/watch/video/game-recap-wizards-110-heat-108", + "https://www.nba.com/game/hou-vs-ind-0022300719?watchRecap=true", + "https://www.nba.com/game/mil-vs-lac-0022300924?watchRecap=true", + "https://www.nba.com/game/ind-vs-orl-0022300928?watchRecap=true", + # With (free) account + "https://www.nba.com/watch/video/2016-dunk-contest-lavine-vs-gordon-best-ever", + "https://www.nba.com/watch/video/2-27-2023-banchero-takes-over-in-clutch-vs-pels", + "https://www.nba.com/watch/video/12-7-23-haliburton-shines-in-in-season-tournament", + ] + + OPTIONS_URL = 'https://ottapp-appgw-client.nba.com/S1/subscriber/{path}/{program_id}/play-options' + ROLL_URL = 'https://ottapp-appgw-amp.nba.com/v1/client/roll' + STS_URL = 'https://identity.nba.com/api/v1/sts' + VIDEO_URL = 'https://www.nba.com/watch/video/{slug}' + LICENSE_URL = "https://ottapp-appgw-amp.nba.com/v1/client/get-widevine-license" + + AUTH_TOKEN = None + AZUKI_IMC = "IMC7.2.0_AN_D3.0.0_S0" + DEVICE_PROFILE = "eyJtb2RlbCI6IkRlc2t0b3AiLCJvc1ZlcnNpb24iOiIxMCIsInZlbmRvck5hbWUiOiJNaWNyb3NvZnQiLCJvc05hbWUiOiJIVE1MNSIsInd2TGV2ZWwiOiJMMyIsImRldmljZVVVSUQiOiJkZXZpY2VVVUlEIn0=" + + @staticmethod + def test_service(): + main_service.run_service(nba_com) + + @staticmethod + def credentials_needed(): + return { + "OPTIONAL": True, + "FIREFOX_COOKIES": True + } + + @staticmethod + def get_auth_token(): + try: + for c in browser_cookie3.firefox(domain_name='nba.com'): + if "mediakindauth2token" in str(c): + return c.value + except browser_cookie3.BrowserCookieError: + pass + return json.loads(requests.get(nba_com.STS_URL).content.decode())["data"]["AccessToken"] + + @staticmethod + def initialize_service(): + if nba_com.AUTH_TOKEN is None: + nba_com.AUTH_TOKEN = nba_com.get_auth_token() + return nba_com + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + nba_com.LICENSE_URL, data=challenge, + headers={ + "AuthorizationToken": nba_com.AUTH_TOKEN, + 'DeviceProfile': nba_com.DEVICE_PROFILE, + 'AzukiIMC': nba_com.AZUKI_IMC + }, + params={ + "ownerUid": "azuki", + "mediaId": additional["video_id"], + "sessionId": "sessionId" + } + ) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_pssh_info(base_uri, manifest_uri): + manifest = f"{base_uri}/{manifest_uri}" + '&sessionId=sessionId' + v_m3u8 = re.findall(r'^v.*?\.m3u8\?.*?$', requests.get(manifest).content.decode(), re.MULTILINE)[-1] + v_m3u8 = f"{base_uri}/{manifest_uri.replace('index.m3u8', v_m3u8)}" + pssh = re.search(r'base64,([^"]+)"', requests.get(v_m3u8).content.decode()).group(1) + return manifest, pssh + + @staticmethod + def get_program_info(source_url): + response = requests.get(source_url).content.decode() + title = json.loads(re.findall( + r'type="application/json">(.*?)', response + )[0])['props']['pageProps'] + try: + title = title['video']['title'] + except: + title = title.get('game', {}).get('gameRecap', {}).get('title', None) + + if "/video/" in source_url: + return "v3/programs", re.findall( + r'"mediakindExternalProgramId":"([^"]*)"', response + )[0], title + if "/game/" in source_url: + return "v2/events", max(re.findall(r'\d+', source_url), key=len), title + return None, None, None + + @staticmethod + def get_video_data(source_element): + path, program_id, title = nba_com.get_program_info(source_element.url) + title = common_tools.get_valid_filename(title) + if title is None: + title = program_id + + if source_element.element is None: + source_element.element = title + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + nba_com.__name__ + ) + + response = requests.get( + nba_com.OPTIONS_URL.format(path=path, program_id=program_id), + headers={'Authorization': f'OAUTH2 access_token="{nba_com.AUTH_TOKEN}"'}, + params={'IsexternalId': 'true'} + ).content.decode() + + matches = re.findall(r'"Id":"([^"]*)"', response) + video_id = sorted( + [r for r in matches if "VIDEO" in r] if "VIDEO" in str(matches) else matches, + key=len, reverse=True + )[0] + + response = json.loads(requests.post( + nba_com.ROLL_URL, data="{}", + params={'ownerUid': 'azuki', 'mediaId': video_id, 'sessionId': 'sessionId'}, + headers={ + 'AuthorizationToken': nba_com.AUTH_TOKEN, + 'AzukiIMC': nba_com.AZUKI_IMC, + 'DeviceProfile': nba_com.DEVICE_PROFILE + } + ).content.decode()) + + if 'error' in response.get("result", ""): + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason='Need account for this content', + solution='Sign into your account using Firefox' + )) + + manifest, pssh = nba_com.get_pssh_info( + response["response"]["cdns"]["cdn"][0]["base_uri"], + response["response"]["manifest_uri"], + ) + return manifest, pssh, {"video_id": video_id} + + @staticmethod + def get_collection_elements(collection_url): + if "/watch/video/" in collection_url: + return [BaseElement(url=collection_url)] + if "/game/" in collection_url and "?watchRecap=" in collection_url: + return [BaseElement(url=collection_url)] + + collection_url = collection_url.rstrip("/") + if "/watch/list/collection/" in collection_url: + collection = [] + response = json.loads(re.findall( + r'type="application/json"[^>]*>(.*?)', + requests.get(collection_url).content.decode() + )[0])['props']['pageProps'] + + collection_name = response.get("meta", {}) + collection_name = collection_name.get("title", collection_name.get("slug", None)) + if collection_name is None: + collection_name = collection_url.split("/")[-1].split("?")[0] + collection_name = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + nba_com.__name__ + ), + common_tools.get_valid_filename(collection_name) + ) + + videos = response.get("videos", []) + if len(videos) == 0: + return [] + + video_index = 0 + for video in videos: + video_index += 1 + check = check_range(False, None, video_index) + if check is True: + continue + elif check is False: + return collection + + video_title = video.get("title", video.get("name", video["slug"])) + video_title = common_tools.get_valid_filename(video_title) + + collection.append(BaseElement( + url=nba_com.VIDEO_URL.format(slug=video["slug"]), + collection=collection_name, + element=f'{video_index}_{video_title}' + )) + + return collection + return None diff --git a/API/proxiesembed/drmproxy/services/nemzetiarchivum_hu.py b/API/proxiesembed/drmproxy/services/nemzetiarchivum_hu.py new file mode 100644 index 0000000..a935573 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/nemzetiarchivum_hu.py @@ -0,0 +1,247 @@ +import builtins +import json +import re +from os.path import join +from urllib.parse import urlparse, parse_qs + +import requests +from bs4 import BeautifulSoup + +from utils.constants.macros import USER_ERROR, ERR_MSG +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.cdm import get_pssh_from_cenc_pssh +from utils.tools.common import get_valid_filename, get_ext_from_url, update_url_params + + +class nemzetiarchivum_hu(BaseService): + DEMO_URLS = [ + "https://nemzetiarchivum.hu/m3/open?id=M3-bFAxTUFOc0xJODY4ZEIxakJhWW5yemtEaHZVQmVGdVpkTFNxVWRpRlBXdz0", + "https://nemzetiarchivum.hu/m3/open?id=M3-bDVlajVyZzBEZXhjcGxycngwaGNLM1lEUWlVYXJZTzZ2Z2FjQzIxcmdvVT0", + "https://nemzetiarchivum.hu/m3/open?series=S3Vrb3JpIMOpcyBLb3Rrb2RhICBJLiBTb3JvemF0", + "https://nemzetiarchivum.hu/m3/open?series=U3rDoXphZHVuaw%3D%3D", + ] + + STREAM_URL = 'https://nemzetiarchivum.hu/api/m3/v3/stream' + SUBTITLE_URL = 'https://nemzetiarchivum.hu/subtitle/{target_id}.srt' + BASE_URL = 'https://nemzetiarchivum.hu' + + USER_AGENT = None + + @staticmethod + def test_service(): + main_service.run_service(nemzetiarchivum_hu) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def initialize_service(): + if nemzetiarchivum_hu.USER_AGENT is None: + nemzetiarchivum_hu.USER_AGENT = builtins.CONFIG["USER_AGENT"] + return nemzetiarchivum_hu + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post(additional["license_url"], data=challenge) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_video_data(source_element): + if source_element.additional is None: + source_element.additional = {} + target_id = source_element.additional.get("target_id", None) + + if target_id is None: + response = requests.get(source_element.url).text + soup = BeautifulSoup(response, 'html5lib') + + if source_element.element is None: + title = soup.find('div', class_='active-info-line') + if title: + titles = list(title.find_previous_siblings(limit=2)) + title = "" + for t in reversed(titles): + try: + temp_title = t.text.strip() + assert len(temp_title) > 0 + title = title + " " + temp_title + except: + pass + + if title in [None, ""]: + try: + title = soup.title.getText().strip() + i = title.find("|") + 1 + if i > 0: + title = title[i:] + assert len(title) > 0 + except: + title = "" + title = title + " " + parse_qs(urlparse(source_element.url).query)["id"][0] + + source_element.element = get_valid_filename(title) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + nemzetiarchivum_hu.__name__ + ) + + if target_id is None: + try: + target_id = soup.find_all(attrs={'id': 'player', 'data-item': True}) + target_id = json.loads(target_id[0]["data-item"])["id"] + assert len(target_id) > 0 and type(target_id) is str + raise + except: + target_id = None + if target_id is None: + try: + target_id = re.findall( + "{[^{}]*id[^:]*:[^\"']*['\"]([^'\"]+)['\"][^{}]*}", + response + )[0] + except: + target_id = None + + if target_id is None: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + response = requests.get(nemzetiarchivum_hu.STREAM_URL, params={'target': target_id, "type": "open"}) + response = response.content.decode() + response = json.loads(response) + + for f in ["mpeg_dash"]: + try: + manifest = response[f]["url"] + assert len(manifest) > 0 + break + except: + manifest = None + + try: + manifest_content = requests.get(manifest, headers={"User-Agent": nemzetiarchivum_hu.USER_AGENT}) + pssh_value = get_pssh_from_cenc_pssh(manifest_content.text) + except: + pssh_value = None + + additional = {} + if pssh_value is not None: + license_url = nemzetiarchivum_hu.BASE_URL + response["proxy_url"] + license_url += "?drm-type=widevine&type=open" + additional["license_url"] = license_url + + srts = [] + srt_path = join(source_element.collection, source_element.element) + srt_url = nemzetiarchivum_hu.SUBTITLE_URL.format(target_id=target_id) + try: + assert 200 <= requests.head(srt_url).status_code < 300 + assert len(requests.get(srt_url).text) > 0 + srts.append((False, BaseElement( + url=srt_url, + collection=srt_path, + element=f'subtitle{get_ext_from_url(srt_url)}' + ))) + except: + pass + + additional["SUBTITLES"] = srts + return manifest, pssh_value, additional + + @staticmethod + def get_collection_elements(collection_url): + if "/m3/open?" not in collection_url: + return None + if "?id=" in collection_url or "&id=" in collection_url: + return [BaseElement(url=collection_url)] + if "?series=" not in collection_url and "&series=" not in collection_url: + return None + + collection_title = None + page = 0 + collection = [] + while True: + page += 1 + check = check_range(True, page, None) + if check is True: + continue + elif check is False: + return collection + + collection_url = update_url_params(collection_url, {"page": page}) + response_page = requests.get(collection_url).text + soup_page = BeautifulSoup(response_page, "html5lib") + + if collection_title is None: + try: + collection_title = soup_page.title.getText().strip() + i = collection_title.find("|") + 1 + if i > 0: + collection_title = collection_title[i:] + assert len(collection_title) > 0 + except: + collection_title = "" + + if collection_title in ["", None]: + collection_title = "Series " + parse_qs(urlparse(collection_url).query)["series"][0] + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + nemzetiarchivum_hu.__name__ + ), + get_valid_filename(collection_title) + ) + + videos = soup_page.find_all(attrs={'data-id': True, 'href': True}) + if len(videos) == 0: + break + + video_index = 0 + for video in videos: + video_index += 1 + check = check_range(False, page, video_index) + if check is True: + continue + elif check is False: + return collection + + video_url = video["href"] + if not video_url.startswith("http"): + video_url = nemzetiarchivum_hu.BASE_URL + "/m3/" + video_url + + video_title = "" + for node_1 in video.find_all(recursive=False): + if not node_1.find(class_="dp-item-inner") and "dp-item-inner" not in node_1.get("class", []): + direct_children = node_1.find_all(recursive=False) + selected_children = direct_children[:1] if len(direct_children) <= 2 else direct_children[:2] + + for node_2 in selected_children: + video_title += node_2.getText().strip() + " " + if len(video_title) > 0: + video_title = video_title.strip() + break + if len(video_title) == 0: + video_title = parse_qs(urlparse(video_url).query)["id"][0] + + try: + target_id = video.find_all(class_="show-bg", attrs={"style": True})[0] + target_id = re.findall(r'/m3/([^/?)]+)', target_id["style"])[0] + except: + target_id = None + + collection.append(BaseElement( + url=video_url, + collection=join(collection_title, f'Page_{page}'), + element=get_valid_filename(f"Video_{video_index} " + video_title), + additional={"target_id": target_id} + )) + + return collection diff --git a/API/proxiesembed/drmproxy/services/netflix_com.py b/API/proxiesembed/drmproxy/services/netflix_com.py new file mode 100644 index 0000000..2651c54 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/netflix_com.py @@ -0,0 +1,218 @@ +import builtins +import json +import os +import re +from os.path import join + +import requests + +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename + + +class netflix_com(BaseService): + DEMO_URLS = [ + 'https://www.netflix.com/tudum/articles/squid-game-the-challenge-winner', + "https://www.netflix.com/tudum/articles/squid-game-the-challenge-where-are-they-now", + "https://www.netflix.com/tudum/videos/squid-game-the-challenge-what-happens-on-set-between-games", + "https://www.netflix.com/tudum/videos/squid-game-the-challenge-what-players-really-think-of-the-pink-guards", + "https://www.netflix.com/tudum/articles/bridgerton-season-3-filming-cast-news", + "https://www.netflix.com/tudum/wednesday-episode-8-finale-ending-explained", + "https://www.netflix.com/tudum/articles/terminator-zero-first-six-minutes", + "https://www.netflix.com/tudum/topics/what-to-watch", + ] + + MANIFEST_URL = 'https://www.netflix.com/playapi/cadmium/manifest/1' + PROFILES = [ + "heaac-2-dash", "heaac-2hq-dash", "vp9-profile0-L30-dash-cenc", + "vp9-profile0-L31-dash-cenc", "av1-main-L30-dash-cbcs-prk", "av1-main-L31-dash-cbcs-prk", + "vp9-profile0-L40-dash-cenc", "av1-main-L40-dash-cbcs-prk", "av1-main-L41-dash-cbcs-prk", + "imsc1.1", "dfxp-ls-sdh", "simplesdh", "nflx-cmisc", "BIF240", "BIF320" + ] + + @staticmethod + def test_service(): + main_service.run_service(netflix_com) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def initialize_service(): + return netflix_com + + @staticmethod + def get_keys(challenge, additional): + raise Exception( + f'{BaseService.get_keys.__name__} must not be called ' + f'for the {netflix_com.__name__} service' + ) + + @staticmethod + def get_video_data(source_element): + master_m3u8_output_path = join(source_element.collection, source_element.element) + if not os.path.exists(master_m3u8_output_path): + os.makedirs(master_m3u8_output_path) + master_m3u8_output_path = str(master_m3u8_output_path) + + response = requests.post( + netflix_com.MANIFEST_URL, + params={'reqAttempt': '1', 'reqName': 'manifest'}, + cookies={"NetflixId": source_element.additional["netflix_id"]}, + data=json.dumps({ + "url": "manifest", "languages": ["en-US"], + "params": { + "type": "standard", "manifestVersion": "v2", + "viewableId": source_element.additional["content_id"], + "profiles": netflix_com.PROFILES, + "isBranching": False, "useHttpsStreams": True + } + }) + ).json()["result"] + master_m3u8_content = "#EXTM3U\n#EXT-X-VERSION:3\n\n" + content_duration = response["duration"] + + all_tracks_index = 0 + for audio_track in response["audio_tracks"]: + audio_codec = audio_track.get("codecName", None) + if audio_codec is None: + audio_codec = audio_track.get("profile", None) + if audio_codec is not None: + audio_codec = audio_codec.split("-")[0] + audio_profile = audio_track.get("profile", None) + + audio_streams = [] + for audio_stream in audio_track["streams"]: + if audio_stream.get("isDrm", False) is True: + continue + if len(audio_stream["urls"]) == 0: + continue + + audio_bitrate = audio_stream.get("bitrate", audio_stream.get("peakBitrate", 1)) + audio_streams.append((audio_bitrate, audio_stream)) + + audio_streams = sorted(audio_streams, key=lambda a: a[0], reverse=True) + for audio_bitrate, audio_stream in audio_streams: + all_tracks_index += 1 + audio_m3u8_title = f"audio_{all_tracks_index}.m3u8" + audio_m3u8_output_path = os.path.join( + master_m3u8_output_path, + audio_m3u8_title + ) + + audio_url = audio_stream["urls"][0]["url"] + if audio_profile is None: + audio_profile = audio_stream["content_profile"] + if audio_codec is None: + audio_codec = audio_profile.split("-")[0] + master_m3u8_content += f'#EXT-X-MEDIA:TYPE=AUDIO,BANDWIDTH={audio_bitrate * 1000},NAME=\"{audio_bitrate} Kbps\",LANGUAGE=\"{audio_codec}\",CODECS=\"{audio_codec}\",GROUP-ID="Audio",URI="{audio_m3u8_title}\"\n' + + audio_m3u8_content = "#EXTM3U\n#EXT-X-VERSION:3\n\n" + audio_m3u8_content += f"#EXTINF:{content_duration // 1000},\n{audio_url}\n" + audio_m3u8_content += "#EXT-X-ENDLIST\n" + with open(audio_m3u8_output_path, "w") as f: + f.write(audio_m3u8_content) + + for video_track in response["video_tracks"]: + video_codec = video_track.get("flavor", None) + video_profile = video_track.get("profile", None) + + for video_stream in video_track["streams"]: + if video_stream.get("isDrm", False) is True: + continue + if len(video_stream["urls"]) == 0: + continue + all_tracks_index += 1 + video_m3u8_title = f"video_{all_tracks_index}.m3u8" + video_m3u8_output_path = os.path.join( + master_m3u8_output_path, + video_m3u8_title + ) + + video_bitrate = video_stream.get("bitrate", video_stream.get("peakBitrate", 1)) + video_width = video_stream.get("res_w", video_stream["crop_w"]) + video_height = video_stream.get("res_h", video_stream["crop_h"]) + video_url = video_stream["urls"][0]["url"] + + if video_profile is None: + video_profile = video_stream["content_profile"] + if video_codec is None: + video_codec = video_profile.split("-")[0] + master_m3u8_content += f'#EXT-X-STREAM-INF:BANDWIDTH={video_bitrate * 1000},RESOLUTION={video_width}x{video_height},CODECS=\"{video_codec}\",TYPE=VIDEO,MIME-TYPE=\"{video_profile}\",AUDIO=\"Audio\"\n' + master_m3u8_content += f"{video_m3u8_title}\n" + + video_m3u8_content = "#EXTM3U\n#EXT-X-VERSION:3\n\n" + video_m3u8_content += f"#EXTINF:{content_duration // 1000},\n{video_url}\n" + video_m3u8_content += "#EXT-X-ENDLIST\n" + with open(video_m3u8_output_path, "w") as f: + f.write(video_m3u8_content) + + sub_index = 0 + subtitles = [] + for text_track in response["timedtexttracks"]: + if len(text_track.get("ttDownloadables", {}).keys()) == 0: + continue + + for _, downloadable in text_track["ttDownloadables"].items(): + sub_index += 1 + subtitle_url = list(downloadable["downloadUrls"].items())[0][1] + subtitles.append((False, BaseElement( + url=subtitle_url, + collection=master_m3u8_output_path, + element=f'subtitle_{sub_index}.xml' + ))) + + master_m3u8_output_path = os.path.join( + master_m3u8_output_path, + "master.m3u8" + ) + with open(master_m3u8_output_path, "w") as f: + f.write(master_m3u8_content) + return master_m3u8_output_path, None, {"SUBTITLES": subtitles} + + @staticmethod + def get_collection_elements(collection_url): + if "/tudum/" not in collection_url: + return None + + collection_url = collection_url.split("?")[0].split("#")[0].rstrip("/") + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + netflix_com.__name__ + ), + get_valid_filename(collection_url.split("/")[-1]) + ) + + response = requests.get(collection_url) + headers = response.headers['Set-cookie'].split(";") + netflix_id = None + for header in headers: + if " NetflixId=" in header: + netflix_id = header.split("NetflixId=")[1].split(" ")[0] + break + assert netflix_id is not None + + response = response.text + content_ids = re.findall(r'id="VideoControls-(\d+)"', response) + content_index = 0 + collection = [] + + for content_id in content_ids: + content_index += 1 + check = check_range(False, None, content_index) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=f'{collection_url}/{content_id}', + collection=collection_title, + element=f'Media_{content_index}_{content_id}', + additional={"netflix_id": netflix_id, "content_id": content_id} + )) + return collection diff --git a/API/proxiesembed/drmproxy/services/ninateka_pl.py b/API/proxiesembed/drmproxy/services/ninateka_pl.py new file mode 100644 index 0000000..3d1c860 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/ninateka_pl.py @@ -0,0 +1,232 @@ +import builtins +import json +import re +from os.path import join + +import requests + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.cdm import get_pssh_from_default_kid, get_pssh_from_playready +from utils.tools.common import get_valid_filename, clean_url + + +class ninateka_pl(BaseService): + DEMO_URLS = [ + "https://ninateka.pl/movies,1/kompozycje-przestrzenne-katarzyny-kobro--jozef-robakowski,6349", + "https://ninateka.pl/series,2/zubr-pompik-odcinki,28044/odcinek-13,S01E13,11171", + "https://ninateka.pl/audio,153683/mistrz-i-malgorzata--michail-bulhakow-odcinki,36460/odcinek-2,S01E02,5610", + "https://ninateka.pl/series,2/pamietnik-florki-odcinki,48956", + "https://ninateka.pl/audio,153683/proces--franz-kafka-odcinki,24524", + ] + + PLAYLIST_URL = 'https://ninateka.pl/api/products/{video_id}/{video_type}/playlist' + VODS_URL = 'https://ninateka.pl/api/products/vods/{video_id}' + SEASONS_URL = 'https://ninateka.pl/api/products/vods/serials/{show_id}/seasons' + EPISODES_URL = 'https://ninateka.pl/api/products/vods/serials/{show_id}/seasons/{season_id}/episodes' + SHOW_URL = 'https://ninateka.pl/api/products/vods/serials/{show_id}' + + @staticmethod + def test_service(): + main_service.run_service(ninateka_pl) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def initialize_service(): + return ninateka_pl + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post(additional["license_url"], data=challenge) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_video_data(source_element): + video_id = source_element.url.split(",")[-1] + video_type = "videos" + if "/audio," in source_element.url: + video_type = "audios" + + response = requests.get( + ninateka_pl.PLAYLIST_URL.format( + video_id=video_id, + video_type=video_type + ), + params={ + 'videoType': 'MOVIE', + 'platform': 'BROWSER' + } + ) + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + error = response.get("code", "").lower() + + if 400 <= status_code < 500 or "not_exists" in error: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + drm = response.get("drm", {}) + if drm is None: + drm = {} + drms = [d.lower() for d in drm.keys()] + has_drm = len(drms) > 0 + + license_url = None + if has_drm: + if "widevine" not in drms: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine wasn't found", + solution="Do not attempt to download it" + )) + license_url = drm["WIDEVINE"]["src"] + + manifest = None + for m in ["DASH", "SS", "HLS"]: + try: + manifest = response["sources"][m][0]["src"] + if not manifest.startswith("https:"): + manifest = "https:" + manifest + break + except: + continue + + pssh_value = None + if has_drm: + manifest_content = requests.get(manifest).content.decode() + try: + pssh_value = get_pssh_from_default_kid(manifest_content) + except: + pssh_value = None + + if pssh_value is None: + try: + pssh_value = get_pssh_from_playready(manifest_content) + except: + pssh_value = None + + if pssh_value is None: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}. Can't extract pssh", + solution=f"Extend the {ninateka_pl.__name__} service" + )) + + if source_element.element is None: + response = requests.get( + ninateka_pl.VODS_URL.format(video_id=video_id), + params={'platform': 'BROWSER'} + ) + response = response.content.decode() + response = json.loads(response) + + title = response.get("title", None) + if title in ["", None]: + title = source_element.url.split("/")[-1] + source_element.element = get_valid_filename(title) + + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + ninateka_pl.__name__ + ) + return manifest, pssh_value, {"license_url": license_url} + + @staticmethod + def get_collection_elements(collection_url): + collection_url = clean_url(collection_url) + if "/movies," in collection_url: + return [BaseElement(url=collection_url)] + if "/series," not in collection_url and "/audio," not in collection_url: + return None + + content_id = re.findall(r',([^,/]+)', collection_url) + if len(content_id) > 2: + return [BaseElement(url=collection_url)] + content_id = content_id[1] + + response = requests.get( + ninateka_pl.SHOW_URL.format(show_id=content_id), + params={'platform': 'BROWSER'} + ) + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + + error = response.get("code", "").lower() + if 400 <= status_code < 500 or "not_exists" in error: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + collection_title = response.get("title", response.get("slug", None)) + if collection_title in [None, ""]: + collection_title = collection_url.split(content_id)[0].split("/")[-1] + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + ninateka_pl.__name__ + ), + get_valid_filename(collection_title) + ) + + response = requests.get( + ninateka_pl.SEASONS_URL.format(show_id=content_id), + params={'platform': 'BROWSER'} + ) + response = response.content.decode() + response = json.loads(response) + seasons = sorted(response, key=lambda s: s["number"]) + + collection = [] + for season in seasons: + season_index = season["number"] + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + season_id = season["id"] + response = requests.get( + ninateka_pl.EPISODES_URL.format(show_id=content_id, season_id=season_id), + params={'platform': 'BROWSER'} + ) + response = response.content.decode() + response = json.loads(response) + + episodes = sorted(response, key=lambda e: e["number"]) + for episode in episodes: + episode_index = episode["number"] + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + episode_url = episode["webUrl"] + episode_title = episode.get("title", episode["id"]) + episode_title = get_valid_filename(f'Episode_{episode_index}_{episode_title}') + collection.append(BaseElement( + url=episode_url, + collection=join(collection_title, f'Season_{season_index}'), + element=episode_title + )) + + return collection diff --git a/API/proxiesembed/drmproxy/services/npo_nl.py b/API/proxiesembed/drmproxy/services/npo_nl.py new file mode 100644 index 0000000..7f0e873 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/npo_nl.py @@ -0,0 +1,523 @@ +import builtins +import json +import re +import time +from os.path import join + +import browser_cookie3 +import requests +from bs4 import BeautifulSoup + +from utils.constants.macros import ERR_MSG, USER_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename, get_ext_from_url + + +class npo_nl(BaseService): + DEMO_URLS = [ + "https://npo.nl/npo3/undercover-sven/POMS_S_KN_20188850", + "https://npo.nl/npo3/qucee-zoekt-cash/POMS_S_KN_16983903", + "https://npo.nl/npo3/3-op-reis/10-05-2024/BV_101410427/POMS_BV_20193871", + "https://npo.nl/npo3/houda-34-verdoofde-met-binge-eating-haar-gevoelens-de-bovenkamer-4-npo3/29-04-2024/WO_BV_20190951", + "https://npo.nl/start/serie/dit-was-het-nieuws", + "https://npo.nl/start/serie/powned-of-view", + "https://npo.nl/start/serie/de-lama-s", + "https://npo.nl/start/serie/hunted", + "https://npo.nl/start/video/kom-hier-dat-ik-u-kus", + "https://npo.nl/start/video/het-leven-is-vurrukkulluk", + "https://npo.nl/start/serie/op1/seizoen-5/op1_505/afspelen", + "https://npo.nl/start/serie/het-mooiste-meisje-van-de-klas/seizoen-16/femke/afspelen", + ] + + STREAM_URL = 'https://prod.npoplayer.nl/stream-link' + BASE_URL = 'https://npo.nl' + TOKEN_URL = f'{BASE_URL}/start/api/domain/player-token' + TICKETS_URL = f'{BASE_URL}/npo3/video_tickets' + LICENSE_URL = 'https://npo-drm-gateway.samgcloud.nepworldwide.nl/authentication' + + LOGIN_COOKIES = None + LICENSE_RETRIES = 3 + + @staticmethod + def test_service(): + main_service.run_service(npo_nl) + + @staticmethod + def get_additional_params(additional): + return [("MUXER", lambda s: s.format(args="mkv:muxer=mkvmerge"))] + + @staticmethod + def credentials_needed(): + return { + "OPTIONAL": True, + "FIREFOX_COOKIES": True + } + + @staticmethod + def get_login_cookies(): + cookie_dict = {} + try: + for c in browser_cookie3.firefox(domain_name='npo.nl'): + if c.name.lower().startswith("npoid."): + continue + cookie_dict[c.name] = c.value + except browser_cookie3.BrowserCookieError: + pass + + try: + assert len(cookie_dict.keys()) > 0 + return cookie_dict + except: + return {} + + @staticmethod + def initialize_service(): + if npo_nl.LOGIN_COOKIES is None: + npo_nl.LOGIN_COOKIES = npo_nl.get_login_cookies() + return npo_nl + + @staticmethod + def get_keys(challenge, additional): + licence = None + for i in range(1, npo_nl.LICENSE_RETRIES + 1): + try: + licence = requests.post( + npo_nl.LICENSE_URL, + params={'custom_data': additional["custom_data"]}, + data=challenge + ) + licence.raise_for_status() + break + except Exception as e: + response = e.response + if response.status_code == 500: + if i < npo_nl.LICENSE_RETRIES: + time.sleep(1) + continue + + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=additional["URL"], + reason='You requested too much content recently', + solution="Wait 1 minute" + )) + raise e + + return licence.content + + @staticmethod + def get_json_content(source_text): + for start_char, end_char in [("{", "}")]: + start_str = f'type="application/json">{start_char}' + start_index = source_text.find(start_str) + if start_index == -1: + continue + + opening_brackets = 0 + start_index += len(start_str) - 1 + + text_len = len(source_text) + for char_index in range(start_index, text_len): + if source_text[char_index] == start_char: + opening_brackets += 1 + elif source_text[char_index] == end_char: + opening_brackets -= 1 + if opening_brackets == 0: + json_object = json.loads(source_text[start_index:char_index + 1]) + return json_object + return None + + @staticmethod + def get_video_data_npo3(source_element): + if "_" not in source_element.url: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Video not found. URL not supported", + solution=f"Extend the {npo_nl.__name__} service" + )) + + mid = None + for p in list(reversed(source_element.url.split("/"))): + if "_" in p: + mid = p + break + + response = requests.post( + npo_nl.TICKETS_URL, + params={'mid': mid}, + json={ + 'data': { + 'elementId': 'elementId', + 'sterSiteId': 'npo3', + 'hasAdConsent': '1', + 'sterIdentifier': 'npo3-desktop' + } + } + ) + response = response.content.decode() + response = re.search(r"= '(ey[^/']+)'", response).group(1) + + response = json.loads(requests.post( + npo_nl.STREAM_URL, + headers={'Authorization': response}, + json={ + 'profileName': 'dash', + 'drmType': 'widevine', + 'referrerUrl': source_element.url, + 'ster': { + 'identifier': 'npo-app-desktop', + 'player': 'web' + } + } + ).content.decode()) + return response + + @staticmethod + def get_video_data(source_element): + if "/npo3/" in source_element.url: + response = npo_nl.get_video_data_npo3(source_element) + else: + response = requests.get(source_element.url).content.decode() + response = npo_nl.get_json_content(response) + + response = response["props"]["pageProps"] + for k in response: + if "state" in k.lower(): + response = response[k] + break + + slug = None + if "/afspelen" in source_element.url: + slug = source_element.url.split("/afspelen")[0].split("/")[-1] + elif "/video/" in source_element.url: + slug = source_element.url.split("/video")[1].split("/")[-1] + + for query in response["queries"]: + data = query["state"]["data"] + + if type(data) is not list: + data = [data] + + for d in data: + if d.get('slug', None) is None: + continue + + if d["slug"] == slug and type(d["productId"]) is str: + try: + d["programKey"] + except: + continue + + response = d["productId"] + break + else: + continue + break + + if type(response) is not str: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available anymore", + solution="Do not attempt to download it" + )) + + response = json.loads(requests.get( + npo_nl.TOKEN_URL, + cookies=npo_nl.LOGIN_COOKIES, + params={'productId': response} + ).content.decode())["jwt"] + + response = json.loads(requests.post( + npo_nl.STREAM_URL, + cookies=npo_nl.LOGIN_COOKIES, + headers={'Authorization': response}, + json={ + 'profileName': 'dash', + 'drmType': 'widevine', + 'referrerUrl': source_element.url, + 'ster': { + 'identifier': 'npo-app-desktop', + 'player': 'web' + } + } + ).content.decode()) + + status_code = response.get("code", response.get("status", None)) + if status_code in [401, 451]: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need Dutch IP to access content (and in this case, even to download it)", + solution="Use a VPN" + )) + + if "npo plus" in response.get("body", "").lower() or status_code in [402]: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Cannot download paid content", + solution="Do not attempt to download paid content" + )) + + if source_element.element is None: + name = response["metadata"]["title"] + # if "/npo3/" in source_element.url: + # name += "_" + response["metadata"]["prid"] + source_element.element = get_valid_filename(name) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + npo_nl.__name__ + ) + additional = {"URL": source_element.url} + + subtitles = [] + index = 0 + assets = [] + if response["assets"].get("subtitles", None) is not None: + assets = response["assets"]["subtitles"] + + for subtitle in assets: + index += 1 + url = subtitle["location"] + srt_ext = get_ext_from_url(url) + + subtitles.append((False, BaseElement( + url=url, + collection=join(source_element.collection, source_element.element), + element=f'subtitle_{index}_{subtitle["iso"].lower()}{srt_ext}' + ))) + additional["SUBTITLES"] = subtitles + + manifest = response["stream"]["streamURL"] + manifest_response = None + try: + manifest_response = requests.get(manifest) + if manifest_response.status_code < 200 or manifest_response.status_code >= 300: + raise + + pssh_value = str(min(re.findall( + r']*>(.*?)', + manifest_response.content.decode() + ), key=len)) + except: + pssh_value = None + + if manifest_response is not None and manifest_response.status_code == 403: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason=f"The VPN was detected", + solution="Use a better VPN" + )) + + if pssh_value is not None: + additional["custom_data"] = response["stream"]["drmToken"] + # if builtins.CONFIG.get("BASIC", False) is True: + # manifest = re.sub(r'/eyJ[^/]*/', '//', manifest) + return manifest, pssh_value, additional + + @staticmethod + def npo_start_broadcasts_handler(url, response): + contents = [] + for page_query in response["queries"]: + data = page_query["state"]["data"] + if type(data) is not list: + continue + + for d in data: + contents.append(( + get_valid_filename(d.get("title", d["slug"])), + f'{url}/{d["season"]["slug"]}/{d["slug"]}/afspelen' + )) + + # contents = list(reversed(contents)) + contents = [(index + 1, v1, v2) for index, (v1, v2) in enumerate(contents)] + + collection = [] + collection_name = get_valid_filename(url.split("/serie/")[1].split("/")[0]) + + for content_index, content_title, content_url in contents: + check = check_range(False, None, content_index) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=content_url, + collection=join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + npo_nl.__name__ + ), + collection_name + ), + element=f"{content_index}" + f'_' + f"{content_title}" + )) + return collection + + @staticmethod + def get_collection_elements_npo3(collection_url): + collection_name = get_valid_filename(collection_url.split("/npo3/")[1].split("/")[0]) + if not collection_url.endswith("/"): + collection_url = collection_url + "/" + + collection = [] + visited = [] + content_index = 0 + page = 0 + while True: + page += 1 + response = requests.get(f'{collection_url}lists/all/{page}').content.decode() + + soup = BeautifulSoup(response, 'html5lib') + links = soup.find_all( + 'a', class_='is-full-link', + href=lambda href: href and href.startswith('/npo3/') and "_" in href + ) + + if len(links) == 0: + break + if links[0]["href"] in visited: + break + + for link in links: + content_index += 1 + check = check_range(False, None, content_index) + if check is True: + continue + elif check is False: + return collection + + visited.append(link["href"]) + content_title = get_valid_filename(link["href"].split("/npo3/")[1].split("/")[0]) + collection.append(BaseElement( + url=npo_nl.BASE_URL + link["href"], + collection=join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + npo_nl.__name__ + ), + collection_name + ), + element=f"{content_index}" + f'_' + f"{content_title}" + )) + + return collection + + @staticmethod + def get_collection_elements(collection_url): + if "/npo3/" in collection_url: + if collection_url.split("/npo3/")[1].count("/") >= 2: + return [BaseElement(url=collection_url)] + return npo_nl.get_collection_elements_npo3(collection_url) + + if "/start/" not in collection_url: + return None + + if "/afspelen" in collection_url or "/video/" in collection_url: + return [BaseElement(url=collection_url)] + + if "/seizoen-" in collection_url: + return None + + if "/serie/" in collection_url: + collection = [] + collection_name = get_valid_filename(collection_url.split("/serie/")[1].split("/")[0]) + response = requests.get(collection_url).content.decode() + response = npo_nl.get_json_content(response) + + response = response["props"]["pageProps"] + for k in response: + if "state" in k.lower(): + response = response[k] + break + + seasons = [] + for page_query in response["queries"]: + data = page_query["state"]["data"] + if type(data) is not list: + continue + + for d in data: + if d.get("seasonKey", None) is None: + continue + seasons.append(( + int(d["seasonKey"]), + f'{collection_url}/{d["slug"]}', + d["label"] + )) + + if len(seasons) == 0: + return npo_nl.npo_start_broadcasts_handler(collection_url, response) + + seasons = sorted(seasons, key=lambda s: s[0]) + seasons = [(index + 1, v1, v2) for index, (_, v1, v2) in enumerate(seasons)] + + for season_index, season_url, season_name in seasons: + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + response = requests.get(season_url).content.decode() + response = npo_nl.get_json_content(response) + + response = response["props"]["pageProps"] + for k in response: + if "state" in k.lower(): + response = response[k] + break + + episodes = [] + for season_query in response["queries"]: + data = season_query["state"]["data"] + if type(data) is not list: + continue + + for d in data: + if d.get("programKey", None) is None: + continue + + episodes.append(( + int(d["programKey"]), + f'{season_url}/{d["slug"]}/afspelen', + d["title"] + )) + + episodes = sorted(episodes, key=lambda s: s[0]) + episodes = [(index + 1, v1, v2) for index, (_, v1, v2) in enumerate(episodes)] + + for episode_index, episode_url, episode_name in episodes: + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=episode_url, + collection=join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + npo_nl.__name__ + ), + join(collection_name, f'Season_{season_index}') + ), + element=f"Episode_{episode_index}" + f'_' + f"{get_valid_filename(episode_name)}" + )) + + return collection + return None diff --git a/API/proxiesembed/drmproxy/services/pianogroove_com.py b/API/proxiesembed/drmproxy/services/pianogroove_com.py new file mode 100644 index 0000000..a43bd9b --- /dev/null +++ b/API/proxiesembed/drmproxy/services/pianogroove_com.py @@ -0,0 +1,212 @@ +import builtins +import json +import re +from html import unescape +from os.path import join + +import requests +from bs4 import BeautifulSoup + +from utils.constants.macros import ERR_MSG, USER_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_last_path, get_valid_filename, get_ext_from_url, get_base_url, get_nr_paths + + +class pianogroove_com(BaseService): + DEMO_URLS = [ + "https://www.pianogroove.com/jazz-piano-lessons/jazz-piano-foundations/", + "https://www.pianogroove.com/bossa-nova-lessons/jovino-santos-neto-masterclasses/", + "https://www.pianogroove.com/blues-piano-lessons/blues-left-hand-shuffle-patterns/", + "https://www.pianogroove.com/blues-piano-lessons/minor-blues-introduction/", + ] + + ADMIN_PHP_URL = 'https://www.pianogroove.com/wp-admin/admin-ajax.php' + VIMEO_URL = 'https://vimeo.com' + + @staticmethod + def test_service(): + main_service.run_service(pianogroove_com) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def initialize_service(): + return pianogroove_com + + @staticmethod + def get_keys(challenge, additional): + raise Exception( + f'{BaseService.get_keys.__name__} must not be called ' + f'for the {pianogroove_com.__name__} service' + ) + + @staticmethod + def get_key_url(manifest): + response = requests.get(manifest).content.decode() + response = re.findall(r'(https?://\S+)', response)[-1] + + response = requests.get(response).content.decode() + response = re.findall(r',URI="([^"]+)"', response) + + if len(response) == 0: + return None + return response[0] + + @staticmethod + def get_video_data(source_element): + response = requests.get(source_element.url).content.decode() + response = re.findall(r'data-item="([^"]+)"', response) + if len(response) == 0: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="No content has been found", + solution="Do not attempt to download it" + )) + + response = json.loads(unescape(response[0])) + response["sources"] = sorted(response["sources"], key=lambda r: r.get("type", "")) + manifest = None + orig_duration = response.get("duration", None) + + for source in response["sources"]: + if source.get("src", None) is None: + continue + manifest = source + break + + if source_element.element is None: + source_element.element = response.get("fv_title", get_last_path(source_element.url)) + source_element.element = get_valid_filename(source_element.element) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + pianogroove_com.__name__ + ) + + subtitles = [] + if response.get("chapters", None) is not None: + srt_ext = get_ext_from_url(response["chapters"]) + + subtitles.append((False, BaseElement( + url=response["chapters"], + collection=join(source_element.collection, source_element.element), + element=f'subtitle_1_chapters{srt_ext}' + ))) + + key = None + if "mp4" in manifest["type"].lower(): + response = requests.post( + pianogroove_com.ADMIN_PHP_URL, + headers={'Referer': source_element.url}, + data={ + 'action': 'fv_fp_get_vimeo', + 'sources[0][src]': manifest["src"] + } + ).content.decode() + + response = re.findall(r'(.+)', response)[0] + response = json.loads(response) + vimeo_duration = response.get("video", {}).get("duration", None) + if vimeo_duration != orig_duration: + subtitles = [] + + response = response["request"] + index = len(subtitles) + for text_track in response.get("text_tracks", []): + index += 1 + srt_url = f'{pianogroove_com.VIMEO_URL}{text_track["url"]}' + srt_ext = get_ext_from_url(srt_url) + + subtitles.append((False, BaseElement( + url=srt_url, + collection=join(source_element.collection, source_element.element), + element=f'subtitle_{index}_{text_track["lang"]}{srt_ext}' + ))) + + response = response["files"] + for file in response: + stream = response[file] + manifest = stream["cdns"][stream["default_cdn"]]["url"] + manifest = manifest.replace("master.json", "master.mpd") + break + else: + manifest = manifest["src"] + + key_url = pianogroove_com.get_key_url(manifest) + if key_url is not None: + requests.post( + pianogroove_com.ADMIN_PHP_URL, + data={ + 'action': 'fv_player_performance', + 'summary': manifest + } + ) + response = requests.get(key_url) + key = response.content.hex() + + return manifest, None, { + "AES": {"KEY": key}, + "SUBTITLES": subtitles + } + + @staticmethod + def get_collection_elements(collection_url): + if get_nr_paths(collection_url.split(get_base_url(collection_url))[1]) != 2: + return None + + response = requests.get(collection_url).content.decode() + if "#course-info" in response: + content_title = get_valid_filename(get_last_path(collection_url)) + collection = [] + index = 1 + if check_range(False, None, index) not in [True, False]: + collection.append(BaseElement( + url=collection_url, + collection=join(join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + pianogroove_com.__name__ + ), content_title), + element=f'Course_{index}' + f'_' + f'Introduction' + )) + + soup = BeautifulSoup(response, 'html5lib') + for li in soup.find_all('li'): + node = li.find('div', class_=True) + if not node: + continue + node = node.find('input', {'data-course_name': True}) + if not node: + continue + + title = unescape(node["data-course_name"]) + node = li.find('a') + if not node: + continue + + index += 1 + check = check_range(False, None, index) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=node["href"], + collection=join(join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + pianogroove_com.__name__ + ), content_title), + element=f'Course_{index}' + f'_' + f'{get_valid_filename(title)}' + )) + + return collection + return [BaseElement(url=collection_url)] diff --git a/API/proxiesembed/drmproxy/services/play_tv3_lt.py b/API/proxiesembed/drmproxy/services/play_tv3_lt.py new file mode 100644 index 0000000..bd72f8b --- /dev/null +++ b/API/proxiesembed/drmproxy/services/play_tv3_lt.py @@ -0,0 +1,726 @@ +import builtins +import json +import os +import re +import time +from os.path import join + +import requests +import xmltodict + +import utils.tools.cdm as cdm_tools +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename + + +class play_tv3_lt(BaseService): + DEMO_URLS = [ + "https://play.tv3.lt/series/cesapiko-krantai,serial-5649152", + "https://play.tv3.lt/shows/tevai-paprastai,serial-4654553", + "https://play.tv3.lt/news/dienos-pjuvis,serial-2941600", + "https://play.tv3.lt/shows/entertainment,4197826", + "https://play.tv3.lt/shows/sections/lietuvos-talentai,3983709", + 'https://play.tv3.lt/series/sections/nenugalima-meile,7491265', + "https://play.tv3.lt/clips/sections/x-faktorius,3351498", + "https://play.tv3.lt/news/tv3_zinios,4198085", + "https://play.tv3.lt/news/sections/tv3-zinios-tiesiogiai-ir-archyvas,2871419", + "https://play.tv3.lt/show/tv3-plus,live-4929289/kaip-ilgai-as-taves-laukiau,programme-7554014", + "https://play.tv3.lt/lives/tv3-lt,live-2831094/tv3-orai,programme-7547397", + "https://play.tv3.lt/clip/oziaragio-horoskopas-06100617,clip-7545830", + "https://play.tv3.lt/series/nepaleisk-mano-rankos-,serial-5981793/serija-1,episode-5928727", + "https://play.tv3.lt/kids_series/ar-zinai-kaip-as-tave-myliu,serial-1601493/serija-50,episode-1601571", + ] + + PLAYLIST_URL = 'https://play.tv3.lt/api/products/{product_id}/videos/playlist' + INFO_URL = 'https://play.tv3.lt/api/info' + VOD_URL = 'https://play.tv3.lt/api/products/vods/{vod_id}' + PROGRAM_URL = 'https://play.tv3.lt/api/products/lives/programmes/{content_id}' + LIVE_URL = 'https://play.tv3.lt/api/products/lives/{content_id}' + SECTION_URL = 'https://play.tv3.lt/api/products/sections/{section_id}' + VODS_URL = 'https://play.tv3.lt/api/products/vods' + CATALOG_URL = 'https://play.tv3.lt/api/products/lives/programmes/catalog' + SERIAL_URL = 'https://play.tv3.lt/api/products/vods/serials/{serial_id}' + SEASONS_URL = "https://play.tv3.lt/api/products/vods/serials/{serial_id}/seasons" + EPISODES_URL = "https://play.tv3.lt/api/products/vods/serials/{serial_id}/seasons/{season_id}/episodes" + RELATED_URL = 'https://play.tv3.lt/api/products/{product_id}/related/CLIP' + BASE_URL = 'https://play.tv3.lt' + + TENANT = None + LANGUAGE = None + PLATFORM = "BROWSER" + CODEC = None + CODEC_PRIORITY = {"DASH": 1, "DASH_HEVC": 2} + PAGE_SIZE = 50 + RETRIES_TIMER = 10 + RETRIES_COUNT = 10 + + @staticmethod + def test_service(): + main_service.run_service(play_tv3_lt) + + @staticmethod + def is_content_livestream(content, additional): + return "LIVE" in additional.get("video_type", "") + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def get_site_info(): + response = json.loads(requests.get( + play_tv3_lt.INFO_URL, + params={'platform': play_tv3_lt.PLATFORM} + ).content.decode()) + return response["defaultLanguage"], response["defaultTenant"] + + @staticmethod + def initialize_service(): + if builtins.CONFIG.get("BASIC", False) is True: + play_tv3_lt.CODEC = 'DASH' + + if play_tv3_lt.LANGUAGE is None or play_tv3_lt.TENANT is None: + play_tv3_lt.LANGUAGE, play_tv3_lt.TENANT = play_tv3_lt.get_site_info() + return play_tv3_lt + + @staticmethod + def get_keys(challenge, additional): + licence = None + for i in range(1, play_tv3_lt.RETRIES_COUNT + 1): + try: + licence = requests.post(additional["license_url"], data=challenge) + licence.raise_for_status() + break + except Exception as e: + response = e.response + if response.status_code >= 300 or response.status_code < 200: + if i < play_tv3_lt.RETRIES_COUNT: + time.sleep(play_tv3_lt.RETRIES_TIMER) + continue + raise e + return licence.content + + @staticmethod + def generate_master_mpd(source_element, manifests): + manifests_contents = [] + for mpd_url in manifests: + mpd_url = mpd_url.rstrip("/") + mpd_content = play_tv3_lt.get_manifest_content(mpd_url) + mpd_content = xmltodict.parse(mpd_content) + manifests_contents.append((mpd_url, mpd_content)) + + video_set = [] + index = -1 + for mpd_url, mpd_content in manifests_contents: + index += 1 + + base_url = mpd_content["MPD"]["Period"].get("BaseURL", "") + dots_count = base_url.count("../") + base_url = "/".join(mpd_url.split("/")[0:-(dots_count + 1)]) + "/" + base_url.split("../")[dots_count] + mpd_content["MPD"]["Period"].pop("BaseURL", None) + + manifest_content = mpd_content["MPD"]["Period"]["AdaptationSet"] + if type(manifest_content) is not list: + manifest_content = [manifest_content] + + for ad_set in manifest_content: + if index > 0: + if "video/" not in ad_set["@mimeType"]: + continue + + ad_set_rep = ad_set["Representation"] + if type(ad_set_rep) is not list: + ad_set_rep = [ad_set_rep] + + for ad_rep in ad_set_rep: + ad_rep["BaseURL"] = base_url + if len(ad_set_rep) == 1: + ad_set_rep = ad_set_rep[0] + ad_set["Representation"] = ad_set_rep + + if index > 0: + video_set.append(ad_set) + + manifests_contents = [m[1] for m in manifests_contents] + manifest_content = manifests_contents[0]["MPD"]["Period"]["AdaptationSet"] + manifest_content += video_set + manifests_contents[0]["MPD"]["Period"]["AdaptationSet"] = manifest_content + manifest_content = manifests_contents[0] + manifest_content = xmltodict.unparse(manifest_content, pretty=True) + + output_path = join(source_element.collection, source_element.element) + if not os.path.exists(output_path): + os.makedirs(output_path) + output_path = join(str(output_path), "master.mpd") + + with open(output_path, "w") as f: + f.write(manifest_content) + return output_path + + @staticmethod + def get_manifest_content(mpd_url): + for i in range(1, play_tv3_lt.RETRIES_COUNT + 1): + try: + mpd_content = requests.get(mpd_url) + status_code = mpd_content.status_code + mpd_content = mpd_content.content.decode() + assert 200 <= status_code < 300 + assert "403 forbidden" not in mpd_content.lower() + return mpd_content + except: + if i < play_tv3_lt.RETRIES_COUNT: + time.sleep(play_tv3_lt.RETRIES_TIMER) + return None + + @staticmethod + def get_init_from_mpd(mpd_url, mpd_content): + try: + return False, str(min( + re.findall( + r']*>(.*?)', + mpd_content + ), key=len + )) + except: + pass + + mpd_content = xmltodict.parse(mpd_content)["MPD"] + mpd_content = mpd_content["Period"] + base_url = mpd_content.get("BaseURL", "") + dots_count = base_url.count("../") + base_url = "/".join(mpd_url.split("/")[0:-(dots_count + 1)]) + "/" + base_url.split("../")[dots_count] + + if type(mpd_content["AdaptationSet"]) is not list: + mpd_content["AdaptationSet"] = [mpd_content["AdaptationSet"]] + + best_content = None + best_height = None + best_bandwidth = None + for content in mpd_content["AdaptationSet"]: + if content["@contentType"] != "video": + continue + update_content = False + + height = content.get("@maxHeight", content.get("@height", None)) + if height is None: + continue + height = int(height) + bandwidth = content.get("@maxBandwidth", content.get("@bandwidth", None)) + + if best_content is None: + update_content = True + else: + if height > best_height: + update_content = True + elif height == best_height: + if bandwidth is not None: + if best_bandwidth is None: + update_content = True + elif int(bandwidth) > int(best_bandwidth): + update_content = True + + if update_content: + best_content = content + best_height = height + best_bandwidth = bandwidth + + mpd_content = best_content + init_url = mpd_content["SegmentTemplate"]["@initialization"] + if type(mpd_content["Representation"]) is not list: + mpd_content["Representation"] = [mpd_content["Representation"]] + + best_content = None + for content in mpd_content["Representation"]: + if best_content is None: + best_content = content + continue + + content_h = int(content.get("@height", mpd_content.get("@height", None))) + best_content_h = int(best_content.get("@height", mpd_content.get("@height", None))) + if content_h > best_content_h: + best_content = content + continue + elif content_h == best_content_h: + if int(content["@bandwidth"]) > int(best_content["@bandwidth"]): + best_content = content + continue + + init_url = init_url.replace("$RepresentationID$", best_content["@id"]) + init_url = init_url.replace("$Bandwidth$", best_content["@bandwidth"]) + init_url = base_url + init_url + return True, init_url + + @staticmethod + def get_pssh_from_manifest(mpd_url, mpd_content): + is_init, init = play_tv3_lt.get_init_from_mpd(mpd_url, mpd_content) + if not is_init: + return init + return cdm_tools.get_pssh_from_init(init) + + @staticmethod + def get_video_data(source_element): + video_type = "MOVIE" + product_id = source_element.url.split("-")[-1] + response = None + + if ",live-" in source_element.url: + video_type = "LIVE" + nr_slash = source_element.url.split(play_tv3_lt.BASE_URL)[-1].count("/") + lives_url = play_tv3_lt.LIVE_URL + + if ",programme-" in source_element.url or nr_slash >= 3: + video_type = "CATCHUP" + lives_url = play_tv3_lt.PROGRAM_URL + + response = json.loads(requests.get( + lives_url.format(content_id=product_id), + params={ + 'platform': play_tv3_lt.PLATFORM, + 'lang': play_tv3_lt.LANGUAGE, + 'tenant': play_tv3_lt.TENANT + } + ).content.decode()) + status_code = response.get("codeNumber", None) + if status_code == 404: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + if video_type == "CATCHUP": + product_id = response["programRecordingId"] + else: + product_id = response["id"] + + if source_element.element is None: + if response is None: + response = json.loads(requests.get( + play_tv3_lt.VOD_URL.format(vod_id=product_id), + params={ + 'platform': play_tv3_lt.PLATFORM, + 'lang': play_tv3_lt.LANGUAGE, + 'tenant': play_tv3_lt.TENANT + } + ).content.decode()) + + status_code = response.get("codeNumber", None) + if status_code == 404: + title = product_id + else: + title = response.get("title", response.get("slug", product_id)) + + serial = response.get("season", {}) + if serial.get("number", None) is not None: + title = f"Season_{serial['number']}_" + title + + serial = serial.get("serial", {}) + serial = serial.get("title", serial.get("slug", None)) + if serial is not None: + title = serial + " " + title + + source_element.element = get_valid_filename(title) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + play_tv3_lt.__name__ + ) + + response = json.loads(requests.get( + play_tv3_lt.PLAYLIST_URL.format(product_id=product_id), + params={ + 'platform': play_tv3_lt.PLATFORM, + 'videoType': video_type, + 'lang': play_tv3_lt.LANGUAGE, + 'tenant': play_tv3_lt.TENANT + } + ).content.decode()) + status_code = response.get("codeNumber", None) + if status_code == 404: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + sources = response.get("sources", []) + if len(sources) == 0: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="The content isn't available yet", + solution="Wait until you can watch it on your browser" + )) + + for k, v in sources.items(): + if type(v) is not list: + v = [v] + sources[k] = max(v, key=lambda s: s.get("aspectWidth", 0)) + + sources = [(play_tv3_lt.CODEC_PRIORITY.get(kv[0], 0), kv) for kv in sources.items()] + sources = sorted(sources, key=lambda s: s[0], reverse=True) + sources = list(filter(lambda s: s[0] > 0, sources)) + sources = [s[1] for s in sources] + sources = list(filter(lambda s: len(s[1]) > 0, sources)) + + if len(sources) == 0: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {str(response.get('sources', []))}", + solution=f"Extend the {play_tv3_lt.__name__} service" + )) + + if play_tv3_lt.CODEC is not None: + temp_src = [(codec, _) for codec, _ in sources if codec == play_tv3_lt.CODEC] + if len(temp_src) > 0: + sources = [temp_src[0]] + else: + sources = [sources[0]] + + license_url = None + has_drm = False + if response.get("drm", {}) not in [None, {}] and len(response["drm"].keys()) > 0: + has_drm = True + if has_drm: + for d, s in response["drm"].items(): + if "widevine" in d.lower(): + license_url = s["src"] + break + if has_drm and license_url is None: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine wasn't found", + solution="Do not attempt to download it" + )) + + manifests = [] + pssh_values = [] + additional = {"video_type": video_type} + + for _, source in sources: + manifest = source["src"] + if manifest.startswith("//"): + manifest = manifest.replace("//", "https://") + + if manifest in manifests: + continue + manifests.append(manifest) + + pssh_value = None + if license_url is not None: + mpd_content = play_tv3_lt.get_manifest_content(manifest) + assert mpd_content is not None + + try: + pssh_value = play_tv3_lt.get_pssh_from_manifest(manifest, mpd_content) + except Exception as e: + if builtins.CONFIG["DEBUG_MODE"]: + raise e + pssh_value = None + + if pssh_value is not None: + if pssh_value not in pssh_values: + pssh_values.append(pssh_value) + additional[pssh_value] = {"license_url": license_url} + if pssh_value is None and license_url is not None: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine wasn't found", + solution="Do not attempt to download it" + )) + + if len(manifests) > 1: + manifests = play_tv3_lt.generate_master_mpd(source_element, manifests) + else: + manifests = manifests[0] + return manifests, pssh_values, additional + + @staticmethod + def get_video_url(item): + video_url = play_tv3_lt.BASE_URL + item_type = item.get("type_", item["type"]) + + if item_type == "EPISODE": + season = item["season"] + serial = season["serial"] + + video_url += "/" + serial["mainCategory"]["label"] + video_url += "/" + serial["slug"] + video_url += "," + serial["type_"].lower() + video_url += "-" + str(serial["id"]) + + video_url += "/" + item["slug"] + video_url += "," + item_type.lower() + video_url += "-" + str(item["id"]) + return video_url + + if item_type == "PROGRAMME": + live = item["live"] + + video_url += "/" + item["mainCategory"]["label"] + video_url += "/" + live["slug"] + video_url += "," + live["type_"].lower() + video_url += "-" + str(live["id"]) + + video_url += "/" + item["slug"] + video_url += "," + item_type.lower() + video_url += "-" + str(item["id"]) + return video_url + + if item_type == "CLIP": + video_url += "/" + item.get("mainCategory", {}).get("label", "clip") + video_url += "/" + item["slug"] + video_url += "," + item_type.lower() + video_url += "-" + str(item["id"]) + return video_url + + if item_type == "VOD": + video_url += "/" + item["mainCategory"]["label"] + video_url += "/" + item["slug"] + video_url += "," + item_type.lower() + video_url += "-" + str(item["id"]) + return video_url + + if item_type == "SERIAL": + return None + raise Exception("Unknown Type: ", str(item)) + + @staticmethod + def sections_handler(collection_url): + collection = [] + content_id = collection_url.split(",")[-1].split("-")[-1] + collection_name = None + + episode_index = 0 + first_result = 0 + while True: + + if "/sections/" in collection_url: + response = json.loads(requests.get( + play_tv3_lt.SECTION_URL.format(section_id=content_id), + params={ + 'platform': play_tv3_lt.PLATFORM, + 'lang': play_tv3_lt.LANGUAGE, + 'tenant': play_tv3_lt.TENANT, + "maxResults": play_tv3_lt.PAGE_SIZE, + "firstResult": first_result + } + ).content.decode()) + episodes = [e["item"] for e in response.get("elements", [])] + else: + response = json.loads(requests.get( + play_tv3_lt.CATALOG_URL if "/lives/" in collection_url else play_tv3_lt.VODS_URL, + params={ + 'platform': play_tv3_lt.PLATFORM, + 'lang': play_tv3_lt.LANGUAGE, + 'tenant': play_tv3_lt.TENANT, + "maxResults": play_tv3_lt.PAGE_SIZE, + "firstResult": first_result, + "categoryId[]": content_id, + "sort": "createdAt", + "order": "desc" + } + ).content.decode()) + episodes = response.get("items", []) + + first_result += play_tv3_lt.PAGE_SIZE + if type(response) is list and len(response) == 0: + return [] + + if collection_name is None: + collection_name = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + play_tv3_lt.__name__ + ), + get_valid_filename(response.get( + "title", + response.get("slug", collection_url.split("/")[-1].split(",")[0]) + )) + ) + + if len(episodes) == 0: + break + + for episode in episodes: + episode_index += 1 + + check = check_range(False, None, episode_index) + if check is True: + continue + elif check is False: + return collection + + episode_url = play_tv3_lt.get_video_url(episode) + if episode_url is None: + continue + + episode_title = episode.get("title", episode.get("slug", episode["id"])) + episode_title = get_valid_filename(episode_title) + + collection.append(BaseElement( + url=episode_url, + collection=collection_name, + element=f'{episode_index}_{episode_title}' + )) + + return collection + + @staticmethod + def series_handler(collection_url): + collection = [] + content_id = collection_url.split(",")[-1].split("-")[-1] + collection_name = collection_url.split("/")[-1].split(",")[0] + + response = json.loads(requests.get( + play_tv3_lt.SERIAL_URL.format(serial_id=content_id), + params={ + 'platform': play_tv3_lt.PLATFORM, + 'lang': play_tv3_lt.LANGUAGE, + 'tenant': play_tv3_lt.TENANT + } + ).content.decode()) + status_code = response.get("codeNumber", None) + if status_code == 404: + return [] + + collection_name = get_valid_filename(response.get( + "title", + response.get("slug", collection_name) + )) + collection_name = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + play_tv3_lt.__name__ + ), + collection_name + ) + + response = json.loads(requests.get( + play_tv3_lt.SEASONS_URL.format(serial_id=content_id), + params={ + 'platform': play_tv3_lt.PLATFORM, + 'lang': play_tv3_lt.LANGUAGE, + 'tenant': play_tv3_lt.TENANT + } + ).content.decode()) + if type(response) is not list: + status_code = response.get("codeNumber", None) + if status_code == 404: + return [] + + seasons = sorted(response, key=lambda s: s["number"]) + if len(seasons) == 0: + return [] + + season_index = seasons[-1]["number"] + related = [] + for season in seasons: + season_index += 1 + related.append({ + "RELATED": True, + "id": season["id"], + "number": season_index + }) + seasons += related + + for season in seasons: + check = check_range(True, season["number"], None) + if check is True: + continue + elif check is False: + return collection + + if season.get("RELATED", False) is False: + response = json.loads(requests.get( + play_tv3_lt.EPISODES_URL.format( + serial_id=content_id, + season_id=str(season["id"]) + ), + params={ + 'platform': play_tv3_lt.PLATFORM, + 'lang': play_tv3_lt.LANGUAGE, + 'tenant': play_tv3_lt.TENANT + } + ).content.decode()) + if type(response) is not list: + continue + + episodes = sorted(response, key=lambda e: e["episode"]) + for episode in episodes: + check = check_range(False, season["number"], episode['episode']) + if check is True: + continue + elif check is False: + return collection + + episode_url = collection_url + "/" + episode["slug"] + episode_url += "," + episode.get("type_", episode["type"]).lower() + episode_url += "-" + str(episode["id"]) + episode_title = get_valid_filename(episode.get("title", episode["slug"])) + + collection.append(BaseElement( + url=episode_url, + collection=join(collection_name, f'Season_{season["number"]}'), + element=f"Episode_{episode['episode']}_{episode_title}" + )) + + else: + response = json.loads(requests.get( + play_tv3_lt.RELATED_URL.format(product_id=str(season["id"])), + params={ + 'platform': play_tv3_lt.PLATFORM, + 'lang': play_tv3_lt.LANGUAGE, + 'tenant': play_tv3_lt.TENANT, + "maxResults": 1000 + } + ).content.decode()) + if type(response) is not list: + response = [] + + episodes = response + episode_index = 0 + for episode in episodes: + episode_index += 1 + check = check_range(False, season["number"], episode_index) + if check is True: + continue + elif check is False: + return collection + + episode_url = play_tv3_lt.get_video_url(episode) + episode_title = get_valid_filename(episode.get("title", episode["slug"])) + + collection.append(BaseElement( + url=episode_url, + collection=join(collection_name, f'Season_{season["number"]}_Clips'), + element=f"Clip_{episode_index}_{episode_title}" + )) + + return collection + + @staticmethod + def get_collection_elements(collection_url): + collection_url = collection_url.rstrip("/") + for p in [",vod-", ",episode-", ",clip-", ",programme-", ",live-"]: + if p in collection_url: + return [BaseElement(url=collection_url)] + + if "/sections/" in collection_url or "/lives/" in collection_url: + return play_tv3_lt.sections_handler(collection_url) + + nr_slash = collection_url.split(play_tv3_lt.BASE_URL)[-1].count("/") + if "," in collection_url and "-" not in collection_url.split(",")[-1] and nr_slash == 2: + return play_tv3_lt.sections_handler(collection_url) + + if ",serial-" in collection_url: + return play_tv3_lt.series_handler(collection_url) + return None diff --git a/API/proxiesembed/drmproxy/services/play_tv3_lv.py b/API/proxiesembed/drmproxy/services/play_tv3_lv.py new file mode 100644 index 0000000..3339d42 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/play_tv3_lv.py @@ -0,0 +1,564 @@ +import builtins +import json +import os +import re +import time +from os.path import join + +import requests +import xmltodict + +import utils.tools.cdm as cdm_tools +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename, clean_url + + +class play_tv3_lv(BaseService): + DEMO_URLS = [ + "https://play.tv3.lv/video/nba-7346592/nba-top-10-2702-2025-8997558/", + "https://play.tv3.lv/video/kornelijs-un-berni-5554508/serija-52-5554562/", + "https://play.tv3.lv/video/sefu-gaidijat-5069270/serija-11-8877550/", + "https://play.tv3.lv/filmas/tornis-5523881/", + "https://play.tv3.lv/video/nemiletie-svesie-1915103/", + "https://play.tv3.lv/video/nebaidies-ne-no-ka-2441397/", + "https://play.tv3.lv/video/misters-bins-8882922/", + "https://play.tv3.lv/video/sefu-gaidijat-5069270/", + "https://play.tv3.lv/video/ufc---jaukta-cinas-maksla-3428494/", + ] + + PLAYLIST_URL = 'https://play.tv3.lv/api/products/{product_id}/videos/playlist' + INFO_URL = 'https://play.tv3.lv/api/info' + VOD_URL = 'https://play.tv3.lv/api/products/vods/{vod_id}' + SERIAL_URL = 'https://play.tv3.lv/api/products/vods/serials/{serial_id}' + SEASONS_URL = "https://play.tv3.lv/api/products/vods/serials/{serial_id}/seasons" + EPISODES_URL = "https://play.tv3.lv/api/products/vods/serials/{serial_id}/seasons/{season_id}/episodes" + RELATED_URL = 'https://play.tv3.lv/api/products/{product_id}/related/CLIP' + + TENANT = None + LANGUAGE = None + PLATFORM = "BROWSER" + CODEC = None + CODEC_PRIORITY = {"DASH": 1, "DASH_HEVC": 2} + PAGE_SIZE = 50 + RETRIES_TIMER = 10 + RETRIES_COUNT = 10 + + @staticmethod + def test_service(): + main_service.run_service(play_tv3_lv) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def get_site_info(): + response = json.loads(requests.get( + play_tv3_lv.INFO_URL, + params={'platform': play_tv3_lv.PLATFORM} + ).content.decode()) + return response["defaultLanguage"], response["defaultTenant"] + + @staticmethod + def initialize_service(): + if builtins.CONFIG.get("BASIC", False) is True: + play_tv3_lv.CODEC = 'DASH' + + if play_tv3_lv.LANGUAGE is None or play_tv3_lv.TENANT is None: + play_tv3_lv.LANGUAGE, play_tv3_lv.TENANT = play_tv3_lv.get_site_info() + return play_tv3_lv + + @staticmethod + def get_keys(challenge, additional): + licence = None + for i in range(1, play_tv3_lv.RETRIES_COUNT + 1): + try: + licence = requests.post(additional["license_url"], data=challenge) + licence.raise_for_status() + break + except Exception as e: + response = e.response + if response.status_code >= 300 or response.status_code < 200: + if i < play_tv3_lv.RETRIES_COUNT: + time.sleep(play_tv3_lv.RETRIES_TIMER) + continue + raise e + return licence.content + + @staticmethod + def get_manifest_content(mpd_url): + for i in range(1, play_tv3_lv.RETRIES_COUNT + 1): + try: + mpd_content = requests.get(mpd_url) + status_code = mpd_content.status_code + mpd_content = mpd_content.content.decode() + assert 200 <= status_code < 300 + assert "403 forbidden" not in mpd_content.lower() + return mpd_content + except: + if i < play_tv3_lv.RETRIES_COUNT: + time.sleep(play_tv3_lv.RETRIES_TIMER) + return None + + @staticmethod + def generate_master_mpd(source_element, manifests): + manifests_contents = [] + for mpd_url in manifests: + mpd_url = mpd_url.rstrip("/") + mpd_content = play_tv3_lv.get_manifest_content(mpd_url) + mpd_content = xmltodict.parse(mpd_content) + manifests_contents.append((mpd_url, mpd_content)) + + video_set = [] + index = -1 + for mpd_url, mpd_content in manifests_contents: + index += 1 + + base_url = mpd_content["MPD"]["Period"].get("BaseURL", "") + dots_count = base_url.count("../") + base_url = "/".join(mpd_url.split("/")[0:-(dots_count + 1)]) + "/" + base_url.split("../")[dots_count] + mpd_content["MPD"]["Period"].pop("BaseURL", None) + + manifest_content = mpd_content["MPD"]["Period"]["AdaptationSet"] + if type(manifest_content) is not list: + manifest_content = [manifest_content] + + for ad_set in manifest_content: + if index > 0: + if "video/" not in ad_set["@mimeType"]: + continue + + ad_set_rep = ad_set["Representation"] + if type(ad_set_rep) is not list: + ad_set_rep = [ad_set_rep] + + for ad_rep in ad_set_rep: + ad_rep["BaseURL"] = base_url + if len(ad_set_rep) == 1: + ad_set_rep = ad_set_rep[0] + ad_set["Representation"] = ad_set_rep + + if index > 0: + video_set.append(ad_set) + + manifests_contents = [m[1] for m in manifests_contents] + manifest_content = manifests_contents[0]["MPD"]["Period"]["AdaptationSet"] + manifest_content += video_set + manifests_contents[0]["MPD"]["Period"]["AdaptationSet"] = manifest_content + manifest_content = manifests_contents[0] + manifest_content = xmltodict.unparse(manifest_content, pretty=True) + + output_path = join(source_element.collection, source_element.element) + if not os.path.exists(output_path): + os.makedirs(output_path) + output_path = join(str(output_path), "master.mpd") + + with open(output_path, "w") as f: + f.write(manifest_content) + return output_path + + @staticmethod + def get_init_from_mpd(mpd_url, mpd_content): + try: + return False, str(min( + re.findall( + r']*>(.*?)', + mpd_content + ), key=len + )) + except: + pass + + mpd_content = xmltodict.parse(mpd_content)["MPD"] + mpd_content = mpd_content["Period"] + base_url = mpd_content.get("BaseURL", "") + dots_count = base_url.count("../") + base_url = "/".join(mpd_url.split("/")[0:-(dots_count + 1)]) + "/" + base_url.split("../")[dots_count] + + if type(mpd_content["AdaptationSet"]) is not list: + mpd_content["AdaptationSet"] = [mpd_content["AdaptationSet"]] + + best_content = None + best_height = None + best_bandwidth = None + for content in mpd_content["AdaptationSet"]: + if content["@contentType"] != "video": + continue + update_content = False + + height = content.get("@maxHeight", content.get("@height", None)) + if height is None: + continue + height = int(height) + bandwidth = content.get("@maxBandwidth", content.get("@bandwidth", None)) + + if best_content is None: + update_content = True + else: + if height > best_height: + update_content = True + elif height == best_height: + if bandwidth is not None: + if best_bandwidth is None: + update_content = True + elif int(bandwidth) > int(best_bandwidth): + update_content = True + + if update_content: + best_content = content + best_height = height + best_bandwidth = bandwidth + + mpd_content = best_content + init_url = mpd_content["SegmentTemplate"]["@initialization"] + if type(mpd_content["Representation"]) is not list: + mpd_content["Representation"] = [mpd_content["Representation"]] + + best_content = None + for content in mpd_content["Representation"]: + if best_content is None: + best_content = content + continue + + content_h = int(content.get("@height", mpd_content.get("@height", None))) + best_content_h = int(best_content.get("@height", mpd_content.get("@height", None))) + if content_h > best_content_h: + best_content = content + continue + elif content_h == best_content_h: + if int(content["@bandwidth"]) > int(best_content["@bandwidth"]): + best_content = content + continue + + init_url = init_url.replace("$RepresentationID$", best_content["@id"]) + init_url = init_url.replace("$Bandwidth$", best_content["@bandwidth"]) + init_url = base_url + init_url + return True, init_url + + @staticmethod + def get_pssh_from_manifest(mpd_url, mpd_content): + is_init, init = play_tv3_lv.get_init_from_mpd(mpd_url, mpd_content) + if not is_init: + return init + return cdm_tools.get_pssh_from_init(init) + + @staticmethod + def get_video_data(source_element): + video_type = "MOVIE" + product_id = source_element.url.split("-")[-1] + response = None + + if source_element.element is None: + if response is None: + response = json.loads(requests.get( + play_tv3_lv.VOD_URL.format(vod_id=product_id), + params={ + 'platform': play_tv3_lv.PLATFORM, + 'lang': play_tv3_lv.LANGUAGE, + 'tenant': play_tv3_lv.TENANT + } + ).content.decode()) + + status_code = response.get("codeNumber", None) + if status_code == 404: + title = product_id + else: + title = response.get("title", response.get("slug", product_id)) + + serial = response.get("season", {}) + if serial.get("number", None) is not None: + title = f"Season_{serial['number']}_" + title + + serial = serial.get("serial", {}) + serial = serial.get("title", serial.get("slug", None)) + if serial is not None: + title = serial + " " + title + + source_element.element = get_valid_filename(title) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + play_tv3_lv.__name__ + ) + + response = json.loads(requests.get( + play_tv3_lv.PLAYLIST_URL.format(product_id=product_id), + params={ + 'platform': play_tv3_lv.PLATFORM, + 'videoType': video_type, + 'lang': play_tv3_lv.LANGUAGE, + 'tenant': play_tv3_lv.TENANT + } + ).content.decode()) + status_code = response.get("codeNumber", None) + if status_code == 404: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + sources = response.get("sources", []) + if len(sources) == 0: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="The content isn't available yet", + solution="Wait until you can watch it on your browser" + )) + + for k, v in sources.items(): + if type(v) is not list: + v = [v] + sources[k] = max(v, key=lambda s: s.get("aspectWidth", 0)) + + sources = [(play_tv3_lv.CODEC_PRIORITY.get(kv[0], 0), kv) for kv in sources.items()] + sources = sorted(sources, key=lambda s: s[0], reverse=True) + sources = list(filter(lambda s: s[0] > 0, sources)) + sources = [s[1] for s in sources] + sources = list(filter(lambda s: len(s[1]) > 0, sources)) + + if len(sources) == 0: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {str(response.get('sources', []))}", + solution=f"Extend the {play_tv3_lv.__name__} service" + )) + + if play_tv3_lv.CODEC is not None: + temp_src = [(codec, _) for codec, _ in sources if codec == play_tv3_lv.CODEC] + if len(temp_src) > 0: + sources = [temp_src[0]] + else: + sources = [sources[0]] + + license_url = None + has_drm = False + if response.get("drm", {}) not in [None, {}] and len(response["drm"].keys()) > 0: + has_drm = True + if has_drm: + for d, s in response["drm"].items(): + if "widevine" in d.lower(): + license_url = s["src"] + break + if has_drm and license_url is None: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine wasn't found", + solution="Do not attempt to download it" + )) + + manifests = [] + pssh_values = [] + additional = {"video_type": video_type} + + for _, source in sources: + manifest = source["src"] + if manifest.startswith("//"): + manifest = manifest.replace("//", "https://") + + if manifest in manifests: + continue + manifests.append(manifest) + + pssh_value = None + if license_url is not None: + mpd_content = play_tv3_lv.get_manifest_content(manifest) + assert mpd_content is not None + + try: + pssh_value = play_tv3_lv.get_pssh_from_manifest(manifest, mpd_content) + except Exception as e: + if builtins.CONFIG["DEBUG_MODE"]: + raise e + pssh_value = None + + if pssh_value is not None: + if pssh_value not in pssh_values: + pssh_values.append(pssh_value) + additional[pssh_value] = {"license_url": license_url} + if pssh_value is None and license_url is not None: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine wasn't found", + solution="Do not attempt to download it" + )) + + if len(manifests) > 1: + manifests = play_tv3_lv.generate_master_mpd(source_element, manifests) + else: + manifests = manifests[0] + return manifests, pssh_values, additional + + @staticmethod + def get_video_url(collection_url, item): + video_url = collection_url + item_type = item.get("type_", item["type"]) + + if item_type in ["EPISODE", "PROGRAMME", "SERIAL"]: + return None + + if item_type in ["CLIP", "VOD"]: + video_url += "/" + item["slug"] + video_url += "-" + str(item["id"]) + return video_url + + raise Exception("Unknown Type: ", str(item)) + + @staticmethod + def series_handler(collection_url): + collection = [] + content_id = collection_url.split(",")[-1].split("-")[-1] + collection_name = collection_url.split("/")[-1].split(",")[0] + + response = json.loads(requests.get( + play_tv3_lv.SERIAL_URL.format(serial_id=content_id), + params={ + 'platform': play_tv3_lv.PLATFORM, + 'lang': play_tv3_lv.LANGUAGE, + 'tenant': play_tv3_lv.TENANT + } + ).content.decode()) + status_code = response.get("codeNumber", None) + if status_code == 404: + return [] + + collection_name = get_valid_filename(response.get( + "title", + response.get("slug", collection_name) + )) + collection_name = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + play_tv3_lv.__name__ + ), + collection_name + ) + + response = json.loads(requests.get( + play_tv3_lv.SEASONS_URL.format(serial_id=content_id), + params={ + 'platform': play_tv3_lv.PLATFORM, + 'lang': play_tv3_lv.LANGUAGE, + 'tenant': play_tv3_lv.TENANT + } + ).content.decode()) + if type(response) is not list: + status_code = response.get("codeNumber", None) + if status_code == 404: + return [] + + seasons = sorted(response, key=lambda s: s["number"]) + if len(seasons) == 0: + return [] + + season_index = seasons[-1]["number"] + related = [] + for season in seasons: + season_index += 1 + related.append({ + "RELATED": True, + "id": season["id"], + "number": season_index + }) + seasons += related + + for season in seasons: + check = check_range(True, season["number"], None) + if check is True: + continue + elif check is False: + return collection + + if season.get("RELATED", False) is False: + response = json.loads(requests.get( + play_tv3_lv.EPISODES_URL.format( + serial_id=content_id, + season_id=str(season["id"]) + ), + params={ + 'platform': play_tv3_lv.PLATFORM, + 'lang': play_tv3_lv.LANGUAGE, + 'tenant': play_tv3_lv.TENANT + } + ).content.decode()) + if type(response) is not list: + continue + + episodes = sorted(response, key=lambda e: e["episode"]) + for episode in episodes: + check = check_range(False, season["number"], episode['episode']) + if check is True: + continue + elif check is False: + return collection + + episode_url = collection_url + "/" + episode["slug"] + episode_url += "-" + str(episode["id"]) + episode_title = get_valid_filename(episode.get("title", episode["slug"])) + + collection.append(BaseElement( + url=episode_url, + collection=join(collection_name, f'Season_{season["number"]}'), + element=f"Episode_{episode['episode']}_{episode_title}" + )) + + else: + response = json.loads(requests.get( + play_tv3_lv.RELATED_URL.format(product_id=str(season["id"])), + params={ + 'platform': play_tv3_lv.PLATFORM, + 'lang': play_tv3_lv.LANGUAGE, + 'tenant': play_tv3_lv.TENANT, + "maxResults": 1000 + } + ).content.decode()) + if type(response) is not list: + response = [] + + episodes = response + episode_index = 0 + for episode in episodes: + try: + episode_url = play_tv3_lv.get_video_url(collection_url, episode) + except: + continue + + episode_index += 1 + check = check_range(False, season["number"], episode_index) + if check is True: + continue + elif check is False: + return collection + + episode_title = get_valid_filename(episode.get("title", episode["slug"])) + collection.append(BaseElement( + url=episode_url, + collection=join(collection_name, f'Season_{season["number"]}_Clips'), + element=f"Clip_{episode_index}_{episode_title}" + )) + + return collection + + @staticmethod + def get_collection_elements(collection_url): + collection_url = clean_url(collection_url).rstrip("/") + if "/tiesraides/" in collection_url: + return None + if "/filmas/" in collection_url: + return [BaseElement(url=collection_url)] + + if "/video/" in collection_url: + slash_count = collection_url.split("/video/")[1].count("/") + if "/serija-" in collection_url or slash_count == 1: + return [BaseElement(url=collection_url)] + + return play_tv3_lv.series_handler(collection_url) + return None diff --git a/API/proxiesembed/drmproxy/services/play_virginmediatelevision_ie.py b/API/proxiesembed/drmproxy/services/play_virginmediatelevision_ie.py new file mode 100644 index 0000000..bb6c693 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/play_virginmediatelevision_ie.py @@ -0,0 +1,339 @@ +import builtins +import json +import re +from os.path import join + +import requests +from bs4 import BeautifulSoup + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.cdm import get_pssh_from_cenc_pssh +from utils.tools.common import clean_url, get_valid_filename + + +class play_virginmediatelevision_ie(BaseService): + DEMO_URLS = [ + "https://play.virginmediatelevision.ie/watch/vod/52664902/waterford-city", + "https://play.virginmediatelevision.ie/watch/replay/19121626/uhl-irelands-hospital-crisis", + "https://play.virginmediatelevision.ie/shows/596a0d0e-3ea9-11ef-b7e3-0276c1f87d2f/gogglebox-ireland", + "https://play.virginmediatelevision.ie/shows/4405bcba-3212-11ef-8c5c-020f80c0527e/emmerdale", + "https://play.virginmediatelevision.ie/vod/34824/virgin-media-two", + "https://play.virginmediatelevision.ie/vod/34822/virgin-media-three", + ] + + COMPANY_ID = "company_942f683c-9041-42de-9911-a9e4cd98a4e9" + STREAM_URL = 'https://api-virginmedia.simplestreamcdn.com/streams/v2/' + COMPANY_ID + '/vod/{vod_id}' + SLIDER_URL = 'https://play.virginmediatelevision.ie/renderable/slider/rendered' + + @staticmethod + def test_service(): + main_service.run_service(play_virginmediatelevision_ie) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def initialize_service(): + return play_virginmediatelevision_ie + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + additional["license_url"], + data=challenge + ) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_video_data(source_element): + vod_id = re.findall(r'/watch/[^/]+/([^/]+)', source_element.url)[0] + response = requests.post( + play_virginmediatelevision_ie.STREAM_URL.format(vod_id=vod_id), + params={'platform': 'chrome'}, + headers={'Userid': 'Userid'} + ) + + status_code = response.status_code + response = response.content.decode() + message = response.lower() + if status_code in [404] or "video not found" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + response = json.loads(response)["response"] + drm = response.get("drm", None) + if drm is None: + drm = {} + + try: + license_url = drm["widevine"]["licenseAcquisitionUrl"] + manifest = drm["widevine"]["stream"] + assert len(license_url) > 0 and len(manifest) > 0 + except: + manifest = license_url = None + + pssh_value = None + if license_url is None: + try: + manifest = response["stream"] + assert len(manifest) > 0 + except: + manifest = None + + if manifest is None: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine wasn't found", + solution="Do not attempt to download it" + )) + else: + manifest_content = requests.get(manifest).content.decode() + try: + pssh_value = get_pssh_from_cenc_pssh(manifest_content) + except: + pssh_value = None + + if pssh_value is None: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}", + solution=f"Extend the {play_virginmediatelevision_ie.__name__} service" + )) + + if source_element.element is None: + try: + title = response["metadata"]["name"] + assert len(title) > 0 + except: + title = None + if title is None: + try: + title = response["metadata"]["metadata"]["title"] + assert len(title) > 0 + except: + title = None + + if title is None: + title = source_element.url.split("/")[-1] + source_element.element = get_valid_filename(title) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + play_virginmediatelevision_ie.__name__ + ) + + return manifest, pssh_value, {"license_url": license_url} + + @staticmethod + def get_collection_elements(collection_url): + collection_url = clean_url(collection_url) + if "/watch/" in collection_url: + return [BaseElement(url=collection_url)] + if "/shows/" not in collection_url and "/vod/" not in collection_url: + return None + + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + play_virginmediatelevision_ie.__name__ + ), + get_valid_filename(collection_url.split("/")[-1]) + ) + response = requests.get(collection_url) + response = response.content.decode() + soup = BeautifulSoup(response, 'html5lib') + if "service unavailable" in soup.title.get_text().lower(): + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="Need Irish IP to access content", + solution="Use a VPN" + )) + collection = [] + + if "/vod/" in collection_url: + catch_id = re.findall(r'/vod/([^/]+)', collection_url)[0] + render_nodes = re.findall( + r'this\.url\.params\s*=\s*(\{.*?})\s*this\.url\.', + response, flags=re.DOTALL + ) + + section_index = 0 + for render_node in render_nodes: + try: + render_node = render_node.encode().decode('unicode_escape') + except: + pass + section_id = re.findall(r'"id":"([^"]+)"', render_node) + if len(section_id) == 0: + continue + section_id = section_id[0] + + section_index += 1 + check = check_range(True, section_index, None) + if check is True: + continue + elif check is False: + return collection + + section_title = re.findall(r'"title":"([^"]+)"', render_node) + if len(section_title) == 0: + section_title = "" + else: + section_title = section_title[0] + section_title = f"Rail_{section_index} {section_title}" + section_title = join(collection_title, get_valid_filename(section_title)) + + response = requests.get( + play_virginmediatelevision_ie.SLIDER_URL, + params={ + 'endpoint': f'/api/vod/{catch_id}', + 'finder': json.dumps([ + {"key": "sections"}, + {"key": "id", "value": section_id}, + {"key": "tiles"} + ]), + 'slider': json.dumps({"showTitle": True}) + } + ) + response = response.content.decode() + soup = BeautifulSoup(response, 'html5lib') + episode_nodes = soup.find_all(lambda tag: tag.has_attr('class') and 'slider-card' in tag['class']) + + episode_index = 0 + for episode_node in episode_nodes: + episode_index += 1 + check = check_range(False, section_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + try: + episode_url = episode_node.find( + "a", attrs={"x-data": lambda x: x and "href" in x} + )["x-data"] + original_url = episode_url + episode_url = re.findall(r"href[^:]*:[^']*'([^']+)'", original_url) + if len(episode_url) == 0: + re.findall(r'href[^:]*:[^"]*"([^"]+)"', original_url) + episode_url = episode_url[0] + assert "/watch/" in episode_url + except: + continue + + try: + episode_title = episode_node.find( + attrs={"class": lambda c: c and "card-title" in c} + ).getText() + assert len(episode_title) > 0 + except: + episode_title = "" + episode_title = f"Video_{episode_index} {episode_title}" + episode_title = get_valid_filename(episode_title) + + collection.append(BaseElement( + url=episode_url, + collection=section_title, + element=episode_title + )) + + if "/shows/" in collection_url: + soup = soup.find("div", {"id": "seasonsContent"}) + if soup is None: + return [] + a_nodes = soup.find_all('a', href=True) + a_nodes = [a for a in a_nodes if "/watch/" in a["href"]] + episodes = [] + + for a_node in a_nodes: + episode_title = a_node.text + if episode_title is None: + episode_title = "" + episode_title = episode_title.strip() + if len(episode_title) == 0: + episode_title = a_node["href"].split("/")[-1] + + episodes.append((a_node["href"], episode_title)) + episodes = list(reversed(episodes)) + + contents = [] + episode_nodes = soup.find_all(lambda tag: tag.has_attr('class') and 'card-body' in tag['class']) + for episode_node in episode_nodes: + try: + season_index = episode_node.find('span', attrs={"data-content-type": "season"}) + season_index = season_index.text.strip() + season_index = re.findall(r'\d+', season_index)[0] + assert len(season_index) > 0 + season_index = int(season_index) + except: + continue + + try: + title_node = episode_node.find(lambda tag: tag.has_attr('class') and 'card-title' in tag['class']) + episode_index = title_node.text.strip() + episode_index = episode_index.split(".")[0] + episode_index = re.findall(r'\d+', episode_index)[0] + assert len(episode_index) > 0 + episode_index = int(episode_index) + except: + episode_index = None + + episode = episodes.pop() + if episode_index is None: + try: + episode_title = episode[1].lower() + episode_index = re.findall(r'ep\.(\d+)', episode_title) + if len(episode_index) == 0: + episode_index = re.findall(r'episode\s*(\d+)', episode_title) + episode_index = episode_index[0] + assert len(episode_index) > 0 + episode_index = int(episode_index) + except: + episode_index = None + + assert episode_index is not None + found = False + for c_s, c_e in contents: + if c_s == season_index: + c_e.append((episode_index, episode)) + found = True + break + + if not found: + contents.append((season_index, [(episode_index, episode)])) + + contents = sorted(contents, key=lambda ct: ct[0]) + for season_index, episodes in contents: + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + episodes = sorted(episodes, key=lambda ep: ep[0]) + for episode_index, episode in episodes: + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=episode[0], + collection=join(collection_title, f'Season_{season_index}'), + element=f'Episode_{episode_index}_{get_valid_filename(episode[1])}' + )) + + return collection diff --git a/API/proxiesembed/drmproxy/services/play_xumo_com.py b/API/proxiesembed/drmproxy/services/play_xumo_com.py new file mode 100644 index 0000000..f68ff74 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/play_xumo_com.py @@ -0,0 +1,309 @@ +import builtins +import json +import re +from os.path import join + +import requests +from bs4 import BeautifulSoup + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.cdm import get_pssh_from_cenc_pssh +from utils.tools.common import get_valid_filename, clean_url, update_url_params, get_ext_from_url + + +class play_xumo_com(BaseService): + DEMO_URLS = [ + "https://play.xumo.com/free-movies/doc-holliday/XM0KLO5UBLRFZ7", + "https://play.xumo.com/free-movies/anacondas-trail-of-blood/XM02D5MTHWY69Z", + "https://play.xumo.com/free-movies/decision-at-sundown/XM099Z665IVEUP", + "https://play.xumo.com/tv-shows/family-affair/XM0G6RCH6S9MBW", + "https://play.xumo.com/tv-shows/the-joy-of-painting-with-bob-ross/XM0EH52ODUEUVA", + "https://play.xumo.com/tv-shows/comanche-moon-the-second-chapter-in-the-lonesome-dove-saga/XM02N0DYOW6L05", + "https://play.xumo.com/tv-shows/deal-or-no-deal-australia/XM0SJGVW8YW3OQ", + ] + + DEVICE_URL = "/v2/devices/device/id.json" + LICENSE_URL = None + ASSET_URL = "/v2/assets/asset/{asset_id}.json" + BASE_URL = "https://play.xumo.com" + + API_KEY = None + DEVICE_ID = None + CLIENT_VERSION = None + HOST = None + + @staticmethod + def test_service(): + main_service.run_service(play_xumo_com) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def set_variables(): + response = requests.post( + play_xumo_com.DEVICE_URL, + headers={'Authorization': f'XumoValenciaId id={play_xumo_com.API_KEY}'} + ) + response = json.loads(response.content.decode()) + play_xumo_com.DEVICE_ID = response["id"] + + @staticmethod + def set_api_endpoints(): + response = requests.get(play_xumo_com.BASE_URL).content.decode() + soup = BeautifulSoup(response, 'html5lib') + script = soup.find_all('script', id="__NEXT_DATA__") + script = script[0].string + script = json.loads(script) + + script = script["runtimeConfig"] + play_xumo_com.CLIENT_VERSION = script["APP_VERSION"] + play_xumo_com.API_KEY = script["XUMO_API_KEY"] + + play_xumo_com.HOST = script["XUMO_API_URL"] + base_url = f'https://{play_xumo_com.HOST}' + play_xumo_com.DEVICE_URL = base_url + play_xumo_com.DEVICE_URL + play_xumo_com.ASSET_URL = base_url + play_xumo_com.ASSET_URL + + app_js = soup.find_all('script', attrs={"src": True}) + for a in app_js: + a = a["src"] + if "_app-" in a.split("/")[-1]: + app_js = play_xumo_com.BASE_URL + a + break + + app_js = requests.get(app_js).content.decode() + app_js = re.findall(r'[^_]WIDEVINE:"([^"]+)"', app_js) + play_xumo_com.LICENSE_URL = app_js[0] + + @staticmethod + def initialize_service(): + if play_xumo_com.API_KEY is None: + play_xumo_com.set_api_endpoints() + if play_xumo_com.DEVICE_ID is None: + play_xumo_com.set_variables() + return play_xumo_com + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + additional["license_url"], + data=challenge + ) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_video_data(source_element): + content_id = source_element.url.split("/")[-1] + response = requests.get( + play_xumo_com.ASSET_URL.format(asset_id=content_id), + params={'f': ['providers', 'title', 'episodeTitle']} + ) + if 400 <= response.status_code < 500: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + response = json.loads(response.content.decode()) + + providers = response.get("providers", []) + if len(providers) == 0: + raise CustomException(ERR_MSG.format( + type=f'{APP_ERROR}', + url=source_element.url, + reason=f"No manifest has been found for content id: {content_id}", + solution=f"Debug the {play_xumo_com.__name__} service" + )) + + if source_element.element is None: + video_title = response.get("title", None) + if video_title in ["", None]: + video_title = source_element.url.split("/")[-2] + source_element.element = get_valid_filename(video_title) + + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + play_xumo_com.__name__ + ) + + provider_id = None + has_drm = False + manifest = None + captions = None + + for provider in providers: + provider_id = provider["id"] + captions = provider.get("captions", []) + + for source in provider.get("sources", []): + drm = source.get("drm", None) + if drm is None or drm.get("widevine", False) is True: + manifest = source["uri"] + has_drm = drm is not None + break + + if manifest is not None: + break + + if captions is None: + captions = [] + subtitles = [] + + srt_index = 0 + output_path = join(source_element.collection, source_element.element) + for caption in captions: + srt_url = caption.get("file", caption.get("url", None)) + if srt_url is None: + continue + + srt_ext = get_ext_from_url(srt_url) + if srt_ext not in [".srt", ".vtt"]: + continue + srt_index += 1 + srt_lang = caption.get("lang", caption.get("language", "unknown")) + + subtitles.append((False, BaseElement( + url=srt_url, + collection=output_path, + element=f'subtitle_{srt_index}_{get_valid_filename(srt_lang)}{srt_ext}' + ))) + + pssh = None + additional = {"SUBTITLES": subtitles} + if has_drm: + try: + manifest_content = requests.get(manifest).content.decode() + pssh = get_pssh_from_cenc_pssh(manifest_content) + except: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}", + solution=f"Extend the {play_xumo_com.__name__} service" + )) + + additional["license_url"] = update_url_params( + play_xumo_com.LICENSE_URL, + { + "CustomData": json.dumps({ + "host": play_xumo_com.HOST, + "deviceId": play_xumo_com.DEVICE_ID, + "clientVersion": play_xumo_com.CLIENT_VERSION, + "providerId": provider_id, + "assetId": content_id + }) + } + ) + + return manifest, pssh, additional + + @staticmethod + def get_collection_elements(collection_url): + collection_url = clean_url(collection_url) + if "/free-movies/" in collection_url: + return [BaseElement(url=collection_url)] + + if "/tv-shows/" not in collection_url: + return None + + response = requests.get(collection_url).content.decode() + if "/geo-block" in response: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="Need American IP to access content", + solution="Use a VPN" + )) + + soup = BeautifulSoup(response, 'html5lib') + script = soup.find_all('script', id="__NEXT_DATA__") + script = script[0].string + script = json.loads(script) + + for f in ["entity", "seoObj"]: + try: + page_props = script["props"]["pageProps"] + if f == "entity": + page_props = page_props["page"] + + collection_title = page_props[f]["title"] + assert len(collection_title) > 0 + break + except: + collection_title = None + if collection_title is None: + collection_title = collection_url.split("/")[-2] + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + play_xumo_com.__name__ + ), + get_valid_filename(collection_title) + ) + + try: + seasons = script["props"]["pageProps"]["page"]["entity"]["seasons"] + if type(seasons) is not list: + seasons = [seasons] + except: + seasons = [] + + for season in seasons: + try: + season["season"]["number"] = int(season["season"]["number"]) + except: + season["season"]["number"] = 0 + + collection = [] + video_url = collection_url.replace("/tv-shows/", "/free-movies/").split("/") + + seasons = list(sorted(seasons, key=lambda s: s["season"]["number"])) + for season in seasons: + season_index = season["season"]["number"] + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + try: + episodes = season["cards"] + if type(episodes) is not list: + episodes = [episodes] + except: + episodes = [] + + for episode in episodes: + try: + episode["episode"] = int(episode["episode"]) + except: + episode["episode"] = 0 + + episodes = list(sorted(episodes, key=lambda e: e["episode"])) + for episode in episodes: + episode_index = episode["episode"] + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url="/".join(video_url + [episode["id"]]), + collection=join(collection_title, f'Season_{season_index}'), + element=get_valid_filename( + f'Episode_{episode_index}' + f'_' + f'{episode["title"]}' + ) + )) + + return collection diff --git a/API/proxiesembed/drmproxy/services/player_pl.py b/API/proxiesembed/drmproxy/services/player_pl.py new file mode 100644 index 0000000..350724a --- /dev/null +++ b/API/proxiesembed/drmproxy/services/player_pl.py @@ -0,0 +1,313 @@ +import builtins +import json +import re +from os.path import join + +import requests + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseService, CustomException, BaseElement +from utils.tools.args import check_range +from utils.tools.cdm import get_pssh_from_cenc_pssh, get_pssh_from_default_kid, get_pssh_from_playready +from utils.tools.common import get_valid_filename, clean_url + + +class player_pl(BaseService): + DEMO_URLS = [ + "https://player.pl/filmy-online/1800-gramow,169874", + "https://player.pl/filmy-online/podatek-od-milosci,106758", + "https://player.pl/seriale-online/szkola-odcinki,2395/odcinek-2,S01E02,32279", + "https://player.pl/seriale-online/na-wspolnej-odcinki,144/odcinek-2590,S01E2590,86158", + "https://player.pl/programy-online/masterchef-odcinki,996/odcinek-12,S08E12,151746", + "https://player.pl/programy-online/power-couple-odcinki,29479/odcinek-3,S01E03,198875", + "https://player.pl/strefa-sport/motocyklicznie-odcinki,120/odcinek-4,S03E04,2063", + "https://player.pl/strefa-sport/krolowie-driftu-odcinki,118/odcinek-3,S01E03,2013", + "https://player.pl/seriale-online/prawo-agaty-odcinki,562", + "https://player.pl/seriale-online/pulapka-odcinki,13643", + "https://player.pl/programy-online/warsaw-shore-ekipa-z-warszawy-odcinki,4365", + "https://player.pl/programy-online/projekt-lady-odcinki,4554", + "https://player.pl/seriale-online/19--odcinki,4814", + "https://player.pl/seriale-online/lab-odcinki,29386", + "https://player.pl/programy-online/one-night-squad-odcinki,31426", + "https://player.pl/programy-online/anatomia-piekna-odcinki,44796", + "https://player.pl/strefa-sport/rajd-hiszpanii-odcinki,1334", + "https://player.pl/strefa-sport/rajd-dakar-2016-odcinki,4256", + ] + + PLAYLIST_URL = 'https://player.pl/playerapi/item/{item_id}/playlist' + TRANSLATE_URL = 'https://player.pl/playerapi/item/translate' + SERIAL_URL = 'https://player.pl/playerapi/product/vod/serial/{show_id}' + SEASONS_URL = 'https://player.pl/playerapi/product/vod/serial/{show_id}/season/list' + EPISODES_URL = 'https://player.pl/playerapi/product/vod/serial/{show_id}/season/{season_id}/episode/list' + + PLATFORM = "BROWSER" + + @staticmethod + def test_service(): + main_service.run_service(player_pl) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def initialize_service(): + return player_pl + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + additional["license_url"], + data=challenge + ) + + if licence.status_code == 403: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=additional["URL"], + reason="Can't download paid content", + solution='Do not attempt to download it' + )) + + licence.raise_for_status() + return licence.content + + @staticmethod + def get_video_data(source_element): + item_type = "MOVIE" + item_key = "articleId" + item_id = source_element.url.split(",")[-1] + response = requests.get( + player_pl.TRANSLATE_URL, + params={item_key: item_id, 'platform': player_pl.PLATFORM} + ) + + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + message = response.get("code", "").lower() + + if status_code == 404 and "not_exists" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Don't attempt to download it" + )) + + item_id = response["id"] + response = requests.get( + player_pl.PLAYLIST_URL.format(item_id=item_id), + params={'type': item_type, 'platform': player_pl.PLATFORM} + ) + + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + message = response.get("code", "").lower() + + if status_code == 403 and "not_paid" in message: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Can't download paid content", + solution='Do not attempt to download it' + )) + + if source_element.element is None: + content_info = response["movie"].get("info", {}) + content_stats = response["movie"].get("stats", {}) + nl_data = content_stats.get("nl_data", {}) + + title = content_info.get("series_title", None) + if title not in ["", None]: + for f in ["episode_title", "season_number", "episode_number"]: + try: + v = content_info[f] + assert v is not None + v = str(v) + assert len(v) > 0 + assert v != content_info["series_title"] + title += " " + v + except: + pass + + else: + title = nl_data.get("title", None) + + if title not in ["", None]: + for f in ["program"]: + try: + v = nl_data[f] + assert v is not None + v = str(v) + assert len(v) > 0 + assert v != nl_data["title"] + title += " " + v + except: + pass + + if title in ["", None]: + title = source_element.url.split("/")[-1] + source_element.element = get_valid_filename(title) + + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + player_pl.__name__ + ) + + manifest = None + license_url = None + pssh_value = None + response = response["movie"]["video"] + + is_drm = len(response.get("protections", {}).keys()) > 0 + if is_drm: + license_url = response["protections"].get("widevine", {}).get("src", None) + if license_url is None: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine wasn't found", + solution="Do not attempt to download it" + )) + + manifest = response["sources"]["dash"]["url"] + manifest_content = requests.get(manifest).content.decode() + try: + pssh_value = get_pssh_from_default_kid(manifest_content, xml_node="default_KID") + except: + pass + + if pssh_value is None: + try: + pssh_value = get_pssh_from_cenc_pssh(manifest_content) + except: + pass + + if pssh_value is None: + try: + pssh_value = get_pssh_from_playready(manifest_content) + except: + pass + + if pssh_value is None: + manifest = response["sources"]["smooth"]["url"] + manifest_content = requests.get(manifest).content.decode() + try: + pssh_value = get_pssh_from_playready(manifest_content) + except: + pass + + if pssh_value is None: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {str(manifest)}", + solution=f"Extend the {player_pl.__name__} service" + )) + else: + for k, v in response["sources"].items(): + try: + manifest = v["url"] + break + except: + pass + + return manifest, pssh_value, { + "license_url": license_url, + "URL": source_element.url + } + + @staticmethod + def get_collection_elements(collection_url): + collection_url = clean_url(collection_url) + if "/live/" in collection_url: + return None + if "/filmy-online" in collection_url: + return [BaseElement(url=collection_url)] + + match = re.findall(r',S\d+E\d+,\d+$', collection_url.split("/")[-1]) + if len(match) > 0: + return [BaseElement(url=collection_url)] + + content_id = collection_url.split(",")[-1] + response = requests.get( + player_pl.TRANSLATE_URL, + params={'programId': content_id, 'platform': player_pl.PLATFORM} + ) + + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + message = response.get("code", "").lower() + + if status_code == 404 and "not_exists" in message: + return [BaseElement(url=collection_url)] + + content_id = response["id"] + response = requests.get( + player_pl.SERIAL_URL.format(show_id=content_id), + params={'platform': player_pl.PLATFORM} + ) + response = response.content.decode() + response = json.loads(response) + + collection_title = response.get("title", collection_url.split("/")[-1]) + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + player_pl.__name__ + ), + get_valid_filename(collection_title) + ) + + response = requests.get( + player_pl.SEASONS_URL.format(show_id=content_id), + params={'platform': player_pl.PLATFORM} + ) + response = response.content.decode() + response = json.loads(response) + seasons = sorted(response, key=lambda s: s["number"]) + + collection = [] + for season in seasons: + season_index = season["number"] + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + season_id = season["id"] + response = requests.get( + player_pl.EPISODES_URL.format(show_id=content_id, season_id=season_id), + params={'platform': player_pl.PLATFORM} + ) + response = response.content.decode() + response = json.loads(response) + episodes = sorted(response, key=lambda e: e["episode"]) + + for episode in episodes: + episode_index = episode["episode"] + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + episode_url = episode["shareUrl"] + episode_title = episode.get("title", None) + if episode_title in ["", None]: + episode_title = episode_url.split("/")[-1] + episode_title = f'Episode_{episode_index}_{episode_title}' + + collection.append(BaseElement( + url=episode_url, + collection=join(collection_title, f'Season_{season_index}'), + element=get_valid_filename(episode_title) + )) + + return collection diff --git a/API/proxiesembed/drmproxy/services/plus_fifa_com.py b/API/proxiesembed/drmproxy/services/plus_fifa_com.py new file mode 100644 index 0000000..e5519bc --- /dev/null +++ b/API/proxiesembed/drmproxy/services/plus_fifa_com.py @@ -0,0 +1,445 @@ +import builtins +import json +import os +import re +from os.path import join +from urllib.parse import urlparse, parse_qs + +import requests +import xmltodict + +import utils.tools.common as common_tools +from utils.constants.macros import USER_ERROR, ERR_MSG +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range + + +class plus_fifa_com(BaseService): + DEMO_URLS = [ + "https://www.plus.fifa.com/en/archive?filters=season%3Afifa-club-world-cup-saudi-arabia-2023tm%2Cstage%3Aopening-rounds", + "https://www.plus.fifa.com/en/showcase/fifa-world-cup-2022/845fdca5-6741-4ab7-a1aa-af01871843cd", + "https://www.plus.fifa.com/en/showcase/fifa-women-s-world-cup-germany-2011/19e87433-19ba-4f88-b3d3-c6904b7d5a1e", + "https://www.plus.fifa.com/en/content/when-the-world-watched/3f3a5286-32e7-4587-a094-0edb473d3ed2", + "https://www.plus.fifa.com/en/content/the-long-walk/627a8255-ec5f-4b0c-a6d0-0fbae421d699", + "https://www.plus.fifa.com/en/player/580e692e-e8fc-4ad1-a649-5ec0af83f94d?catalogId=5f24e303-ff42-499f-9d7a-b4f8e0eff2ce", + "https://www.plus.fifa.com/en/player/dd457324-057e-4f17-8457-527f6a8c115d?catalogId=bcf168c3-813c-4882-9878-84a1074fa03a", + "https://www.plus.fifa.com/en/player/cd472e9a-21ae-49de-91f4-17da7494e56b?catalogId=bb25cc85-30b2-47e8-b721-a419b961ca19", + "https://www.plus.fifa.com/en/player/d15f15f2-49ce-41b3-a1d8-8fbd8db61cfe?catalogId=3d2612ff-c06f-4a7e-a2d7-ec73504515b5", + "https://www.plus.fifa.com/en/player/8bfee684-8857-4de9-b530-20358eab1c70?catalogId=7e3e3ac2-0d41-49a0-843a-3029456c6572", + "https://www.plus.fifa.com/en/player/6cc0c03f-44d9-4e75-8064-31f5ba8ddc70?catalogId=61b1e4dc-0b9c-4018-bb5f-a89d5746f7cb&entryPoint=CTA", + ] + + DEVICES_URL = 'https://www.plus.fifa.com/gatekeeper/api/v1/devices/' + CONTENTS_URL = 'https://www.plus.fifa.com/entertainment/api/v1/contents/{catalog_id}/child' + SHOWCASES_URL = 'https://www.plus.fifa.com/entertainment/api/v1/showcases/{content_id}/child?orderBy=EDITORIAL' + ASSET_URL = 'https://www.plus.fifa.com/flux-capacitor/api/v1/videoasset?catalog={catalog_id}' + SESSION_URL = 'https://www.plus.fifa.com/flux-capacitor/api/v1/streaming/session' + STREAMING_URL = 'https://www.plus.fifa.com/flux-capacitor/api/v1/streaming/urls' + SEARCH_URL = 'https://www.plus.fifa.com/api/v2/search' + VIDEO_URL = 'https://www.plus.fifa.com/en/player/{video_id}?catalogId={catalog_id}' + LICENSE_URL = "https://www.plus.fifa.com/flux-capacitor/api/v1/licensing/widevine/modular?sessionId={session_id}" + + DEVICE_ID = None + RES_PRIORITY = {"SDP": 0, "SD": 1, "HD": 2, "HDP": 3} + PAGE_LIMIT = 50 + LANGUAGE = None + + @staticmethod + def get_device_id(): + return json.loads(requests.post( + plus_fifa_com.DEVICES_URL, + json={ + 'model': 'model', 'manufacturer': 'manufacturer', + 'profile': 'WEB', 'store': 'CHILI' + } + ).content.decode())["id"] + + @staticmethod + def test_service(): + main_service.run_service(plus_fifa_com) + + @staticmethod + def get_additional_params(additional): + return [("MUXER", lambda s: s.format(args="mkv:muxer=mkvmerge"))] + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def initialize_service(): + if builtins.CONFIG.get("BASIC", False) is True: + plus_fifa_com.LANGUAGE = 'eng' + plus_fifa_com.LANGUAGE = plus_fifa_com.LANGUAGE.lower() + + if plus_fifa_com.DEVICE_ID is None: + plus_fifa_com.DEVICE_ID = plus_fifa_com.get_device_id() + return plus_fifa_com + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post(plus_fifa_com.LICENSE_URL.format( + session_id=additional["session_id"] + ), data=challenge) + licence.raise_for_status() + return licence.content + + @staticmethod + def generate_master_mpd(source_element, manifests): + manifests_contents = [] + for mpd_url in manifests: + mpd_content = requests.get(mpd_url).content.decode() + mpd_content = xmltodict.parse(mpd_content) + manifests_contents.append((mpd_url, mpd_content)) + + audio_set = [] + index = -1 + for mpd_url, mpd_content in manifests_contents: + index += 1 + manifest_content = mpd_content["MPD"]["Period"]["AdaptationSet"] + if type(manifest_content) is not list: + manifest_content = [manifest_content] + + for ad_set in manifest_content: + if index > 0: + if "audio/" not in ad_set["@mimeType"]: + continue + + ad_set["BaseURL"] = mpd_url + + if index > 0: + audio_set.append(ad_set) + + manifests_contents = [manifests_contents[0][1]] + manifest_content = manifests_contents[0]["MPD"]["Period"]["AdaptationSet"] + manifest_content += audio_set + manifests_contents[0]["MPD"]["Period"]["AdaptationSet"] = manifest_content + manifest_content = manifests_contents[0] + manifest_content = xmltodict.unparse(manifest_content, pretty=True) + + output_path = join(source_element.collection, source_element.element) + if not os.path.exists(output_path): + os.makedirs(output_path) + output_path = join(str(output_path), "master.mpd") + + with open(output_path, "w") as f: + f.write(manifest_content) + return output_path + + @staticmethod + def get_video_data(source_element): + if "/player/" in source_element.url: + catalog_id = parse_qs(urlparse(source_element.url).query)["catalogId"][0] + video_id = re.search(r"/player/([^/?]*)", source_element.url).group(1) + elif "/content/" in source_element.url: + catalog_id = source_element.url.split("/")[-1] + video_id = None + assets = json.loads(requests.get( + plus_fifa_com.ASSET_URL.format(catalog_id=catalog_id), + headers={'x-chili-device-id': plus_fifa_com.DEVICE_ID} + ).content.decode()) + for asset in assets: + if asset['type'].lower() != 'main': + continue + + video_id = asset['id'] + break + + assert video_id is not None + else: + raise + + if source_element.element is None: + title = common_tools.get_valid_filename(json.loads(requests.get( + plus_fifa_com.CONTENTS_URL.format(catalog_id=catalog_id).split("/child")[0], + headers={'x-chili-device-id': plus_fifa_com.DEVICE_ID} + ).content.decode())['title']) + if title is None: + title = f"PlayerId_{video_id}" + + source_element.element = title + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + plus_fifa_com.__name__ + ) + + response = json.loads(requests.post( + plus_fifa_com.SESSION_URL, + headers={ + 'x-chili-device-id': plus_fifa_com.DEVICE_ID, + 'x-chili-avod-compatibility': 'free,free-ads', + 'x-chili-accept-stream': 'mpd/cenc+h264;mpd/clear+h264;mp4/', + 'x-chili-accept-stream-mode': 'multi/codec-compatibility;mono/strict', + 'x-chili-manifest-properties': 'subtitles' + }, + json={'videoAssetId': video_id} + ).content.decode()) + + if response.get("id", None) is None: + if response.get("code", "") not in ["", None]: + if "not_playable" in response["code"].lower(): + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="URL doesn't contain a video", + solution="Do not attempt to download it" + )) + + session_id = response["id"] + manifest = sorted(json.loads(requests.get( + plus_fifa_com.STREAMING_URL, headers={'x-chili-streaming-session': session_id} + ).content.decode()), key=lambda m: plus_fifa_com.RES_PRIORITY[m["quality"]], reverse=True) + + manifest = [m for m in manifest if m["quality"] == manifest[0]["quality"]] + if plus_fifa_com.LANGUAGE is not None: + temp_man = [ + m for m in manifest + if m["language"].lower().startswith(plus_fifa_com.LANGUAGE) + or plus_fifa_com.LANGUAGE.startswith(m["language"].lower()) + ] + if len(temp_man) > 0: + manifest = [temp_man[0]] + else: + manifest = [manifest[0]] + + manifest = [m["url"] for m in manifest] + pssh_values = [] + additional = {"PLUS_SERVICE": True} + + for m in manifest: + try: + pssh_value = str(min( + re.findall( + r']*>(.*?)', + requests.get(m).content.decode() + ), key=len + )) + except: + pssh_value = None + + if pssh_value is not None: + if pssh_value not in pssh_values: + pssh_values.append(pssh_value) + additional[pssh_value] = { + "session_id": session_id, + "PLUS_SERVICE": True + } + + if len(manifest) > 1: + manifest = plus_fifa_com.generate_master_mpd(source_element, manifest) + else: + manifest = manifest[0] + return manifest, pssh_values, additional + + @staticmethod + def get_filters_name(filters): + filters = [f.split(":")[1] for f in filters.split(",")] + filters = sorted(filters, key=len) + + filters_name = "Filters_" + str(filters[0]) + filters_name = common_tools.get_valid_filename(filters_name) + return filters_name + + @staticmethod + def get_collection_elements(collection_url): + if "/player/" in collection_url and "catalogId=" in collection_url: + return [BaseElement(url=collection_url)] + + collection = [] + if "/archive" in collection_url and "filters=" in collection_url: + params_dict = parse_qs(urlparse(collection_url).query) + filters = params_dict.get("filters", [None])[0] + if filters is None: + return None + + collection_name = plus_fifa_com.get_filters_name(filters) + collection_name = join(join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + plus_fifa_com.__name__ + ), collection_name) + + if "fifa-plus:archive-project-fifa-plus" not in filters: + filters += ",fifa-plus:archive-project-fifa-plus" + response = requests.get( + plus_fifa_com.SEARCH_URL, + headers={'x-chili-device-id': plus_fifa_com.DEVICE_ID}, + params={ + 'filters': filters, + 'limit': plus_fifa_com.PAGE_LIMIT, + 'after': '0', + 'orderBy': 'TIMESTAMP_DESC' + } + ) + + index = 0 + while True: + response = json.loads(response.content.decode()) + + for result in response.get("results", []): + index += 1 + check = check_range(False, None, index) + if check is True: + continue + elif check is False: + return collection + + c_id = result["id"] + assets = json.loads(requests.get( + plus_fifa_com.ASSET_URL.format(catalog_id=c_id), + headers={'x-chili-device-id': plus_fifa_com.DEVICE_ID} + ).content.decode()) + + video_id = element_title = None + for asset in assets: + if asset['type'].lower() != 'main': + continue + + video_id = asset['id'] + element_title = asset['title'] + break + + if video_id is None: + continue + + collection.append(BaseElement( + url=plus_fifa_com.VIDEO_URL.format(video_id=video_id, catalog_id=c_id), + collection=collection_name, + element=f'{index}' + f'_' + f'{common_tools.get_valid_filename(element_title)}' + )) + + response = response["pagination"].get("next", None) + if response is None or type(response) is not dict: + break + if response.get("url", None) is None: + break + response = requests.get( + response["url"], + headers={'x-chili-device-id': plus_fifa_com.DEVICE_ID} + ) + + return collection + + if "/showcase/" in collection_url: + content_id = re.search(r'/showcase/[^/]+/([^?/]+)', collection_url).group(1) + content_title = common_tools.get_valid_filename(json.loads(requests.get( + plus_fifa_com.SHOWCASES_URL.format(content_id=content_id).split("/child?")[0], + headers={'x-chili-device-id': plus_fifa_com.DEVICE_ID} + ).content.decode())['title']) + if content_title is None: + content_title = f'ShowcaseId_{content_id}' + + response = json.loads(requests.get( + plus_fifa_com.SHOWCASES_URL.format(content_id=content_id), + headers={'x-chili-device-id': plus_fifa_com.DEVICE_ID} + ).content.decode()) + + index = 0 + for content in response: + index += 1 + check = check_range(False, None, index) + if check is True: + continue + elif check is False: + return collection + + c_id = content["id"] + assets = json.loads(requests.get( + plus_fifa_com.ASSET_URL.format(catalog_id=c_id), + headers={'x-chili-device-id': plus_fifa_com.DEVICE_ID} + ).content.decode()) + + video_id = element_title = None + for asset in assets: + if asset['type'].lower() != 'main': + continue + + video_id = asset['id'] + element_title = asset['title'] + break + + if video_id is None: + continue + + collection.append(BaseElement( + url=plus_fifa_com.VIDEO_URL.format(video_id=video_id, catalog_id=c_id), + collection=join(join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + plus_fifa_com.__name__ + ), content_title), + element=f'{index}' + f'_' + f'{common_tools.get_valid_filename(element_title)}' + )) + + return collection + + if "/content/" in collection_url: + try: + content_id = re.search(r'/content/[^/]+/([^/]+)', collection_url).group(1) + except: + content_id = re.search(r'/content/([^/]+)', collection_url).group(1) + + content_title = common_tools.get_valid_filename(json.loads(requests.get( + plus_fifa_com.CONTENTS_URL.format(catalog_id=content_id).split("/child")[0], + headers={'x-chili-device-id': plus_fifa_com.DEVICE_ID} + ).content.decode())['title']) + if content_title is None: + content_title = f'ContentId_{content_id}' + + response = json.loads(requests.get( + plus_fifa_com.CONTENTS_URL.format(catalog_id=content_id), + headers={'x-chili-device-id': plus_fifa_com.DEVICE_ID} + ).content.decode()) + + for content in response: + check = check_range(True, content["orderIndex"], None) + if check is True: + continue + elif check is False: + return collection + + season = json.loads(requests.get( + plus_fifa_com.CONTENTS_URL.format(catalog_id=content["id"]), + headers={'x-chili-device-id': plus_fifa_com.DEVICE_ID} + ).content.decode()) + + for episode in season: + check = check_range(False, content["orderIndex"], episode['orderIndex']) + if check is True: + continue + elif check is False: + return collection + + assets = json.loads(requests.get( + plus_fifa_com.ASSET_URL.format(catalog_id=episode["id"]), + headers={'x-chili-device-id': plus_fifa_com.DEVICE_ID} + ).content.decode()) + + video_id = None + for asset in assets: + if asset['type'].lower() != 'main': + continue + + video_id = asset['id'] + break + + collection.append(BaseElement( + url=plus_fifa_com.VIDEO_URL.format(video_id=video_id, catalog_id=episode["id"]), + collection=join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + plus_fifa_com.__name__ + ), + join(content_title, f'Season_{content["orderIndex"]}') + ), + element=f"Episode_{episode['orderIndex']}" + f'_' + f"{common_tools.get_valid_filename(episode['title'])}" + )) + + return collection + return None diff --git a/API/proxiesembed/drmproxy/services/plus_rtl_de.py b/API/proxiesembed/drmproxy/services/plus_rtl_de.py new file mode 100644 index 0000000..4b244df --- /dev/null +++ b/API/proxiesembed/drmproxy/services/plus_rtl_de.py @@ -0,0 +1,778 @@ +import base64 +import builtins +import json +import os +import re +from os.path import join +from urllib.parse import urlparse, parse_qs + +import requests +from bs4 import BeautifulSoup + +from utils.constants.macros import ERR_MSG, USER_ERROR, CACHE_DIR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, CustomException, BaseService +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename, dict_to_file, file_to_dict + + +class plus_rtl_de(BaseService): + DEMO_URLS = [ + "https://plus.rtl.de/video-tv/shows/ich-bin-ein-star-showdown-der-dschungel-legenden-989299/staffel-1-989300/episode-9-tag-9-989309", + "https://plus.rtl.de/podcast/toni-kroos-the-underrated-one-zwqyvph7kq6n6", + "https://plus.rtl.de/podcast/skandal-skandal-l57kf1b0tfhj9", + "https://plus.rtl.de/podcast/geschichten-aus-der-geschichte-ibf6ymv2kicvq/gag461-das-laengste-autorennen-der-welt-pokffmsrgtd0o", + "https://plus.rtl.de/podcast/dont-worry-be-haenni-k4na6aep6529j/17-nippelklappe-offen-tsmc6mdrqb82k", + "https://plus.rtl.de/video-tv/live-tv/bauer-sucht-frau-62", + "https://plus.rtl.de/video-tv/live-tv/rtl-shine-67", + "https://plus.rtl.de/video-tv/serien/barbara-salesch-das-strafgericht-940586", + "https://plus.rtl.de/video-tv/shows/goodbye-deutschland-die-auswanderer-771084", + "https://plus.rtl.de/video-tv/serien/alarm-fuer-cobra-11-die-autobahnpolizei-41906", + "https://plus.rtl.de/video-tv/serien/pretty-little-liars-summer-school-946099", + "https://plus.rtl.de/video-tv/serien/bushido-anna-maria-alle-auf-tour-992554", + "https://plus.rtl.de/video-tv/shows/princess-charming-883086", + "https://plus.rtl.de/video-tv/serien/medical-detectives-geheimnisse-der-gerichtsmedizin-241410", + "https://plus.rtl.de/video-tv/serien/disko-76-914295/staffel-1-914296/episode-1-folge-1-914297", + "https://plus.rtl.de/video-tv/shows/hilfe-die-camper-kommen-861468/2023-4-971471/episode-6-die-verbleibenden-paare-erreichen-ihr-ziel-in-spanien-861475", + "https://plus.rtl.de/video-tv/filme/soziale-brennpunkte-was-passiert-mit-unseren-staedten-844861", + "https://plus.rtl.de/video-tv/shows/jamies-5-zutaten-kueche-798218/staffel-1-798219/episode-4-von-spaghetti-mit-ricotta-bis-apple-crumble-cookies-798223", + ] + + GRAPHQL_URL = 'https://cdn.gateway.now-plus-prod.aws-cbc.cloud/graphql' + TOKEN_URL = 'https://auth.rtl.de/auth/realms/rtlplus/protocol/openid-connect/token' + AUTH_URL = 'https://auth.rtl.de/auth/realms/rtlplus/protocol/openid-connect/auth' + BASE_URL = "https://plus.rtl.de" + + AUTH_TOKEN = None + RES_PRIORITY = {"sd": 0, "hd": 1, "free": 2} + EMAIL = "" + PASSWORD = "YOUR_PASSWORD (leave at least one field empty if you don't want to use an account)" + CACHE_FILE = None + ACCOUNT_QUALITY = None + CLIENT_ID = 'rci:rtlplus:web' + CLIENT_VERSION = 'rtlplus-client-Version' + PAGE_LIMIT = 50 + + @staticmethod + def test_service(): + main_service.run_service(plus_rtl_de) + + @staticmethod + def is_content_livestream(content, additional): + return "/live-tv/" in content + + @staticmethod + def credentials_needed(): + return { + "OPTIONAL": True, + "EMAIL": plus_rtl_de.EMAIL, + "PASSWORD": plus_rtl_de.PASSWORD + } + + @staticmethod + def get_public_access_token(): + main_js = plus_rtl_de.BASE_URL + "/" + re.search( + r'src="(main.*?\.js)"', + requests.get(plus_rtl_de.BASE_URL).content.decode() + ).group(1) + client_secret = re.search( + r'client_secret:"([^"]+)"', requests.get(main_js).content.decode() + ).group(1) + + return json.loads(requests.post( + plus_rtl_de.TOKEN_URL, data={ + 'grant_type': 'client_credentials', + 'client_id': 'anonymous-user', + 'client_secret': client_secret + } + ).content.decode())["access_token"] + + @staticmethod + def get_access_token(): + class_name = plus_rtl_de.__name__.replace("_", ".") + credentials = builtins.CONFIG["SERVICE_CREDENTIALS"][class_name] + try: + assert type(credentials["EMAIL"]) is str + assert type(credentials["PASSWORD"]) is str + except: + return None + if credentials["EMAIL"].strip() == "" or credentials["PASSWORD"].strip() == "": + return plus_rtl_de.get_public_access_token() + + try: + tokens_dict = file_to_dict(plus_rtl_de.CACHE_FILE) + assert len(tokens_dict.keys()) == 2 + for k in ["access_token", "refresh_token"]: + assert (len(tokens_dict[k])) > 0 + + response = requests.post( + plus_rtl_de.TOKEN_URL, data={ + 'grant_type': 'refresh_token', 'client_id': 'rtlplus-web', + 'refresh_token': tokens_dict["refresh_token"] + } + ) + response = json.loads(response.content.decode()) + + tokens_dict = { + "access_token": response["access_token"], + "refresh_token": response["refresh_token"] + } + dict_to_file(plus_rtl_de.CACHE_FILE, tokens_dict) + return tokens_dict["access_token"] + except: + pass + + response = requests.get( + plus_rtl_de.AUTH_URL, allow_redirects=False, + params={ + 'redirect_uri': plus_rtl_de.BASE_URL, + 'client_id': 'rtlplus-web', + 'response_mode': 'query', + 'response_type': 'code' + } + ) + + login_form_cookies = {} + for s1 in dict(response.headers)["set-cookie"].split(";"): + for s2 in s1.split(","): + if "=" not in s2: + continue + + index = s2.find("=") + login_form_cookies[s2[0:index]] = s2[index + 1:] + + response_soup = BeautifulSoup(response.content.decode(), 'html5lib') + form_login = response_soup.find('form', attrs={'id': 'rtlplus-form-login'}) + response = requests.post( + form_login["action"], cookies=login_form_cookies, + allow_redirects=False, data={ + 'credentialId': '', 'rememberMe': 'on', + 'username': credentials["EMAIL"], + 'password': credentials["PASSWORD"] + } + ) + if response.headers.get("location", None) is None: + return None + + location_params = parse_qs(urlparse(response.headers["location"]).query) + response = requests.post( + plus_rtl_de.TOKEN_URL, + data={ + 'code': location_params["code"][0], + 'redirect_uri': plus_rtl_de.BASE_URL, + 'grant_type': 'authorization_code', + 'client_id': 'rtlplus-web' + } + ) + response = json.loads(response.content.decode()) + + tokens_dict = { + "access_token": response["access_token"], + "refresh_token": response["refresh_token"] + } + dict_to_file(plus_rtl_de.CACHE_FILE, tokens_dict) + return tokens_dict["access_token"] + + @staticmethod + def get_account_quality(): + try: + auth_token = plus_rtl_de.AUTH_TOKEN.split(".")[1] + auth_token = base64.b64decode(auth_token + "==") + auth_token = json.loads(auth_token.decode()) + + qualities = auth_token["permissions"]["streaming"] + return { + "vod": qualities["vodQuality"].lower(), + "live": qualities["liveQuality"].lower(), + "fast": qualities["fastQuality"].lower() + } + except: + return {} + + @staticmethod + def initialize_service(): + if plus_rtl_de.CACHE_FILE is None: + plus_rtl_de.CACHE_FILE = join(CACHE_DIR, f'{plus_rtl_de.__name__}.json') + if builtins.CONFIG.get("FRESH", False) is True: + dict_to_file(plus_rtl_de.CACHE_FILE, {}) + + if plus_rtl_de.AUTH_TOKEN is None: + plus_rtl_de.AUTH_TOKEN = plus_rtl_de.get_access_token() + if plus_rtl_de.AUTH_TOKEN is None: + return None + + if plus_rtl_de.ACCOUNT_QUALITY is None: + plus_rtl_de.ACCOUNT_QUALITY = plus_rtl_de.get_account_quality() + return plus_rtl_de + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + additional["license_url"], data=challenge, + headers={'x-auth-token': plus_rtl_de.AUTH_TOKEN} + ) + try: + licence.raise_for_status() + except Exception as e: + response = e.response + if response.status_code == 403: + response = response.content.decode() + for m in ["proxy", "location"]: + if m in response: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=additional["URL"], + reason="Need German IP to make the license call", + solution="Use a VPN (a good one that is not detected)" + )) + if "free" in response or "premium.package" in response: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=additional["URL"], + reason="Cannot download paid content", + solution="Do not attempt to download paid content" + )) + raise e + return licence.content + + @staticmethod + def replace_vod_manifest_digits(manifest, mpd_name, digit_index, digit_value): + try: + digits_pattern = fr'/(\d+[-\d+\w*]*)\.ism/{mpd_name}\.mpd' + digits = re.findall(digits_pattern, manifest) + if len(digits) == 0: + return manifest + + digits = digits[0].split("-") + if len(digits) <= 1: + return manifest + + digits[digit_index] = digit_value + digits = "/" + "-".join(digits) + f".ism/{mpd_name}.mpd" + manifest = re.sub(digits_pattern, digits, manifest) + return manifest + except: + return manifest + + @staticmethod + def adjust_manifest(manifest, content_type): + if content_type == "vod" and plus_rtl_de.ACCOUNT_QUALITY.get(content_type, "") not in ["hd", "high"]: + if manifest.endswith(".ism/rtlplus.mpd"): + return plus_rtl_de.replace_vod_manifest_digits(manifest, "rtlplus", 1, "10000") + + elif manifest.endswith(".ism/v1.mpd"): + try: + i = -1 + for f in manifest.split(".ism/v1.mpd")[0].split("/")[-1].split("-"): + i += 1 + if re.search(r'[a-zA-Z]+', f): + return plus_rtl_de.replace_vod_manifest_digits(manifest, "v1", i + 1, "1") + except: + pass + return plus_rtl_de.replace_vod_manifest_digits(manifest, "v1", -2, "1") + return manifest + + @staticmethod + def generate_audio_m3u8(output_path, manifest, content_info): + m3u8_content = "#EXTM3U\n#EXT-X-VERSION:3\n\n" + m3u8_content += f'#EXTINF:{content_info.get("duration", 1)},\n' + m3u8_content += f'{manifest}\n' + + m3u8_content += "#EXT-X-ENDLIST\n" + with open(output_path, "w") as f: + f.write(m3u8_content) + + @staticmethod + def generate_master_m3u8(source_element, manifest, content_info): + output_path = str(join(source_element.collection, source_element.element)) + if not os.path.exists(output_path): + os.makedirs(output_path) + m3u8_content = "#EXTM3U\n#EXT-X-VERSION:3\n\n" + + title = f'audio.m3u8' + extension = manifest.split(".")[-1] + plus_rtl_de.generate_audio_m3u8(join(output_path, title), manifest, content_info) + m3u8_content += f"#EXT-X-STREAM-INF:BANDWIDTH=1000,TYPE=AUDIO,MIME-TYPE=\"audio/{extension}\"\n" + m3u8_content += f'{title}\n' + + output_path = join(output_path, "master.m3u8") + with open(output_path, "w") as f: + f.write(m3u8_content) + return output_path + + @staticmethod + def get_video_data_podcast(source_element): + content_id = source_element.url.split("-")[-1].split("/")[0] + response = requests.get( + plus_rtl_de.GRAPHQL_URL, headers={ + 'rtlplus-client-Id': plus_rtl_de.CLIENT_ID, + 'rtlplus-client-Version': plus_rtl_de.CLIENT_VERSION, + 'Authorization': f'Bearer {plus_rtl_de.AUTH_TOKEN}' + }, + params={ + 'operationName': 'PodcastEpisode', + 'variables': json.dumps({ + 'id': content_id, + 'take': 1 + }), + 'extensions': json.dumps({'persistedQuery': { + 'version': 1, + 'sha256Hash': '2693e24ad538a69c8698cf1fcbf984cfa49c7592cf5404cb4369167eab694ee0' + }}) + } + ) + + response = json.loads(response.content.decode()) + data = response.get("data", {}) + if type(data) is not dict or len(data.keys()) == 0: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="This content isn't available", + solution='Do not attempt to download it' + )) + + response = response["data"]["podcastEpisode"] + if source_element.element is None: + source_element.element = response.get("title", response.get("seo", {}).get("title", None)) + + if source_element.element is None: + source_element.element = f'Podcast_{content_id}' + source_element.element = get_valid_filename(source_element.element) + + manifest = response["url"] + try: + redirect = requests.get(manifest, allow_redirects=False) + manifest = redirect.headers["Location"] + except: + pass + + manifest = plus_rtl_de.generate_master_m3u8(source_element, manifest, response) + return manifest, None, {} + + @staticmethod + def get_video_data(source_element): + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + plus_rtl_de.__name__ + ) + if "/podcast/" in source_element.url: + return plus_rtl_de.get_video_data_podcast(source_element) + + content_id = source_element.url.split("-")[-1].split("/")[0] + if "/filme/" in source_element.url: + content_type = "movie" + graphql_hash = "b1c360212cc518ddca2b8377813a54fa918ca424c08086204b7bf7d6ef626ac4" + graphql_operation = "MovieDetail" + graphql_variable = "id" + response_field = "movie" + graphql_id = f"rrn:watch:videohub:{content_type}:{content_id}" + + elif "/live-tv/" in source_element.url: + response = requests.get( + plus_rtl_de.GRAPHQL_URL, headers={ + 'rtlplus-client-Id': plus_rtl_de.CLIENT_ID, + 'rtlplus-client-Version': plus_rtl_de.CLIENT_VERSION, + 'Authorization': f'Bearer {plus_rtl_de.AUTH_TOKEN}' + }, + params={ + 'operationName': 'LiveTvStations', + 'variables': json.dumps({ + 'epgCount': 1, + 'filter': {'channelTypes': ['BROADCAST', 'FAST']} + }), + 'extensions': json.dumps({'persistedQuery': { + 'version': 1, + 'sha256Hash': '845cf56a2a78110a0f978c1a2af2bc7f9a1c937d0f324ffaf852a9a4414c8485' + }}) + } + ) + response = json.loads(response.content.decode()) + response = response["data"]["liveTvStations"] + + graphql_id, content_type = None, None + for station in response: + if source_element.url.endswith(station["urlData"]["watchPath"]): + graphql_id = station["id"] + content_type = graphql_id.split(":")[-2] + + assert graphql_id is not None and content_type is not None + graphql_hash = "14368ab2020057ac3bb29ac3e3a903bcdff44f3a232dd76692f3c96ff97f51a5" + graphql_operation = "LiveTvStationV2" + graphql_variable = "rrn" + response_field = "liveTvStationV2" + + else: + content_type = "episode" + graphql_hash = "04e2f59b9c750df1137f9946258c17686cd4447511383ef05fcf699183f449b8" + graphql_operation = "EpisodeDetail" + graphql_variable = "episodeId" + response_field = "episode" + graphql_id = f"rrn:watch:videohub:{content_type}:{content_id}" + + if source_element.element is None: + is_movie = content_type == "movie" + response = json.loads(requests.get( + plus_rtl_de.GRAPHQL_URL, headers={ + 'rtlplus-client-Id': plus_rtl_de.CLIENT_ID, + 'rtlplus-client-Version': plus_rtl_de.CLIENT_VERSION, + 'Authorization': f'Bearer {plus_rtl_de.AUTH_TOKEN}' + }, params={ + 'operationName': graphql_operation, + 'variables': json.dumps({ + graphql_variable: graphql_id + }), 'extensions': json.dumps({ + "persistedQuery": { + "version": 1, + "sha256Hash": graphql_hash + } + }) + } + ).content.decode())["data"][response_field] + + if "/live-tv/" not in source_element.url: + element_name = f'{response.get("title", "")}' + if not is_movie: + element_name = f'{response.get("format", {}).get("title", "")}_{element_name}' + else: + element_name = response.get("name", "") + + element_name = get_valid_filename(element_name) + if element_name is None or len(element_name) == 1: + element_name = content_id + source_element.element = element_name + + response = next(iter(json.loads(requests.get( + plus_rtl_de.GRAPHQL_URL, headers={ + 'rtlplus-client-Id': plus_rtl_de.CLIENT_ID, + 'rtlplus-client-Version': plus_rtl_de.CLIENT_VERSION, + 'Authorization': f'Bearer {plus_rtl_de.AUTH_TOKEN}' + }, params={ + 'operationName': 'WatchPlayerConfigV3', + 'variables': json.dumps({ + "platform": "WEB", + "id": graphql_id + }), 'extensions': json.dumps({ + "persistedQuery": { + "version": 1, + "sha256Hash": "fea0311fb572b6fded60c5a1a9d652f97f55d182bc4cedbdad676354a8d2797c" + } + }) + } + ).content.decode())["data"].values()))["playoutVariants"] + + video_contents = [] + for variant in response: + license_url = None + for licence in variant["licenses"]: + if "widevine" not in licence["type"].lower(): + continue + license_url = licence["licenseUrl"] + break + if license_url is None: + continue + + manifest = None + for source in variant["sources"]: + if "main" not in source["priority"].lower(): + continue + if ".mpd" not in source["url"]: + continue + manifest = source["url"] + break + if manifest is None: + continue + + quality = variant["type"].lower().replace("dash", "") + video_contents.append((manifest, license_url, quality)) + + video_contents = sorted( + video_contents, key=lambda vc: plus_rtl_de.RES_PRIORITY[vc[2]], reverse=True + )[0] + manifest, license_url = video_contents[0:2] + + additional = {} + try: + pssh_value = str(min(re.findall( + r']*>(.*?)', + requests.get(manifest).content.decode() + ), key=len)) + + additional = { + "license_url": license_url, + "URL": source_element.url + } + except: + pssh_value = None + + additional["USE_SHAKA"] = False + manifest = plus_rtl_de.adjust_manifest(manifest, "vod") + return manifest, pssh_value, additional + + @staticmethod + def get_season_index(season): + season_type = season["seasonType"].lower() + + if season_type == "ordinal": + return season["ordinal"] + + if season_type == "annual": + month = str(season["month"]) + if len(month) == 1: + month = f'0{month}' + return float(f'{season["year"]}.{month}') + return None + + @staticmethod + def get_collection_elements_podcast(collection_url): + content_id = collection_url.split("-")[-1].split("/")[0] + episode_index = 0 + offset = -plus_rtl_de.PAGE_LIMIT + collection = [] + collection_title = None + + while True: + offset += plus_rtl_de.PAGE_LIMIT + + response = requests.get( + plus_rtl_de.GRAPHQL_URL, headers={ + 'rtlplus-client-Id': plus_rtl_de.CLIENT_ID, + 'rtlplus-client-Version': plus_rtl_de.CLIENT_VERSION, + 'Authorization': f'Bearer {plus_rtl_de.AUTH_TOKEN}' + }, + params={ + 'operationName': 'PodcastDetail', + 'variables': json.dumps({ + 'offset': offset, 'id': content_id, + 'take': plus_rtl_de.PAGE_LIMIT, + 'sort': {'direction': 'DEFAULT'} + }), + 'extensions': json.dumps({'persistedQuery': { + 'version': 1, + 'sha256Hash': 'efc69a7094e1c4d7195afd7d9e2597a052d45a2c134304e01a386a089be93334' + }}) + } + ) + response = json.loads(response.content.decode()) + data = response.get("data", {}) + if type(data) is not dict or len(data.keys()) == 0: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=collection_url, + reason="This content isn't available", + solution='Do not attempt to download it' + )) + + response = response["data"]["podcast"] + if collection_title is None: + collection_title = response.get("title", None) + if collection_title is None: + collection_title = response.get("seo", {}).get("title", None) + if collection_title is None: + collection_title = f"Podcast_{content_id}" + + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + plus_rtl_de.__name__ + ), + get_valid_filename(collection_title) + ) + + response = response.get("episodes", {}) + episodes = response.get("items", []) + + if len(episodes) == 0: + break + + for episode in response.get("items", []): + episode_index += 1 + check = check_range(False, None, episode_index) + if check is True: + continue + elif check is False: + return collection + + episode_title = episode.get("title", None) + if episode_title is None: + episode_title = episode.get("seo", {}).get("title", None) + if episode_title is None: + episode_title = episode["id"].split(":")[-1] + episode_title = f'Podcast_{episode_index}_{episode_title}' + episode_title = get_valid_filename(episode_title) + + episode_url = episode.get("canonicalUrl", None) + if episode_url is None: + episode_url = plus_rtl_de.BASE_URL + episode["canonicalPath"] + + collection.append(BaseElement( + url=episode_url, + collection=collection_title, + element=episode_title + )) + + if response.get("pageInfo", {}).get("hasNextPage", True) is False: + break + + return collection + + @staticmethod + def get_collection_elements(collection_url): + if "/video-tv/" in collection_url and collection_url.split("/video-tv/")[1].count("/") >= 3: + return [BaseElement(url=collection_url)] + if "/filme/" in collection_url: + return [BaseElement(url=collection_url)] + if "/video-tv/live/" in collection_url: + return None + + collection_url = collection_url.split("?")[0].split("#")[0].rstrip("/") + if "/podcast/" in collection_url: + if collection_url.split("/podcast/")[1].count("/") >= 1: + return [BaseElement(url=collection_url)] + return plus_rtl_de.get_collection_elements_podcast(collection_url) + + if "/video-tv/live-tv/" in collection_url: + return [BaseElement(url=collection_url)] + content_id = collection_url.split("-")[-1].split("/")[0] + collection = [] + + response = requests.get( + plus_rtl_de.GRAPHQL_URL, headers={ + 'rtlplus-client-Id': plus_rtl_de.CLIENT_ID, + 'rtlplus-client-Version': plus_rtl_de.CLIENT_VERSION, + 'Authorization': f'Bearer {plus_rtl_de.AUTH_TOKEN}' + }, + params={ + 'operationName': 'Format', + 'variables': json.dumps({'id': f'rrn:watch:videohub:format:{content_id}'}), + 'extensions': json.dumps({'persistedQuery': { + 'version': 1, + 'sha256Hash': '1da243e1180ae67a43514c6a52bc756acefcb70c6250498c9e8fb04b3d9e7720' + }}) + } + ) + response = json.loads(response.content.decode()) + data = response.get("data", {}) + if type(data) is not dict or len(data.keys()) == 0: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=collection_url, + reason="This content isn't available", + solution='Do not attempt to download it' + )) + + collection_title = data.get("format", {}).get("title", None) + if collection_title is None: + collection_title = collection_url.split(plus_rtl_de.BASE_URL)[-1] + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + plus_rtl_de.__name__ + ), + get_valid_filename(collection_title) + ) + + seasons = data.get("format", {}).get("seasons", []) + if len(seasons) == 0: + return [] + + extras = list(filter( + lambda s: not s["urlData"]["watchPath"].split("/")[-1].startswith("staffel-"), + seasons + )) + seasons = list(filter( + lambda s: s["urlData"]["watchPath"].split("/")[-1].startswith("staffel-"), + seasons + )) + seasons.extend(list(filter(lambda e: e.get("titleOverride", None) is None, extras))) + extras = list(filter(lambda e: e.get("titleOverride", None) is not None, extras)) + + extras = sorted(extras, key=lambda e: str(e["titleOverride"].lower())) + seasons_type = data["format"]["seasonsType"].lower() + if seasons_type == "annual": + seasons = sorted(seasons, key=lambda s: (s["year"], s["month"])) + elif seasons_type == "ordinal": + seasons = sorted(seasons, key=lambda s: s["ordinal"]) + else: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=collection_url, + reason=f"Unknown season type encountered: {seasons_type}", + solution=f"Extend the {plus_rtl_de.__name__} service" + )) + + if len(extras) > 0: + if len(seasons) == 0: + season_index = 0 + else: + season_index = seasons[-1]["ordinal"] + + for extra in extras: + season_index += 1 + extra["ordinal"] = season_index + seasons.extend(extras) + + for season in seasons: + season_type = season["seasonType"].lower() + season_index = plus_rtl_de.get_season_index(season) + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + if season_type == "ordinal": + season_title = f'Season_{season["ordinal"]}' + if season.get("titleOverride", None) is not None: + season_title += f"_{season['titleOverride']}" + else: # if season_type == "annual": + season_title = f'Year_{season["year"]}_Month_{season["month"]}' + season_title = get_valid_filename(season_title) + season_id = season["id"] + + page_offset = -plus_rtl_de.PAGE_LIMIT + while True: + page_offset += plus_rtl_de.PAGE_LIMIT + response = requests.get( + plus_rtl_de.GRAPHQL_URL, headers={ + 'rtlplus-client-Id': plus_rtl_de.CLIENT_ID, + 'rtlplus-client-Version': plus_rtl_de.CLIENT_VERSION, + 'Authorization': f'Bearer {plus_rtl_de.AUTH_TOKEN}' + }, + params={ + 'operationName': 'SeasonWithFormatAndEpisodes', + 'variables': json.dumps({ + 'seasonId': season_id, 'offset': page_offset, + 'limit': plus_rtl_de.PAGE_LIMIT + }), + 'extensions': json.dumps({'persistedQuery': { + 'version': 1, + 'sha256Hash': 'de1ae6550a2bbb069e00cf253bd1e08658dcf6afa9db93240343d2f8ea641823' + }}) + } + ) + + response = json.loads(response.content.decode()) + data = response.get("data", {}) + if type(data) is not dict: + data = {} + episodes = data.get("season", {}).get("episodes", []) + if len(episodes) == 0: + break + + for episode in episodes: + check = check_range(False, season_index, episode["number"]) + if check in [True, False]: + continue + + episode_url = plus_rtl_de.BASE_URL + episode["urlData"]["watchPath"] + episode_title = episode.get("title", episode["id"].split(":")[-1]) + + collection.append(BaseElement( + url=episode_url, + collection=join(collection_title, season_title), + element=get_valid_filename(f"Episode_{episode['number']}_{episode_title}") + )) + + return collection diff --git a/API/proxiesembed/drmproxy/services/ptvflix_org.py b/API/proxiesembed/drmproxy/services/ptvflix_org.py new file mode 100644 index 0000000..edf29f1 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/ptvflix_org.py @@ -0,0 +1,260 @@ +import base64 +import builtins +import json +import re +from os.path import join + +import requests + +from utils.constants.macros import ERR_MSG, USER_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename + + +class ptvflix_org(BaseService): + DEMO_URLS = [ + "https://ptvflix.org/category/646", + "https://ptvflix.org/category/843", + "https://ptvflix.org/player/4185", + "https://ptvflix.org/player/7488", + ] + + STREAM_URL = 'https://mw.hivesys.net/public/vod/getStreamUrlV3' + CATEGORY_URL = 'https://mw.hivesys.net/public/RecommendationEngine/getCategory' + LOGIN_URL = 'https://mw.hivesys.net/public/customer/login' + BASE_URL = 'https://ptvflix.org' + VIDEO_URL = BASE_URL + '/player/{video_id}' + + EMAIL = "YOUR_EMAIL" + PASSWORD = "YOUR_PASSWORD" + DEVICE_HASH = None + DEVICE_TYPE = "d2ViIHBsYXllcg==" + DEVICE_ID = "Win32" + VENDOR_ID = 1 + BEARER_TOKEN = None + PROFILE_ID = None + + @staticmethod + def test_service(): + main_service.run_service(ptvflix_org) + + @staticmethod + def credentials_needed(): + return { + "EMAIL": ptvflix_org.EMAIL, + "PASSWORD": ptvflix_org.PASSWORD + } + + @staticmethod + def get_devices_hash(): + response = requests.get(ptvflix_org.BASE_URL).content.decode() + response = re.search(r'src="([^"]*?/index-[^"]*?\.js)"', response).group(1) + if not response.startswith("/"): + response = "/" + response + response = f'{ptvflix_org.BASE_URL}{response}' + + response = requests.get(response).content.decode() + response = re.search(r'"([^"]*?/CopyToClipboard-[^"]*?\.js)"', response).group(1) + if not response.startswith("/"): + response = "/" + response + response = f'{ptvflix_org.BASE_URL}{response}' + + response = requests.get(response).content.decode() + response = re.search(r'devices_hash="([^"]+)"', response).group(1) + return response + + @staticmethod + def get_account_info(): + class_name = ptvflix_org.__name__.replace("_", ".") + credentials = builtins.CONFIG["SERVICE_CREDENTIALS"][class_name] + try: + assert type(credentials["EMAIL"]) is str + assert type(credentials["PASSWORD"]) is str + except: + return None, None + + response = json.loads(requests.post( + ptvflix_org.LOGIN_URL, + json={ + 'data': { + 'login': credentials["EMAIL"], + 'password': credentials["PASSWORD"], + 'vendorsId': ptvflix_org.VENDOR_ID + } + } + ).content.decode()) + if response.get("status", None) == 103 or len(response.get("response", [])) == 0: + return None, None + + response = response["response"] + bearer_token = None + profile_id = None + for profile in response["profiles"]: + bearer_token = profile.get("customers_token", None) + profile_id = base64.b64encode(str(profile["profiles_id"]).encode()).decode() + break + + if bearer_token is None: + bearer_token = response.get("customers_token", None) + return bearer_token, profile_id + + @staticmethod + def initialize_service(): + if ptvflix_org.DEVICE_HASH is None: + ptvflix_org.DEVICE_HASH = ptvflix_org.get_devices_hash() + + if ptvflix_org.BEARER_TOKEN is None or ptvflix_org.PROFILE_ID is None: + ptvflix_org.BEARER_TOKEN, ptvflix_org.PROFILE_ID = ptvflix_org.get_account_info() + if ptvflix_org.BEARER_TOKEN is None or ptvflix_org.PROFILE_ID is None: + return None + + return ptvflix_org + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + additional["license_url"], + headers={ + 'authorization': f'Bearer {ptvflix_org.BEARER_TOKEN}', + 'profilesid': ptvflix_org.PROFILE_ID, + 'devicestype': ptvflix_org.DEVICE_TYPE + }, + data=json.dumps({ + "offset": additional["offset"], + "edges_id": additional["edges_id"], + "devices_identification": ptvflix_org.DEVICE_ID, + "devices_hash": ptvflix_org.DEVICE_HASH, + "rawLicense": base64.b64encode(challenge).decode() + }) + ) + licence.raise_for_status() + return json.loads(licence.content.decode())["rawLicense"] + + @staticmethod + def get_video_data(source_element): + vod_id = int(re.search(r"/player/([^/?]*)", source_element.url).group(1)) + + response = json.loads(requests.post( + ptvflix_org.STREAM_URL, + headers={ + 'Authorization': f'Bearer {ptvflix_org.BEARER_TOKEN}', + 'profilesId': ptvflix_org.PROFILE_ID, + 'devicesType': ptvflix_org.DEVICE_TYPE + }, + json={'data': {'vodsId': vod_id, 'type': 'dash'}} + ).content.decode()) + + if response.get("status", None) == 1001 and len(response.get("response", [])) == 0: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason='You requested too much content recently or the content is not free', + solution="Wait 10 minutes or don't attempt to download it" + )) + + response = response["response"] + manifest = response["url"] + + license_url = None + for license_name in response["drms"]: + if "widevine" in license_name.lower(): + license_url = response["drms"][license_name] + break + additional = { + "offset": response["offset"], + "edges_id": response["edgesId"], + "license_url": license_url + } + + if source_element.element is None: + try: + name = manifest.split("/")[-2] + except: + name = str(vod_id) + source_element.element = get_valid_filename(name) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + ptvflix_org.__name__ + ) + + try: + pssh_value = str(min(re.findall( + r']*>(.*?)', + requests.get(manifest).content.decode() + ), key=len)) + except: + return manifest, None, {} + return manifest, pssh_value, additional + + @staticmethod + def get_season_from_row(row): + if "season" in row["title"].lower(): + return row["data"][0]["season_number"] + + if "other episodes" in row["title"].lower(): + return 0 + return None + + @staticmethod + def get_collection_elements(collection_url): + if "/player/" in collection_url: + return [BaseElement(url=collection_url)] + + if "/category/" in collection_url: + collection = [] + category_id = int(re.search(r"/category/([^/?]*)", collection_url).group(1)) + response = json.loads(requests.post( + ptvflix_org.CATEGORY_URL, + headers={ + 'Authorization': f'Bearer {ptvflix_org.BEARER_TOKEN}', + 'profilesId': ptvflix_org.PROFILE_ID, + 'devicesType': ptvflix_org.DEVICE_TYPE + }, + json={'data': {'categoriesId': category_id}} + ).content.decode())["response"] + + collection_name = response.get("category", {}).get( + "categories_name", f"Content_{category_id}" + ) + collection_name = get_valid_filename(collection_name) + response = [(ptvflix_org.get_season_from_row(r), r) for r in response["rows"]] + response = sorted(response, key=lambda r: r[0]) + + for season_index, season in response: + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + index = 0 + for episode in season["data"]: + index += 1 + episode_index = index if episode.get("episode_number", None) is None \ + else episode["episode_number"] + + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=ptvflix_org.VIDEO_URL.format(video_id=episode["id"]), + collection=join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + ptvflix_org.__name__ + ), + join(collection_name, f'Season_{season_index}') + ), + element=f"Episode_{episode_index}" + f'_' + f"{get_valid_filename(episode['title'])}" + )) + return collection + + return None diff --git a/API/proxiesembed/drmproxy/services/rakuten_tv.py b/API/proxiesembed/drmproxy/services/rakuten_tv.py new file mode 100644 index 0000000..f87d222 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/rakuten_tv.py @@ -0,0 +1,507 @@ +import builtins +import json +import os +import re +from os.path import join +from urllib.parse import parse_qs, urlparse + +import requests +import xmltodict + +from utils.constants.macros import ERR_MSG, APP_ERROR, USER_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename + + +class rakuten_tv(BaseService): + DEMO_URLS = [ + "https://www.rakuten.tv/GLOBAL?content_type=tv_shows&tv_show_id=discovering-canary-islands&content_id=discovering-canary-islands-1", + "https://www.rakuten.tv/GLOBAL/gardens/avod-fast?content_type=tv_shows&tv_show_id=revenge-note&content_id=revenge-note-1", + "https://www.rakuten.tv/GLOBAL/live_channels/lone-star", + "https://www.rakuten.tv/GLOBAL/live_channels/bloomberg-tv-new", + "https://www.rakuten.tv/GLOBAL/player/seasons/trailer/champions-1", + "https://www.rakuten.tv/GLOBAL/player/movies/trailer/a-thousand-and-one", + 'https://www.rakuten.tv/GLOBAL/player/movies/stream/ride-your-dream', + 'https://www.rakuten.tv/GLOBAL/player/movies/stream/inside-kilian-jornet', + "https://www.rakuten.tv/GLOBAL/player/episodes/stream/matchday-1/matchday-1-5", + "https://www.rakuten.tv/GLOBAL/player/episodes/stream/discovering-canary-islands-2/discovering-canary-islands-2-2", + ] + + START_URL = 'https://gizmo.rakuten.tv/v3/me/start' + STREAM_URL = 'https://gizmo.rakuten.tv/v3/{category}/streamings' + CONTENT_URL = 'https://gizmo.rakuten.tv/v3/{path_type}/{content_id}' + BASE_URL = 'https://www.rakuten.tv' + EPISODE_URL = BASE_URL + "/{country}/player/episodes/stream/{season_id}/{episode_id}" + + CLASSIFICATION_ID = None + DEVICE_ID = "cast" + DEVICE_IDS = [ + "atvui40", "atvui40_free", "atvui40_stb_free", "cast", "hisui40", + "lgui40", "netgemui40", "panui40", "philui40", "ps4ui40", + "samui40", "sonyui40", "tclui40", "vestelui40", "web" + ] + RES_PRIORITY = {"SD": 0, "HD": 1, "FHD": 2, "UHD": 3} + LANGUAGE = None + + @staticmethod + def test_service(): + main_service.run_service(rakuten_tv) + + @staticmethod + def get_additional_params(additional): + return [("MUXER", lambda s: s.format(args="mkv:muxer=mkvmerge"))] + + @staticmethod + def is_content_livestream(content, additional): + return "/live_channels/" in content + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def get_classification_id(): + response = json.loads(requests.post( + rakuten_tv.START_URL, + json={ + 'device_identifier': rakuten_tv.DEVICE_ID, + 'device_metadata': { + 'app_version': 'app_version', + 'brand': 'brand', 'model': 'model', + 'os': 'os', 'serial_number': 'serial_number', + 'uid': 'uid', 'year': 0 + } + } + ).content.decode()) + + if "forbidden_vpn" in str(response.get("errors", [])).lower(): + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=f'from {rakuten_tv.__name__}', + reason="The VPN was detected", + solution="Get a better VPN or don't use one" + )) + if "forbidden_market" in str(response.get("errors", [])).lower(): + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=f'from {rakuten_tv.__name__}', + reason="Bad device id", + solution=f"Change the device id in the service script file" + )) + + classification_id = response["data"]["user"]["profile"]["classification"]["numerical_id"] + return str(classification_id) + + @staticmethod + def initialize_service(): + if builtins.CONFIG.get("BASIC", False) is True: + rakuten_tv.LANGUAGE = 'eng' + rakuten_tv.LANGUAGE = rakuten_tv.LANGUAGE.lower() + + if rakuten_tv.CLASSIFICATION_ID is None: + rakuten_tv.CLASSIFICATION_ID = rakuten_tv.get_classification_id() + return rakuten_tv + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post(additional["license_url"], data=challenge) + licence.raise_for_status() + return licence.content + + @staticmethod + def generate_master_mpd(source_element, manifests): + manifests_contents = [] + for mpd_url in manifests: + mpd_content = requests.get(mpd_url).content.decode() + mpd_content = xmltodict.parse(mpd_content) + manifests_contents.append(mpd_content) + + audio_set = [] + index = -1 + for c in manifests_contents: + index += 1 + base_url = c["MPD"]["BaseURL"] + del c["MPD"]["BaseURL"] + + manifest_content = c["MPD"]["Period"]["AdaptationSet"] + if type(manifest_content) is not list: + manifest_content = [manifest_content] + + for ad_set in manifest_content: + if index > 0: + if "audio/" not in ad_set["@mimeType"]: + continue + + ad_set_rep = ad_set["Representation"] + if type(ad_set_rep) is not list: + ad_set_rep = [ad_set_rep] + + for ad_rep in ad_set_rep: + ad_rep["BaseURL"] = base_url + ad_rep["BaseURL"] + if len(ad_set_rep) == 1: + ad_set_rep = ad_set_rep[0] + ad_set["Representation"] = ad_set_rep + + if index > 0: + audio_set.append(ad_set) + + manifest_content = manifests_contents[0]["MPD"]["Period"]["AdaptationSet"] + manifest_content += audio_set + manifests_contents[0]["MPD"]["Period"]["AdaptationSet"] = manifest_content + manifest_content = manifests_contents[0] + manifest_content = xmltodict.unparse(manifest_content, pretty=True) + + output_path = join(source_element.collection, source_element.element) + if not os.path.exists(output_path): + os.makedirs(output_path) + output_path = join(str(output_path), "master.mpd") + + with open(output_path, "w") as f: + f.write(manifest_content) + return output_path + + @staticmethod + def get_video_data(source_element): + if "/trailer/" in source_element.url: + content_category = "trailer" + elif "/live_channels/" in source_element.url: + content_category = "live_channels" + else: + content_category = "stream" + + if "/live_channels/" in source_element.url: + content_type = content_category + content_id = re.search(fr"/{content_category}/(.+)", source_element.url).group(1).split("/") + else: + content_type = re.search(fr"/player/([^/?]*)/{content_category}/", source_element.url).group(1) + content_id = re.search(fr"/player/[^/?]*/{content_category}/(.+)", source_element.url).group(1).split("/") + + path_type = "movies" + if content_type in ["episodes", "seasons"]: + path_type = "seasons" + elif content_type in ["live_channels"]: + path_type = "live_channels" + + response = json.loads(requests.get( + rakuten_tv.CONTENT_URL.format(path_type=path_type, content_id=content_id[0]), + params={ + 'classification_id': rakuten_tv.CLASSIFICATION_ID, + 'device_identifier': rakuten_tv.DEVICE_ID + } + ).content.decode()) + + content_title = content_id[0] + if "not_found" in str(response.get("errors", [])).lower(): + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + all_response = None + if "/movies/" in source_element.url or "/seasons/" in source_element.url or "/live_channels/" in source_element.url: + if "/seasons/" not in source_element.url: + content_title = response["data"]["title"] + else: + content_title = response["data"]["tv_show"]["title"] + response = response["data"]["view_options"] + + if content_category == "trailer": + response = response["public"]["trailers"] + else: + response = response["private"]["streams"] + + all_response = response + response = response[0] + elif "/episodes/" in source_element.url: + found = False + content_title = content_id[1] + + for episode in response["data"]["episodes"]: + if episode["id"] == content_id[1]: + content_title = episode["title"] + response = episode["view_options"]["private"]["streams"][0] + found = True + break + + if not found: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + if source_element.element is None: + if "/trailer/" in source_element.url: + content_title += " Trailer" + source_element.element = get_valid_filename(content_title) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rakuten_tv.__name__ + ) + + drm_types = response["streaming_drm_types"] + manifest_type = None + for drm_type in drm_types: + if drm_type["id"].lower().startswith("dash-"): + manifest_type = drm_type["id"] + break + if manifest_type is None: + manifest_type = drm_types[0]["id"] + + audio_quality = response["audio_qualities"] + audio_quality = sorted(audio_quality, key=lambda ad: ad["numerical_id"], reverse=True) + audio_quality = f'{audio_quality[0]["numerical_id"]}.0' + + if all_response is None: + audio_lang = response["audio_languages"] + else: + audio_lang = [] + for r in all_response: + audio_lang.extend(r["audio_languages"]) + + subtitle_language = response["subtitle_languages"][-1]["id"] + video_quality = response["video_qualities"] + video_quality = sorted( + video_quality, reverse=True, + key=lambda v: rakuten_tv.RES_PRIORITY[v["id"]] + ) + video_quality = video_quality[0]["id"] + + json_content_id = content_id[0] + if content_type == "episodes": + json_content_id = content_id[1] + + manifest = [] + subtitles = [] + pssh_values = [] + additional = {} + has_non_mpd = False + + if rakuten_tv.LANGUAGE is not None: + temp_audio = [ + a for a in audio_lang + if a["id"].lower().startswith(rakuten_tv.LANGUAGE) + or rakuten_tv.LANGUAGE.startswith(a["id"].lower()) + ] + if len(temp_audio) > 0: + audio_lang = [temp_audio[0]] + else: + audio_lang = [audio_lang[0]] + + for a in audio_lang: + response = json.loads(requests.post( + rakuten_tv.STREAM_URL.format( + category="avod" if content_category in ["stream", "live_channels"] else "me" + ), + params={"device_identifier": rakuten_tv.DEVICE_ID}, + json={ + 'audio_language': a["id"], + 'audio_quality': audio_quality, + 'classification_id': rakuten_tv.CLASSIFICATION_ID, + 'content_id': json_content_id, + 'content_type': content_type, + 'device_serial': 'device_serial', + 'device_stream_video_quality': video_quality, + 'player': f'{rakuten_tv.DEVICE_ID}:{manifest_type}', + 'subtitle_language': subtitle_language, + 'support_closed_captions': True, + 'video_type': "stream" if content_category in ["stream", "live_channels"] else content_category + } + ).content.decode()) + + if "not_found" in str(response.get("errors", [])).lower(): + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available because of bad device id or because it doesn't exist", + solution=f"Change the device id in the service script file or do not attempt to download it" + )) + + streams = response["data"]["stream_infos"] + streams = sorted( + streams, reverse=True, + key=lambda s: rakuten_tv.RES_PRIORITY[s["video_quality"]] + ) + + if len(subtitles) == 0: # and "/live_channels/" not in source_element.url: + output_path = join(source_element.collection, source_element.element) + visited = [] + index = 0 + + for subtitle in streams[0].get("all_subtitles", []): + if subtitle["url"] in visited: + continue + + index += 1 + subtitles.append((False, BaseElement( + url=subtitle["url"], + collection=output_path, + element=f'subtitle_{index}' + f'_' + f'{subtitle["language"].lower()}.{subtitle["format"].lower()}' + ))) + visited.append(subtitle["url"]) + + manifest_url = streams[0]["url"] + if manifest_url in manifest: + continue + manifest.append(manifest_url) + + if has_non_mpd is False: + has_non_mpd = manifest_type.lower().startswith("hls-") + + if len(manifest) > 1 and has_non_mpd: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {str(manifest)}. Can't merge multiple manifests", + solution=f"Extend the {rakuten_tv.__name__} service" + )) + + license_url = streams[0].get("license_url", None) + if license_url is not None and manifest_type.lower().startswith("hls-"): + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest_type}. Can't extract pssh", + solution=f"Extend the {rakuten_tv.__name__} service" + )) + + try: + if license_url is None: + raise + + pssh_value = str(min(re.findall( + r']*>(.*?)', + requests.get(manifest_url).content.decode() + ), key=len)) + except: + pssh_value = None + + if pssh_value is not None: + if pssh_value not in pssh_values: + pssh_values.append(pssh_value) + additional[pssh_value] = {"license_url": license_url} + + if pssh_value is None and license_url is not None: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine wasn't found", + solution="Do not attempt to download it" + )) + + if len(manifest) > 1: + manifest = rakuten_tv.generate_master_mpd(source_element, manifest) + else: + manifest = manifest[0] + + additional["SUBTITLES"] = subtitles + return manifest, pssh_values, additional + + @staticmethod + def get_collection_elements(collection_url): + collection_url = collection_url.rstrip("/") + + for p in ["movies", "episodes"]: + if f'/player/{p}/stream/' in collection_url: + return [BaseElement(url=collection_url)] + for p in ["movies", "seasons"]: + if f'/player/{p}/trailer/' in collection_url: + return [BaseElement(url=collection_url)] + if "/live_channels/" in collection_url: + return [BaseElement(url=collection_url)] + + if "?" in collection_url and "content_type=" in collection_url and "content_id=" in collection_url: + collection = [] + params_dict = parse_qs(urlparse(collection_url).query) + + content_type = params_dict["content_type"][0] + if content_type not in ["tv_shows"]: + return None + content_id = params_dict["content_id"][0] + if content_id is None: + return None + + country = re.search(fr"{rakuten_tv.BASE_URL}/([^/?]*)[/?]", collection_url).group(1) + response = json.loads(requests.get( + rakuten_tv.CONTENT_URL.format( + path_type="seasons", + content_id=content_id + ), + params={ + 'classification_id': rakuten_tv.CLASSIFICATION_ID, + 'device_identifier': rakuten_tv.DEVICE_ID + } + ).content.decode()) + + if "not_found" in str(response.get("errors", [])).lower(): + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + response = response["data"] + init_episodes = response["episodes"] + collection_name = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rakuten_tv.__name__ + ), + get_valid_filename(response["tv_show"]["title"]) + ) + + season_index = 0 + for season in response["tv_show"]["seasons"]: + season_index += 1 + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + if season["id"] == content_id: + episodes = init_episodes + else: + episodes = json.loads(requests.get( + rakuten_tv.CONTENT_URL.format( + path_type="seasons", + content_id=season["id"] + ), + params={ + 'classification_id': rakuten_tv.CLASSIFICATION_ID, + 'device_identifier': rakuten_tv.DEVICE_ID + } + ).content.decode()) + episodes = episodes["data"]["episodes"] + + episodes = sorted(episodes, key=lambda ep: ep["number"]) + for e in episodes: + check = check_range(False, season_index, e['number']) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=rakuten_tv.EPISODE_URL.format( + country=country, + season_id=season["id"], + episode_id=e["id"] + ), + collection=join(collection_name, f'Season_{season_index}'), + element=f"Episode_{e['number']}" + f"_" + f"{get_valid_filename(e['title'])}" + )) + + return collection + return None diff --git a/API/proxiesembed/drmproxy/services/rmcbfmplay_com.py b/API/proxiesembed/drmproxy/services/rmcbfmplay_com.py new file mode 100644 index 0000000..5d97670 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/rmcbfmplay_com.py @@ -0,0 +1,292 @@ +import base64 +import builtins +import json +import re +from os.path import join +from urllib.parse import urlparse, parse_qs + +import requests +from bs4 import BeautifulSoup + +from utils.constants.macros import USER_ERROR, ERR_MSG +from utils.main_service import main_service +from utils.structs import BaseElement, CustomException, BaseService +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename + + +class rmcbfmplay_com(BaseService): + DEMO_URLS = [ + "https://www.rmcbfmplay.com/info-programme/rmc-bfm-play/australie-la-ruee-vers-lor?contentId=Product::NEUF_BFMAVOD_BAV_623218986527&universe=PROVIDER", + "https://www.rmcbfmplay.com/info-programme/bfm-tv/michel-edouard-leclerc-a-tout-prix?contentId=Product::NEUF_BFMTV_BFM989735110527&universe=PROVIDER", + "https://www.rmcbfmplay.com/info-programme/rmc-decouverte/seuls-face-a-lalaska?contentId=Product::NEUF_RMCDEC_RMCP4341198&universe=PROVIDER", + "https://www.rmcbfmplay.com/video/rmc-story/alien-theory/s6e10-lere-technologique?contentId=Product::NEUF_NUM23_N2341089&universe=PROVIDER", + "https://www.rmcbfmplay.com/video/rmc-story/le-pal-au-coeur-du-zoo-le-plus-insolite-de-france?contentId=Product::NEUF_NUM23_N23544692327527&universe=PROVIDER", + "https://www.rmcbfmplay.com/video/rmc-bfm-play/alexandre-le-grand-la-vraie-histoire-dun-conquerant-de-legende?contentId=Product::NEUF_BFMAVOD_BAV984224866527&universe=PROVIDER", + ] + + CONFIG_URL = 'https://www.rmcbfmplay.com/assets/configs/config.json' + CAS_AUTH_URL = 'https://sso.rmcbfmplay.com/cas/oidc/authorize' + CONTENT_URL = 'https://ws-backendtv.rmcbfmplay.com/gaia-core/rest/api/web/v3/content/{content_id}/options' + DETAIL_URL = 'https://ws-cdn.tv.sfr.net/gaia-core/rest/api/web/v1/content/{content_id}/detail' + EPISODES_URL = 'https://ws-cdn.tv.sfr.net/gaia-core/rest/api/web/v1/content/{content_id}/episodes' + VIDEO_URL = 'https://www.rmcbfmplay.com/video?contentId={content_id}&universe={universe}' + LICENSE_URL = None + + EMAIL = 'YOUR_EMAIL' + PASSWORD = 'YOUR_PASSWORD' + BFM_TOKEN = None + APP_VALUE = None + CONFIG_CONTENT = None + PAGE_LIMIT = 50 + RES_PRIORITY = {"sd": 0, "hd": 1} + + @staticmethod + def test_service(): + main_service.run_service(rmcbfmplay_com) + + @staticmethod + def is_content_livestream(content, additional): + return "/direct-tv/" in content + + @staticmethod + def credentials_needed(): + return { + "EMAIL": rmcbfmplay_com.EMAIL, + "PASSWORD": rmcbfmplay_com.PASSWORD + } + + @staticmethod + def get_token(): + class_name = rmcbfmplay_com.__name__.replace("_", ".") + credentials = builtins.CONFIG["SERVICE_CREDENTIALS"][class_name] + try: + assert type(credentials["EMAIL"]) is str + assert type(credentials["PASSWORD"]) is str + except: + return None + + with requests.session() as login_session: + response = login_session.get( + rmcbfmplay_com.CAS_AUTH_URL, allow_redirects=False, params={ + 'client_id': rmcbfmplay_com.CONFIG_CONTENT["auth"]["OIDC_CLIENT_ID"], + 'scope': 'openid', 'response_type': 'token', + 'redirect_uri': 'https://www.rmcbfmplay.com' + } + ) + redirect = response.headers["location"] + response = login_session.get(redirect) + + soup_login = BeautifulSoup(response.content, 'html5lib') + form_data = {} + for element in soup_login.find('form').find_all('input'): + if element.has_attr('value'): + form_data[element['name']] = element['value'] + + form_data['username'] = credentials["EMAIL"] + form_data['password'] = credentials["PASSWORD"] + form_data['remember-me'] = 'on' + + response = login_session.post(redirect, allow_redirects=False, data=form_data) + redirect = response.headers["location"] + response = login_session.get(redirect, allow_redirects=False) + redirect = response.headers["location"] + + token = parse_qs(urlparse(redirect).query)["access_token"][0] + for b64 in token.split("."): + try: + return json.loads(base64.b64decode(b64 + "==").decode())["tu"] + except: + pass + return None + + @staticmethod + def initialize_service(): + if rmcbfmplay_com.CONFIG_CONTENT is None: + rmcbfmplay_com.CONFIG_CONTENT = json.loads(requests.get(rmcbfmplay_com.CONFIG_URL).content.decode()) + rmcbfmplay_com.APP_VALUE = rmcbfmplay_com.CONFIG_CONTENT["application"]["app"] + + if rmcbfmplay_com.BFM_TOKEN is None: + rmcbfmplay_com.BFM_TOKEN = rmcbfmplay_com.get_token() + if rmcbfmplay_com.BFM_TOKEN is None: + return None + rmcbfmplay_com.LICENSE_URL = rmcbfmplay_com.CONFIG_CONTENT[ + "player" + ]["shaka"]["drm"]["servers"]["com.widevine.alpha"] + + return rmcbfmplay_com + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + rmcbfmplay_com.LICENSE_URL, data=challenge, + headers={ + 'customdata': '&'.join([f"{key}={value}" for key, value in { + "description": "description", + "deviceName": "deviceName", + "deviceType": "PC", + "tokenType": "castoken", + "tokenSSO": rmcbfmplay_com.BFM_TOKEN + }.items()]) + } + ) + if licence.status_code == 520: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=additional["URL"], + reason="Need French IP to access content", + solution="Use a VPN" + )) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_video_data(source_element): + query_params = parse_qs(urlparse(source_element.url).query) + content_id = query_params["contentId"][0] + universe = query_params["universe"][0] + + response = json.loads(requests.get( + rmcbfmplay_com.CONTENT_URL.format(content_id=content_id), + params={ + 'app': rmcbfmplay_com.APP_VALUE, 'device': 'browser', + 'token': rmcbfmplay_com.BFM_TOKEN, 'universe': universe + } + ).content.decode()) + + manifest = [] + element_name = None + for product in response: + if product["productId"] != content_id: + continue + + element_name = product.get("title", None) + for offer in product["offers"]: + for stream in offer["streams"]: + if stream["drm"] != "WIDEVINE": + continue + manifest += [(offer["definition"].lower(), stream["url"])] + if len(manifest) == 0: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Content isn't available anymore", + solution="Do not attempt to download it" + )) + manifest = sorted(manifest, key=lambda m: rmcbfmplay_com.RES_PRIORITY[m[0]], reverse=True)[0][1] + + if source_element.element is None: + if element_name is None: + element_name = content_id + source_element.element = get_valid_filename(element_name) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rmcbfmplay_com.__name__ + ) + + try: + pssh_value = str(min(re.findall( + r'(.+?)', + requests.get(manifest).content.decode() + ), key=len)) + except: + return manifest, None, {} + return manifest, pssh_value, {"URL": source_element.url} + + @staticmethod + def get_collection_elements(collection_url): + if "/video/" in collection_url and "contentId=" in collection_url: + return [BaseElement(url=collection_url)] + if "/info-programme/" in collection_url: + collection = [] + query_params = parse_qs(urlparse(collection_url).query) + content_id = query_params["contentId"][0] + universe = query_params["universe"][0] + + response = json.loads(requests.get( + rmcbfmplay_com.DETAIL_URL.format(content_id=content_id), + params={"universe": universe} + ).content.decode()) + + collection_name = response.get("title", None) + if collection_name is None: + collection_name = content_id + collection_name = get_valid_filename(collection_name) + + is_series = response.get("seasons", None) is not None + collection_key = "episodes" + if is_series: + collection_key = "seasons" + + index = 0 + for collection_object in response.get(collection_key, []): + if not is_series: + index += 1 + episode = collection_object + check = check_range(False, None, index) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=rmcbfmplay_com.VIDEO_URL.format(content_id=episode["id"], universe=universe), + collection=join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rmcbfmplay_com.__name__ + ), + collection_name + ), + element=f'{episode["sequence"]}' + f'_' + f'{get_valid_filename(episode.get("title", episode["id"]))}' + )) + else: + season = collection_object + check = check_range(True, season["sequence"], None) + if check is True: + continue + elif check is False: + return collection + + page = -1 + while True: + page += 1 + + episode_response = json.loads(requests.get( + rmcbfmplay_com.EPISODES_URL.format(content_id=season["id"]), + params={ + 'app': rmcbfmplay_com.APP_VALUE, 'device': 'browser', + 'universe': universe, 'page': page, + 'size': rmcbfmplay_com.PAGE_LIMIT + } + ).content.decode()) + + for episode in episode_response.get("content", []): + check = check_range(False, season["sequence"], episode['episodeNumber']) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=rmcbfmplay_com.VIDEO_URL.format(content_id=episode["id"], universe=universe), + collection=join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rmcbfmplay_com.__name__ + ), + join(collection_name, f'Season_{season["sequence"]}') + ), + element=f'Episode_{episode["episodeNumber"]}' + f'_' + f'{get_valid_filename(episode.get("title", episode["id"]))}' + )) + + if len(episode_response.get("content", [])) < rmcbfmplay_com.PAGE_LIMIT: + break + + return collection + return None diff --git a/API/proxiesembed/drmproxy/services/rsi_ch.py b/API/proxiesembed/drmproxy/services/rsi_ch.py new file mode 100644 index 0000000..0504ccc --- /dev/null +++ b/API/proxiesembed/drmproxy/services/rsi_ch.py @@ -0,0 +1,461 @@ +import builtins +import json +import re +from os.path import join +from urllib.parse import urlparse, parse_qs, quote + +import requests + +import utils.tools.common as common_tools +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range + + +class rsi_ch(BaseService): + DEMO_URLS = [ + "https://www.rsi.ch/play/ricerca?query=&showAll=true&shows=urn%3Arsi%3Ashow%3Atv%3A704146&topics=urn%3Arsi%3Atopic%3Atv%3A7&from=2024-05-26&to=2024-06-26&duration=shorterThan5Mins", + "https://www.rsi.ch/play/ricerca?query=test&shows=urn%3Arsi%3Ashow%3Atv%3A704146&topics=urn%3Arsi%3Atopic%3Atv%3A7&duration=shorterThan5Mins", + "https://www.rsi.ch/play/tv/detail/natura?id=42d6d38a-7b95-4ab3-b198-2300934792b0", + "https://www.rsi.ch/play/tv/programma/narcos?id=704026", + "https://www.rsi.ch/play/tv/programma/turbozauros?id=2167444", + "https://www.rsi.ch/play/tv/programma/la-strategia-dellacqua?id=702315", + "https://www.rsi.ch/play/tv/programma/hudson-e-rex?id=2138198", + "https://www.rsi.ch/play/tv/-/video/intervista-a-angelina-mango-altro-che-noia?urn=urn:rsi:video:2177087", + "https://www.rsi.ch/play/tv/-/video/euro-2024-la-rete-dell1-1-di-mattia-zaccagni-in-croazia-italia-24-06-2024?urn=urn:rsi:video:2186168", + ] + + PRODUCTION_URL = 'https://www.rsi.ch/play/v3/api/rsi/production/{production_type}' + URN_URL = 'https://il.srgssr.ch/integrationlayer/2.0/mediaComposition/byUrn/{urn}.json' + TOKEN_URL = 'https://tp.srgssr.ch/akahd/token' + BASE_URL = "https://www.rsi.ch" + + RES_PRIORITY = {"sd": 0, "hd": 1} + PUBLIC_IP = None + PROD_TYPES = ["media-section", "media-section-with-show"] + + @staticmethod + def test_service(): + main_service.run_service(rsi_ch) + + @staticmethod + def get_additional_params(additional): + return [ + ("HEADER", lambda s: s.format(key="X-Forwarded-For", value=rsi_ch.PUBLIC_IP)), + ("MUXER", lambda s: s.format(args="mkv:muxer=mkvmerge")) + ] + + @staticmethod + def is_content_livestream(content, additional): + return additional.get("LIVE", False) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def initialize_service(): + if rsi_ch.PUBLIC_IP is None: + if builtins.CONFIG.get("BASIC", False) is True: + rsi_ch.PUBLIC_IP = "" + else: + rsi_ch.PUBLIC_IP = common_tools.get_public_ip() + if rsi_ch.PUBLIC_IP is None: + raise CustomException(ERR_MSG.format( + type=f'{APP_ERROR}', + url=f'from the {rsi_ch.__name__} service', + reason="Failed to obtain the public IP", + solution="Fix the code responsible for obtaining the IP" + )) + + return rsi_ch + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post(additional["license_url"], data=challenge) + status_code = licence.status_code + try: + assert status_code < 200 or 300 <= status_code + message = json.loads(licence.content.decode())["message"].lower() + assert len(message) > 0 and type(message) is str + except: + message = "" + + if status_code in [403] or "not available" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=additional["content_url"], + reason="Need Swiss IP to make license call", + solution="Use a VPN (that is not detected)" + )) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_video_data(source_element): + urn = parse_qs(urlparse(source_element.url).query)["urn"][0] + response = requests.get(rsi_ch.URN_URL.format(urn=urn)) + status_code = response.status_code + response = json.loads(response.content.decode()) + message = response.get("status", {}) + + if status_code == 404 or message.get("code") == 404 or "not found" in message.get("msg", "").lower(): + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + if source_element.element is None: + titles = [] + for k in ["channel", "show", "episode"]: + if response.get(k, None) not in [None, {}]: + if response[k].get("title", None) not in [None, ""]: + titles.append(response[k]["title"]) + if len(titles) == 0: + video_title = source_element.url.split("?")[0].split("/")[-1] + else: + video_title = "_".join(titles) + + source_element.element = common_tools.get_valid_filename(video_title) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rsi_ch.__name__ + ) + + chapter = list(filter(lambda c: c["urn"] == urn, response.get("chapterList", []))) + if len(chapter) > 0: + chapter = chapter[0] + else: + chapter = response.get("chapterList", [])[0] + + resources = chapter.get("resourceList", []) + resources = list(filter(lambda r: r['protocol'].lower() in ['hls', 'mpd', 'ism', 'dash'], resources)) + resources = sorted(resources, key=lambda r: rsi_ch.RES_PRIORITY[r["quality"].lower()], reverse=True) + if len(resources) == 0: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need Swiss IP to access content", + solution="Use a VPN (that is not detected)" + )) + + content_resource = None + license_url = None + for resource in resources: + drm_list = resource.get("drmList", None) + is_drm = drm_list not in ["", None, []] and type(drm_list) is list + + if is_drm: + for drm in drm_list: + if drm.get("type", "").lower() == "widevine": + content_resource = resource + license_url = drm["licenseUrl"] + break + else: + content_resource = resource + if content_resource is not None: + break + + if content_resource is None: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine wasn't found", + solution="Do not attempt to download it" + )) + + resource = content_resource + manifest = resource["url"] + acl = manifest.split("//")[1].split("?")[0] + acl = re.search(r"(/.+/)", acl).group(1) + "*" + response = json.loads(requests.get(rsi_ch.TOKEN_URL, params={"acl": acl}).content.decode()) + if "?" not in manifest: + manifest += "?" + else: + manifest += "&" + + auth_params = response["token"]["authparams"].split("&") + temp_params = {} + for p in auth_params: + index = p.index("=") + temp_params[p[0:index]] = quote(p[index + 1:], safe='') + auth_params = '&'.join([ + f'{k}={v}' for k, v in temp_params.items() + ]).replace("~", "%7E") + + manifest += auth_params + manifest_content = requests.get(manifest).content.decode() + if ">access denied<" in manifest_content.lower(): + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need Swiss IP to access content", + solution="Use a VPN" + )) + + pssh_values = None + additional = {"LIVE": resource.get("live", False), "content_url": source_element.url} + if license_url is not None: + values = re.findall( + r'>(AAAA[^<>]+)', + manifest_content + ) + pssh_values = [] + for p in values: + if p in pssh_values: + continue + pssh_values.append(p) + additional[p] = {"license_url": license_url, "content_url": source_element.url} + + if len(pssh_values) == 0: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}", + solution=f"Extend the {rsi_ch.__name__} service" + )) + + return manifest, pssh_values, additional + + @staticmethod + def get_handler_series(collection_url): + collection = [] + collection_name = None + content_id = parse_qs(urlparse(collection_url).query)["id"][0] + + response = [{"id": content_id}] + if "/detail/" not in collection_url: + try: + response = json.loads(re.findall( + r'__remixContext[^{}]*({.*?})[^{}]*', + requests.get(collection_url).content.decode(), + re.MULTILINE + )[0])["state"]["loaderData"]["show"]["show"]["urn"] + except: + response = f'urn:rsi:show:tv:{content_id}' + + response = requests.get( + rsi_ch.PRODUCTION_URL.format(production_type='show-page'), + params={'showUrn': response, 'preview': 'false'} + ) + response = response.content.decode() + response = json.loads(response).get("data", {}).get("sections", []) + else: + collection_name = collection_url.split("?")[0].split("/")[-1] + collection_name = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rsi_ch.__name__ + ), + common_tools.get_valid_filename(collection_name) + ) + + if len(response) == 0: + return collection + + section_index = 0 + sections = response + visited = [] + flag_all = False + + for section in sections: + if section["id"] in visited: + continue + visited.append(section["id"]) + section_index += 1 + + check = check_range(True, section_index, None) + if check is True: + continue + elif check is False: + return collection + + section_name = f'Section_{section_index}' + if section.get("representation", {}) not in [None, {}]: + if section["representation"].get("title", "") not in ["", None]: + section_name += "_" + section["representation"]["title"] + section_name = common_tools.get_valid_filename(section_name) + + section_type = section.get("sectionType", "MediaSection") + prod_type = rsi_ch.PROD_TYPES[0] + + if section_type == "MediaSection": + for p in rsi_ch.PROD_TYPES: + response = requests.get( + rsi_ch.PRODUCTION_URL.format(production_type=p), + params={'sectionId': section["id"], 'preview': 'false'} + ) + if 200 <= response.status_code < 300: + prod_type = p + break + else: + if flag_all: + continue + flag_all = True + response = requests.get( + rsi_ch.PRODUCTION_URL.format(production_type="videos-by-show-id"), + params={'showId': content_id} + ) + + video_index = 0 + while True: + response = json.loads(response.content.decode()).get("data", {}) + if type(response) is not dict: + break + videos = response.get("data", []) + if len(videos) == 0: + videos = response.get("medias", []) + if len(videos) == 0: + break + + for video in videos: + if collection_name is None: + titles = [] + for k in ["channel", "show"]: + if video.get(k, None) not in [None, {}]: + if video[k].get("title", None) not in [None, ""]: + titles.append(video[k]["title"]) + + collection_name = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rsi_ch.__name__ + ), + common_tools.get_valid_filename("_".join(titles)) + ) + + if video["urn"] in visited: + continue + visited.append(video["urn"]) + + video_index += 1 + check = check_range(False, section_index, video_index) + if check is True: + continue + elif check is False: + return collection + + video_title = common_tools.get_valid_filename(video["title"]) + video_url = collection_url.split("?")[0].replace("/programma/", "/") + video_url += "/video/" + video_title.replace("_", "-").lower() + video_url += "?urn=" + video["urn"] + + collection.append(BaseElement( + url=video_url, + collection=join(collection_name, section_name), + element=f'Video_{video_index}_{video_title}' + )) + + next_page = response.get("next", None) + if next_page is None: + break + + if section_type == "MediaSection": + response = requests.get( + rsi_ch.PRODUCTION_URL.format(production_type=prod_type), + params={'sectionId': section["id"], 'next': next_page, 'preview': 'false'} + ) + else: + response = requests.get( + rsi_ch.PRODUCTION_URL.format(production_type="videos-by-show-id"), + params={'showId': content_id, 'next': next_page} + ) + + return collection + + @staticmethod + def get_handler_search(collection_url): + collection = [] + collection_name = "Search_" + common_tools.rand_str(4) + + params = parse_qs(urlparse(collection_url).query) + temp_params = {'includeAggregations': 'false', 'mediaType': 'VIDEO'} + for k, v in params.items(): + collection_name += "_" + k + "_" + v[0] + temp_params[k] = v[0] + collection_name = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rsi_ch.__name__ + ), + common_tools.get_valid_filename(collection_name[0:60]) + ) + params = temp_params + + if "query" in params.keys(): + params["searchTerm"] = params["query"] + del params["query"] + + visited = [] + response = requests.get( + rsi_ch.PRODUCTION_URL.format(production_type="search/media"), + params=params + ) + + video_index = 0 + while True: + response = json.loads(response.content.decode()).get("data", {}) + if type(response) is not dict: + break + videos = response.get("results", []) + if len(videos) == 0: + break + + for video in videos: + if video["urn"] in visited: + continue + visited.append(video["urn"]) + + video_index += 1 + check = check_range(False, None, video_index) + if check is True: + continue + elif check is False: + return collection + + video_url = rsi_ch.BASE_URL + "/play/" + video_url += video["show"].get("transmission", video["show"]["urn"].split(":")[-2]).lower() + video_url += "/" + common_tools.get_valid_filename(video["show"]["title"]).lower().replace("_", "-") + + video_title = common_tools.get_valid_filename(video["title"]) + video_url += "/video/" + video_title.replace("_", "-").lower() + video_url += "?urn=" + video["urn"] + + collection.append(BaseElement( + url=video_url, + collection=collection_name, + element=f'Video_{video_index}_{video_title}' + )) + + next_page = response.get("next", None) + if next_page is None: + break + + params["next"] = next_page + response = requests.get( + rsi_ch.PRODUCTION_URL.format(production_type="search/media"), + params=params + ) + + return collection + + @staticmethod + def get_collection_elements(collection_url): + if (rsi_ch.BASE_URL + "/play/") not in collection_url: + return None + collection_url = collection_url.rstrip("/") + + if "/video/" in collection_url and "urn=" in collection_url: + return [BaseElement(url=collection_url)] + + if "id=" in collection_url: + if "/programma/" in collection_url or "/detail/" in collection_url: + return rsi_ch.get_handler_series(collection_url) + + if "/ricerca?" in collection_url: + return rsi_ch.get_handler_search(collection_url) + return None diff --git a/API/proxiesembed/drmproxy/services/rtlplay_be.py b/API/proxiesembed/drmproxy/services/rtlplay_be.py new file mode 100644 index 0000000..e8c03de --- /dev/null +++ b/API/proxiesembed/drmproxy/services/rtlplay_be.py @@ -0,0 +1,407 @@ +import builtins +import json +import re +from os.path import join + +import browser_cookie3 +import requests +from bs4 import BeautifulSoup + +from utils.constants.macros import USER_ERROR, ERR_MSG, APP_ERROR, REQUESTS_TIMEOUT +from utils.main_service import main_service +from utils.structs import BaseElement, CustomException, BaseService +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename, get_ext_from_url, clean_url + + +class rtlplay_be(BaseService): + DEMO_URLS = [ + "https://www.rtlplay.be/rtlplay/player/7f0e4189-2fbd-420a-b9a6-ba2427313bc2", + "https://www.rtlplay.be/rtlplay/player/d0e99c40-1615-49de-a673-4f5080e56d74", + "https://www.rtlplay.be/rtlplay/night-shift~73788600-5c11-4bd0-8001-2ac03a2c606d", + "https://www.rtlplay.be/rtlplay/un-gars-une-fille~988763d8-30ce-418c-9cab-022f0a4bef45", + "https://www.rtlplay.be/rtlplay/the-girlfriend-experience~7d95ecee-a8cf-45e2-be49-f2900cbe705b", + "https://www.rtlplay.be/rtlplay/direct", + "https://www.rtlplay.be/rtlplay/direct/tvi", + "https://www.rtlplay.be/rtlplay/direct/contact", + ] + + CONFIG_URL = 'https://videoplayer-service.dpgmedia.net/play-config/{content_id}' + VIDEO_URL = "https://www.rtlplay.be/rtlplay/player/{video_id}" + BASE_URL = "https://www.rtlplay.be/rtlplay" + + LOGIN_COOKIES = None + USER_AGENT = None + POPCORN_SDK = '8' + + @staticmethod + def test_service(): + main_service.run_service(rtlplay_be) + + @staticmethod + def is_content_livestream(content, additional): + return "/direct/" in content and "/player/" not in content + + @staticmethod + def credentials_needed(): + return {"FIREFOX_COOKIES": True} + + @staticmethod + def get_login_cookies(): + cookie_dict = {} + for c in browser_cookie3.firefox(domain_name='rtlplay.be'): + cookie_dict[c.name] = c.value + + try: + assert len(cookie_dict.keys()) > 0 + assert cookie_dict["lfvp_auth_token"] is not None + return cookie_dict + except: + return None + + @staticmethod + def get_site_data(site_url, is_livestream): + with requests.Session() as session: + response = session.get( + site_url, cookies=rtlplay_be.LOGIN_COOKIES, allow_redirects=False + ).content.decode() + + try: + api_key = re.search(r'apiKey: "([^"]*)"', response).group(1) + except: + api_key = None + + try: + token = re.search(r'token: "([^"]*)"', response).group(1) + except: + token = None + + if is_livestream: + for r1, r2 in [(r"playerData\s*=", "assetId"), (r"channel\s*:", "id")]: + try: + content_id = re.search(r1 + "[^{}]+{([^{}]+)}", response).group(1) + content_id = re.search(r2 + "[^\"']+[\"']([^\"']+)[\"']", content_id).group(1) + assert len(content_id) > 0 + break + except: + content_id = None + else: + content_id = re.search(r"/player/([^/?]*)", site_url).group(1) + return api_key, token, content_id + + @staticmethod + def initialize_service(): + if rtlplay_be.USER_AGENT is None: + rtlplay_be.USER_AGENT = builtins.CONFIG["USER_AGENT"] + + if rtlplay_be.LOGIN_COOKIES is None: + rtlplay_be.LOGIN_COOKIES = rtlplay_be.get_login_cookies() + if rtlplay_be.LOGIN_COOKIES is None: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=f'from {rtlplay_be.__name__}', + reason='Need account for this service', + solution='Sign into your account using Firefox' + )) + + return rtlplay_be + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + additional["license_url"], data=challenge, + headers={"x-dt-auth-token": additional["auth_token"]} + ) + licence.raise_for_status() + return json.loads(licence.content.decode())["license"] + + @staticmethod + def get_video_data(source_element): + is_livestream = "/direct/" in source_element.url and "/player/" not in source_element.url + api_key, bearer_token, content_id = rtlplay_be.get_site_data(source_element.url, is_livestream) + if bearer_token is None: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}/{APP_ERROR}', + url=source_element.url, + reason='This content is no longer available or refresh the site cookies or VPN issues (Belgium)', + solution='Do not attempt to download it or sign into your account using Firefox and play a ' + 'random video or fix your VPN. If it persists then debug the service' + )) + if api_key is None: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}/{APP_ERROR}', + url=f'from {rtlplay_be.__name__}', + reason='Refresh the site cookies', + solution='Sign into your account using Firefox and play a random video. ' + 'If it persists then debug the service' + )) + + try: + response = requests.post( + rtlplay_be.CONFIG_URL.format(content_id=content_id), + json={'deviceType': 'web', 'zone': 'rtlplay'}, + headers={ + 'User-Agent': rtlplay_be.USER_AGENT, + 'x-api-key': api_key, + 'popcorn-sdk-version': rtlplay_be.POPCORN_SDK, + 'authorization': f'Bearer {bearer_token}' + }, + timeout=REQUESTS_TIMEOUT + ) + + if response.status_code == 403: + raise + except: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Timeout most likely due to fake user agent", + solution='Use your real user agent' + )) + + response = json.loads(response.content.decode()) + if response.get("code", None) == 103 and "available" in response.get("type", "").lower(): + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Can't download paid content", + solution='Do not attempt to download it' + )) + if response.get("code", None) == 104 and "found" in response.get("type", "").lower(): + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="This content is no longer available", + solution='Do not attempt to download it' + )) + + response = response["video"] + if source_element.element is None: + metadata = response.get("metadata", {}) + source_element.element = get_valid_filename(( + f'{metadata.get("program", {}).get("title", "Livestream" if is_livestream else "Movie")}' + f'_' + f'{metadata.get("title", source_element.url.split("/")[-1] if is_livestream else content_id)}' + )) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rtlplay_be.__name__ + ) + + additional = {} + manifest = None + is_drm = True + for stream in response["streams"]: + if stream["type"] != "dash" or ".mpd" not in stream["url"]: + continue + manifest = stream["url"] + + drm = stream.get("drm", None) + if drm is None: + is_drm = False + break + + for k in drm: + if "widevine" in k.lower(): + drm = drm[k] + break + + additional["license_url"] = drm["licenseUrl"] + additional["auth_token"] = drm["drmtoday"]["authToken"] + break + + subtitles = [] + index = 0 + for subtitle in response.get("subtitles", []): + index += 1 + srt_ext = get_ext_from_url(subtitle["url"]) + + subtitles.append((False, BaseElement( + url=subtitle["url"], + collection=join(source_element.collection, source_element.element), + element=f'subtitle_{index}_{subtitle["language"]}{srt_ext}' + ))) + additional["SUBTITLES"] = subtitles + + try: + if not is_drm: + raise + pssh_value = str(min(re.findall( + r']*>(.*?)', + requests.get(manifest).content.decode() + ), key=len)) + except: + pssh_value = None + return manifest, pssh_value, additional + + @staticmethod + def get_episode_index(label): + if label is None or len(label) == 0: + return None + label = label.lower() + label = re.sub(r'\s+', ' ', label) + label = label.replace(' ', "_") + for r in ["pisode_(\\d+)", "(\\d+)\\.", "-_(\\d+)", "\\d+"]: + try: + return int(re.findall(r, label)[0]) + except: + pass + return None + + @staticmethod + def handle_live_list(collection_url): + collection = [] + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rtlplay_be.__name__ + ), + get_valid_filename(collection_url.split("/")[-1] + " livestreams") + ) + + with requests.Session() as session: + response = session.get(collection_url, cookies=rtlplay_be.LOGIN_COOKIES).content.decode() + livestreams = re.findall(r'href="([^"]+rtlplay.be/rtlplay/direct/[^"]+)"', response) + if len(livestreams) == 0: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}/{APP_ERROR}', + url=f'from {rtlplay_be.__name__}', + reason='Refresh the site cookies', + solution='Sign into your account using Firefox and play a random video. ' + 'If it persists then debug the service' + )) + + live_index = 0 + for livestream in livestreams: + live_index += 1 + check = check_range(False, None, live_index) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=livestream, + collection=collection_title, + element=get_valid_filename(f"Channel {live_index} {livestream.split('/')[-1]}") + )) + return collection + + @staticmethod + def get_collection_elements(collection_url): + collection_url = clean_url(collection_url).rstrip("/") + if "/rtlplay/" not in collection_url: + return None + if "/player/" in collection_url or "/direct/" in collection_url: + return [BaseElement(url=collection_url)] + if collection_url.endswith("/direct"): + return rtlplay_be.handle_live_list(collection_url) + + if collection_url.split(rtlplay_be.BASE_URL)[1].count("/") == 1 and "~" in collection_url: + collection = [] + series_id = collection_url.split("~")[1] + response = requests.get(collection_url, cookies=rtlplay_be.LOGIN_COOKIES).content.decode() + + matches = re.findall(r'"detail__title"[^>]*>([^<]+) 0: + collection_name = matches[0] + else: + collection_name = series_id + collection_name = get_valid_filename(collection_name) + + matches = re.findall(fr'href="({collection_url}/saison-\d+)["#]', response) + matches = [(m, int(m.split("/saison-")[1])) for m in matches] + matches = sorted(matches, key=lambda m: m[1]) + + indexes = [] + seasons = [] + for season_url, season_index in matches: + if season_index in indexes: + continue + indexes.append(season_index) + seasons.append((season_url, season_index)) + + for season_url, season_index in seasons: + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + response = requests.get(season_url, cookies=rtlplay_be.LOGIN_COOKIES).content.decode() + soup = BeautifulSoup(response, 'html5lib') + episodes_soup = soup.find_all(attrs={'class': 'detail__season'})[0] + episodes_soup = episodes_soup.find_all(attrs={'class': 'list__item'}) + + episodes = [] + for episode_soup in episodes_soup: + episode_soup = episode_soup.find_all(attrs={'class': 'media'}) + if len(episode_soup) == 0: + continue + episode_soup = episode_soup[0] + + episode_name = episode_soup.find_all(attrs={'class': 'media__title'})[0] + try: + temp_url = episode_name.find_all(attrs={'id': True})[0]['id'] + temp_url = temp_url[temp_url.index("-") + 1:] + temp_url = rtlplay_be.VIDEO_URL.format(video_id=temp_url) + except: + temp_url = None + + try: + temp_name = episode_name.find_all('span')[0].find(text=True, recursive=False).strip() + assert len(temp_name) > 0 + except: + temp_name = None + + if temp_name is None: + episode_name = episode_name.find(text=True, recursive=False).strip() + else: + episode_name = temp_name + episode_index = rtlplay_be.get_episode_index(episode_name) + + try: + episode_url = episode_soup.find_all(attrs={'class': 'media__figure-link'})[0] + episode_url = episode_url["href"] + assert "/player/" in episode_url + except: + episode_url = temp_url + episodes.append((episode_url, episode_name, episode_index)) + + episodes = sorted(episodes, key=lambda m: m[2]) + index = 0 + duplicates = [] + for episode_url, episode_name, episode_index in episodes: + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + if episode_url is None: + continue + + if episode_name in duplicates: + index += 1 + index_name = "_" + str(index) + else: + duplicates.append(episode_name) + index_name = "" + + collection.append(BaseElement( + url=episode_url, + collection=join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rtlplay_be.__name__ + ), + join(collection_name, f'Season_{season_index}') + ), + element=f"Episode_{episode_index}" + f"_" + f"{get_valid_filename(episode_name)}" + f"{index_name}" + )) + + return collection + return None diff --git a/API/proxiesembed/drmproxy/services/rtp_pt.py b/API/proxiesembed/drmproxy/services/rtp_pt.py new file mode 100644 index 0000000..bb4b5a6 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/rtp_pt.py @@ -0,0 +1,665 @@ +import base64 +import builtins +import json +import os +import re +import time +from os.path import join +from urllib.parse import unquote + +import m3u8 +import requests +from bs4 import BeautifulSoup +from requests.exceptions import ChunkedEncodingError + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.cdm import get_pssh_from_cenc_pssh, get_pssh_from_default_kid +from utils.tools.common import get_valid_filename, clean_url, get_ext_from_url + + +class rtp_pt(BaseService): + DEMO_URLS = [ + "https://www.rtp.pt/play/p12760/e798080/bem-vindos/1273111", + "https://www.rtp.pt/play/p12795/e742829/matilha", + "https://www.rtp.pt/play/direto/rtpinternacional", + "https://www.rtp.pt/play/direto/antena3", + "https://www.rtp.pt/play/p303/e798812/ultima-edicao", + "https://www.rtp.pt/play/zigzag/p13883/e799760/radar-xs", + "https://www.rtp.pt/play/zigzag/p13605/e799752/vegesaurs", + "https://www.rtp.pt/play/zigzag/direto/radio", + "https://www.rtp.pt/play/zigzag/p3934/e316186/poe-mais-alto", + "https://www.rtp.pt/play/palco/p13432/e769137/por-debaixo-dos-panos-dayse-albuquerque", + "https://www.rtp.pt/play/palco/p12895/e749289/quis-saber-quem-sou-podcast", + "https://www.rtp.pt/play/estudoemcasa/p7783/e501010/matematica-2-ano", + "https://www.rtp.pt/play/p12763/a-prova-dos-factos", + "https://www.rtp.pt/play/p13552/astro-mano", + "https://www.rtp.pt/play/p10654/electromagnetico", + "https://www.rtp.pt/play/zigzag/p10320/o-mundo-do-simao", + "https://www.rtp.pt/play/zigzag/p13866/sempre-atrasados", + "https://www.rtp.pt/play/zigzag/p2759/nacao-valente-personagens-historia", + "https://www.rtp.pt/play/palco/p10973/womex-2022", + "https://www.rtp.pt/play/palco/p305/teatro-sem-fios", + "https://www.rtp.pt/play/estudoemcasa/p7789/matematica-3-e-4-anos", + ] + + BASE_URL = "https://www.rtp.pt" + EPISODES_URL = '{base_path}/bg_l_ep/' + + LICENSE_URL = "https://lic.drmtoday.com/license-proxy-widevine/cenc/" + LICENSE_DATA = "eyJ1c2VySWQiOiJwdXJjaGFzZSIsInNlc3Npb25JZCI6InNlc3Npb25JZCIsIm1lcmNoYW50IjoibW9nX3J0cCJ9" + USER_AGENT = None + RETRIES_COUNT = 5 + RETRIES_TIMER = 5 + + @staticmethod + def test_service(): + main_service.run_service(rtp_pt) + + @staticmethod + def is_content_livestream(content, additional): + return "/direto/" in content + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def initialize_service(): + if rtp_pt.USER_AGENT is None: + rtp_pt.USER_AGENT = builtins.CONFIG["USER_AGENT"] + return rtp_pt + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + rtp_pt.LICENSE_URL, + headers={"x-dt-custom-data": rtp_pt.LICENSE_DATA}, + data=challenge + ) + licence.raise_for_status() + return json.loads(licence.content)["license"] + + @staticmethod + def get_pssh_from_m3u8(m3u8_url, m3u8_content): + m3u8_url = clean_url(m3u8_url) + m3u8_content = m3u8.loads(m3u8_content) + segment_url = m3u8_content.playlists[0].uri + + if not segment_url.startswith("http"): + if not segment_url.startswith("/"): + segment_url = "../" + segment_url + + dots = segment_url.count("../") + temp_base_url = m3u8_url.split("/") + temp_base_url = temp_base_url[0:len(temp_base_url) - dots] + temp_base_url = "/".join(temp_base_url) + + segment_url = segment_url.replace("../", "") + if not segment_url.startswith("/"): + segment_url = "/" + segment_url + segment_url = temp_base_url + segment_url + + for attempt in range(0, rtp_pt.RETRIES_COUNT): + try: + m3u8_content = requests.get( + segment_url, + headers={'User-Agent': rtp_pt.USER_AGENT} + ).content.decode() + break + except ChunkedEncodingError: + if attempt == rtp_pt.RETRIES_COUNT - 1: + raise + time.sleep(rtp_pt.RETRIES_TIMER) + except: + raise + + try: + return re.findall(r'base64,([^"]+)"', m3u8_content)[0] + except: + pass + + key_id = re.findall(r'[?&]keyId=([^&"]+)[&"]', m3u8_content)[0] + return get_pssh_from_default_kid(None, None, key_id) + + @staticmethod + def generate_audio_m3u8(output_path, manifest, content_duration): + m3u8_content = "#EXTM3U\n#EXT-X-VERSION:3\n\n" + m3u8_content += f'#EXTINF:{content_duration},\n' + m3u8_content += f'{manifest}\n' + + m3u8_content += "#EXT-X-ENDLIST\n" + with open(output_path, "w") as f: + f.write(m3u8_content) + + @staticmethod + def generate_master_m3u8(source_element, manifest, content_duration): + output_path = str(join(source_element.collection, source_element.element)) + if not os.path.exists(output_path): + os.makedirs(output_path) + m3u8_content = "#EXTM3U\n#EXT-X-VERSION:3\n\n" + + title = f'audio.m3u8' + rtp_pt.generate_audio_m3u8(join(output_path, title), manifest, content_duration) + m3u8_content += f'#EXT-X-STREAM-INF:BANDWIDTH=1000,TYPE=AUDIO,MIME-TYPE=\"audio/mp3\"\n' + m3u8_content += f'{title}\n' + + output_path = join(output_path, "master.m3u8") + with open(output_path, "w") as f: + f.write(m3u8_content) + return output_path + + @staticmethod + def get_video_data(source_element): + if "/direto/" in source_element.url: + is_live = True + p_id = None + else: + is_live = False + p_id = re.findall(r'/p\d+/', source_element.url)[0] + + response = None + try: + response = source_element.additional["page_html"] + assert response is not None + except: + for attempt in range(0, rtp_pt.RETRIES_COUNT): + try: + response = requests.get( + source_element.url, + headers={'User-Agent': rtp_pt.USER_AGENT} + ) + response = response.text + break + except ChunkedEncodingError: + if attempt == rtp_pt.RETRIES_COUNT - 1: + raise + time.sleep(rtp_pt.RETRIES_TIMER) + except: + raise + + is_drm = "drm: true," in response + for f in ["content_type", "mediaType"]: + try: + content_type = re.findall(fr'{f}[^:]*:[^"]*"([^"]+)"[^,]*,', response) + content_type = content_type[0] + assert type(content_type) is str and content_type not in ["", None] + except: + content_type = None + if content_type is None: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="This content isn't available", + solution='Do not attempt to download it' + )) + + manifest = re.findall(r'atob[^()]*\([^()]*decodeURIComponent[^()]*\([^\[\]]*\[([^\[\]]*)]', response) + temp_manifest = re.findall(r'file[^:]*:[^{}]*{([^{}]+)},', response) + if len(temp_manifest) > 0: + temp_manifest = temp_manifest[0] + if "decodeURIComponent" in temp_manifest: + temp_manifest = "" + temp_manifest = re.findall(r'\w+[^":]*:[^":]*"([^"]+)"', temp_manifest) + manifest += temp_manifest + + temp_manifest = re.findall(r'\w\s*=\s*"(http[^"]+\.[^"]+)";', response) + if len(temp_manifest) == 0: + temp_manifest = re.findall(r'file[^:]*:[^"]*"(http[^"]+\.[^"]+)"', response) + if len(temp_manifest) > 0: + temp_manifest = [temp_manifest[0]] + manifest += temp_manifest + + for m in manifest: + is_valid_url = m.startswith("http") + if is_valid_url: + is_valid_url = get_ext_from_url(m) in [".mpd", ".m3u8", ".mp3"] + + if not is_valid_url: + try: + m = m.replace(" ", "").replace('"', "") + m = ''.join([unquote(chunk) for chunk in m.split(',')]) + m = base64.b64decode(unquote(m)).decode(errors='replace') + except: + continue + + if not m.startswith("http"): + continue + + if content_type == "video": + if p_id is not None and p_id not in m: + continue + is_valid_url = get_ext_from_url(m) in [".mpd", ".m3u8"] + if not is_valid_url: + continue + + elif content_type == "audio": + is_mp3 = get_ext_from_url(m) in [".mp3"] + if is_live and is_mp3: + continue + if not is_live and not is_mp3: + continue + + if is_live and is_drm: + if get_ext_from_url(m) not in [".mpd"]: + continue + if "/drm-fps/" in m: + continue + manifest = m + break + + if type(manifest) is not str: + if is_drm: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine wasn't found", + solution="Do not attempt to download it" + )) + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason="The manifest couldn't be extracted", + solution=f'Debug the {rtp_pt.__name__} service' + )) + + if source_element.element is None: + title = "" + program_info = re.findall(r'program:[^{]*{([^{}]+)}', response) + if len(program_info) == 0: + program_info = None + else: + program_info = program_info[0] + try: + title += re.findall(r'title:[^"]*"([^"]+)"', program_info)[0] + except: + pass + + episode_info = re.findall(r'episode:[^{]*{([^{}]+)}', response) + if len(episode_info) == 0: + episode_info = None + else: + episode_info = episode_info[0] + + for f in ["title", "number", "date", "part"]: + try: + title += " " + re.findall(fr'{f}:[^"]*"([^"]+)"', episode_info)[0] + except: + pass + + if is_live: + channel_info = re.findall(r'channel:[^{]*{([^{}]+)}', response) + if len(channel_info) == 0: + channel_info = None + else: + channel_info = channel_info[0] + try: + title += " " + re.findall(r'name:[^"]*"([^"]+)"', channel_info)[0] + except: + pass + + title = title.strip() + if len(title) == 0: + title = source_element.url.split("/play/")[-1] + source_element.element = get_valid_filename(title) + + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rtp_pt.__name__ + ) + + pssh_value = None + manifest_content = None + if get_ext_from_url(manifest) in [".mpd", ".m3u8"]: + for attempt in range(0, rtp_pt.RETRIES_COUNT): + try: + manifest_content = requests.get( + manifest, + headers={'User-Agent': rtp_pt.USER_AGENT} + ) + break + except ChunkedEncodingError: + if attempt == rtp_pt.RETRIES_COUNT - 1: + raise + time.sleep(rtp_pt.RETRIES_TIMER) + except: + raise + + status_code = manifest_content.status_code + manifest_content = manifest_content.content.decode() + if status_code == 403 or (status_code == 204 and len(manifest_content) == 0): + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need Portuguese IP to access content", + solution="Use a VPN" + )) + + if is_drm or "/drm-" in manifest: + if content_type == "audio": + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}", + solution=f"Extend the {rtp_pt.__name__} service" + )) + + manifest_ext = get_ext_from_url(manifest) + if manifest_ext == ".mpd": + try: + pssh_value = get_pssh_from_cenc_pssh(manifest_content) + except: + pssh_value = None + + if pssh_value is None: + try: + pssh_value = get_pssh_from_default_kid(manifest_content) + except: + pssh_value = None + elif manifest_ext == ".m3u8": + try: + pssh_value = rtp_pt.get_pssh_from_m3u8(manifest, manifest_content) + except: + pssh_value = None + + if pssh_value is None: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}", + solution=f"Extend the {rtp_pt.__name__} service" + )) + + if content_type == "audio" and not is_live: + for f in ["content_duration_complete", "content_duration"]: + content_duration = re.findall(fr'{f}[^:\w]*:[^"]*"([^"]+)"[^,]*,', response) + if len(content_duration) > 0: + content_duration = content_duration[0] + if re.search(r'^\d+$', content_duration) is not None: + break + content_duration = "1" + manifest = rtp_pt.generate_master_m3u8(source_element, manifest, content_duration) + + srts = [] + if content_type == "video": + page_srts = re.findall(r'vtt:[^\[]*(\[\[.*?]]),', response) + else: + page_srts = [] + + if len(page_srts) > 0: + srt_path = join(source_element.collection, source_element.element) + page_srts = page_srts[0] + page_srts = page_srts.replace("]]", "]") + page_srts = re.findall(r"\[('[^\[\]]+')]", page_srts) + + srt_index = 0 + for page_srt in page_srts: + page_srt = re.findall(r"'([^']+)'", page_srt) + srt_url = [s for s in page_srt if s.startswith("http")] + if len(srt_url) == 0: + continue + + srt_index += 1 + srt_url = srt_url[0] + srt_title = [s for s in page_srt if not s.startswith("http")] + if len(srt_title) == 0: + srt_title = [""] + srt_title = f'subtitle_{srt_index} {srt_title[0]}' + + srt_ext = get_ext_from_url(srt_url) + srts.append((False, BaseElement( + url=srt_url, + collection=srt_path, + element=f'{get_valid_filename(srt_title)}{srt_ext}' + ))) + + return manifest, pssh_value, {"SUBTITLES": srts} + + @staticmethod + def get_collection_elements(collection_url): + collection_url = clean_url(collection_url) + if "/play/" not in collection_url: + return None + if "/direto/" in collection_url: + return [BaseElement(url=collection_url)] + + is_video = True + for f in ["p", "e"]: + if re.search(fr'/{f}\d+/', collection_url) is None: + is_video = False + break + if is_video: + return [BaseElement(url=collection_url)] + + program_id = re.findall(r'/p(\d+)/', collection_url) + if len(program_id) == 0: + return None + program_id = program_id[0] + base_endpoint = collection_url.split(f"/p{program_id}")[0] + + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rtp_pt.__name__ + ), + get_valid_filename(collection_url.split("/")[-1]) + ) + + collection = [] + response = None + for attempt in range(0, rtp_pt.RETRIES_COUNT): + try: + response = requests.get( + collection_url, + headers={'User-Agent': rtp_pt.USER_AGENT} + ) + response = response.text + break + except ChunkedEncodingError: + if attempt == rtp_pt.RETRIES_COUNT - 1: + raise + time.sleep(rtp_pt.RETRIES_TIMER) + except: + raise + show_soup = BeautifulSoup(response, 'html5lib') + + seasons = [] + seasons_container = show_soup.find("div", class_=lambda c: c and "seasons-container" in c) + if seasons_container is not None: + seasons_container = seasons_container.find("select", attrs={"onchange": True}) + if seasons_container is not None: + seasons_container = seasons_container.find_all("option", attrs={"value": True}) + if seasons_container is not None and len(seasons_container) == 0: + seasons_container = None + + if seasons_container is not None: + for season_option in seasons_container: + season_id = season_option.get("value", None) + if season_id is None: + continue + season_id = re.findall(r'/p(\d+)/', season_id) + if len(season_id) == 0: + continue + season_id = season_id[0] + seasons.append((season_id, season_option.get_text())) + + if seasons_container is None: + seasons_container = show_soup.find("div", class_=lambda c: c and "seasons-available" in c) + if seasons_container is not None: + seasons_container = seasons_container.find_all( + "a", class_=lambda c: c and "episode-item" in c, + attrs={"href": True} + ) + if seasons_container is not None and len(seasons_container) == 0: + seasons_container = None + + if seasons_container is not None: + for season_a in seasons_container: + season_id = season_a.get("href", None) + if season_id is None: + continue + season_id = re.findall(r'/p(\d+)/', season_id) + if len(season_id) == 0: + continue + season_id = season_id[0] + + season_title = season_a.get("title", "") + if " - " in season_title: + season_title = season_title.split(" - ")[-1] + seasons.append((season_id, season_title)) + + if seasons_container is None: + seasons = [(program_id, "")] + + season_index = 0 + for season_id, season_title in seasons: + season_index += 1 + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + season_title = get_valid_filename(f"S{season_index} {season_title}") + page = 0 + episode_index = 0 + + while True: + page += 1 + for attempt in range(0, rtp_pt.RETRIES_COUNT): + try: + response = requests.get( + rtp_pt.EPISODES_URL.format(base_path=base_endpoint), + headers={'User-Agent': rtp_pt.USER_AGENT}, + params={ + 'listProgram': season_id, 'listtype': 'recent', + 'page': page + } + ) + response = response.text + break + except ChunkedEncodingError: + if attempt == rtp_pt.RETRIES_COUNT - 1: + raise + time.sleep(rtp_pt.RETRIES_TIMER) + except: + raise + + episodes_soup = BeautifulSoup(response, 'html5lib') + episode_nodes = episodes_soup.find_all("article", attrs={"class": True}) + if len(episode_nodes) == 0: + break + + for episode_node in episode_nodes: + episode_a = episode_node.find("a", class_=lambda c: c and "episode-item" in c, attrs={"href": True}) + if episode_a is None: + continue + + try: + episode_url = episode_a["href"] + if not episode_url.startswith("http"): + episode_url = rtp_pt.BASE_URL + episode_url + except: + continue + + episode_index += 1 + check1 = check_range(False, season_index, episode_index) + check2 = check_range(False, season_index, episode_index + 1) + if check1 is True and check2 is True: + continue + elif check1 is False and check2 is False: + return collection + + episode_title = "" + visited_text = [] + try: + episode_title = episode_a["title"] + if " - " in episode_title: + episode_title = episode_title.split(" - ")[-1] + visited_text.append(get_valid_filename(episode_title)) + else: + episode_title = "" + except: + pass + + metadata = episode_a.find("div", class_=lambda c: c and "article-meta-data" in c) + if metadata is not None: + for meta_node in metadata.find_all(recursive=True): + meta_class = meta_node.get("class", None) + if meta_class is None: + continue + + for f in ["episode-title", "episode", "episode-date"]: + if f in meta_class: + meta_text = meta_node.get_text() + tmp_text = get_valid_filename(meta_text) + + is_visited = False + for txt in visited_text: + if tmp_text is None: + break + if txt in tmp_text or tmp_text in txt: + is_visited = True + break + if is_visited: + continue + + episode_title += " " + meta_text + visited_text.append(get_valid_filename(meta_text)) + + if episode_title == "": + episode_title = episode_url.split("/play/")[-1] + episode_page = None + + for attempt in range(0, rtp_pt.RETRIES_COUNT): + try: + episode_page = requests.get( + episode_url, + headers={'User-Agent': rtp_pt.USER_AGENT} + ) + episode_page = episode_page.text + break + except ChunkedEncodingError: + if attempt == rtp_pt.RETRIES_COUNT - 1: + raise + time.sleep(rtp_pt.RETRIES_TIMER) + except: + raise + + episode_parts_soup = BeautifulSoup(episode_page, 'html5lib') + episode_parts = episode_parts_soup.find("div", lambda c: c and "section-parts" in c) + if episode_parts is None: + episode_parts = [] + else: + episode_parts = episode_parts.find_all("a", {"href": True}) + + part_index = 1 + parts = [(part_index, episode_url, episode_page)] + for episode_part in episode_parts: + try: + part_url = episode_part["href"] + if not part_url.startswith("http"): + part_url = rtp_pt.BASE_URL + part_url + except: + continue + part_index += 1 + parts.append((part_index, part_url, None)) + + for part_index, part_url, part_page in parts: + content_index = episode_index + part_index * 0.01 + check = check_range(False, season_index, content_index) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=part_url, + collection=join(collection_title, season_title), + element=get_valid_filename(f'E{episode_index}P{part_index} {episode_title}'), + additional={"page_html": part_page} + )) + return collection diff --git a/API/proxiesembed/drmproxy/services/rts_ch.py b/API/proxiesembed/drmproxy/services/rts_ch.py new file mode 100644 index 0000000..6c06574 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/rts_ch.py @@ -0,0 +1,458 @@ +import builtins +import json +import re +from os.path import join +from urllib.parse import urlparse, parse_qs, quote + +import requests + +import utils.tools.common as common_tools +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range + + +class rts_ch(BaseService): + DEMO_URLS = [ + "https://www.rts.ch/play/tv/doc-portrait/video/les-dents-de-la-mer-un-succes-monstre?urn=urn:rts:video:15483865", + "https://www.rts.ch/play/tv/19h30-signe/video/19h30-signe?urn=urn:rts:video:15507141", + "https://www.rts.ch/play/recherche?query=football&shows=urn%3Arts%3Ashow%3Atv%3A3437925&topics=urn%3Arts%3Atopic%3Atv%3A10193", + "https://www.rts.ch/play/tv/detail/les-films-jeunesse?id=5f7793fc-7a30-4da7-bbf5-3f95855f7963", + "https://www.rts.ch/play/tv/detail/lactu-la-plus-recente?id=0c5ea90b-2faa-4733-bf91-170466b1038a", + "https://www.rts.ch/play/tv/emission/les-pique-meurons?id=1799044", + "https://www.rts.ch/play/tv/emission/animalis?id=8055962", + ] + + PRODUCTION_URL = 'https://www.rts.ch/play/v3/api/rts/production/{production_type}' + URN_URL = 'https://il.srgssr.ch/integrationlayer/2.0/mediaComposition/byUrn/{urn}.json' + TOKEN_URL = 'https://tp.srgssr.ch/akahd/token' + BASE_URL = "https://www.rts.ch" + + RES_PRIORITY = {"sd": 0, "hd": 1} + PUBLIC_IP = None + PROD_TYPES = ["media-section", "media-section-with-show"] + + @staticmethod + def test_service(): + main_service.run_service(rts_ch) + + @staticmethod + def get_additional_params(additional): + return [ + ("HEADER", lambda s: s.format(key="X-Forwarded-For", value=rts_ch.PUBLIC_IP)), + ("MUXER", lambda s: s.format(args="mkv:muxer=mkvmerge")) + ] + + @staticmethod + def is_content_livestream(content, additional): + return additional.get("LIVE", False) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def initialize_service(): + if rts_ch.PUBLIC_IP is None: + if builtins.CONFIG.get("BASIC", False) is True: + rts_ch.PUBLIC_IP = "" + else: + rts_ch.PUBLIC_IP = common_tools.get_public_ip() + if rts_ch.PUBLIC_IP is None: + raise CustomException(ERR_MSG.format( + type=f'{APP_ERROR}', + url=f'from the {rts_ch.__name__} service', + reason="Failed to obtain the public IP", + solution="Fix the code responsible for obtaining the IP" + )) + + return rts_ch + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post(additional["license_url"], data=challenge) + status_code = licence.status_code + try: + assert status_code < 200 or 300 <= status_code + message = json.loads(licence.content.decode())["message"].lower() + assert len(message) > 0 and type(message) is str + except: + message = "" + + if status_code in [403] or "not available" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=additional["content_url"], + reason="Need Swiss IP to make license call", + solution="Use a VPN (that is not detected)" + )) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_video_data(source_element): + urn = parse_qs(urlparse(source_element.url).query)["urn"][0] + response = requests.get(rts_ch.URN_URL.format(urn=urn)) + status_code = response.status_code + response = json.loads(response.content.decode()) + message = response.get("status", {}) + + if status_code == 404 or message.get("code") == 404 or "not found" in message.get("msg", "").lower(): + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + if source_element.element is None: + titles = [] + for k in ["channel", "show", "episode"]: + if response.get(k, None) not in [None, {}]: + if response[k].get("title", None) not in [None, ""]: + titles.append(response[k]["title"]) + if len(titles) == 0: + video_title = source_element.url.split("?")[0].split("/")[-1] + else: + video_title = "_".join(titles) + + source_element.element = common_tools.get_valid_filename(video_title) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rts_ch.__name__ + ) + + chapter = list(filter(lambda c: c["urn"] == urn, response.get("chapterList", []))) + if len(chapter) > 0: + chapter = chapter[0] + else: + chapter = response.get("chapterList", [])[0] + + resources = chapter.get("resourceList", []) + resources = list(filter(lambda r: r['protocol'].lower() in ['hls', 'mpd', 'ism', 'dash'], resources)) + resources = sorted(resources, key=lambda r: rts_ch.RES_PRIORITY[r["quality"].lower()], reverse=True) + if len(resources) == 0: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need Swiss IP to access content", + solution="Use a VPN (that is not detected)" + )) + + content_resource = None + license_url = None + for resource in resources: + drm_list = resource.get("drmList", None) + is_drm = drm_list not in ["", None, []] and type(drm_list) is list + + if is_drm: + for drm in drm_list: + if drm.get("type", "").lower() == "widevine": + content_resource = resource + license_url = drm["licenseUrl"] + break + else: + content_resource = resource + if content_resource is not None: + break + + if content_resource is None: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine wasn't found", + solution="Do not attempt to download it" + )) + + resource = content_resource + manifest = resource["url"] + acl = manifest.split("//")[1].split("?")[0] + acl = re.search(r"(/.+/)", acl).group(1) + "*" + response = json.loads(requests.get(rts_ch.TOKEN_URL, params={"acl": acl}).content.decode()) + if "?" not in manifest: + manifest += "?" + else: + manifest += "&" + + auth_params = response["token"]["authparams"].split("&") + temp_params = {} + for p in auth_params: + index = p.index("=") + temp_params[p[0:index]] = quote(p[index + 1:], safe='') + auth_params = '&'.join([ + f'{k}={v}' for k, v in temp_params.items() + ]).replace("~", "%7E") + + manifest += auth_params + manifest_content = requests.get(manifest).content.decode() + if ">access denied<" in manifest_content.lower(): + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need Swiss IP to access content", + solution="Use a VPN (that is not detected)" + )) + + pssh_values = None + additional = {"LIVE": resource.get("live", False), "content_url": source_element.url} + if license_url is not None: + values = re.findall( + r'>(AAAA[^<>]+)', + manifest_content + ) + pssh_values = [] + for p in values: + if p in pssh_values: + continue + pssh_values.append(p) + additional[p] = {"license_url": license_url, "content_url": source_element.url} + + if len(pssh_values) == 0: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}", + solution=f"Extend the {rts_ch.__name__} service" + )) + + return manifest, pssh_values, additional + + @staticmethod + def get_handler_series(collection_url): + collection = [] + collection_name = None + content_id = parse_qs(urlparse(collection_url).query)["id"][0] + + response = [{"id": content_id}] + if "/detail/" not in collection_url: + try: + response = json.loads(re.findall( + r'__remixContext[^{}]*({.*?})[^{}]*', + requests.get(collection_url).content.decode(), + re.MULTILINE + )[0])["state"]["loaderData"]["show"]["show"]["urn"] + except: + response = f'urn:rts:show:tv:{content_id}' + + response = requests.get( + rts_ch.PRODUCTION_URL.format(production_type='show-page'), + params={'showUrn': response, 'preview': 'false'} + ) + response = response.content.decode() + response = json.loads(response).get("data", {}).get("sections", []) + else: + collection_name = collection_url.split("?")[0].split("/")[-1] + collection_name = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rts_ch.__name__ + ), + common_tools.get_valid_filename(collection_name) + ) + + if len(response) == 0: + return collection + + section_index = 0 + sections = response + visited = [] + flag_all = False + + for section in sections: + if section["id"] in visited: + continue + visited.append(section["id"]) + section_index += 1 + + check = check_range(True, section_index, None) + if check is True: + continue + elif check is False: + return collection + + section_name = f'Section_{section_index}' + if section.get("representation", {}) not in [None, {}]: + if section["representation"].get("title", "") not in ["", None]: + section_name += "_" + section["representation"]["title"] + section_name = common_tools.get_valid_filename(section_name) + section_type = section.get("sectionType", "MediaSection") + prod_type = rts_ch.PROD_TYPES[0] + + if section_type == "MediaSection": + for p in rts_ch.PROD_TYPES: + response = requests.get( + rts_ch.PRODUCTION_URL.format(production_type=p), + params={'sectionId': section["id"], 'preview': 'false'} + ) + if 200 <= response.status_code < 300: + prod_type = p + break + else: + if flag_all: + continue + flag_all = True + response = requests.get( + rts_ch.PRODUCTION_URL.format(production_type="videos-by-show-id"), + params={'showId': content_id} + ) + + video_index = 0 + while True: + response = json.loads(response.content.decode()).get("data", {}) + if type(response) is not dict: + break + videos = response.get("data", []) + if len(videos) == 0: + videos = response.get("medias", []) + if len(videos) == 0: + break + + for video in videos: + if collection_name is None: + titles = [] + for k in ["channel", "show"]: + if video.get(k, None) not in [None, {}]: + if video[k].get("title", None) not in [None, ""]: + titles.append(video[k]["title"]) + + collection_name = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rts_ch.__name__ + ), + common_tools.get_valid_filename("_".join(titles)) + ) + + if video["urn"] in visited: + continue + visited.append(video["urn"]) + + video_index += 1 + check = check_range(False, section_index, video_index) + if check is True: + continue + elif check is False: + return collection + + video_title = common_tools.get_valid_filename(video["title"]) + video_url = collection_url.split("?")[0].replace("/programma/", "/") + video_url += "/video/" + video_title.replace("_", "-").lower() + video_url += "?urn=" + video["urn"] + + collection.append(BaseElement( + url=video_url, + collection=join(collection_name, section_name), + element=f'Video_{video_index}_{video_title}' + )) + + next_page = response.get("next", None) + if next_page is None: + break + + if section_type == "MediaSection": + response = requests.get( + rts_ch.PRODUCTION_URL.format(production_type=prod_type), + params={'sectionId': section["id"], 'next': next_page, 'preview': 'false'} + ) + else: + response = requests.get( + rts_ch.PRODUCTION_URL.format(production_type="videos-by-show-id"), + params={'showId': content_id, 'next': next_page} + ) + + return collection + + @staticmethod + def get_handler_search(collection_url): + collection = [] + collection_name = "Search_" + common_tools.rand_str(4) + + params = parse_qs(urlparse(collection_url).query) + temp_params = {'includeAggregations': 'false', 'mediaType': 'VIDEO'} + for k, v in params.items(): + collection_name += "_" + k + "_" + v[0] + temp_params[k] = v[0] + collection_name = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rts_ch.__name__ + ), + common_tools.get_valid_filename(collection_name[0:60]) + ) + params = temp_params + + if "query" in params.keys(): + params["searchTerm"] = params["query"] + del params["query"] + + visited = [] + response = requests.get( + rts_ch.PRODUCTION_URL.format(production_type="search/media"), + params=params + ) + + video_index = 0 + while True: + response = json.loads(response.content.decode()).get("data", {}) + if type(response) is not dict: + break + videos = response.get("results", []) + if len(videos) == 0: + break + + for video in videos: + if video["urn"] in visited: + continue + visited.append(video["urn"]) + + video_index += 1 + check = check_range(False, None, video_index) + if check is True: + continue + elif check is False: + return collection + + video_url = rts_ch.BASE_URL + "/play/" + video_url += video["show"].get("transmission", video["show"]["urn"].split(":")[-2]).lower() + video_url += "/" + common_tools.get_valid_filename(video["show"]["title"]).lower().replace("_", "-") + + video_title = common_tools.get_valid_filename(video["title"]) + video_url += "/video/" + video_title.replace("_", "-").lower() + video_url += "?urn=" + video["urn"] + + collection.append(BaseElement( + url=video_url, + collection=collection_name, + element=f'Video_{video_index}_{video_title}' + )) + + next_page = response.get("next", None) + if next_page is None: + break + + params["next"] = next_page + response = requests.get( + rts_ch.PRODUCTION_URL.format(production_type="search/media"), + params=params + ) + + return collection + + @staticmethod + def get_collection_elements(collection_url): + if (rts_ch.BASE_URL + "/play/") not in collection_url: + return None + collection_url = collection_url.rstrip("/") + + if "/video/" in collection_url and "urn=" in collection_url: + return [BaseElement(url=collection_url)] + + if "id=" in collection_url: + if "/emission/" in collection_url or "/detail/" in collection_url: + return rts_ch.get_handler_series(collection_url) + + if "/recherche?" in collection_url: + return rts_ch.get_handler_search(collection_url) + return None diff --git a/API/proxiesembed/drmproxy/services/rtve_es.py b/API/proxiesembed/drmproxy/services/rtve_es.py new file mode 100644 index 0000000..f54740d --- /dev/null +++ b/API/proxiesembed/drmproxy/services/rtve_es.py @@ -0,0 +1,528 @@ +import base64 +import builtins +import json +import os +import re +from os.path import join + +import requests +from bs4 import BeautifulSoup + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.cdm import get_pssh_from_cenc_pssh +from utils.tools.common import clean_url, get_valid_filename, get_ext_from_url + + +class rtve_es(BaseService): + DEMO_URLS = [ + "https://www.rtve.es/play/videos/valle-salvaje/episodio-8/16259694/", + "https://www.rtve.es/play/videos/telediario-2/inteligencia-artificial-centra-debates-davos-entre-lideres-empresariales-expertos/16421776/", + "https://www.rtve.es/play/videos/valle-salvaje/", + "https://www.rtve.es/play/videos/los-pilares-del-tiempo/", + ] + + ZTNR_URL = "https://ztnr.rtve.es/ztnr" + MANIFEST_RED_URL = ZTNR_URL + "/{asset_id}.{manifest_type}" + MANIFEST_PNG_URL = ZTNR_URL + "/movil/thumbnail/rtveplayw/videos/{asset_id}.png" + VIDEO_INFO_URL = "https://api-ztnr.rtve.es/api/videos/{asset_id}.json" + TOKEN_URL = "https://api.rtve.es/api/token/{asset_id}" + SUBTITLES_URL = "https://api2.rtve.es/api/videos/{asset_id}/subtitulos.json" + BASE_URL = "https://www.rtve.es" + + MANIFEST_FORMATS = ["mpd", "mp4", "m3u8"] + NON_MANIFEST_TYPES = ["mp4"] + ALLOWED_COLLECTIONS = ["capitulos", "clips"] + + @staticmethod + def test_service(): + main_service.run_service(rtve_es) + + @staticmethod + def get_additional_params(additional): + additional_params = BaseService.get_additional_params(additional) + manifest_url = additional.get("manifest_url", None) + if manifest_url is not None: + manifest_url = clean_url(manifest_url) + additional_params = [( + "BASE_URL", lambda s: s.format(value=manifest_url) + )] + additional_params + return additional_params + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def initialize_service(): + return rtve_es + + @staticmethod + def get_keys(challenge, additional): + headers = {} + if additional.get("drm_token", None) not in ["", None]: + headers = {"x-axdrm-message": additional["drm_token"]} + licence = requests.post( + additional["license_url"], data=challenge, + headers=headers + ) + licence.raise_for_status() + return licence.content + + @staticmethod + def read_byte(data, state): + if state['bits_length'] == 0: + if state['position'] >= len(data): + return -1 + state['bits'] = data[state['position']] + state['position'] += 1 + state['bits_length'] = 8 + + state['bits_length'] -= 8 + return (state['bits'] >> state['bits_length']) & 0xFF + + @staticmethod + def skip(data, state, count): + for _ in range(count): + rtve_es.read_byte(data, state) + + @staticmethod + def read_chunk(data, state): + bytes_data = data[state['position']:state['position'] + 4] + state['position'] += 4 + length = int.from_bytes(bytes_data, byteorder='big') + + chunk_type = '' + for _ in range(4): + byte = rtve_es.read_byte(data, state) + char = None if byte == -1 else chr(byte) + + if not char: + break + chunk_type += char + + chunk_data = [0] * length + index = 0 + while index < length: + byte = rtve_es.read_byte(data, state) + if byte == -1: + break + chunk_data[index] = byte + index += 1 + assert index == length + + rtve_es.skip(data, state, 4) + return {'type': chunk_type, 'data': chunk_data} + + @staticmethod + def translate(input_string): + sources = [] + data = base64.b64decode(input_string) + state = {'position': 0, 'bits': 0, 'bits_length': 0} + rtve_es.skip(data, state, 8) + chunk = rtve_es.read_chunk(data, state) + + while chunk['type'] != 'IEND': + if chunk['type'] == 'tEXt': + text = ''.join(chr(byte) for byte in chunk['data'] if byte != 0) + text = text if '%%' not in text else text.split('#')[0] + '#' + text.split('#')[1].split('%%')[1] + item = text + + hash_index = item.index('#') + text = item[:hash_index] + alphabet = '' + char_index = 0 + step = 0 + for i in range(len(text)): + if step == 0: + alphabet += text[i] + char_index = (char_index + 1) % 4 + step = char_index + else: + step -= 1 + + text = item[hash_index + 1:] + decoded = '' + char_index = 0 + position = 3 + counter = 1 + number = 0 + + for i in range(len(text)): + if char_index == 0: + number = int(text[i]) * 10 + char_index = 1 + else: + if position == 0: + number += int(text[i]) + decoded += alphabet[number] + position = (counter + 3) % 4 + char_index = 0 + counter += 1 + else: + position -= 1 + + sources.append(decoded) + chunk = rtve_es.read_chunk(data, state) + return sources + + @staticmethod + def fix_manifest(source_element, manifest_url, manifest_content, asset_content, manifest_type): + is_valid_manifest = manifest_type not in rtve_es.NON_MANIFEST_TYPES + if builtins.CONFIG.get("BASIC", False) is True and is_valid_manifest: + return manifest_url + if manifest_type in ["m3u8"]: + return manifest_url + + output_path = str(join(source_element.collection, source_element.element)) + if not os.path.exists(output_path): + os.makedirs(output_path) + + if not is_valid_manifest: + output_path = join(output_path, 'video.m3u8') + content_duration = asset_content.get("duration", 1000) + m3u8_content = "#EXTM3U\n#EXT-X-VERSION:3\n\n" + m3u8_content += f'#EXTINF:{content_duration / 1000},\n' + m3u8_content += f'{manifest_url}\n' + + m3u8_content += "#EXT-X-ENDLIST\n" + with open(output_path, "w") as f: + f.write(m3u8_content) + return output_path + + output_path = join(output_path, f'master.{manifest_type}') + with open(output_path, "w") as f: + f.write(manifest_content) + return output_path + + @staticmethod + def get_video_data(source_element): + try: + asset_id = source_element.url.split("/")[-1] + assert asset_id.isdigit() + except: + asset_id = None + if asset_id is None: + response = requests.get(source_element.url).text + try: + asset_id = re.findall(r'\s*data-idasset=[\s\'"]*([^\s,\'"L<>]+)', response)[0].lower() + except: + asset_id = None + + if asset_id is None: + asset_id = re.findall(r'[\'"]idAsset[\'"]:[\'"\s]*([^\s,\'"]+)', response)[0].lower() + + response = requests.get(rtve_es.VIDEO_INFO_URL.format(asset_id=asset_id)) + response = json.loads(response.content.decode()) + try: + response = response["page"]["items"] + assert len(response) > 0 + except: + response = [] + + asset_content = None + for item in response: + if item.get("id", "") != asset_id: + continue + asset_content = item + + if asset_content is None: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + if source_element.element is None: + title = "" + for f in ["longTitle", "title", "shortTitle"]: + if asset_content.get(f, None) not in ["", None]: + title = asset_content[f] + break + + if len(title) == 0: + title = f"Video {asset_id}" + source_element.element = get_valid_filename(title) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rtve_es.__name__ + ) + + has_drm = asset_content.get("hasDRM", False) + try: + png_manifests = rtve_es.translate(requests.get( + rtve_es.MANIFEST_PNG_URL.format(asset_id=asset_id) + ).text) + except: + png_manifests = [] + + asset_manifest = None + manifest_content = None + asset_type = None + for manifest_type in rtve_es.MANIFEST_FORMATS: + if asset_manifest is not None: + break + is_valid_manifest = manifest_type not in rtve_es.NON_MANIFEST_TYPES + + possible_manifests = [rtve_es.MANIFEST_RED_URL.format(asset_id=asset_id, manifest_type=manifest_type)] + for png_manifest in png_manifests: + temp_manifest = clean_url(png_manifest).split(".")[-1] + if f"{manifest_type}" in temp_manifest: + possible_manifests += [png_manifest] + break + + for manifest_url in possible_manifests: + status_code = requests.head(manifest_url).status_code + if 300 <= status_code < 400: + response = requests.get(manifest_url, allow_redirects=False) + manifest_url = response.headers.get("location", None) + status_code = requests.head(manifest_url).status_code + + if status_code == 403: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need Spanish IP to access content", + solution="Use a VPN" + )) + + if 200 <= status_code < 300: + if is_valid_manifest: + manifest_content = requests.get(manifest_url).text + asset_manifest = manifest_url + asset_type = manifest_type + break + + if asset_manifest is None: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + if asset_manifest in png_manifests: + has_drm = "_drm" in asset_manifest + additional = {} + is_valid_manifest = asset_type not in rtve_es.NON_MANIFEST_TYPES + pssh_value = None + + if has_drm: + if is_valid_manifest: + try: + pssh_value = get_pssh_from_cenc_pssh(manifest_content) + except: + pssh_value = None + + response = requests.get(rtve_es.TOKEN_URL.format(asset_id=asset_id)) + response = json.loads(response.content.decode()) + try: + license_url = response["widevineURL"] + assert license_url not in ["", None] + except: + license_url = None + + if license_url is None: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine wasn't found", + solution="Do not attempt to download it" + )) + + if "AxDrmMessage=" not in license_url: + additional["drm_token"] = response["token"] + license_url = clean_url(license_url) + additional["license_url"] = license_url + + if pssh_value is None: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {asset_manifest}", + solution=f"Extend the {rtve_es.__name__} service" + )) + + original_manifest = asset_manifest + asset_manifest = rtve_es.fix_manifest( + source_element, asset_manifest, manifest_content, + asset_content, asset_type + ) + if original_manifest != asset_manifest and is_valid_manifest: + additional["manifest_url"] = original_manifest + + try: + response = requests.get(rtve_es.SUBTITLES_URL.format(asset_id=asset_id)) + response = json.loads(response.content.decode()) + subtitles = response["page"]["items"] + assert len(subtitles) > 0 + except: + subtitles = [] + + srt_index = 0 + srts = [] + srt_path = join(source_element.collection, source_element.element) + for subtitle in subtitles: + try: + srt_index += 1 + srt_url = subtitle['src'] + assert srt_url.startswith("http") + + srt_title = subtitle.get("lang", "") + srt_title = f'subtitle_{srt_index} {srt_title}' + + srts.append((False, BaseElement( + url=srt_url, + collection=srt_path, + element=f'{get_valid_filename(srt_title)}{get_ext_from_url(srt_url)}' + ))) + except: + pass + + additional["SUBTITLES"] = srts + return asset_manifest, pssh_value, additional + + @staticmethod + def get_collection_elements(collection_url): + collection_url = clean_url(collection_url) + if "/play/videos/" not in collection_url: + return None + if "/play/videos/directo/" in collection_url: + return None + slash = collection_url.split("/play/videos/")[1].count("/") + + if slash >= 2: + return [BaseElement(url=collection_url)] + + collection_title = collection_url.split("/play/videos/")[1].split("/")[0] + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rtve_es.__name__ + ), + get_valid_filename(collection_title) + ) + + page_response = requests.get(collection_url).text + page_soup = BeautifulSoup(page_response, 'html5lib') + + modulos = page_soup.find_all( + 'a', + attrs={'data-module': lambda x: x and "/modulos/" in x} + ) + modulo_elements = [] + for modulo in modulos: + modulo_type = None + for a in rtve_es.ALLOWED_COLLECTIONS: + if f'/{a}/' in modulo["data-module"]: + modulo_type = a + break + if modulo_type is None: + continue + + modulo_url = modulo["data-module"] + if not modulo_url.startswith("http"): + modulo_url = rtve_es.BASE_URL + modulo_url + modulo_name = modulo.getText().strip() + modulo_elements.append((modulo_url, modulo_name, modulo_type)) + + seasons = [] + for modulo_url, modulo_name, modulo_type in modulo_elements: + modulo_response = requests.get(modulo_url).text + modulo_soup = BeautifulSoup(modulo_response, 'html5lib') + sub_modulos = modulo_soup.find_all( + 'a', + attrs={'href': lambda x: x and f"/modulos/{modulo_type}/" in x} + ) + + sub_modulo_elements = [] + for s in sub_modulos: + sub_modulo_url = s["href"] + if not sub_modulo_url.startswith("http"): + sub_modulo_url = rtve_es.BASE_URL + sub_modulo_url + sub_modulo_name = s.getText().strip() + sub_modulo_elements.append((sub_modulo_url, sub_modulo_name)) + + if len(sub_modulo_elements) == 0: + seasons.append((modulo_url, modulo_name)) + else: + seasons.extend(sub_modulo_elements) + + season_index = 0 + collection = [] + for season_url, season_name in seasons: + season_index += 1 + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + season_name = get_valid_filename(f'Season {season_index} {season_name}') + page_index = 0 + episode_index = 0 + visited = [] + episode_stop = False + + while not episode_stop: + page_index += 1 + episodes_response = requests.get( + season_url, params={"page": page_index} + ) + episodes_soup = BeautifulSoup(episodes_response.text, 'html5lib') + + status_code = episodes_response.status_code + episodes = episodes_soup.find_all( + 'a', + attrs={'href': lambda x: x and f"{rtve_es.BASE_URL}/play/videos/" in x} + ) + + if len(episodes) == 0 or status_code < 200 or status_code >= 300: + break + + for episode in episodes: + episode_url = episode["href"] + if episode_url in visited: + episode_stop = True + break + visited.append(episode_url) + + episode_index += 1 + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + try: + episode_id = clean_url(episode_url).split("/")[-1] + assert episode_id.isdigit() + except: + episode_id = None + + episode_name = "" + if episode_id is not None: + data_share = episodes_soup.find_all( + lambda tag: tag.has_attr('data-idasset') and + tag['data-idasset'] == episode_id and + tag.has_attr('data-share') + ) + + try: + episode_name = json.loads(data_share[0]["data-share"])["contentTitle"] + assert len(episode_name) > 0 + except: + episode_name = "" + + episode_name = get_valid_filename(f'Episode {episode_index} {episode_name}') + collection.append(BaseElement( + url=episode_url, + collection=join(collection_title, season_name), + element=episode_name + )) + + return collection diff --git a/API/proxiesembed/drmproxy/services/rugbypass_tv.py b/API/proxiesembed/drmproxy/services/rugbypass_tv.py new file mode 100644 index 0000000..4e81368 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/rugbypass_tv.py @@ -0,0 +1,667 @@ +import builtins +import json +import os +import re +import threading +from os.path import join + +import m3u8 +import requests + +from utils.constants.macros import CACHE_DIR, ERR_MSG, USER_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import clean_url, get_valid_filename, dict_to_file, file_to_dict + + +class rugbypass_tv(BaseService): + DEMO_URLS = [ + "https://rugbypass.tv/video/505498?seasonId=17639", + "https://rugbypass.tv/video/693898?t=0", + "https://rugbypass.tv/video/645717?t=0", + "https://rugbypass.tv/playlist/24405", + "https://rugbypass.tv/playlist/20513", + "https://rugbypass.tv/playlist/22440", + "https://rugbypass.tv/series/985", + "https://rugbypass.tv/series/981", + "https://rugbypass.tv/series/984", + "https://rugbypass.tv/section/SVNS", + "https://rugbypass.tv/section/Womens%20Home", + "https://rugbypass.tv/section/IRELAND", + ] + + REALM_URL = 'https://dce-frontoffice.imggaming.com/api/v1/init/' + LOGIN_URL = 'https://dce-frontoffice.imggaming.com/api/v2/login' + REFRESH_URL = 'https://dce-frontoffice.imggaming.com/api/v2/token/refresh' + VOD_URL = 'https://dce-frontoffice.imggaming.com/api/v4/vod/{vod_id}' + PLAYLIST_URL = 'https://dce-frontoffice.imggaming.com/api/v4/playlist/{playlist_id}' + EPISODES_URL = 'https://dce-frontoffice.imggaming.com/api/v4/season/{season_id}' + SEASONS_URL = 'https://dce-frontoffice.imggaming.com/api/v4/series/{series_id}' + BUCKETS_URL = 'https://dce-frontoffice.imggaming.com/api/v4/content/{section_id}' + BUCKET_VODS_URL = 'https://dce-frontoffice.imggaming.com/api/v4/content/{section_id}/bucket/{bucket_id}' + BASE_URL = "https://rugbypass.tv" + VIDEO_URL = BASE_URL + "/video/{vod_id}" + + EMAIL = "YOUR_EMAIL" + PASSWORD = "YOUR_PASSWORD" + SITE_DICT = None + CACHE_FILE = None + LOCK = None + PAGE_SIZE = 25 + BUCKET_SIZE = 10 + + @staticmethod + def test_service(): + main_service.run_service(rugbypass_tv) + + @staticmethod + def get_additional_params(additional): + add_params = BaseService.get_additional_params(additional) + if additional.get("USE_BASE_URL", False) is True: + add_params += [("BASE_URL", lambda s: s.format(value=additional["MANIFEST_URL"]))] + return add_params + + @staticmethod + def credentials_needed(): + return { + "EMAIL": rugbypass_tv.EMAIL, + "PASSWORD": rugbypass_tv.PASSWORD + } + + @staticmethod + def refresh_account_tokens(source_url): + old_auth_token = rugbypass_tv.SITE_DICT["AUTH_TOKEN"] + with rugbypass_tv.LOCK: + if old_auth_token == rugbypass_tv.SITE_DICT["AUTH_TOKEN"]: + response = requests.post( + rugbypass_tv.REFRESH_URL, + headers={ + 'realm': rugbypass_tv.SITE_DICT["REALM_ID"], + 'x-api-key': rugbypass_tv.SITE_DICT["REALM_API_KEY"], + 'Authorization': f'Bearer {rugbypass_tv.SITE_DICT["AUTH_TOKEN"]}' + }, + json={'refreshToken': rugbypass_tv.SITE_DICT["REFRESH_TOKEN"]} + ) + response = response.content.decode() + response = json.loads(response) + + if response.get("authorisationToken", None) in ["", None]: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_url, + reason="Can't access the video content because the cached information expired", + solution=f'Delete the {rugbypass_tv.CACHE_FILE} cache manually or add the parameter --fresh to your command' + )) + + rugbypass_tv.SITE_DICT["AUTH_TOKEN"] = response["authorisationToken"] + dict_to_file(rugbypass_tv.CACHE_FILE, rugbypass_tv.SITE_DICT) + + @staticmethod + def set_site_dict(): + try: + file_dict = file_to_dict(rugbypass_tv.CACHE_FILE) + assert len(file_dict.keys()) == 4 + rugbypass_tv.SITE_DICT = file_dict + return True + except: + pass + + class_name = rugbypass_tv.__name__.replace("_", ".") + credentials = builtins.CONFIG["SERVICE_CREDENTIALS"][class_name] + try: + assert type(credentials["EMAIL"]) is str + assert type(credentials["PASSWORD"]) is str + except: + return None + + response = requests.get(rugbypass_tv.BASE_URL).content.decode() + app_js = re.findall(r'src="([^"]*app\.js)"', response)[0] + if app_js[0] != "/": + app_js = "/" + app_js + app_js = rugbypass_tv.BASE_URL + app_js + response = requests.get(app_js).content.decode() + realm_api_key = re.findall(r'API_KEY:"([^"]+)"', response)[0] + + response = requests.get( + rugbypass_tv.REALM_URL, + headers={ + 'x-api-key': realm_api_key, + 'Origin': rugbypass_tv.BASE_URL + } + ) + response = response.content.decode() + response = json.loads(response) + realm_id = response["settings"]["realm"] + + response = requests.post( + rugbypass_tv.LOGIN_URL, + headers={ + 'x-api-key': realm_api_key, 'Realm': realm_id, + 'Authorization': f'Bearer {response["authentication"]["authorisationToken"]}' + }, + json={ + 'id': credentials["EMAIL"], + 'secret': credentials["PASSWORD"] + } + ) + response = response.content.decode() + response = json.loads(response) + message = str(response.get("messages", [])).lower() + if response.get("status", "") in [404] and response.get("code", "").lower() in ["not_found"]: + if "failedauthentication" in message: + return None + + site_dict = { + "REALM_ID": realm_id, + "REALM_API_KEY": realm_api_key, + "AUTH_TOKEN": response["authorisationToken"], + "REFRESH_TOKEN": response["refreshToken"] + } + dict_to_file(rugbypass_tv.CACHE_FILE, site_dict) + rugbypass_tv.SITE_DICT = site_dict + return True + + @staticmethod + def initialize_service(): + if rugbypass_tv.CACHE_FILE is None: + rugbypass_tv.CACHE_FILE = join(CACHE_DIR, f'{rugbypass_tv.__name__}.json') + if builtins.CONFIG.get("FRESH", False) is True: + dict_to_file(rugbypass_tv.CACHE_FILE, {}) + + if rugbypass_tv.SITE_DICT is None: + flag = rugbypass_tv.set_site_dict() + if flag is None: + return flag + if rugbypass_tv.LOCK is None: + rugbypass_tv.LOCK = threading.Lock() + return rugbypass_tv + + @staticmethod + def get_keys(challenge, additional): + raise Exception( + f'{BaseService.get_keys.__name__} must not be called ' + f'for the {rugbypass_tv.__name__} service' + ) + + @staticmethod + def generate_master_file(output_path, manifest, manifest_type): + manifest_content = requests.get(manifest).content.decode() + if not os.path.exists(output_path): + os.makedirs(output_path) + + if manifest_type not in ["hls"]: + output_path = join(output_path, "master.mpd") + with open(output_path, "w") as f: + f.write(manifest_content) + return output_path + + base_url = clean_url(manifest).split("/") + del base_url[-1] + base_url = "/".join(base_url) + + manifest_content = m3u8.loads(manifest_content) + for segment in manifest_content.playlists + manifest_content.media + manifest_content.segments: + if not segment.uri.startswith("http"): + if segment.uri.startswith("/"): + segment.uri = ".." + segment.uri + + dots = segment.uri.count("../") + temp_base_url = base_url.split("/") + temp_base_url = temp_base_url[0:len(temp_base_url) - dots] + temp_base_url = "/".join(temp_base_url) + + segment.uri = segment.uri.replace("../", "") + if not segment.uri.startswith("/"): + segment.uri = "/" + segment.uri + segment.uri = temp_base_url + segment.uri + + output_path = join(output_path, "master.m3u8") + with open(output_path, "w") as f: + f.write(manifest_content.dumps()) + return output_path + + @staticmethod + def get_video_data(source_element): + vod_id = re.search(r"/video/([^/?]*)", source_element.url).group(1) + response = {} + + for i in range(0, 2): + response = requests.get( + rugbypass_tv.VOD_URL.format(vod_id=vod_id), + params={'includePlaybackDetails': 'URL'}, + headers={ + 'realm': rugbypass_tv.SITE_DICT["REALM_ID"], + 'x-api-key': rugbypass_tv.SITE_DICT["REALM_API_KEY"], + 'Authorization': f'Bearer {rugbypass_tv.SITE_DICT["AUTH_TOKEN"]}' + } + ) + response = response.content.decode() + response = json.loads(response) + + message = str(response.get("messages", [])).lower() + if 400 <= response.get("status", 200) < 500 and " not found" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + if response.get("playerUrlCallback", None) in ["", None]: + if i == 1: + break + rugbypass_tv.refresh_account_tokens(source_element.url) + continue + break + + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rugbypass_tv.__name__ + ) + if source_element.element is None: + title = response.get("title", f'Video_{vod_id}') + info = response.get("episodeInformation", {}) + for f in ["seasonNumber", "episodeNumber"]: + try: + assert info[f] not in ["", None] + title += " " + f[0].upper() + str(info[f]) + except: + pass + source_element.element = get_valid_filename(title) + + response = requests.get(response["playerUrlCallback"]) + response = response.content.decode() + response = json.loads(response) + + manifest = None + manifest_type = None + for f in ["hls", "dash"]: + try: + manifest = response[f][0]["url"] + assert manifest not in ["", None] + manifest_type = f + break + except: + pass + + additional = { + "USE_BASE_URL": manifest_type in ["dash"], + "MANIFEST_URL": clean_url(manifest) + } + manifest = rugbypass_tv.generate_master_file( + join(source_element.collection, source_element.element), + manifest, manifest_type + ) + return manifest, None, additional + + @staticmethod + def get_playlist(collection_url): + playlist_id = re.search(r"/playlist/([^/?]*)", collection_url).group(1) + response = {} + last_seen = None + collection_title = None + + collection = [] + vod_index = 0 + while True: + playlist_params = {'rpp': rugbypass_tv.PAGE_SIZE} + if last_seen is not None: + playlist_params["lastSeen"] = last_seen + + for i in range(0, 2): + response = requests.get( + rugbypass_tv.PLAYLIST_URL.format(playlist_id=playlist_id), + params=playlist_params, + headers={ + 'realm': rugbypass_tv.SITE_DICT["REALM_ID"], + 'x-api-key': rugbypass_tv.SITE_DICT["REALM_API_KEY"], + 'Authorization': f'Bearer {rugbypass_tv.SITE_DICT["AUTH_TOKEN"]}' + } + ) + response = response.content.decode() + response = json.loads(response) + + if response.get("code", None) in ["UNAUTHORIZED"]: + if i == 1: + break + rugbypass_tv.refresh_account_tokens(collection_url) + continue + break + + vods = response.get("vods", []) + if len(vods) == 0: + break + + if collection_title is None: + collection_title = response.get("title", f'Playlist_{playlist_id}') + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rugbypass_tv.__name__ + ), + get_valid_filename(collection_title) + ) + + for vod in vods: + vod_index += 1 + check = check_range(False, None, vod_index) + if check is True: + continue + elif check is False: + return collection + + if vod.get("type", "").lower() not in ["vod"]: + continue + vod_url = rugbypass_tv.VIDEO_URL.format(vod_id=vod["id"]) + vod_title = vod.get("title", vod["id"]) + vod_title = f'Vod_{vod_index}_{vod_title}' + + collection.append(BaseElement( + url=vod_url, + collection=collection_title, + element=get_valid_filename(vod_title) + )) + + paging = response.get("paging", {}) + if paging in ["", None]: + break + if paging.get("moreDataAvailable", False) in [None, False]: + break + last_seen = paging.get("lastSeen", None) + if last_seen is None: + break + + return collection + + @staticmethod + def get_series(collection_url): + series_id = re.search(r"/series/([^/?]*)", collection_url).group(1) + seasons_response = {} + seasons_last_seen = None + collection_title = None + + collection = [] + season_index = 0 + while True: + seasons_params = {'rpp': rugbypass_tv.PAGE_SIZE} + if seasons_last_seen is not None: + seasons_params["lastSeen"] = seasons_last_seen + + for i in range(0, 2): + seasons_response = requests.get( + rugbypass_tv.SEASONS_URL.format(series_id=series_id), + params=seasons_params, + headers={ + 'realm': rugbypass_tv.SITE_DICT["REALM_ID"], + 'x-api-key': rugbypass_tv.SITE_DICT["REALM_API_KEY"], + 'Authorization': f'Bearer {rugbypass_tv.SITE_DICT["AUTH_TOKEN"]}' + } + ) + seasons_response = seasons_response.content.decode() + seasons_response = json.loads(seasons_response) + + if seasons_response.get("code", None) in ["UNAUTHORIZED"]: + if i == 1: + break + rugbypass_tv.refresh_account_tokens(collection_url) + continue + break + + seasons = seasons_response.get("seasons", []) + if len(seasons) == 0: + break + + if collection_title is None: + collection_title = seasons_response.get("title", f'Series_{series_id}') + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rugbypass_tv.__name__ + ), + get_valid_filename(collection_title) + ) + + for season in seasons: + season_index += 1 + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + season_title = f'S{season_index} {season.get("title", "")}' + season_title = get_valid_filename(season_title) + season_id = season["id"] + + episodes_response = {} + episodes_last_seen = None + episode_index = 0 + while True: + episodes_params = {'rpp': rugbypass_tv.PAGE_SIZE} + if episodes_last_seen is not None: + episodes_params["lastSeen"] = episodes_last_seen + + for i in range(0, 2): + episodes_response = requests.get( + rugbypass_tv.EPISODES_URL.format(season_id=season_id), + params=seasons_params, + headers={ + 'realm': rugbypass_tv.SITE_DICT["REALM_ID"], + 'x-api-key': rugbypass_tv.SITE_DICT["REALM_API_KEY"], + 'Authorization': f'Bearer {rugbypass_tv.SITE_DICT["AUTH_TOKEN"]}' + } + ) + episodes_response = episodes_response.content.decode() + episodes_response = json.loads(episodes_response) + + if episodes_response.get("code", None) in ["UNAUTHORIZED"]: + if i == 1: + break + rugbypass_tv.refresh_account_tokens(collection_url) + continue + break + + episodes = episodes_response.get("episodes", []) + if len(episodes) == 0: + break + + for episode in episodes: + episode_index += 1 + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + if episode.get("type", "").lower() not in ["vod"]: + continue + episode_url = rugbypass_tv.VIDEO_URL.format(vod_id=episode["id"]) + episode_title = episode.get("title", episode["id"]) + episode_title = f'E{episode_index}_{episode_title}' + + collection.append(BaseElement( + url=episode_url, + collection=join(collection_title, season_title), + element=get_valid_filename(episode_title) + )) + + episodes_paging = episodes_response.get("paging", {}) + if episodes_paging in ["", None]: + break + if episodes_paging.get("moreDataAvailable", False) in [None, False]: + break + episodes_last_seen = episodes_paging.get("lastSeen", None) + if episodes_last_seen is None: + break + + seasons_paging = seasons_response.get("paging", {}) + if seasons_paging in ["", None]: + break + if seasons_paging.get("moreDataAvailable", False) in [None, False]: + break + seasons_last_seen = seasons_paging.get("lastSeen", None) + if seasons_last_seen is None: + break + + return collection + + @staticmethod + def get_section(collection_url): + section_id = collection_url.split("/")[-1] + buckets_response = {} + buckets_last_seen = None + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + rugbypass_tv.__name__ + ), + get_valid_filename(f"Section {section_id}") + ) + + collection = [] + bucket_index = 0 + while True: + buckets_params = { + 'bpp': rugbypass_tv.BUCKET_SIZE, + 'rpp': rugbypass_tv.PAGE_SIZE, + 'displaySectionLinkBuckets': 'SHOW', + 'displayEpgBuckets': 'HIDE', + 'displayEmptyBucketShortcuts': 'SHOW', + 'displayContentAvailableOnSignIn': 'SHOW', + 'displayGeoblocked': 'SHOW', + 'bspp': rugbypass_tv.BUCKET_SIZE + } + if buckets_last_seen is not None: + buckets_params["lastSeen"] = buckets_last_seen + + for i in range(0, 2): + buckets_response = requests.get( + rugbypass_tv.BUCKETS_URL.format(section_id=section_id), + params=buckets_params, + headers={ + 'realm': rugbypass_tv.SITE_DICT["REALM_ID"], + 'x-api-key': rugbypass_tv.SITE_DICT["REALM_API_KEY"], + 'Authorization': f'Bearer {rugbypass_tv.SITE_DICT["AUTH_TOKEN"]}' + } + ) + buckets_response = buckets_response.content.decode() + buckets_response = json.loads(buckets_response) + + if buckets_response.get("code", None) in ["UNAUTHORIZED"]: + if i == 1: + break + rugbypass_tv.refresh_account_tokens(collection_url) + continue + break + + buckets = buckets_response.get("buckets", []) + if len(buckets) == 0: + break + + for bucket in buckets: + bucket_index += 1 + check = check_range(True, bucket_index, None) + if check is True: + continue + elif check is False: + return collection + + bucket_type = bucket.get("type", "").lower() + if "vod" not in bucket_type and "video" not in bucket_type: + continue + + bucket_title = bucket.get("name", bucket.get("rowTypeData", {}).get("title", "")) + bucket_title = get_valid_filename(f'Rail {bucket_index} {bucket_title}') + bucket_id = bucket["exid"] + + vods_response = {} + vods_last_seen = None + vod_index = 0 + while True: + vods_params = { + 'rpp': rugbypass_tv.PAGE_SIZE, + 'displayContentAvailableOnSignIn': 'SHOW', + 'displayGeoblocked': 'SHOW' + } + if vods_last_seen is not None: + vods_params["lastSeen"] = vods_last_seen + + for i in range(0, 2): + vods_response = requests.get( + rugbypass_tv.BUCKET_VODS_URL.format(section_id=section_id, bucket_id=bucket_id), + params=vods_params, + headers={ + 'realm': rugbypass_tv.SITE_DICT["REALM_ID"], + 'x-api-key': rugbypass_tv.SITE_DICT["REALM_API_KEY"], + 'Authorization': f'Bearer {rugbypass_tv.SITE_DICT["AUTH_TOKEN"]}' + } + ) + vods_response = vods_response.content.decode() + vods_response = json.loads(vods_response) + + if vods_response.get("code", None) in ["UNAUTHORIZED"]: + if i == 1: + break + rugbypass_tv.refresh_account_tokens(collection_url) + continue + break + + vods = vods_response.get("contentList", []) + if len(vods) == 0: + break + + for vod in vods: + vod_index += 1 + check = check_range(False, bucket_index, vod_index) + if check is True: + continue + elif check is False: + return collection + + if vod.get("type", "").lower() not in ["vod"]: + continue + vod_url = rugbypass_tv.VIDEO_URL.format(vod_id=vod["id"]) + vod_title = vod.get("title", vod["id"]) + vod_title = f'Vod_{vod_index}_{vod_title}' + + collection.append(BaseElement( + url=vod_url, + collection=join(collection_title, bucket_title), + element=get_valid_filename(vod_title) + )) + + vods_paging = vods_response.get("paging", {}) + if vods_paging in ["", None]: + break + if vods_paging.get("moreDataAvailable", False) in [None, False]: + break + vods_last_seen = vods_paging.get("lastSeen", None) + if vods_last_seen is None: + break + + buckets_paging = buckets_response.get("paging", {}) + if buckets_paging in ["", None]: + break + if buckets_paging.get("moreDataAvailable", False) in [None, False]: + break + buckets_last_seen = buckets_paging.get("lastSeen", None) + if buckets_last_seen is None: + break + + return collection + + @staticmethod + def get_collection_elements(collection_url): + collection_url = clean_url(collection_url) + if "/video/" in collection_url: + return [BaseElement(url=collection_url)] + + if "/playlist/" in collection_url: + return rugbypass_tv.get_playlist(collection_url) + if "/series/" in collection_url: + return rugbypass_tv.get_series(collection_url) + if "/section/" in collection_url: + return rugbypass_tv.get_section(collection_url) + return None diff --git a/API/proxiesembed/drmproxy/services/shahid_mbc_net.py b/API/proxiesembed/drmproxy/services/shahid_mbc_net.py new file mode 100644 index 0000000..01ba198 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/shahid_mbc_net.py @@ -0,0 +1,338 @@ +import binascii +import builtins +import hashlib +import hmac +import json +import re +import time +from os.path import join + +import requests + +from utils.constants.macros import ERR_MSG, APP_ERROR, CACHE_DIR, USER_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import dict_to_file, file_to_dict, get_valid_filename, clean_url + + +class shahid_mbc_net(BaseService): + DEMO_URLS = [ + "https://shahid.mbc.net/en/shows/Ma'-Al-Mestikawy/show-88548", + "https://shahid.mbc.net/en/series/Leh%20Laa!-season-1/season-413520-413521", + "https://shahid.mbc.net/en/player/episodes/Standup-Sketch-season-1-episode-1/id-921243", + "https://shahid.mbc.net/en/player/movies/Special-Interview/id-979254", + "https://shahid.mbc.net/ar/player/episodes/%D9%85%D9%81%D8%AA%D8%B1%D9%82-%D8%B7%D8%B1%D9%82-%D8%A7%D9%84%D9%85%D9%88%D8%B3%D9%85-1-%D8%A7%D9%84%D8%AD%D9%84%D9%82%D8%A9-1/id-1027258", + "https://shahid.mbc.net/en/livestream/MBC-Masr/livechannel-387290", + "https://shahid.mbc.net/en/livestream/MBC-Drama/livechannel-387251", + ] + + DRM_URL = 'https://api3.shahid.net/proxy/v2.1/playout/new/drm' + MANIFEST_URL = 'https://api3.shahid.net/proxy/v2.1/playout/new/url/{id}' + ASSET_URL = 'https://api3.shahid.net/proxy/v2.1/playableAsset' + PLAYLIST_URL = 'https://api3.shahid.net/proxy/v2.1/product/playlist' + CHUNK_JS_URL = 'https://shahid.mbc.net/streaming-pages/_next/static/chunks/{chunk}' + BASE_URL = 'https://shahid.mbc.net' + + CACHE_FILE = None + SITE_INFO = None + COUNTRY = "ARE" + PAGE_SIZE = 25 + + @staticmethod + def test_service(): + main_service.run_service(shahid_mbc_net) + + @staticmethod + def is_content_livestream(content, additional): + return "/livestream/" in content + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def get_site_info(): + try: + file_dict = file_to_dict(shahid_mbc_net.CACHE_FILE) + assert len(file_dict.keys()) == 2 + return file_dict + except: + pass + + response = requests.get(shahid_mbc_net.CHUNK_JS_URL.format(chunk="remoteEntry.js")).content.decode() + response = re.search(r'"static/chunks/"(.*?)"\.js"', response).group(1) + + response = re.findall(r'(\d+):"([^"]+)"', response) + for r in response: + if not bool(re.search(r"\d", r[1])): + continue + + response = requests.get(shahid_mbc_net.CHUNK_JS_URL.format(chunk=f"{r[0]}.{r[1]}.js")).content.decode() + try: + site_info = { + "BROWSER_VERSION": re.search(r'BROWSER_VERSION="([^\"]+)"', response).group(1), + "SECRET_KEY": max(re.findall(r'{let t="([^\"]+)";', response), key=len), + # "BROWSER_VERSION": "50.0.0", + # "SECRET_KEY": "z3qQSk17nbajIYUF0dU5f4+O/CxjFizcsEJr9ejOYFw=", + } + + dict_to_file(shahid_mbc_net.CACHE_FILE, site_info) + return site_info + except: + pass + raise "Failed to extract site information" + + @staticmethod + def initialize_service(): + if shahid_mbc_net.CACHE_FILE is None: + shahid_mbc_net.CACHE_FILE = join(CACHE_DIR, f'{shahid_mbc_net.__name__}.json') + if builtins.CONFIG.get("FRESH", False) is True: + dict_to_file(shahid_mbc_net.CACHE_FILE, {}) + + if shahid_mbc_net.SITE_INFO is None: + shahid_mbc_net.SITE_INFO = shahid_mbc_net.get_site_info() + return shahid_mbc_net + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post(additional["license_url"], data=challenge) + licence.raise_for_status() + return licence.content + + @staticmethod + def generate_auth(auth_params): + return binascii.hexlify(hmac.new( + shahid_mbc_net.SITE_INFO["SECRET_KEY"].encode('utf-8'), + ";".join( + f"{k}={auth_params[k]}" + for k in sorted(auth_params.keys()) + ).encode('utf-8'), + hashlib.sha256 + ).digest()).decode('utf-8') + + @staticmethod + def get_video_data(source_element): + asset_type = "/id-" + if "/livestream/" in source_element.url: + asset_type = "/livechannel-" + + asset_id = re.search(fr"{asset_type}([^/?#]+)", source_element.url).group(1) + if source_element.element is None: + source_element.element = f"VideoId_{asset_id}" + if "/ar/" not in source_element.url: + source_element.element = source_element.url.split(asset_type)[0].split("/")[-1] + source_element.element = get_valid_filename(source_element.element) + + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + shahid_mbc_net.__name__ + ) + + response = json.loads(requests.get( + shahid_mbc_net.MANIFEST_URL.format(id=asset_id), + params={'outputParameter': 'vmap', 'country': shahid_mbc_net.COUNTRY} + ).content.decode()) + status_code = response.get("responseCode", None) + + message = str(response).lower() + if status_code == 404: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Don't attempt to download it" + )) + if status_code == 401 and ("vpn" in message or "proxy" in message): + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The VPN was detected", + solution="Get a better VPN or don't use one" + )) + if status_code == 422 and "subscriber" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need Emirati IP to access content or it is paid content", + solution="Use a VPN or don't attempt to download it" + )) + + response = response["playout"] + manifest = clean_url(response["url"]).split("&")[0] + license_url = None + pssh_value = None + if response.get("drm", False) is False: + return manifest, pssh_value, {"license_url": license_url} + + auth_params = { + 'country': shahid_mbc_net.COUNTRY, 'ts': int(time.time() * 1000), + 'request': json.dumps({"assetId": asset_id}) + } + response = json.loads(requests.get( + shahid_mbc_net.DRM_URL, params=auth_params, + headers={ + 'SHAHID_OS': 'WINDOWS', 'BROWSER_NAME': 'CHROME', + 'BROWSER_VERSION': shahid_mbc_net.SITE_INFO["BROWSER_VERSION"], + 'Authorization': shahid_mbc_net.generate_auth(auth_params) + } + ).content.decode()) + + status_code = response.get("responseCode", None) + if status_code == 403: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Can't access the video content because the secret key was changed", + solution=f'Delete the {shahid_mbc_net.CACHE_FILE} cache manually or add the parameter --fresh to your command' + )) + + license_url = response["signature"] + try: + pssh_value = str(min( + re.findall( + r']*>(.*?)', + requests.get(manifest).content.decode() + ), key=len + )) + except: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Couldn't extract PSSH. Manifest not supported: {manifest}", + solution=f"Extend the {shahid_mbc_net.__name__} service" + )) + + return manifest, pssh_value, {"license_url": license_url} + + @staticmethod + def get_series_handler(collection_url): + site_language = collection_url.split(shahid_mbc_net.BASE_URL + "/")[1].split("/")[0] + site_language = shahid_mbc_net.BASE_URL + "/" + site_language + "/" + + collection = [] + response = json.loads(re.findall( + r'type="application/json"[^<>]*>({.*?})', + requests.get(collection_url).content.decode() + )[0])["props"]["pageProps"]["response"]["productModel"]["show"] + + collection_name = None + if "/ar/" not in collection_url: + collection_name = response.get("title", None) + if collection_name is None: + if "/ar/" not in collection_url: + if "-season-" in collection_url: + collection_name = collection_url.split("-season-")[0].split("/")[-1] + elif "/show-" in collection_url: + collection_name = collection_url.split("/show-")[0].split("/")[-1] + else: + collection_name = collection_url.split("/")[-2] + else: + collection_name = collection_url.split("/")[-1] + collection_name = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + shahid_mbc_net.__name__ + ), + get_valid_filename(collection_name) + ) + + seasons = response.get("seasons", []) + seasons = sorted(seasons, key=lambda s: int(s["seasonNumber"])) + if len(seasons) == 0: + return [] + extra_season_index = int(seasons[-1]["seasonNumber"]) + + for season in seasons: + extra_season_index += 1 + season_index = int(season["seasonNumber"]) + + playlists = season.get("EXTRA_CONTENT", None) + if playlists is None: + response = json.loads(requests.get( + shahid_mbc_net.ASSET_URL, + params={ + 'request': json.dumps({"seasonId": str(season["id"])}), + 'country': shahid_mbc_net.COUNTRY + } + ).content.decode())["productModel"] + playlist = response["playlist"] + + playlists = response.get("show", {}).get("season", {}).get("playlists", []) + playlists = filter(lambda p: p["id"] != playlist["id"], playlists) + playlists = sorted(playlists, key=lambda p: p["id"]) + + seasons.append({ + "seasonNumber": extra_season_index, + "EXTRA_CONTENT": playlists + }) + playlists = [playlist] + + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + extra_episode_index = 0 + for playlist in playlists: + page = -1 + while True: + page += 1 + + episodes = json.loads(requests.get( + shahid_mbc_net.PLAYLIST_URL, + params={ + 'request': json.dumps({ + "pageNumber": page, "pageSize": shahid_mbc_net.PAGE_SIZE, + "playListId": playlist["id"], "isDynamicPlaylist": False, + "sorts": [{"order": "DESC", "type": "SORTDATE"}] + }), + 'country': shahid_mbc_net.COUNTRY + } + ).content.decode()).get("productList", {}).get("products", []) + + if len(episodes) == 0: + break + + for episode in episodes: + extra_episode_index += 1 + if season.get("EXTRA_CONTENT", None) is not None: + episode["number"] = extra_episode_index + + check = check_range(False, season_index, int(episode["number"])) + if check in [True, False]: + continue + + episode_urls = episode.get("productUrls", []) + [episode.get("productUrl", {})] + episode_url = None + for url in episode_urls: + if url["url"].startswith(site_language): + episode_url = url["url"] + break + + collection.append(BaseElement( + url=episode_url, + collection=join( + collection_name, + f'Season_{season_index}_{get_valid_filename(playlist["type"].lower())}' + ), + element=f'Episode_{episode["number"]}' + )) + + return collection + + @staticmethod + def get_collection_elements(collection_url): + collection_url = collection_url.rstrip("/") + + if "/player/" in collection_url and "/id-" in collection_url: + return [BaseElement(url=collection_url)] + if "/livestream/" in collection_url and "/livechannel-" in collection_url: + return [BaseElement(url=collection_url)] + + if "/series/" in collection_url or "/shows/" in collection_url: + return shahid_mbc_net.get_series_handler(collection_url) + + return None diff --git a/API/proxiesembed/drmproxy/services/stirr_com.py b/API/proxiesembed/drmproxy/services/stirr_com.py new file mode 100644 index 0000000..000dcba --- /dev/null +++ b/API/proxiesembed/drmproxy/services/stirr_com.py @@ -0,0 +1,247 @@ +import builtins +import json +import re +from os.path import join +from urllib.parse import parse_qs, urlparse + +import requests + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename, clean_url + + +class stirr_com(BaseService): + DEMO_URLS = [ + "https://stirr.com/watch/5726/nautical-channel", + "https://stirr.com/watch/5691/the-surprising-world-of-rabbits", + "https://stirr.com/watch/6423/the-bagman-official-trailer", + "https://stirr.com/watch/6134/of-souls-plus-water-the-elder", + "https://stirr.com/watch/4246?type=series&series_id=174&season_id=238", + "https://stirr.com/live?channel_id=5735", + "https://stirr.com/tv-shows/174/beyond-the-beaten-path", + "https://stirr.com/tv-shows/170/epic-trails", + ] + + PLAYABLE_URL = 'https://stirr.com/api/v2/videos/{video_id}/playable' + SERIES_URL = 'https://stirr.com/api/series/list/{series_id}' + SEASONS_URL = 'https://stirr.com/api/season/list/{series_id}' + EPISODES_URL = 'https://stirr.com/api/season/data?series_id={series_id}&season_id={season_id}&page={page}&paginate=1' + EPISODE_URL = "https://stirr.com/watch/{video_id}" + BASE_URL = 'https://stirr.com' + + @staticmethod + def test_service(): + main_service.run_service(stirr_com) + + @staticmethod + def is_content_livestream(content, additional): + return "/live?channel_id=" in content or additional.get("IS_LIVE", False) is True + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def initialize_service(): + return stirr_com + + @staticmethod + def get_keys(challenge, additional): + raise Exception( + f'{BaseService.get_keys.__name__} must not be called ' + f'for the {stirr_com.__name__} service' + ) + + @staticmethod + def get_video_data(source_element): + if "/live?channel_id" in source_element.url: + is_live = True + params_dict = parse_qs(urlparse(source_element.url).query) + video_id = params_dict["channel_id"][0] + else: + is_live = None + video_id = re.search(r"/watch/([^/?]*)", source_element.url).group(1) + response = requests.post(stirr_com.PLAYABLE_URL.format(video_id=video_id)) + + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + error = response.get("error_code", "").lower() + message = response.get("message", "").lower() + + if status_code == 403 and "region" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need American IP to access content", + solution="Use a VPN" + )) + + if 400 <= status_code < 500 or "video_not_found" in error: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + response = response["data"] + if type(response) is not list: + response = [response] + response = [r for r in response if str(r["content"]["videoid"]) == video_id][0] + if is_live is None: + is_live = response["content"].get("content_type_label", "").lower() in ["live"] + + if source_element.element is None: + title = response["content"].get("title", None) + if title in ["", None]: + title = source_element.url.split("/")[-1] + + if is_live: + title = f'Livestream_{title}' + source_element.element = get_valid_filename(title) + + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + stirr_com.__name__ + ) + + if response["content"].get("drm_protected", "").lower() not in ["", "no"]: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine found", + solution=f"Extend the {stirr_com.__name__} service" + )) + + manifest = None + if manifest is None: + for k, f in [("media", None), ("_media", "src"), ("media_v2", "url")]: + if response.get(k, []) not in [None, []]: + if type(response[k]) is not list: + response[k] = [response[k]] + + manifest = response[k][0] + if f is not None: + manifest = manifest.get(f, None) + if manifest is not None: + break + + if manifest is None and is_live: + manifest = response["content"]["live"] + assert manifest not in [None, ""] + return manifest, None, {"IS_LIVE": is_live} + + @staticmethod + def get_collection_elements(collection_url): + if "/watch/" in collection_url or "/live?channel_id=" in collection_url: + return [BaseElement(url=collection_url)] + if "/tv-shows/" not in collection_url: + return None + + collection_url = clean_url(collection_url) + series_id = re.search(r"/tv-shows/([^/?]*)", collection_url).group(1) + response = requests.get(stirr_com.SERIES_URL.format(series_id=series_id)) + + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + message = response.get("message", "").lower() + + if 400 <= status_code < 500 and "found" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + collection_name = None + for series in response.get("series", {}).get("series_by_id", []): + if str(series["series_id"]) != series_id: + continue + + collection_name = series.get("series_name", None) + if collection_name not in ["", None]: + break + + if collection_name in ["", None]: + collection_name = collection_url.split("/")[-1] + collection_name = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + stirr_com.__name__ + ), + get_valid_filename(collection_name) + ) + + response = requests.get(stirr_com.SEASONS_URL.format(series_id=series_id)) + response = response.content.decode() + response = json.loads(response) + seasons = response.get("data", {}).get("seasons", []) + seasons = sorted(seasons, key=lambda s: s["sequence"]) + + collection = [] + episode_count = 0 + for season in seasons: + season_index = season["sequence"] + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + season_id = season["season_id"] + page = 0 + episode_index = 0 + while True: + page += 1 + response = requests.get(stirr_com.EPISODES_URL.format( + series_id=series_id, season_id=season_id, page=page + )) + response = response.content.decode() + response = json.loads(response) + + episodes = response.get("data", {}).get("data", []) + if len(episodes) == 0: + break + + for episode in episodes: + # episode_index += 1 + episode_index = episode["sequence"] + episode_index = episode_index - episode_count + check = check_range(False, season_index, episode_index) + if check in [True, False]: + continue + + episode_id = episode["videoid"] + episode_title = episode.get("title", None) + episode_url = None + + for f in ["watch_url", "url", "shareable"]: + if episode.get(f, "") in ["", None]: + continue + episode_url = episode[f] + break + + if episode_url is None: + episode_url = stirr_com.EPISODE_URL.format(video_id=episode_id) + elif not episode_url.startswith("http"): + episode_url = stirr_com.BASE_URL + episode_url + + if episode_title in ["", None]: + episode_title = clean_url(episode_url).split("/")[-1] + episode_title = f'Episode_{episode_index}_{episode_title}' + + collection.append(BaseElement( + url=episode_url, + collection=join(collection_name, f'Season_{season_index}'), + element=get_valid_filename(episode_title) + )) + episode_count += season["episode_count"] + + return collection diff --git a/API/proxiesembed/drmproxy/services/tf1_fr.py b/API/proxiesembed/drmproxy/services/tf1_fr.py new file mode 100644 index 0000000..2f032a5 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/tf1_fr.py @@ -0,0 +1,316 @@ +import builtins +import json +import re +from os.path import join + +import requests + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, CustomException, BaseService +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename + + +class tf1_fr(BaseService): + DEMO_URLS = [ + "https://www.tf1.fr/tf1/gladiators/videos/extract", + "https://www.tf1.fr/tf1/les-freres-scott/videos", + "https://www.tf1.fr/tf1/les-bracelets-rouges/videos/extract", + "https://www.tf1.fr/tmc/les-mysteres-de-l-amour/videos", + "https://www.tf1.fr/tf1/gladiators/videos", + "https://www.tf1.fr/tmc/quotidien-avec-yann-barthes/videos/invites-fanny-ardant-et-thierry-klifa-rois-de-la-piste-et-de-larnaque-85679919.html", + "https://www.tf1.fr/tmc/la-mode-by-loic-prigent/videos/5-minutes-de-mode-by-loic-prigent-du-8-mars-2024-73931950.html", + "https://www.tf1.fr/tf1/double-zero/videos/double-zero-70592950.html", + ] + + LOGIN_URL = 'https://compte.tf1.fr/accounts.login' + TOKEN_URL = 'https://www.tf1.fr/token/gigya/web' + MEDIAINFO_URL = 'https://mediainfo.tf1.fr/mediainfocombo/{media_id}' + PLAYER_URL = 'https://prod-player.tf1.fr' + BASE_URL = 'https://www.tf1.fr' + LICENSE_URL = "https://widevine-proxy-m.prod.p.tf1.fr/proxy" + + EMAIL = "YOUR_EMAIL" + PASSWORD = "YOUR_PASSWORD" + BEARER_TOKEN = None + API_KEY, CONSENT_IDS, PLAYER_VERSION = None, None, None + + @staticmethod + def test_service(): + main_service.run_service(tf1_fr) + + @staticmethod + def credentials_needed(): + return { + "EMAIL": tf1_fr.EMAIL, + "PASSWORD": tf1_fr.PASSWORD + } + + @staticmethod + def format_version(version): + major, minor, patch = map(int, version.split('.')) + return str(major * 1000000 + minor * 1000 + patch) + + @staticmethod + def get_tf1_info(): + response = requests.get(tf1_fr.BASE_URL).content.decode().replace('\\"', '"') + api_key = re.findall(r'"apiKey":"([^"]+)"', response)[0] + consent_ids = re.findall(r'neededConsentIds":\[(.*?)]', response)[0].replace("\"", "").split(",") + + player_version = re.findall( + rf'"playerEndpoint":"{tf1_fr.PLAYER_URL}/","version":"([^"]+)"', response + )[0] + return api_key, consent_ids, tf1_fr.format_version(player_version) + + @staticmethod + def get_bearer_token(): + class_name = tf1_fr.__name__.replace("_", ".") + credentials = builtins.CONFIG["SERVICE_CREDENTIALS"][class_name] + try: + assert type(credentials["EMAIL"]) is str + assert type(credentials["PASSWORD"]) is str + except: + return None + + response = json.loads(requests.post( + tf1_fr.LOGIN_URL, + data={ + "loginID": credentials["EMAIL"], + "password": credentials["PASSWORD"], + "APIKey": tf1_fr.API_KEY + } + ).content.decode()) + + status_code = response.get('statusCode', None) + if status_code != 200: + if status_code == 403: + return None + raise CustomException(ERR_MSG.format( + type=f'{APP_ERROR}', + url=f"from the {tf1_fr.__name__} service", + reason=f"Unknown error encountered: {str(response)}", + solution="Debug the service" + )) + + return json.loads(requests.post( + tf1_fr.TOKEN_URL, + json={ + 'uid': response["UID"], 'signature': response["UIDSignature"], + 'timestamp': int(response["signatureTimestamp"]), + 'consent_ids': tf1_fr.CONSENT_IDS + } + ).content.decode())["token"] + + @staticmethod + def initialize_service(): + if tf1_fr.API_KEY is None or tf1_fr.CONSENT_IDS is None or tf1_fr.PLAYER_VERSION is None: + tf1_fr.API_KEY, tf1_fr.CONSENT_IDS, tf1_fr.PLAYER_VERSION = tf1_fr.get_tf1_info() + if tf1_fr.BEARER_TOKEN is None: + tf1_fr.BEARER_TOKEN = tf1_fr.get_bearer_token() + if tf1_fr.BEARER_TOKEN is None: + return None + return tf1_fr + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post(tf1_fr.LICENSE_URL, data=challenge) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_video_data(source_element): + matches = re.findall( + r'"embedUrl":"([^"]+)"', requests.get(source_element.url).content.decode() + ) + match = [m for m in matches if "/player/" in m] + if len(match) == 0: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Content isn't available anymore", + solution="Do not attempt to download it" + )) + + media_id = re.findall(r'/player/([^/]+)', match[0])[0] + response = requests.get( + tf1_fr.MEDIAINFO_URL.format(media_id=media_id), + params={'pver': tf1_fr.PLAYER_VERSION, 'context': 'context'}, + headers={'authorization': f'Bearer {tf1_fr.BEARER_TOKEN}'} + ) + + response = response.content.decode() + if "geoblocked" in response.lower(): + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need French IP to access content", + solution="Use a VPN" + )) + response = json.loads(response) + if (response.get("delivery", {}).get("code", None) == 4034 or + "permission_denied" in response.get("media", {}).get("error_code", "").lower()): + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Premium content can't be downloaded", + solution="Do not attempt to download it" + )) + + if source_element.element is None: + source_element.element = get_valid_filename(response.get("media", {}).get("title", media_id)) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + tf1_fr.__name__ + ) + + manifest = response["delivery"]["url"] + try: + pssh_value = str(min(re.findall( + r'(.+?)', + requests.get(manifest).content.decode() + ), key=len)) + except: + pssh_value = None + + if builtins.CONFIG.get("BASIC", False) is True: + manifest = re.sub(r'/eyJ[^/]*/', '//', manifest) + return manifest, pssh_value, {} + + @staticmethod + def get_episode_index(label): + if label is None or len(label) == 0: + return None + label = label.lower() + label = re.sub(r'\s+', ' ', label) + label = label.replace(' ', "_") + for s in ["e", "pisode_", "pisodes_", "part_", "emission_"]: + try: + return int(re.findall(fr'{s}(\d+)', label)[0]) + except: + if s == "emission_" and "emission_" in label: + return 1 + return None + + @staticmethod + def get_collection_elements(collection_url): + if "/playlist" in collection_url: + return None + if "/videos/" in collection_url and ".html" in collection_url: + return [BaseElement(url=collection_url)] + + if "/videos" in collection_url: + collection = [] + try: + section = re.search(r"/videos/([^/?]*)", collection_url).group(1) + except: + section = None + + response = requests.get(collection_url).content.decode() + collection_name = re.search(r"([^/]+)/videos", collection_url).group(1) + collection_name = get_valid_filename(collection_name) + + re_href = 'href="' + re_href += re.search(fr"{tf1_fr.BASE_URL}(.*?)/videos", collection_url).group(1) + re_href += "/videos/" + + if section is not None and len(section) > 0: + collection_name = collection_name + "_" + section + collection_name = get_valid_filename(collection_name) + + matches = re.findall(fr'({re_href}.*?\.html)"[^>]*>]*>([^<]+)', response) + if len(matches) == 0: + matches = re.findall(fr'({re_href}.*?\.html)"[^>]*>([^<]+)<', response) + + matches = [( + tf1_fr.BASE_URL + m[0].split('"')[1], m[1] + ) for m in matches] + matches = [(*value, index + 1) for index, value in enumerate(matches)] + + for content_url, content_name, content_index in matches: + check = check_range(False, None, content_index) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=content_url, + collection=join(join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + tf1_fr.__name__ + ), collection_name), + element=f'{content_index}' + f'_' + f'{get_valid_filename(content_name)}' + )) + return collection + + re_href += "saison-" + matches = re.findall(fr'{re_href}\d+"', response) + matches = [m.split('"')[1] for m in matches] + matches = [( + f'{tf1_fr.BASE_URL}{m}', int(m.split("/videos/saison-")[1]) + ) for m in matches] + matches = sorted(matches, key=lambda m: m[1]) + + re_href = re_href.replace("saison-", "") + for season_url, season_index in matches: + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + page = 0 + while True: + page += 1 + if page > 1: + response = requests.get(f'{season_url}/{page}', allow_redirects=False) + try: + assert 300 <= response.status_code < 400 + assert len(response.headers["Location"]) > 0 + assert response.headers["Location"] in season_url + break + except: + pass + else: + response = requests.get(f'{season_url}/{page}') + + response = response.content.decode() + matches = re.findall(fr'({re_href}.*?\.html)"[^>]*>]*>([^<]+)', response) + if len(matches) == 0: + matches = re.findall(fr'({re_href}.*?\.html)"[^>]*>([^<]+)<', response) + + matches = [( + tf1_fr.BASE_URL + m[0].split('"')[1], + m[1], + tf1_fr.get_episode_index(m[1]) + ) for m in matches] + matches = [m for m in matches if m[2] is not None] + + for episode_url, episode_name, episode_index in matches: + check = check_range(False, season_index, episode_index) + if check in [True, False]: + continue + + collection.append(BaseElement( + url=episode_url, + collection=join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + tf1_fr.__name__ + ), + join(collection_name, f'Season_{season_index}') + ), + element=f"Episode_{episode_index}" + f"_" + f"{get_valid_filename(episode_name)}" + )) + + if len(matches) == 0: + break + + return collection + return None diff --git a/API/proxiesembed/drmproxy/services/tg4_ie.py b/API/proxiesembed/drmproxy/services/tg4_ie.py new file mode 100644 index 0000000..b3b9fd3 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/tg4_ie.py @@ -0,0 +1,286 @@ +import builtins +import json +import re +from os.path import join +from urllib.parse import parse_qs, urlparse + +import requests + +from utils.constants.macros import CACHE_DIR, ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename, dict_to_file, file_to_dict, clean_url + + +class tg4_ie(BaseService): + DEMO_URLS = [ + "https://www.tg4.ie/en/player/categories/top-documentaries/play/?pid=6318469898112&title=Moving%20West&series=Moving%20West&genre=Faisneis", + "https://www.tg4.ie/ga/player/catagoir/nuacht/seinn/?pid=6353807078112&title=%C3%89ire%20Aontaithe&series=Ini%C3%BAchadh%20TG4&genre=Cursai%20Reatha", + "https://www.tg4.ie/en/player/online-boxsets/?series=Bailte&genre=Faisneis", + "https://www.tg4.ie/ga/player/catagoir/saolchlar/?series=%C3%93%20Cuisine&genre=Saolchlar", + ] + + PLAYBACK_URL = 'https://edge.api.brightcove.com/playback/v1/accounts/{account_id}/videos/{video_id}' + EPISODES_URL = 'https://playerapi.tg4tech.com/series/videos' + WATCH_LIVE_URL = 'https://www.tg4.ie/en/player/watch-live/' + CATEGORIES_URL = 'https://www.tg4.ie/en/player/categories/' + BASE_URL = 'https://www.tg4.ie' + + API_DICT = None + CACHE_FILE = None + + @staticmethod + def test_service(): + main_service.run_service(tg4_ie) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def get_api_dict(): + try: + api_dict = file_to_dict(tg4_ie.CACHE_FILE) + assert len(api_dict.keys()) == 3 + return api_dict + except: + pass + + response = requests.get(tg4_ie.WATCH_LIVE_URL).content.decode() + response = re.findall(r'src="([^"]*index\.min\.js)"', response)[0] + account_id = re.findall(r'(\d{5}\d+)', response)[0] + + response = requests.get(response).content.decode() + policy_key = re.findall(r'policyKey:"([^"]+)"', response)[0] + + response = requests.get(tg4_ie.CATEGORIES_URL).content.decode() + api_key = re.findall(r'"x-api-key"[^:]*:[^"]*"([^"]+)"', response)[0] + + api_dict = { + "account_id": account_id, + "policy_key": policy_key, + "api_key": api_key + } + dict_to_file(tg4_ie.CACHE_FILE, api_dict) + return api_dict + + @staticmethod + def initialize_service(): + if tg4_ie.CACHE_FILE is None: + tg4_ie.CACHE_FILE = join(CACHE_DIR, f'{tg4_ie.__name__}.json') + if builtins.CONFIG.get("FRESH", False) is True: + dict_to_file(tg4_ie.CACHE_FILE, {}) + + if tg4_ie.API_DICT is None: + tg4_ie.API_DICT = tg4_ie.get_api_dict() + return tg4_ie + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + additional["license_url"], + data=challenge + ) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_video_data(source_element): + params_dict = parse_qs(urlparse(source_element.url).query) + video_id = params_dict["pid"][0] + try: + alias = params_dict["title"][0] + except: + alias = f"Video_{video_id}" + + if video_id is None: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Don't attempt to download it" + )) + + response = requests.get( + tg4_ie.PLAYBACK_URL.format( + account_id=tg4_ie.API_DICT["account_id"], + video_id=video_id + ), + headers={ + 'Accept': f'pk={tg4_ie.API_DICT["policy_key"]}', + 'Origin': tg4_ie.BASE_URL + } + ) + response = response.content.decode() + response = json.loads(response) + + message = str(response).lower() + if "video_not_found" in message or "resource_not_found" in message or "video_not_playable" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Don't attempt to download it" + )) + if "account_not_found" in message or "invalid_policy_key" in message: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Can't access the video content because the account id/policy key expired", + solution=f'Delete the {tg4_ie.CACHE_FILE} cache manually or add the parameter --fresh to your command' + )) + + if source_element.element is None: + title = response.get("name", None) + if title in ["", None]: + title = alias + fields = response.get("custom_fields", {}) + + for f in ["series", "episode"]: + try: + title += " " + f[0] + fields[f] + except: + pass + source_element.element = get_valid_filename(title) + + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + tg4_ie.__name__ + ) + + license_url = None + manifest = None + for source in response.get("sources", []): + key_systems = source.get("key_systems", {}) + if len(key_systems.items()) > 0: + if "widevine" not in str(source).lower(): + continue + + for k, v in key_systems.items(): + if "widevine" not in k.lower(): + continue + license_url = v.get("license_url", None) + + if license_url is None: + continue + manifest = source.get("src", None) + if manifest is not None: + break + + try: + if license_url is None: + raise + + pssh_value = str(min( + re.findall( + r']*>(.*?)', + requests.get(manifest).content.decode() + ), key=len + )) + except: + pssh_value = None + + if license_url is not None and pssh_value is None: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}. Can't extract pssh", + solution=f"Extend the {tg4_ie.__name__} service" + )) + + return manifest, pssh_value, {"license_url": license_url} + + @staticmethod + def get_collection_elements(collection_url): + for f in ["play", "seinn"]: + if (f"/{f}?" in collection_url or f"/{f}/" in collection_url) and "pid=" in collection_url: + return [BaseElement(url=collection_url)] + for f in ["watch-live", "feach-beo"]: + if f"/{f}/" in collection_url: + return None + if "series=" not in collection_url: + return None + + params_dict = parse_qs(urlparse(collection_url).query) + series = params_dict["series"][0] + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + tg4_ie.__name__ + ), + get_valid_filename(series) + ) + + response = requests.get( + tg4_ie.EPISODES_URL, + params={'seriesTitle': series}, + headers={'x-api-key': tg4_ie.API_DICT["api_key"]} + ) + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + + err_msg = "" + if type(response) is dict: + err_msg = response.get("message", "").lower() + if status_code == 403 or "forbidden" == err_msg: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=collection_url, + reason="Can't access the video content because the api key expired", + solution=f'Delete the {tg4_ie.CACHE_FILE} cache manually or add the parameter --fresh to your command' + )) + if len(response) == 0: + return [] + + collection = [] + episode_url = clean_url(collection_url) + "/play/?pid=" + seasons = {} + for episode in response: + try: + series_index = int(episode["custom_fields"]["series"]) + episode_index = int(episode["custom_fields"]["episode"]) + if seasons.get(series_index, None) is None: + seasons[series_index] = [] + seasons[series_index].append((episode_index, episode)) + except: + pass + + for season_index, episodes in sorted(seasons.items()): + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + if len(episodes) == 0: + continue + episodes = sorted(episodes, key=lambda e: e[0]) + + for episode_index, episode in episodes: + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + episode_id = episode.get("videoId", None) + if episode_id in ["", None]: + episode_id = episode["id"] + + episode_title = episode.get("name", None) + if episode_title in ["", None]: + episode_title = episode["custom_fields"].get("title", None) + if episode_title in ["", None]: + episode_title = episode_id + episode_title = f'Episode_{episode_index}_{episode_title}' + + collection.append(BaseElement( + url=episode_url + episode_id, + collection=join(collection_title, f'Season_{season_index}'), + element=get_valid_filename(episode_title) + )) + + return collection diff --git a/API/proxiesembed/drmproxy/services/threenow_co_nz.py b/API/proxiesembed/drmproxy/services/threenow_co_nz.py new file mode 100644 index 0000000..3655ae1 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/threenow_co_nz.py @@ -0,0 +1,258 @@ +import builtins +import json +import re +import urllib.parse +from os.path import join + +import requests +from bs4 import BeautifulSoup + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, CustomException, BaseService +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename + + +class threenow_co_nz(BaseService): + DEMO_URLS = [ + "https://www.threenow.co.nz/shows/below-deck/S1647-006", + "https://www.threenow.co.nz/shows/7-days/61183", + "https://www.threenow.co.nz/shows/high-country/1712093997956", + "https://www.threenow.co.nz/shows/toke/S2279-908", + "https://www.threenow.co.nz/shows/the-hui-post-election-special/the-hui-post-election-special-/1695160987788/M78388-748", + "https://www.threenow.co.nz/shows/a-winter-song/a-winter-song/S4271-793/M66384-367", + "https://www.threenow.co.nz/shows/25-siblings-and-me/25-siblings-and-me/S3922-434/M60237-576", + ] + + SHOWS_URL = 'https://now-api.fullscreen.nz/v5/shows/{show_id}' + PLAYBACK_URL = 'https://edge.api.brightcove.com/playback/v1/accounts/{account_id}/videos/{video_id}' + BASE_URL = 'https://www.threenow.co.nz' + VIDEO_URL = BASE_URL + '/shows/-/-/{show_id}/{video_id}' + + ACCOUNT_ID = None + POLICY_KEY = None + + @staticmethod + def test_service(): + main_service.run_service(threenow_co_nz) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def get_site_info(): + response = requests.get('https://www.threenow.co.nz/').content.decode() + soup = BeautifulSoup(response, 'html5lib') + meta = soup.find_all('meta') + meta = [m for m in meta if 'config/environment' in m.get('name', '')] + + if len(meta) == 0: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=f'from {threenow_co_nz.__name__}', + reason="Need New Zealander IP to access content", + solution="Use a VPN" + )) + + meta = json.loads(urllib.parse.unquote(meta[0]["content"])) + account_id = meta["brightcoveAccountId"] + policy_key = meta["brightcovePolicyKey"] + return account_id, policy_key + + @staticmethod + def initialize_service(): + if threenow_co_nz.ACCOUNT_ID is None or threenow_co_nz.POLICY_KEY is None: + threenow_co_nz.ACCOUNT_ID, threenow_co_nz.POLICY_KEY = threenow_co_nz.get_site_info() + return threenow_co_nz + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post(additional["license_url"], data=challenge) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_full_seasons(response): + seasons = response.get("seasons", []) + if len(response.get("episodes", [])) > 0: + season_number = 0 + if len(seasons) > 0: + season_number = int(seasons[-1]["seasonNumber"]) + + seasons.append({ + "seasonNumber": season_number + 1, + "episodes": response["episodes"] + }) + + seasons = sorted(seasons, key=lambda s: int(s["seasonNumber"])) + if len(response.get("extras", [])) > 0: + season_number = 0 + if len(seasons) > 0: + season_number = int(seasons[-1]["seasonNumber"]) + + index = 0 + for e in response["extras"]: + index += 1 + e["episode"] = index + seasons.append({ + "seasonNumber": season_number + 1, + "episodes": response["extras"] + }) + return seasons + + @staticmethod + def get_video_data(source_element): + video_id = source_element.url.split("/")[-1] + show_id = source_element.url.split("/")[-2] + + response = json.loads(requests.get( + threenow_co_nz.SHOWS_URL.format(show_id=show_id) + ).content.decode()) + + content = None + seasons = threenow_co_nz.get_full_seasons(response) + + for season in seasons: + episodes = season.get("episodes", []) + episodes = sorted(episodes, key=lambda e: int(e["episode"])) + + for episode in episodes: + if episode["videoId"] == video_id: + content = episode + break + + if content is not None: + break + + if content is None: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + if source_element.element is None: + source_element.element = get_valid_filename(content.get("name", video_id)) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + threenow_co_nz.__name__ + ) + + video_id = content["externalMediaId"] + response = json.loads(requests.get( + threenow_co_nz.PLAYBACK_URL.format( + account_id=threenow_co_nz.ACCOUNT_ID, + video_id=video_id + ), + headers={'Accept': f'pk={threenow_co_nz.POLICY_KEY}'} + ).content.decode()) + + message = str(response).lower() + if "client_geo" in message and "access_denied" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need New Zealander IP to access content", + solution="Use a VPN" + )) + + license_url = None + manifest = None + for source in response.get("sources", []): + key_systems = source.get("key_systems", {}) + if len(key_systems.items()) > 0: + if "widevine" not in str(source).lower(): + continue + + for k, v in key_systems.items(): + if "widevine" not in k.lower(): + continue + license_url = v.get("license_url", None) + + if license_url is None: + continue + manifest = source.get("src", None) + if manifest is not None: + break + + try: + if license_url is None: + raise + + pssh_value = str(min( + re.findall( + r']*>(.*?)', + requests.get(manifest).content.decode() + ), key=len + )) + except: + pssh_value = None + + if license_url is not None and pssh_value is None: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}. Can't extract pssh", + solution=f"Extend the {threenow_co_nz.__name__} service" + )) + + return manifest, pssh_value, {"license_url": license_url} + + @staticmethod + def get_collection_elements(collection_url): + collection_url = collection_url.rstrip("/") + if "/shows/" not in collection_url: + return None + if collection_url.split("/shows/")[1].count("/") >= 3: + return [BaseElement(url=collection_url)] + + if collection_url.split("/shows/")[1].count("/") < 3: + collection = [] + show_id = collection_url.split("/")[-1] + + response = json.loads(requests.get( + threenow_co_nz.SHOWS_URL.format(show_id=show_id) + ).content.decode()) + + collection_name = response.get("name", response.get("showAdName", collection_url.split("/")[-2])) + collection_name = get_valid_filename(collection_name) + collection_name = join(join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + threenow_co_nz.__name__ + ), collection_name) + + seasons = threenow_co_nz.get_full_seasons(response) + for season in seasons: + check = check_range(True, int(season["seasonNumber"]), None) + if check is True: + continue + elif check is False: + return collection + + episodes = season.get("episodes", []) + episodes = sorted(episodes, key=lambda e: int(e["episode"])) + + for episode in episodes: + check = check_range(False, int(season["seasonNumber"]), int(episode['episode'])) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=threenow_co_nz.VIDEO_URL.format( + show_id=response["showId"], + video_id=episode["videoId"] + ), + collection=join(collection_name, f'Season_{season["seasonNumber"]}'), + element=f"Episode_{episode['episode']}" + f"_" + f"{get_valid_filename(episode['name'])}" + )) + + return collection + return None diff --git a/API/proxiesembed/drmproxy/services/tv5mondeplus_com.py b/API/proxiesembed/drmproxy/services/tv5mondeplus_com.py new file mode 100644 index 0000000..b98b0f4 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/tv5mondeplus_com.py @@ -0,0 +1,375 @@ +import builtins +import json +import os +import re +from os.path import join + +import requests + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename, has_only_roman_chars + + +class tv5mondeplus_com(BaseService): + DEMO_URLS = [ + "https://www.tv5mondeplus.com/en/series-et-films-tv/comedie/la-maison-bleue-s-1-e2-le-projet-de-societe/play", + "https://www.tv5mondeplus.com/en/podcast/subcategory/dingue-14884767_74079A/play", + "https://www.tv5mondeplus.com/en/cinema/policier-et-suspense/mille-milliards-de-dollars", + "https://www.tv5mondeplus.com/en/series-et-films-tv/comedie/la-maison-bleue", + "https://www.tv5mondeplus.com/en/podcast/subcategory/micro-sciences", + "https://www.tv5mondeplus.com/en/series-et-films-tv/policier-et-suspense/avocats-associes", + ] + + AUTH_URL = 'https://api.tv5mondeplus.com/v2/customer/TV5MONDE/businessunit/TV5MONDEplus/auth/anonymous' + GRAPHQL_URL = 'https://www.tv5mondeplus.com/api/graphql/v1/' + PLAY_URL = 'https://api.tv5mondeplus.com/v2/customer/TV5MONDE/businessunit/TV5MONDEplus/entitlement/{play_id}/play' + ASSET_URL = 'https://api.tv5mondeplus.com/v1/customer/TV5MONDE/businessunit/TV5MONDEplus/content/asset/{asset_id}' + + BEARER_TOKEN = None + + @staticmethod + def test_service(): + main_service.run_service(tv5mondeplus_com) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def get_bearer_token(): + return json.loads(requests.post( + tv5mondeplus_com.AUTH_URL, + json={'device': {}, 'deviceId': 'deviceId'} + ).content.decode())["sessionToken"] + + @staticmethod + def initialize_service(): + if tv5mondeplus_com.BEARER_TOKEN is None: + tv5mondeplus_com.BEARER_TOKEN = tv5mondeplus_com.get_bearer_token() + + return tv5mondeplus_com + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + additional["license_url"], + data=challenge + ) + licence.raise_for_status() + return licence.content + + @staticmethod + def generate_segment_m3u8(output_path, manifest, content_info): + m3u8_content = "#EXTM3U\n#EXT-X-VERSION:3\n\n" + m3u8_content += f'#EXTINF:{content_info.get("durationInMilliseconds", 1)},\n' + m3u8_content += f'{manifest}\n' + + m3u8_content += "#EXT-X-ENDLIST\n" + with open(output_path, "w") as f: + f.write(m3u8_content) + + @staticmethod + def generate_master_m3u8(source_element, manifest, extension, content_info): + output_path = str(join(source_element.collection, source_element.element)) + if not os.path.exists(output_path): + os.makedirs(output_path) + m3u8_content = "#EXTM3U\n#EXT-X-VERSION:3\n\n" + + title = f'audio.m3u8' + tv5mondeplus_com.generate_segment_m3u8(join(output_path, title), manifest, content_info) + m3u8_content += f"#EXT-X-STREAM-INF:BANDWIDTH=1000,TYPE=AUDIO,MIME-TYPE=\"audio/{extension}\"\n" + m3u8_content += f'{title}\n' + + output_path = join(output_path, "master.m3u8") + with open(output_path, "w") as f: + f.write(m3u8_content) + return output_path + + @staticmethod + def get_video_data(source_element): + video_slug = source_element.url.split("/play")[0].split("/")[-1] + language = source_element.url.split("/")[3] + + response = requests.post( + tv5mondeplus_com.GRAPHQL_URL, + json={ + 'operationName': 'VODContentDetails', + 'variables': {'contentId': 'redbee:' + video_slug + ':' + language}, + 'extensions': {'persistedQuery': { + 'version': 1, + 'sha256Hash': 'e396131572f170605ea7a9f13139568323ab9e398a350741952e690be38efb30' + }} + } + ) + + if response.status_code == 400: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Unknown language format", + solution="Use a valid content URL" + )) + if response.status_code == 404: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + response = json.loads(response.content.decode()) + + if source_element.element is None: + video_title = response["data"]["lookupContent"]["title"] + episode_index = response["data"]["lookupContent"].get("episodeNumber", None) + if episode_index is not None: + video_title = f'{video_title}_{episode_index}' + + source_element.element = get_valid_filename(video_title) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + tv5mondeplus_com.__name__ + ) + + play_id = response["data"]["lookupContent"]["id"].split(":")[0] + response = json.loads(requests.get( + tv5mondeplus_com.PLAY_URL.format(play_id=play_id), + headers={'Authorization': f'Bearer {tv5mondeplus_com.BEARER_TOKEN}'}, + params={ + 'supportedFormats': 'dash,hls,mss,mp3', + 'supportedDrms': 'widevine' + } + ).content.decode()) + + formats = response["formats"] + drm_free = list(filter(lambda f: f.get("drm", None) in ["", None, {}], formats)) + license_url = None + + if len(drm_free) == 0: + drm_widevine = list(filter(lambda f: f.get("drm", None) not in ["", None, {}], formats)) + drm_widevine = list(filter( + lambda f: len([w for w in f["drm"].keys() if "widevine" in w.lower()]) > 0, + drm_widevine + )) + + if len(drm_widevine) == 0: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine wasn't found", + solution="Do not attempt to download it" + )) + drm_widevine = drm_widevine[0] + + for k, v in drm_widevine["drm"].items(): + if "widevine" not in k.lower(): + continue + license_url = v["licenseServerUrl"] + break + + selected_drm = drm_widevine + else: + selected_drm = drm_free[0] + + manifest = selected_drm["mediaLocator"] + manifest_format = selected_drm["format"].lower() + + pssh_value = None + if license_url is not None: + try: + if manifest_format in ["mp3"]: + raise + + pssh_value = str(min(re.findall( + r'<[^<>]*cenc:pssh[^<>]*>(.*?)]*cenc:pssh[^<>]*>', + requests.get(manifest).content.decode() + ), key=len)) + except: + pass + + if pssh_value is None: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}", + solution=f"Extend the {tv5mondeplus_com.__name__} service" + )) + + if manifest_format in ["mp3"]: + manifest = tv5mondeplus_com.generate_master_m3u8(source_element, manifest, manifest_format, response) + return manifest, pssh_value, {"license_url": license_url} + + @staticmethod + def get_locale_name(content, language): + content_name = None + for i in range(0, 2): + for local in content.get("localized", []): + if i == 0: + valid_title = local.get("locale", "").lower() in ["en", "eng", language] + if not valid_title: + continue + + valid_title = has_only_roman_chars(local.get("title", None)) + if valid_title: + content_name = local["title"] + else: + valid_title = has_only_roman_chars(local.get("sortingTitle", None)) + if valid_title: + content_name = local["sortingTitle"] + if content_name is not None and len(content_name.strip()) > 0: + break + + if content_name is not None: + break + return content_name + + @staticmethod + def get_collection_elements(collection_url): + collection_url = collection_url.split("?")[0].split("#")[0].rstrip("/") + if collection_url.endswith("/play"): + return [BaseElement(url=collection_url)] + + series_slug = collection_url.split("/")[-1] + language = collection_url.split("/")[3] + response = requests.get( + tv5mondeplus_com.ASSET_URL.format(asset_id=series_slug), + params={ + 'fieldSet': 'ALL', + 'types': 'MOVIE,TV_SHOW,PODCAST', + 'onlyPublished': 'true', + 'includeEpisodes': 'true', + 'client': 'json' + } + ) + if response.status_code == 404: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + collection = [] + response = json.loads(response.content.decode()) + collection_name = tv5mondeplus_com.get_locale_name(response, language) + + if collection_name is None: + collection_name = series_slug + collection_name = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + tv5mondeplus_com.__name__ + ), + get_valid_filename(collection_name) + ) + + seasons = [] + for season in response.get("seasons", []): + season_index = season.get("season", 1) + try: + season_index = int(season_index) + except: + season_index = 1 + seasons.append((season_index, season)) + seasons = sorted(seasons, key=lambda s: s[0]) + + for season_index, season in seasons: + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + for episode in season.get("episodes", []): + episode_index = int(episode.get("episode", 1)) + check = check_range(False, season_index, episode_index) + if check in [True, False]: + continue + + episode_name = tv5mondeplus_com.get_locale_name(episode, language) + episode_url = collection_url.split("/") + try: + episode_url[-1] = episode["slugs"][0] + except: + episode_url[-1] = episode["assetId"] + + if episode_name is None: + episode_name = episode_url[-1] + episode_url.append("play") + episode_url = "/".join(episode_url) + + collection.append(BaseElement( + url=episode_url, + collection=join(collection_name, f'Season_{season_index}'), + element=f'Episode_{episode_index}' + f'_' + f'{get_valid_filename(episode_name)}' + )) + + if len(collection) > 0: + return collection + + response = requests.post( + tv5mondeplus_com.GRAPHQL_URL, + json={ + 'operationName': 'VODContentDetails', + 'variables': {'contentId': f'redbee:{series_slug}:{language}'}, + 'extensions': {'persistedQuery': { + 'version': 1, + 'sha256Hash': 'e396131572f170605ea7a9f13139568323ab9e398a350741952e690be38efb30' + }} + } + ) + + response = json.loads(response.content.decode()) + content_id = response["data"]["lookupContent"]["id"].split(":")[0] + + response = requests.post( + tv5mondeplus_com.GRAPHQL_URL, + json={ + 'operationName': 'VODContentEpisodes', + 'variables': {'contentId': f'PODCAST:{content_id}:{language}'}, + 'extensions': {'persistedQuery': { + 'version': 1, + 'sha256Hash': '3ef37000cba42e64e4f2505fa4fa48d42f84e4335039c4e82f5ca24c11db0676' + }} + } + ) + response = json.loads(response.content.decode()) + + try: + episodes = response["data"]["lookupContent"]["episodes"]["items"] + assert len(episodes) > 0 + except: + return [BaseElement(url=collection_url)] + + episode_index = 0 + for episode in episodes: + episode_index += 1 + check = check_range(False, None, episode_index) + if check is True: + continue + elif check is False: + return collection + + episode_url = collection_url.split("/") + episode_url[-1] = episode["id"].split(":")[0] + episode_url.append("play") + episode_url = "/".join(episode_url) + + if has_only_roman_chars(episode.get("title", None)): + episode_name = episode["title"] + else: + episode_name = episode["id"] + + collection.append(BaseElement( + url=episode_url, + collection=collection_name, + element=f'Podcast_{episode_index}' + f'_' + f'{get_valid_filename(episode_name)}' + )) + return collection diff --git a/API/proxiesembed/drmproxy/services/uefa_tv.py b/API/proxiesembed/drmproxy/services/uefa_tv.py new file mode 100644 index 0000000..b045196 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/uefa_tv.py @@ -0,0 +1,653 @@ +import builtins +import json +import os +import re +import threading +from os.path import join +from urllib.parse import parse_qs, urlparse + +import browser_cookie3 +import m3u8 +import requests + +from utils.constants.macros import ERR_MSG, USER_ERROR, CACHE_DIR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename, clean_url, dict_to_file, file_to_dict + + +class uefa_tv(BaseService): + DEMO_URLS = [ + "https://www.uefa.tv/video/vod/159916/", + "https://www.uefa.tv/video/vod/644523/?playlistId=23974", + "https://www.uefa.tv/match/vod/676686/2040798", + "https://www.uefa.tv/video/vod/153377/?bucketExId=Vg~M&lastSeen=0%3A153377§ion=UCL", + "https://www.uefa.tv/playlist/5649", + "https://www.uefa.tv/playlist/8415", + "https://www.uefa.tv/search/videos?q=Messi%20UEFA", + "https://www.uefa.tv/competition/UCL", + "https://www.uefa.tv/competition/U-17", + ] + + GET_JWT_URL = 'https://idp-prod.uefa.tv/accounts.getJWT' + GIGYA_JWT_URL = 'https://dce-frontoffice.imggaming.com/api/v2/user/gigya/jwt' + CHUNK_JS_URL = 'https://www.uefa.tv/static/js/{chunk_id}.{chunk_str}.chunk.js' + STREAM_VOD_URL = 'https://dce-frontoffice.imggaming.com/api/v2/stream/vod/{vod_id}' + REFRESH_TOKEN_URL = 'https://dce-frontoffice.imggaming.com/api/v2/token/refresh' + VOD_METADATA_URL = 'https://dce-frontoffice.imggaming.com/api/v2/vod/{vod_id}' + PLAYLIST_URL = 'https://dce-frontoffice.imggaming.com/api/v2/vod/playlist/{playlist_id}' + SEARCH_QUERY_URL = 'https://{app_id}-dsn.algolia.net/1/indexes/prod-dce.uefa-livestreaming-events/query' + COMP_BUCKET_URL = 'https://dce-frontoffice.imggaming.com/api/v4/content/{competition_id}/bucket/{bucket_id}' + COMP_CONTENT_URL = 'https://dce-frontoffice.imggaming.com/api/v2/content/{competition_id}' + VOD_URL = 'https://www.uefa.tv/video/vod/{vod_id}' + BASE_URL = 'https://www.uefa.tv' + + LOCK = None + CACHE_FILE = None + USER_AGENT = None + ACCOUNT_TOKENS = None + LOGIN_COOKIES = None + LOGIN_TOKEN = None + API_KEY = None + REALM_DICT = None + PAGE_SIZE = 50 + + @staticmethod + def test_service(): + main_service.run_service(uefa_tv) + + @staticmethod + def credentials_needed(): + return {"FIREFOX_COOKIES": True} + + @staticmethod + def get_login_cookies(): + cookie_dict = {} + for c in browser_cookie3.firefox(domain_name='uefa.tv'): + cookie_dict[c.name] = c.value + if uefa_tv.LOGIN_TOKEN is None and c.name.startswith("glt_"): + uefa_tv.LOGIN_TOKEN = c.value + uefa_tv.API_KEY = c.name[len("glt_"):] + + try: + assert uefa_tv.LOGIN_TOKEN is not None + assert uefa_tv.API_KEY is not None + assert len(cookie_dict.keys()) > 0 + except: + return None + return cookie_dict + + @staticmethod + def set_account_tokens(): + response = requests.post( + uefa_tv.GET_JWT_URL, + cookies=uefa_tv.LOGIN_COOKIES, + data={ + 'fields': 'firstName,lastName,email', + 'APIKey': uefa_tv.API_KEY, + 'login_token': uefa_tv.LOGIN_TOKEN, + 'sdk': 'js_latest', + 'authMode': 'cookie', + 'format': 'json' + } + ) + + response = response.content.decode() + response = json.loads(response) + response = response["id_token"] + + response = requests.post( + uefa_tv.GIGYA_JWT_URL, + headers={ + 'realm': uefa_tv.REALM_DICT["REALM_ID"], + 'x-api-key': uefa_tv.REALM_DICT["REALM_API_KEY"] + }, + json={'jwt': response} + ) + + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + message = str(response.get("messages", "")).lower() + + if status_code == 401 or "api key" in message: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=f'from {uefa_tv.__name__}', + reason="Can't access the video content because the API key was changed", + solution=f'Delete the {uefa_tv.CACHE_FILE} cache manually or add the parameter --fresh to your command' + )) + + uefa_tv.ACCOUNT_TOKENS = response + + @staticmethod + def get_realm_dict(): + try: + file_dict = file_to_dict(uefa_tv.CACHE_FILE) + assert len(file_dict.keys()) == 4 + return file_dict + except: + pass + + response = requests.get( + uefa_tv.BASE_URL, + headers={'User-Agent': uefa_tv.USER_AGENT} + ).content.decode() + response = re.findall(r'"static/js/".*"\.chunk\.js"', response)[0] + response = re.findall(r'(\d+:"[^"]+")', response) + + for chunk in response: + chunk = chunk.replace('"', "").split(":") + chunk_js = requests.get( + uefa_tv.CHUNK_JS_URL.format( + chunk_id=chunk[0], + chunk_str=chunk[1] + ), + headers={'User-Agent': uefa_tv.USER_AGENT} + ).content.decode() + + try: + realm_id = re.findall(r'REACT_APP_DICE_REALM_ID:"([^"]+)"', chunk_js)[0] + realm_api_key = re.findall(r'REACT_APP_DICE_API_KEY:"([^"]+)"', chunk_js)[0] + algolia_app_id = re.findall(r'REACT_APP_ALGOLIA_APP_ID:"([^"]+)"', chunk_js)[0] + algolia_api_key = re.findall(r'REACT_APP_ALGOLIA_API_KEY:"([^"]+)"', chunk_js)[0] + + assert realm_id is not None + assert realm_api_key is not None + assert algolia_app_id is not None + assert algolia_api_key is not None + + realm_dict = { + "REALM_ID": realm_id, + "REALM_API_KEY": realm_api_key, + "ALGOLIA_APP_ID": algolia_app_id, + "ALGOLIA_API_KEY": algolia_api_key + } + dict_to_file(uefa_tv.CACHE_FILE, realm_dict) + return realm_dict + except: + pass + raise "Failed to extract site information" + + @staticmethod + def initialize_service(): + if uefa_tv.CACHE_FILE is None: + uefa_tv.CACHE_FILE = join(CACHE_DIR, f'{uefa_tv.__name__}.json') + if builtins.CONFIG.get("FRESH", False) is True: + dict_to_file(uefa_tv.CACHE_FILE, {}) + if uefa_tv.USER_AGENT is None: + uefa_tv.USER_AGENT = builtins.CONFIG["USER_AGENT"] + + if uefa_tv.LOGIN_COOKIES is None: + uefa_tv.LOGIN_COOKIES = uefa_tv.get_login_cookies() + if uefa_tv.LOGIN_COOKIES is None: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=f'from {uefa_tv.__name__}', + reason='Need account for this service', + solution='Sign into your account using Firefox' + )) + + if uefa_tv.REALM_DICT is None: + uefa_tv.REALM_DICT = uefa_tv.get_realm_dict() + uefa_tv.SEARCH_QUERY_URL = uefa_tv.SEARCH_QUERY_URL.format( + app_id=uefa_tv.REALM_DICT["ALGOLIA_APP_ID"].lower() + ) + if uefa_tv.ACCOUNT_TOKENS is None: + uefa_tv.set_account_tokens() + if uefa_tv.LOCK is None: + uefa_tv.LOCK = threading.Lock() + return uefa_tv + + @staticmethod + def get_keys(challenge, additional): + raise Exception( + f'{BaseService.get_keys.__name__} must not be called ' + f'for the {uefa_tv.__name__} service' + ) + + @staticmethod + def refresh_account_tokens(): + old_auth_token = uefa_tv.ACCOUNT_TOKENS["authorisationToken"] + with uefa_tv.LOCK: + if old_auth_token == uefa_tv.ACCOUNT_TOKENS["authorisationToken"]: + response = requests.post( + uefa_tv.REFRESH_TOKEN_URL, + headers={ + 'realm': uefa_tv.REALM_DICT["REALM_ID"], + 'x-api-key': uefa_tv.REALM_DICT["REALM_API_KEY"], + 'Authorization': f'Bearer {uefa_tv.ACCOUNT_TOKENS["authorisationToken"]}' + }, + json={'refreshToken': uefa_tv.ACCOUNT_TOKENS["refreshToken"]} + ) + + response = response.content.decode() + response = json.loads(response) + uefa_tv.ACCOUNT_TOKENS = response + + @staticmethod + def generate_master_m3u8(output_path, manifest): + m3u8_content = requests.get(manifest).content.decode() + if not os.path.exists(output_path): + os.makedirs(output_path) + + base_url = clean_url(manifest).split("/") + del base_url[-1] + base_url = "/".join(base_url) + + m3u8_content = m3u8.loads(m3u8_content) + for segment in m3u8_content.playlists + m3u8_content.media: + if not segment.uri.startswith("http"): + dots = segment.uri.count("../") + temp_base_url = base_url.split("/") + temp_base_url = temp_base_url[0:len(temp_base_url) - dots] + temp_base_url = "/".join(temp_base_url) + + segment.uri = segment.uri.replace("../", "") + if not segment.uri.startswith("/"): + segment.uri = "/" + segment.uri + segment.uri = temp_base_url + segment.uri + + output_path = join(output_path, "master.m3u8") + with open(output_path, "w") as f: + f.write(m3u8_content.dumps()) + return output_path + + @staticmethod + def get_video_data(source_element): + vod_id = re.search(r"/vod/([^/?]*)", source_element.url).group(1) + response = None + + for i in range(0, 2): + if i == 1: + uefa_tv.refresh_account_tokens() + + response = requests.get( + url=uefa_tv.STREAM_VOD_URL.format(vod_id=vod_id), + headers={ + 'realm': uefa_tv.REALM_DICT["REALM_ID"], + 'x-api-key': uefa_tv.REALM_DICT["REALM_API_KEY"], + 'Authorization': f'Bearer {uefa_tv.ACCOUNT_TOKENS["authorisationToken"]}' + } + ) + + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + message = str(response.get("messages", "")).lower() + + if i == 0: + if status_code == 401 and "bearer token" in message: + continue + if 400 <= status_code < 500: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + break + + assert response is not None + response = response["playerUrlCallback"] + response = requests.get(response) + + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + message = str(response.get("message", "")).lower() + + if status_code == 403 and "not available in your location" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available in your location", + solution="Use a VPN" + )) + + if source_element.element is None: + metadata = {} + for i in range(0, 2): + if i == 1: + uefa_tv.refresh_account_tokens() + + metadata = requests.get( + uefa_tv.VOD_METADATA_URL.format(vod_id=vod_id), + headers={ + 'realm': uefa_tv.REALM_DICT["REALM_ID"], + 'x-api-key': uefa_tv.REALM_DICT["REALM_API_KEY"], + 'Authorization': f'Bearer {uefa_tv.ACCOUNT_TOKENS["authorisationToken"]}' + } + ) + + status_code = metadata.status_code + metadata = metadata.content.decode() + metadata = json.loads(metadata) + message = str(metadata.get("messages", "")).lower() + + if i == 0: + if status_code == 401 and "bearer token" in message: + continue + break + + title = metadata.get("title", f'Vod_{vod_id}') + source_element.element = get_valid_filename(title) + + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + uefa_tv.__name__ + ) + + manifest = response.get("hlsUrl", None) + if manifest in ["", None]: + for f in ["hls", "dash", "smoothStreaming"]: + try: + manifest = response[f]["url"] + assert manifest not in ["", None] + break + except: + pass + + assert manifest not in ["", None] + manifest = uefa_tv.generate_master_m3u8( + join(source_element.collection, source_element.element), + manifest + ) + return manifest, None, {} + + @staticmethod + def get_playlist(collection_url): + playlist_id = re.search(r"/playlist/([^/?]*)", collection_url).group(1) + response = None + p = 0 + total = None + collection_title = None + + vod_index = 0 + collection = [] + while True: + p += 1 + for i in range(0, 2): + if i == 1: + uefa_tv.refresh_account_tokens() + + response = requests.get( + uefa_tv.PLAYLIST_URL.format(playlist_id=playlist_id), + params={'p': p}, + headers={ + 'realm': uefa_tv.REALM_DICT["REALM_ID"], + 'x-api-key': uefa_tv.REALM_DICT["REALM_API_KEY"], + 'Authorization': f'Bearer {uefa_tv.ACCOUNT_TOKENS["authorisationToken"]}' + } + ) + + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + message = str(response.get("messages", "")).lower() + + if i == 0: + if status_code == 401 and "bearer token" in message: + continue + if 400 <= status_code < 500: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + break + + if collection_title is None: + collection_title = response.get("title", f'Playlist_{playlist_id}') + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + uefa_tv.__name__ + ), + get_valid_filename(collection_title) + ) + + response = response.get("videos", {}) + if total is None: + total = response.get("totalPages", None) + + vods = response.get("vods", []) + for vod in vods: + vod_index += 1 + check = check_range(False, None, vod_index) + if check is True: + continue + elif check is False: + return collection + + if vod.get("type", "").lower() not in ["vod"]: + continue + vod_url = uefa_tv.VOD_URL.format(vod_id=vod["id"]) + vod_title = vod.get("title", vod["id"]) + vod_title = f'Vod_{vod_index}_{vod_title}' + + collection.append(BaseElement( + url=vod_url, + collection=collection_title, + element=get_valid_filename(vod_title) + )) + + if (total is not None and p >= total) or len(vods) == 0: + break + + return collection + + @staticmethod + def get_search(collection_url): + params_dict = parse_qs(urlparse(collection_url).query) + query = params_dict["q"][0] + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + uefa_tv.__name__ + ), + get_valid_filename(f'Search_{query}') + ) + + page = -1 + total = None + collection = [] + vod_index = 0 + while True: + page += 1 + + response = requests.post( + url=uefa_tv.SEARCH_QUERY_URL, + params={ + 'x-algolia-application-id': uefa_tv.REALM_DICT["ALGOLIA_APP_ID"], + 'x-algolia-api-key': uefa_tv.REALM_DICT["ALGOLIA_API_KEY"] + }, + data=json.dumps({ + 'query': query, 'page': page, + 'hitsPerPage': uefa_tv.PAGE_SIZE, + 'filters': 'type:LIVE_EVENT OR type:VOD_VIDEO' + }) + ) + + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + message = response.get("message", "").lower() + + if status_code == 403 or "api key" in message: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=f'from {uefa_tv.__name__}', + reason="Can't access the video content because the API key was changed", + solution=f'Delete the {uefa_tv.CACHE_FILE} cache manually or add the parameter --fresh to your command' + )) + if total is None: + total = response.get("nbPages", None) + + vods = response.get("hits", []) + for vod in vods: + vod_index += 1 + check = check_range(False, None, vod_index) + if check is True: + continue + elif check is False: + return collection + + if vod.get("type", "").lower() not in ["vod_video"]: + continue + vod_url = uefa_tv.VOD_URL.format(vod_id=vod["id"]) + vod_title = vod.get("name", vod["id"]) + vod_title = f'Vod_{vod_index}_{vod_title}' + + collection.append(BaseElement( + url=vod_url, + collection=collection_title, + element=get_valid_filename(vod_title) + )) + if (total is not None and page + 1 >= total) or len(vods) == 0: + break + return collection + + @staticmethod + def get_competition(collection_url): + competition_id = collection_url.split("/")[-1] + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + uefa_tv.__name__ + ), + get_valid_filename(f'Competition_{competition_id}') + ) + + bucket_page = 0 + bucket_total = None + bucket_index = 0 + visited_vods = [] + collection = [] + while True: + bucket_page += 1 + buckets_response = None + + for i in range(0, 2): + if i == 1: + uefa_tv.refresh_account_tokens() + + buckets_response = requests.get( + uefa_tv.COMP_CONTENT_URL.format(competition_id=competition_id), + params={'bp': bucket_page}, + headers={ + 'realm': uefa_tv.REALM_DICT["REALM_ID"], + 'x-api-key': uefa_tv.REALM_DICT["REALM_API_KEY"], + 'Authorization': f'Bearer {uefa_tv.ACCOUNT_TOKENS["authorisationToken"]}' + } + ) + + status_code = buckets_response.status_code + buckets_response = buckets_response.content.decode() + buckets_response = json.loads(buckets_response) + message = str(buckets_response.get("messages", "")).lower() + + if i == 0: + if status_code == 401 and "bearer token" in message: + continue + break + + if bucket_total is None: + bucket_total = buckets_response.get("totalPages", None) + buckets_response = buckets_response.get("buckets", []) + + for bucket in buckets_response: + bucket_index += 1 + check = check_range(True, bucket_index, None) + if check is True: + continue + elif check is False: + return collection + if bucket.get("type", "").lower() not in ["vod_video"]: + continue + + bucket_id = bucket["exid"] + bucket_title = bucket.get("name", bucket_id) + bucket_title = get_valid_filename(f'Rail_{bucket_index}_{bucket_title}') + + bucket_params = {} + vod_index = 0 + while True: + vods_response = None + + for i in range(0, 2): + if i == 1: + uefa_tv.refresh_account_tokens() + + vods_response = requests.get( + uefa_tv.COMP_BUCKET_URL.format( + competition_id=competition_id, + bucket_id=bucket_id + ), + params=bucket_params, + headers={ + 'realm': uefa_tv.REALM_DICT["REALM_ID"], + 'x-api-key': uefa_tv.REALM_DICT["REALM_API_KEY"], + 'Authorization': f'Bearer {uefa_tv.ACCOUNT_TOKENS["authorisationToken"]}' + } + ) + + status_code = vods_response.status_code + vods_response = vods_response.content.decode() + vods_response = json.loads(vods_response) + message = str(vods_response.get("messages", "")).lower() + + if i == 0: + if status_code == 401 and "bearer token" in message: + continue + break + + vods = vods_response.get("contentList", []) + for vod in vods: + vod_index += 1 + check = check_range(False, bucket_index, vod_index) + if check is True: + continue + elif check is False: + return collection + if vod.get("type", "").lower() not in ["vod"]: + continue + + if vod["id"] in visited_vods: + continue + visited_vods.append(vod["id"]) + vod_title = vod.get("title", vod["id"]) + vod_title = f'Vod_{vod_index}_{vod_title}' + + collection.append(BaseElement( + url=uefa_tv.VOD_URL.format(vod_id=vod["id"]), + collection=join(collection_title, bucket_title), + element=get_valid_filename(vod_title) + )) + + if vods_response.get("paging", {}).get("moreDataAvailable", False) is False or len(vods) == 0: + break + bucket_params = {"lastSeen": vods_response["paging"]["lastSeen"]} + + if (bucket_total is not None and bucket_page >= bucket_total) or len(buckets_response) == 0: + break + return collection + + @staticmethod + def get_collection_elements(collection_url): + if "/live/" in collection_url: + return None + if "/search/videos?q=" in collection_url: + return uefa_tv.get_search(collection_url) + + collection_url = clean_url(collection_url) + if "/video/vod/" in collection_url or "/match/vod/" in collection_url: + return [BaseElement(url=collection_url)] + if "/playlist/" in collection_url: + return uefa_tv.get_playlist(collection_url) + if "/competition/" in collection_url: + return uefa_tv.get_competition(collection_url) + return None diff --git a/API/proxiesembed/drmproxy/services/veeps_com.py b/API/proxiesembed/drmproxy/services/veeps_com.py new file mode 100644 index 0000000..51c2d15 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/veeps_com.py @@ -0,0 +1,280 @@ +import builtins +import re +from html import unescape +from os.path import join + +import browser_cookie3 +import requests +from bs4 import BeautifulSoup +from chompjs import parse_js_object + +from utils.constants.macros import ERR_MSG, USER_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, CustomException, BaseService +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename + + +class veeps_com(BaseService): + DEMO_URLS = [ + "https://veeps.com/e/artistfriendly/6da4a3b9-6f05-400b-a1f2-16209bc70a6c/312347b6-2345-1111-1111-234562972866", + "https://veeps.com/e/b/68ea8351-ba2d-4313-9f2f-ec8b5f5cd164/312347b6-2345-1111-1111-234562972866", + "https://veeps.com/a/b62bf5d7-2a65-42e4-a26b-a8df42f6db47", + "https://veeps.com/artistfriendly/6da4a3b9-6f05-400b-a1f2-16209bc70a6c", + "https://veeps.com/browse/country", + ] + + LICENSE_URL = 'https://widevine-dash.ezdrm.com/proxy' + BASE_URL = "https://veeps.com" + + LOGIN_COOKIES = None + USER_ID = None + LICENSE_ID = "72D27A" + + @staticmethod + def test_service(): + main_service.run_service(veeps_com) + + @staticmethod + def credentials_needed(): + return {"FIREFOX_COOKIES": True} + + @staticmethod + def get_login_cookies(): + cookie_dict = {} + for c in browser_cookie3.firefox(domain_name='veeps.com'): + cookie_dict[c.name] = c.value + + try: + assert len(cookie_dict.keys()) > 0 + return cookie_dict + except: + return None + + @staticmethod + def get_user_id(): + response = requests.get(veeps_com.BASE_URL, cookies=veeps_com.LOGIN_COOKIES).content.decode() + user_id = re.search(r'"user_id":[^"]*"(.+?)"', response).group(1) + return user_id + + @staticmethod + def initialize_service(): + if veeps_com.LOGIN_COOKIES is None: + veeps_com.LOGIN_COOKIES = veeps_com.get_login_cookies() + if veeps_com.LOGIN_COOKIES is None: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=f'from {veeps_com.__name__}', + reason='Need account for this service', + solution='Sign into your account using Firefox' + )) + + if veeps_com.USER_ID is None: + veeps_com.USER_ID = veeps_com.get_user_id() + return veeps_com + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + veeps_com.LICENSE_URL, + params={'pX': veeps_com.LICENSE_ID}, + data=challenge + ) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_video_data(source_element): + response = requests.get(source_element.url, cookies=veeps_com.LOGIN_COOKIES).content.decode() + soup = BeautifulSoup(response, 'html5lib') + scripts = soup.find_all('script') + + response = None + pattern = re.compile(r'window\.__CONFIG__[^={]*=[^{]*({.*?});', re.DOTALL) + for script in scripts: + code = script.string + + if code: + match = pattern.search(code) + if match: + try: + response = parse_js_object(match.group(1)) + except: + continue + break + + if response is None: + response = {} + + manifest = None + video_title = "" + for _, v in response.items(): + if type(v) is not list: + v = [v] + + try: + for d in v: + try: + manifest = d["playback"]["widevine_url"] + if len(manifest) == 0: + raise + except: + manifest = None + manifest = d["playback"]["stream_url"] + + try: + video_title = d["event_name"] + except: + pass + try: + video_title = d["presentation"]["subtitle"] + " " + video_title + except: + pass + if manifest is not None: + break + except: + pass + + if manifest is not None: + break + + if manifest is None: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Can't download paid content", + solution='Do not attempt to download it' + )) + + if len(video_title) == 0: + try: + video_title = unescape(soup.title.string) + except: + video_title = source_element.url.split(veeps_com.BASE_URL)[-1] + video_title = get_valid_filename(video_title) + + if source_element.element is None: + source_element.element = video_title + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + veeps_com.__name__ + ) + + response = requests.get(manifest).content.decode() + try: + pssh_value = re.search(r'base64,([^"]+)"', response).group(1) + except: + pssh_value = None + + if pssh_value is None: + try: + pssh_value = str(min(re.findall( + r'<[^<>]*cenc:pssh[^<>]*>(.*?)]*cenc:pssh[^<>]*>', + response + ), key=len)) + except: + pssh_value = None + return manifest, pssh_value, {} + + @staticmethod + def is_wide_card(tag): + while tag: + if tag.has_attr('data-card-content') and tag['data-card-content'] == 'wide': + return True + tag = tag.find_parent() + return False + + @staticmethod + def get_rails(tag): + while tag: + if tag.name == 'section': + return tag + tag = tag.find_parent() + return None + + @staticmethod + def get_collection_elements(collection_url): + collection_url = collection_url.split("#")[0].split("?")[0].rstrip("/") + if collection_url.startswith(veeps_com.BASE_URL + "/e/"): + return [BaseElement(url=collection_url)] + + response = requests.get(collection_url, cookies=veeps_com.LOGIN_COOKIES).content.decode() + if '"widevine_url":"' in response or '"stream_url":"' in response: + return [BaseElement(url=collection_url)] + + soup = BeautifulSoup(response, 'html5lib') + a_nodes = soup.find_all('a', attrs={ + 'data-phx-link': 'redirect', + 'data-testid': 'ds_card_link', + 'data-list-item': True + }) + + try: + collection_name = unescape(soup.title.string) + except: + collection_name = collection_url.split(veeps_com.BASE_URL)[-1] + collection_name = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + veeps_com.__name__ + ), + get_valid_filename(collection_name) + ) + + collection = [] + rail_index = 0 + video_index = 0 + visited_videos = [] + visited_rails = [] + + for a_node in a_nodes: + if a_node.find(attrs={'data-testid': 'ds_card_subtitle'}) is None: + continue + if a_node["href"].startswith("/browse/"): + continue + if veeps_com.is_wide_card(a_node): + continue + rail = veeps_com.get_rails(a_node) + + try: + rail_id = rail.get("id", rail["data-list-id"]) + except: + rail_id = None + if rail_id not in visited_rails: + rail_index += 1 + video_index = 0 + visited_rails.append(rail_id) + + check = check_range(True, rail_index, None) + if check is True: + continue + elif check is False: + return collection + + try: + if rail_id is None: + raise + rail_name = get_valid_filename(f'Rail_{rail_index}_{rail["data-list-name"]}') + except: + rail_name = f"Rail_{rail_index}" + rail_name = join(collection_name, rail_name) + + video_index += 1 + check = check_range(False, rail_index, video_index) + if check is True: + continue + elif check is False: + return collection + + if a_node["href"] in visited_videos: + continue + visited_videos.append(a_node["href"]) + collection.append(BaseElement( + url=f'{veeps_com.BASE_URL}/e{a_node["href"]}/{veeps_com.USER_ID}', + collection=rail_name, + element=f'Video_{video_index}' + f'_' + f'{get_valid_filename(a_node["data-item-name"])}' + )) + return collection diff --git a/API/proxiesembed/drmproxy/services/video_telequebec_tv.py b/API/proxiesembed/drmproxy/services/video_telequebec_tv.py new file mode 100644 index 0000000..2071534 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/video_telequebec_tv.py @@ -0,0 +1,340 @@ +import builtins +import json +import re +from os.path import join + +import requests + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.cdm import get_pssh_from_cenc_pssh +from utils.tools.common import get_valid_filename, clean_url + + +class video_telequebec_tv(BaseService): + DEMO_URLS = [ + "https://video.telequebec.tv/player/46320/stream?assetType=episodes", + "https://video.telequebec.tv/player/47446/stream?assetType=episodes&playlist_id=379", + "https://video.telequebec.tv/player/35829/stream?assetType=episodes&playlist_id=439", + "https://video.telequebec.tv/en%20vedette/details/31828?playlist_id=411", + "https://video.telequebec.tv/details/44539?playlist_id=358", + "https://video.telequebec.tv/jeunesse/details/35777?playlist_id=439", + ] + + ANONYMOUS_LOGIN_URL = 'https://beacon.playback.api.brightcove.com/telequebec/api/account/anonymous_login' + ASSET_INFO_URL = 'https://beacon.playback.api.brightcove.com/telequebec/api/account/{account_token}/asset_info/{asset_id}' + CONFIG_JSON_URL = 'https://players.brightcove.net/{account_id}/{config_id}_default/config.json' + CONFIGS_JSON_URL = 'https://video.telequebec.tv/assets/configs/config.json' + API_SETTINGS_URL = 'https://beacon.playback.api.brightcove.com/telequebec/api/settings' + PLAYBACK_URL = 'https://edge.api.brightcove.com/playback/v1/accounts/{account_id}/videos/{video_id}' + EPISODES_URL = 'https://beacon.playback.api.brightcove.com/telequebec/api/tvshow/{show_id}/season/{season_id}/episodes' + SEASONS_URL = 'https://beacon.playback.api.brightcove.com/telequebec/api/assets/{show_id}' + VIDEO_URL = 'https://video.telequebec.tv/player/{video_id}/stream' + + AUTH_TOKEN = None + ACCOUNT_TOKEN = None + ACCOUNT_ID = None + POLICY_KEY = None + PAGE_LIMIT = 500 + + @staticmethod + def test_service(): + main_service.run_service(video_telequebec_tv) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def set_anonymous_account(): + response = requests.post( + video_telequebec_tv.ANONYMOUS_LOGIN_URL, + params={'device_type': 'web', 'duid': 'duid'} + ) + response = response.content.decode() + response = json.loads(response) + + video_telequebec_tv.AUTH_TOKEN = response["auth_token"] + video_telequebec_tv.ACCOUNT_TOKEN = response["account_token"] + + @staticmethod + def set_policy_key(): + response = requests.get( + video_telequebec_tv.API_SETTINGS_URL, + params={ + 'device_type': 'web', + 'device_layout': 'web', + 'build_version': 'build_version' + } + ) + response = response.content.decode() + response = json.loads(response) + config_id = response["data"]["feature_flags"]["bc_web_player_id"]["vod"] + + response = requests.get(video_telequebec_tv.CONFIGS_JSON_URL) + response = response.content.decode() + response = json.loads(response) + video_telequebec_tv.ACCOUNT_ID = response["brightcoveAccounts"][0]["accountId"] + + response = requests.get( + video_telequebec_tv.CONFIG_JSON_URL.format( + account_id=video_telequebec_tv.ACCOUNT_ID, + config_id=config_id + ) + ) + response = response.content.decode() + response = json.loads(response) + video_telequebec_tv.POLICY_KEY = response["video_cloud"]["policy_key"] + + @staticmethod + def initialize_service(): + if video_telequebec_tv.ACCOUNT_TOKEN is None: + video_telequebec_tv.set_anonymous_account() + if video_telequebec_tv.POLICY_KEY is None: + video_telequebec_tv.set_policy_key() + return video_telequebec_tv + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + additional["license_url"], + data=challenge + ) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_video_data(source_element): + asset_id = re.search(r"/player/([^/?]+)", source_element.url).group(1) + + response = requests.get( + video_telequebec_tv.ASSET_INFO_URL.format( + account_token=video_telequebec_tv.ACCOUNT_TOKEN, + asset_id=asset_id + ), + params={'device_type': 'web', 'ngsw-bypass': '1'}, + headers={'Authorization': f'Bearer {video_telequebec_tv.AUTH_TOKEN}'} + ) + + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + error = response.get("error", "").lower() + + if 400 <= status_code < 500 or "pas valide" in error: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + video_id = response["data"]["video_playback_details"][0]["video_id"] + + response = requests.get( + video_telequebec_tv.PLAYBACK_URL.format( + account_id=video_telequebec_tv.ACCOUNT_ID, + video_id=video_id + ), + headers={'Accept': f'application/json;pk={video_telequebec_tv.POLICY_KEY}'} + ) + response = response.content.decode() + response = json.loads(response) + + if source_element.element is None: + title = response.get("name", None) + if title not in ["", None]: + fields = response.get("custom_fields", {}) + + for f in ["beacon_episode_seriename", "beacon_episode_seasonnumber", "beacon_episode_number"]: + try: + title += " " + fields[f] + except: + pass + else: + title = asset_id + source_element.element = get_valid_filename(title) + + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + video_telequebec_tv.__name__ + ) + + sources = response["sources"] + no_drm = list(filter( + lambda s: + s.get("key_systems", None) is None or + (type(s["key_systems"]) is dict and len(s["key_systems"].keys()) == 0), + sources + )) + + has_drm = len(no_drm) == 0 + if not has_drm: + sources = no_drm + + manifest = None + license_url = None + for source in sources: + manifest = source["src"] + if has_drm: + keys = list(source["key_systems"].keys()) + keys = [k for k in keys if "widevine" in k.lower()] + + if len(keys) > 0: + license_url = source["key_systems"][keys[0]]["license_url"] + + if manifest is not None: + if has_drm and license_url is not None: + break + if not has_drm: + break + + pssh_value = None + if has_drm: + if license_url is None: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine wasn't found", + solution="Do not attempt to download it" + )) + + try: + manifest_content = requests.get(manifest) + manifest_content = manifest_content.content.decode() + pssh_value = get_pssh_from_cenc_pssh(manifest_content) + except: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}. Can't extract pssh", + solution=f"Extend the {video_telequebec_tv.__name__} service" + )) + + return manifest, pssh_value, {"license_url": license_url} + + @staticmethod + def get_collection_elements(collection_url): + collection_url = clean_url(collection_url) + if "/player/" in collection_url: + return [BaseElement(url=collection_url)] + if "/details/" not in collection_url: + return None + + show_id = re.search(r"/details/([^/?]+)", collection_url).group(1) + response = requests.get( + video_telequebec_tv.SEASONS_URL.format(show_id=show_id), + params={ + 'device_type': 'web', + 'device_layout': 'web', + 'asset_id': show_id + } + ) + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + + error = response.get("error", "").lower() + if 400 <= status_code < 500 or "not found" in error: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + response = response["data"] + asset = response.get("asset", {}) + if asset is None: + asset = {} + + collection_title = asset.get("name", asset.get("original_name", "")) + collection_title += " " + asset.get("subtitle", "") + collection_title = collection_title.strip() + + if len(collection_title) == 0: + collection_title = asset.get("seo", {}).get("name", "") + if len(collection_title) == 0: + collection_title = asset.get("slug", "") + if len(collection_title) == 0: + collection_title = show_id + + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + video_telequebec_tv.__name__ + ), + get_valid_filename(collection_title) + ) + + response = response["screen"]["blocks"] + seasons = [] + visited = [] + for block in response: + for widget in block["widgets"]: + playlist = widget["playlist"] + if playlist["type"].lower() not in ["seasons"]: + continue + + for content in playlist["contents"]: + if content["season_number"] in visited: + continue + seasons.append((content["season_number"], content["slug"])) + visited.append(content["season_number"]) + + seasons = sorted(seasons, key=lambda s: s[0]) + collection = [] + for season_index, season_id in seasons: + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + page = 0 + while True: + page += 1 + + response = requests.get( + video_telequebec_tv.EPISODES_URL.format( + show_id=show_id, + season_id=season_id + ), + params={ + 'device_type': 'web', + 'device_layout': 'web', + 'layout_id': '1', + 'page': page, + 'limit': video_telequebec_tv.PAGE_LIMIT + } + ) + response = response.content.decode() + response = json.loads(response) + + episodes = response.get("data", []) + if episodes is None: + episodes = [] + if len(episodes) == 0: + break + + for episode in episodes: + check = check_range(False, season_index, episode["episode_number"]) + if check in [True, False]: + continue + + episode_title = episode.get("name", None) + if episode_title in ["", None]: + episode_title = episode["id"] + episode_title = f'Episode_{episode["episode_number"]}_{episode_title}' + + collection.append(BaseElement( + url=video_telequebec_tv.VIDEO_URL.format( + video_id=episode["id"] + ), + collection=join(collection_title, f'Season_{season_index}'), + element=get_valid_filename(episode_title) + )) + + return collection diff --git a/API/proxiesembed/drmproxy/services/viki_com.py b/API/proxiesembed/drmproxy/services/viki_com.py new file mode 100644 index 0000000..aaf35e4 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/viki_com.py @@ -0,0 +1,320 @@ +import base64 +import builtins +import json +import re +from os.path import join + +import browser_cookie3 +import requests + +from utils.constants.macros import ERR_MSG, USER_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename + + +class viki_com(BaseService): + DEMO_URLS = [ + "https://www.viki.com/tv/35630c-because-this-is-my-first-life", + "https://www.viki.com/tv/40179c-perfect-marriage-revenge", + "https://www.viki.com/tv/38381c-from-now-on-showtime", + "https://www.viki.com/movies/37657c-project-gutenberg", + "https://www.viki.com/videos/1249930v-makemate1-episode-3", + "https://www.viki.com/videos/1123051v", + "https://www.viki.com/videos/1233367v", + ] + + CONTAINER_URL = 'https://api.viki.io/v4/containers/{id}/{resource}.json' + VIDEO_JSON_URL = "https://api.viki.io/v4/videos/{id}.json" + VIDEO_URL = 'https://www.viki.com/api/videos/{video_id}' + BASE_URL = "https://www.viki.com" + + APP_ID, APP_VER = None, '1.1.1' + PAGE_SIZE = 50 + LOGIN_COOKIES = None + + @staticmethod + def test_service(): + main_service.run_service(viki_com) + + @staticmethod + def credentials_needed(): + return { + "OPTIONAL": True, + "FIREFOX_COOKIES": True + } + + @staticmethod + def get_app_info(): + response = requests.get(viki_com.BASE_URL).content.decode() + app_id = re.findall(r'"appID":"(.*?)"', response)[0] + return app_id + + @staticmethod + def get_login_cookies(): + cookie_dict = {} + try: + for c in browser_cookie3.firefox(domain_name='viki.com'): + cookie_dict[c.name] = c.value + except browser_cookie3.BrowserCookieError: + pass + + try: + assert len(cookie_dict.keys()) > 0 + return cookie_dict + except: + return {} + + @staticmethod + def initialize_service(): + if viki_com.LOGIN_COOKIES is None: + viki_com.LOGIN_COOKIES = viki_com.get_login_cookies() + if viki_com.APP_ID is None: + viki_com.APP_ID = viki_com.get_app_info() + return viki_com + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post(additional["license_url"], data=challenge) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_video_title(video_info, only_title=False): + video_title = "" + temp_title = "" + if video_info.get("titles", None) not in [None, "", {}]: + titles = video_info["titles"] + if titles.get("en", None) not in [None, "", {}]: + temp_title = titles["en"] + video_title += "_" + titles["en"] + + if only_title: + return temp_title + + for f in ["type", "number"]: + if video_info.get(f, None) not in [None, "", {}]: + video_title += "_" + str(video_info[f]) + + if video_info.get("container", None) not in [None, "", {}]: + video_info = video_info["container"] + + if video_info.get("titles", None) not in [None, "", {}]: + titles = video_info["titles"] + if titles.get("en", None) not in [None, "", {}]: + if temp_title != titles["en"]: + video_title = titles["en"] + video_title + elif video_info.get("i18n_title") not in [None, "", {}]: + if temp_title != video_info["i18n_title"]: + video_title = video_info["i18n_title"] + video_title + + if len(video_title) == 0: + video_title = None + elif video_title[0] == "_": + video_title = video_title[1:] + return video_title + + @staticmethod + def get_video_data(source_element): + video_id = re.search(r"/videos/([^-?#/]*)", source_element.url).group(1) + response = requests.get( + viki_com.VIDEO_URL.format(video_id=video_id), + headers={'x-viki-app-ver': viki_com.APP_VER}, + cookies=viki_com.LOGIN_COOKIES + ) + status_code = response.status_code + response = response.content.decode() + + try: + response = json.loads(response) + except Exception as e: + response = response.lower() + if ("429" in response and "too many requests" in response) or status_code in [429]: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="You downloaded too much content recently", + solution="Wait 30-45 minutes. Change the value of MEDIA_DOWNLOADER to 1 (from config json file). " + "Remove the -mt N_m3u8DL-RE parameter" + )) + raise e + + if response.get("error", None) not in ["", {}, None]: + status_code = response["error"].get("status", None) + if status_code == 404: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + if status_code == 403: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The VPN was detected", + solution="Get a better VPN or don't use one" + )) + + if source_element.element is None: + video_title = None + if response.get("video", None) not in [None, "", {}]: + video_title = viki_com.get_video_title(response["video"]) + + if video_title is None: + video_title = source_element.url.split("/videos/")[-1] + source_element.element = get_valid_filename(video_title) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + viki_com.__name__ + ) + + manifest = response.get("queue", []) + manifest = [m for m in manifest if m["type"] == "video"] + if len(manifest) == 0: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Can't download paid content or the video isn't available yet", + solution='Do not attempt to download it or wait until you can watch it' + )) + + manifest = manifest[0]["url"] + license_url = None + pssh_value = None + if response.get("drm", None) not in ["", {}, None]: + drm = json.loads(base64.b64decode(response["drm"]).decode()) + + if drm.get("dt3", None) not in ["", {}, None]: + license_url = drm["dt3"] + else: + drm_types = list(drm.keys()) + drm_types = [d for d in drm_types if re.match(r"dt\d+", d.lower())] + + if len(drm_types) > 0: + drm_types = max(drm_types, key=lambda d: int(d[2:])) + if drm[drm_types] not in ["", {}, None]: + license_url = drm[drm_types] + + try: + pssh_value = str(min(re.findall( + r']*>(.*?)', + requests.get(manifest).content.decode() + ), key=len)) + except: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine wasn't found", + solution="Do not attempt to download it" + )) + + return manifest, pssh_value, {"license_url": license_url} + + @staticmethod + def get_collection_elements(collection_url): + collection_url = collection_url.split("#")[0].split("?")[0].rstrip("/") + if "/videos/" in collection_url: + return [BaseElement(url=collection_url)] + + if "/tv/" in collection_url or "/movies/" in collection_url: + content_id = re.search( + fr"{viki_com.BASE_URL}/[^/]+/([^-?#/]*)", + collection_url + ).group(1) + + response = requests.get( + viki_com.VIDEO_JSON_URL.format(id=content_id), + params={"app": viki_com.APP_ID} + ) + status_code = response.status_code + response = response.content.decode() + + try: + response = json.loads(response) + except Exception as e: + response = response.lower() + if ("429" in response and "too many requests" in response) or status_code in [429]: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="You downloaded too much content recently", + solution="Wait 30-45 minutes. Change the value of MEDIA_DOWNLOADER to 1 (from config json file). " + "Remove the -mt N_m3u8DL-RE parameter" + )) + raise e + + if response.get("vcode", None) == 404: + return [] + + collection_name = viki_com.get_video_title(response) + if collection_name is None: + collection_name = collection_url.split("/tv/")[-1] + collection_name = get_valid_filename(collection_name) + collection_name = join(join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + viki_com.__name__ + ), collection_name) + + season_index = 0 + collection = [] + for season in ["episodes", "clips", "trailers"]: + season_index += 1 + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + page = 0 + temp_ep_index = 0 + while True: + page += 1 + + if season == "episodes": + params = { + 'token': 'undefined', 'direction': 'asc', + 'with_upcoming': 'true', 'sort': 'number', + 'blocked': 'true', 'app': viki_com.APP_ID, + 'page': page, 'per_page': viki_com.PAGE_SIZE + } + else: + params = { + 'sort': 'newest_video', 'app': viki_com.APP_ID, + 'page': page, 'per_page': viki_com.PAGE_SIZE + } + + episodes = json.loads(requests.get( + viki_com.CONTAINER_URL.format(id=content_id, resource=season), + params=params + ).content.decode()).get("response", []) + if len(episodes) == 0: + break + + for episode in episodes: + temp_ep_index += 1 + episode_index = temp_ep_index if episode["number"] == 0 else episode["number"] + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + episode_url = episode["url"]["web"] + episode_title = viki_com.get_video_title(episode, only_title=True) + if episode_title in ["", None]: + episode_title = f'Episode_{episode_index}' + else: + episode_title = get_valid_filename(episode_title) + episode_title = f'Episode_{episode_index}_{episode_title}' + + collection.append(BaseElement( + url=episode_url, + collection=join(collection_name, f'Season_{season_index}_{season}'), + element=episode_title + )) + + return collection + return None diff --git a/API/proxiesembed/drmproxy/services/viu_com.py b/API/proxiesembed/drmproxy/services/viu_com.py new file mode 100644 index 0000000..309ffb9 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/viu_com.py @@ -0,0 +1,522 @@ +import builtins +import json +import os +import re +import time +from os.path import join + +import requests +from bs4 import BeautifulSoup + +from utils.constants.macros import USER_ERROR, ERR_MSG, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, CustomException, BaseService +from utils.tools.args import check_range +from utils.tools.cdm import get_pssh_from_cenc_pssh +from utils.tools.common import get_valid_filename, clean_url, get_country_code, has_only_roman_chars, \ + get_width_res_from_height, get_ext_from_url + + +class viu_com(BaseService): + DEMO_URLS = [ + "https://www.viu.com/ott/hk/zh/vod/102327/Viu-Beauty", + "https://www.viu.com/ott/za/en/vod/2379047/Skeem-Saam-S13", + "https://www.viu.com/ott/sg/en/vod/318741/Running-Man-2020", + "https://www.viu.com/ott/sg/en/vod/2552615/aespa-WORLD-TOUR-in-cinemas", + "https://www.viu.com/ott/sg/en/vod/2404949/Love-My-Scent", + "https://www.viu.com/ott/th/th/vod/2573027/Trailer-FWB-%E0%B8%AB%E0%B9%89%E0%B8%B2%E0%B8%A1%E0%B8%A3%E0%B8%B1%E0%B8%81-%E0%B8%AB%E0%B9%89%E0%B8%B2%E0%B8%A1%E0%B8%A3%E0%B8%B9%E0%B9%89%E0%B8%AA%E0%B8%B6%E0%B8%81", + ] + + PLAYBACK_URL = 'https://api-gateway-global.viu.com/api/playback/distribute' + TOKEN_URL = 'https://api-gateway-global.viu.com/api/auth/token' + MOBILE_URL = 'https://api-gateway-global.viu.com/api/mobile' + + COUNTRY_CODE = None + BEARER_TOKEN = None + REGIONS = [ + "MY", "ID", "IN", "AE", "BH", "EG", "IQ", "JO", "KW", "OM", "QA", + "SA", "MM", "ZA", "YE", "LS", "SZ", "ZM", "BW", "NA", "MW", "KE", + "RW", "UG", "TZ", "GH", "NG", "ET", "DZ", "LY", "MR", "MA", "TN", + "LB", "IL", "PS", "SD", "HK", "SG", "TH", "PH", "AU", "NZ" + ] + PAGE_SIZE = 50 + LICENSE_RETRIES = 4 + PLATFORM = 'web' + + @staticmethod + def test_service(): + main_service.run_service(viu_com) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def get_bearer_token(): + response = requests.post( + viu_com.TOKEN_URL, + params={'platformFlagLabel': viu_com.PLATFORM, 'countryCode': viu_com.COUNTRY_CODE}, + json={'language': 'en', 'platform': 'browser', 'uuid': 'uuid'} + ) + status_code = response.status_code + response = response.content.decode() + + if (400 <= status_code < 500 + and + ("error.general.out_of_region" in response or "country code must be" in response) + ): + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=f'from the {viu_com.__name__} service', + reason="Need specific region IP to access content", + solution=f"Use a VPN with one of the following regions: {viu_com.REGIONS}" + )) + + response = json.loads(response) + bearer_token = response.get("token", None) + if bearer_token is None: + raise CustomException(ERR_MSG.format( + type=f'{APP_ERROR}', + url=f'from the {viu_com.__name__} service', + reason=f"Failed to get bearer token: {str(response)}", + solution="Debug the service" + )) + return bearer_token + + @staticmethod + def initialize_service(): + if viu_com.COUNTRY_CODE is None: + viu_com.COUNTRY_CODE = get_country_code() + + if viu_com.COUNTRY_CODE is None: + raise CustomException(ERR_MSG.format( + type=f'{APP_ERROR}', + url=f'from the {viu_com.__name__} service', + reason="Failed to obtain the country code", + solution="Fix the code responsible for obtaining the country code" + )) + else: + viu_com.COUNTRY_CODE = viu_com.COUNTRY_CODE.upper() + + if viu_com.BEARER_TOKEN is None: + viu_com.BEARER_TOKEN = viu_com.get_bearer_token() + return viu_com + + @staticmethod + def get_keys(challenge, additional): + licence = None + for i in range(1, viu_com.LICENSE_RETRIES + 1): + try: + licence = requests.post( + additional["license_url"], data=challenge, + headers={ + "authorization": additional["license_token"], + "x-client": viu_com.PLATFORM + } + ) + licence.raise_for_status() + break + except Exception as e: + response = e.response + if response.status_code >= 300 or response.status_code < 200: + if i < viu_com.LICENSE_RETRIES: + time.sleep(3) + continue + raise e + return licence.content + + @staticmethod + def merge_manifest_dict(manifest_dict, source_element): + m3u8s = [] + for m_res, m_src in manifest_dict.items(): + temp_url = clean_url(m_src) + + if not temp_url.endswith(".m3u8"): + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format can't be merged: {temp_url}", + solution=f"Extend the {viu_com.__name__} service" + )) + try: + res = int(re.findall(r"\d+", m_res)[0]) + m3u8s.append((int(res), m_src)) + except: + pass + + status_code = requests.head(m3u8s[-1][1]).status_code + if status_code < 200 or status_code >= 300: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Can't download paid content or your VPN was detected", + solution='Do not attempt to download it or change your VPN IP' + )) + + output_path = join(source_element.collection, source_element.element) + if not os.path.exists(output_path): + os.makedirs(output_path) + + m3u8_content = "#EXTM3U\n#EXT-X-VERSION:3\n" + for m_res, m_src in m3u8s: + resolution = f'{get_width_res_from_height(m_res)}x{m_res}' + m3u8_content += f"#EXT-X-STREAM-INF:BANDWIDTH={int(m_res) * 100000},RESOLUTION={resolution}\n" + m3u8_content += f"{m_src}\n" + m3u8_content += "#EXT-X-ENDLIST\n" + + output_path = join(str(output_path), "master.m3u8") + with open(output_path, "w") as f: + f.write(m3u8_content) + return output_path + + @staticmethod + def get_video_data(source_element): + if source_element.additional is None: + source_element.additional = {} + product_id = source_element.additional.get("product_id", None) + if product_id in ["", None]: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Can't download paid content", + solution='Do not attempt to download it' + )) + + content_region = source_element.additional.get("content_region", "") + content_id = source_element.additional.get("content_id", "") + content_params = source_element.additional.get("content_params", None) + subtitles = source_element.additional.get("subtitles", None) + if subtitles is None: + _, _, subtitles, content_params = viu_com.analyse_page(source_element.url, content_id, content_region) + + additional = {} + resolutions = [] + is_drm = None + for duration in [None, '180']: + params = content_params + params['ccs_product_id'] = product_id + is_preview = duration is not None + if is_preview: + params['duration'] = duration + + manifest_dict = {} + try: + response = requests.get( + viu_com.PLAYBACK_URL, params=params, + headers={'Authorization': f'Bearer {viu_com.BEARER_TOKEN}'} + ) + response = response.content.decode() + response = json.loads(response)["data"]["stream"] + assert type(response) is dict + + is_drm = response.get("is_drm", "") + if is_drm is None: + is_drm = "" + is_drm = is_drm.lower() in ["y", "yes"] + if is_drm: + drm_dict = response["drm"] + additional["license_url"] = drm_dict["license_url"] + additional["license_token"] = drm_dict["token"]["authorization"] + + resolutions = list(response["size"].keys()) + for stream_k, stream_v in response.items(): + if type(stream_v) is not dict: + continue + + is_valid = True + for source_k, source_v in stream_v.items(): + if source_k not in resolutions or type(source_v) is not str: + is_valid = False + break + temp_str = clean_url(source_v).split("/")[-1] + if is_drm: + if not temp_str.endswith(".mpd"): + is_valid = False + break + + if is_preview: + if "_var_" not in temp_str and "_var." not in temp_str: + is_valid = False + break + source_v = re.sub( + fr"/{temp_str}\?", + f'/{temp_str.replace("_var_", "_").replace("_var.", ".")}?', + source_v + ) + manifest_dict[source_k] = source_v + + if not is_valid: + manifest_dict = {} + continue + break + + assert len(manifest_dict.keys()) > 0 + assert len(resolutions) > 0 + break + except: + manifest_dict = {} + continue + + if len(manifest_dict.keys()) == 0: + if is_drm: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason=f"DRM not supported. Widevine DASH/MPD wasn't found", + solution="Do not attempt to download it" + )) + if is_preview: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Can't download paid content", + solution='Do not attempt to download it' + )) + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason=f"The content isn't available, or you need {content_region} IP", + solution=f"Do not attempt to download it or use a VPN (that is not detected)" + )) + + pssh_value = None + if is_drm: + manifest_url = manifest_dict[resolutions[-1]] + is_free = True + try: + manifest_content = requests.get(manifest_url) + is_free = 200 <= manifest_content.status_code < 300 + pssh_value = get_pssh_from_cenc_pssh(manifest_content.text) + except: + pssh_value = None + + if not is_free: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Can't download paid content or your VPN was detected", + solution='Do not attempt to download it or change your VPN IP' + )) + + if pssh_value is None: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {clean_url(manifest_url)}", + solution=f"Extend the {viu_com.__name__} service" + )) + + else: + manifest_url = viu_com.merge_manifest_dict(manifest_dict, source_element) + + srt_index = 0 + srts = [] + srt_path = join(source_element.collection, source_element.element) + for subtitle in subtitles: + for u in ['url', 'second_subtitle_url']: + try: + srt_url = subtitle[u] + assert srt_url.startswith("http") + srt_index += 1 + + srt_title = subtitle.get("code", "") + srt_title = f'subtitle_{srt_index} {srt_title}' + srt_ext = get_ext_from_url(srt_url) + if srt_ext in ["", None]: + srt_ext = ".srt" + + srts.append((False, BaseElement( + url=srt_url, + collection=srt_path, + element=f'{get_valid_filename(srt_title)}{srt_ext}' + ))) + except: + pass + + additional["SUBTITLES"] = srts + return manifest_url, pssh_value, additional + + @staticmethod + def analyse_page(page_url, content_id, content_region): + series_id = None + collection_title = None + current_subtitles = [] + distribute_params = { + 'platform_flag_label': viu_com.PLATFORM, + 'platformFlagLabel': viu_com.PLATFORM, 'ut': '0' + } + + try: + response = requests.get(page_url).text + soup = BeautifulSoup(response, 'html5lib') + script = soup.find_all('script', {'type': 'application/json'}) + script = [s for s in script if s.get("id", None) == "__NEXT_DATA__"] + + assert len(script) > 0 + for s in script: + s_text = s.string.lower() + if "product_detail" in s_text and content_id in s_text: + script = json.loads(s.string) + break + assert type(script) is dict + + script = script["props"]["pageProps"]["fallback"] + for script_key, script_val in script.items(): + script_key = script_key.lower() + if "product_detail" not in script_key or content_id not in script_key: + continue + + try: + series_id = script_val['data']["series"]["series_id"] + assert len(series_id) > 0 + except: + series_id = None + continue + + try: + current_subtitles = script_val['data']['current_product']['subtitle'] + assert len(current_subtitles) > 0 + except: + current_subtitles = [] + + try: + d_params = script_val['server']['area'] + assert type(d_params) is dict + except: + d_params = {} + + try: + area_id = d_params['area_id'] + assert type(area_id) in [str, int] and area_id != '' + area_id = str(area_id) + distribute_params['area_id'] = area_id + distribute_params['areaId'] = area_id + except: + pass + try: + country = d_params['country']['code'] + assert len(country) > 0 and type(country) is str + distribute_params['countryCode'] = country + except: + pass + + try: + langs = d_params['language'] + if type(langs) is not list: + langs = [langs] + + def_lang = [lg for lg in langs if lg.get('is_default', None) == '1'] + if len(def_lang) > 0: + lang_id = def_lang[0]['language_flag_id'] + else: + lang_id = langs[0]['language_flag_id'] + + assert len(lang_id) > 0 and type(lang_id) is str + distribute_params['language_flag_id'] = lang_id + distribute_params['languageFlagId'] = lang_id + except: + pass + + try: + collection_title = script_val['data']["series"]["name"] + assert len(collection_title) > 0 + assert has_only_roman_chars(collection_title) + except: + collection_title = f'Series {content_id}' + break + + assert len(series_id) > 0 + except: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=page_url, + reason=f"The content isn't available or need {content_region} IP to access content", + solution=f"Do not attempt to download it or use a VPN" + )) + return series_id, collection_title, current_subtitles, distribute_params + + @staticmethod + def get_collection_elements(collection_url): + collection_url = clean_url(collection_url) + if "/vod/" not in collection_url or "/ott/" not in collection_url: + return None + + content_id = re.findall(r"/vod/([^/]+)/", collection_url)[0] + content_region = collection_url.split("/")[4] + series_id, collection_title, current_subtitles, dist_params = viu_com.analyse_page( + collection_url, content_id, content_region + ) + + try: + assert len(collection_title) > 0 + assert has_only_roman_chars(collection_title) + except: + collection_title = f'Series {content_id}' + collection_title = join(join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + viu_com.__name__ + ), get_valid_filename(collection_title)) + + page = 0 + collection = [] + while True: + page += 1 + response = requests.get( + viu_com.MOBILE_URL, + params={ + 'countryCode': viu_com.COUNTRY_CODE, 'series_id': series_id, + 'size': viu_com.PAGE_SIZE, 'page': page, + 'platformFlagLabel': viu_com.PLATFORM, + 'r': '/vod/product-list', 'sort': 'asc' + } + ) + response = response.content.decode() + response = json.loads(response) + + try: + products = response["data"]["product_list"] + assert type(products) is list and len(products) > 0 + except: + products = [] + if len(products) == 0: + break + + for product in products: + try: + product_index = int(product["number"]) + assert len(product["product_id"]) > 0 + assert len(product["ccs_product_id"]) > 0 + except: + continue + + check = check_range(False, None, product_index) + if check is True: + continue + elif check is False: + return collection + + try: + episode_title = product.get("synopsis", "") + assert len(episode_title) > 0 + assert has_only_roman_chars(episode_title) + except: + episode_title = product['product_id'] + + content_subtitles = current_subtitles if product["product_id"] == content_id else None + content_params = dist_params if product["product_id"] == content_id else None + collection.append(BaseElement( + url=re.sub( + r"/vod/[^/]+/", f"/vod/{product['product_id']}/", + collection_url + ), + collection=collection_title, + element=get_valid_filename(f'Episode_{product_index} {episode_title}'), + additional={ + "product_id": product["ccs_product_id"], + "content_region": content_region, + "content_id": product['product_id'], + 'subtitles': content_subtitles, + "content_params": content_params + } + )) + return collection diff --git a/API/proxiesembed/drmproxy/services/vix_com.py b/API/proxiesembed/drmproxy/services/vix_com.py new file mode 100644 index 0000000..ce48b75 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/vix_com.py @@ -0,0 +1,336 @@ +import builtins +import json +import threading +from json import JSONDecodeError +from os.path import join + +import requests + +from utils.constants.macros import USER_ERROR, ERR_MSG +from utils.main_service import main_service +from utils.structs import BaseElement, CustomException, BaseService +from utils.tools.args import check_range +from utils.tools.cdm import get_pssh_from_cenc_pssh +from utils.tools.common import get_valid_filename, clean_url + + +class vix_com(BaseService): + DEMO_URLS = [ + "https://vix.com/es-es/video/video-4564160", + "https://vix.com/es-es/video/video-4326106", + "https://vix.com/es-es/video/video-4561911", + "https://vix.com/es-es/detail/series-502", + "https://vix.com/es-es/detail/series-4715", + "https://vix.com/es-es/detail/series-4027", + ] + + PLAY_URL = "https://nxs.mp.lura.live/v1/play/{play_id}" + TOKEN_URL = 'https://vix.com/api/video/token' + ANON_URL = 'https://vix.com/api/proxy/user/create-anon-user' + GRAPHQL_URL = 'https://client-api.vix.com/gql/v2' + VIDEO_URL = "https://vix.com/video/video-{video_id}" + + MANIFEST_PRIORITY = {"application/dash+xml": 1, 'application/x-mpegurl': 0} + BEARER_TOKEN = None + LOCK = None + PAGE_SIZE = 50 + APP_PLATFORM = 'web' + APP_VERSION = 'v0.0.0' + APP_DEVICE = 'desktop' + + @staticmethod + def test_service(): + main_service.run_service(vix_com) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def initialize_service(): + if vix_com.LOCK is None: + vix_com.LOCK = threading.Lock() + return vix_com + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post(additional["license_url"], data=challenge) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_video_data(source_element): + play_id = source_element.url.split("/video-")[-1] + response = requests.get( + vix_com.TOKEN_URL, + params={'videoId': play_id}, + headers={'x-video-type': 'VOD'} + ) + response = response.content.decode() + try: + response = json.loads(response) + except JSONDecodeError: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need Colombian IP to access content", + solution="Use a VPN" + )) + + response = requests.post( + vix_com.PLAY_URL.format(play_id=play_id), + data={'token': response["token"]} + ) + status_code = response.status_code + response = response.content.decode() + message = response.lower() + + if status_code in [404] and "not found" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + response = json.loads(response) + response = response["content"] + + if source_element.element is None: + title = response.get("title", None) + if title in ["", None]: + title = f"Video_{play_id}" + source_element.element = get_valid_filename(title) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + vix_com.__name__ + ) + + manifest = [] + media = response.get("media", []) + if media is None: + media = [] + for m in media: + try: + m["type"] = m["type"].lower() + except: + continue + + if m["type"] in vix_com.MANIFEST_PRIORITY.keys(): + manifest.append(m) + + manifest = sorted(manifest, key=lambda mn: vix_com.MANIFEST_PRIORITY[mn["type"]], reverse=True) + manifest = manifest[0] + license_url = manifest.get('licenseUrl', None) + manifest = manifest["url"] + + manifest_content = requests.get(manifest).content.decode() + try: + pssh_value = get_pssh_from_cenc_pssh(manifest_content, xml_node=":pssh") + except: + pssh_value = None + + if pssh_value is None: + license_url = None + return manifest, pssh_value, {"license_url": license_url} + + @staticmethod + def get_collection_elements(collection_url): + collection_url = clean_url(collection_url) + if "/video/" in collection_url and "/video-" in collection_url: + return [BaseElement(url=collection_url)] + if "/canales/" in collection_url: + return None + + if "/detail/" not in collection_url or "/series-" not in collection_url: + return None + if vix_com.BEARER_TOKEN is None: + with vix_com.LOCK: + if vix_com.BEARER_TOKEN is None: + response = requests.post( + vix_com.ANON_URL, json={'installationId': 'installationId'} + ) + response = response.content.decode() + + try: + response = json.loads(response) + vix_com.BEARER_TOKEN = response["accessToken"] + assert len(vix_com.BEARER_TOKEN) > 0 + except (JSONDecodeError, KeyError, AssertionError): + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="Need Colombian IP to access content", + solution="Use a VPN" + )) + + show_id = collection_url.split("/series-")[-1] + series_id = f'series:mcp:{show_id}' + collection_title = None + collection = [] + + season_after_id = None + season_index = 0 + while True: + seasons_response = requests.post( + vix_com.GRAPHQL_URL, + headers={ + 'authorization': f'Bearer {vix_com.BEARER_TOKEN}', + 'x-vix-platform': vix_com.APP_PLATFORM, + 'x-vix-app-version': vix_com.APP_VERSION, + 'x-vix-device-type': vix_com.APP_DEVICE + }, + json={ + 'operationName': 'DetailData', + 'variables': { + 'id': series_id, 'navigationSection': {'urlPath': ''}, + 'pagination': {'first': vix_com.PAGE_SIZE, 'after': season_after_id} + }, + 'query': ''' + query DetailData($id: ID!, $pagination: PaginationParams!) { + videoById(id: $id) { + ...VideoContentFullFragment videoTypeData { + ... on VideoTypeSeriesData { ...SeasonsConnectionBasicFragment } + } + } + } + fragment VideoContentFullFragment on VideoContent { ...VideoContentBasicFragment } + fragment VideoContentBasicFragment on VideoContent { title videoType } + fragment SeasonsConnectionBasicFragment on VideoTypeSeriesData { + seasonsConnection(pagination: $pagination) { edges { node { id title } } } + } + ''' + } + ) + + seasons_response = seasons_response.content.decode() + seasons_response = json.loads(seasons_response) + if collection_title is None: + try: + collection_title = seasons_response["data"]["videoById"]["title"] + collection_title = get_valid_filename(collection_title) + assert len(collection_title) > 0 + except: + collection_title = f"Series {show_id}" + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + vix_com.__name__ + ), + get_valid_filename(collection_title) + ) + + try: + seasons = seasons_response["data"]["videoById"]["videoTypeData"]["seasonsConnection"]["edges"] + except: + seasons = [] + if len(seasons) == 0: + break + season_after_id = None + + for season in seasons: + season = season.get("node", None) + if season is None: + continue + season_id = season.get("id", "") + if season_id == "": + continue + season_after_id = season_id + + season_index += 1 + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + season_title = season.get("title", "") + season_title = join( + collection_title, + get_valid_filename(f'Season_{season_index} {season_title}') + ) + + episode_after_id = None + while True: + episodes_response = requests.post( + vix_com.GRAPHQL_URL, + headers={ + 'authorization': f'Bearer {vix_com.BEARER_TOKEN}', + 'x-vix-platform': vix_com.APP_PLATFORM, + 'x-vix-app-version': vix_com.APP_VERSION, + 'x-vix-device-type': vix_com.APP_DEVICE + }, + json={ + 'operationName': 'SeasonById', + 'variables': { + 'seriesId': series_id, 'seasonId': season_id, + 'episodePagination': { + 'first': vix_com.PAGE_SIZE, + 'after': episode_after_id + }, + 'navigationSection': {'urlPath': ''} + }, + 'query': ''' + query SeasonById( + $seriesId: ID!, $seasonId: ID!, $episodePagination: PaginationParams! + ) { + seasonById(seriesId: $seriesId, seasonId: $seasonId) { ...SeasonByIdFragment } + } + fragment SeasonByIdFragment on Season { + episodesConnection(pagination: $episodePagination) { + edges { node { ...EpisodeFullFragment } } + } + } + fragment EpisodeFullFragment on VideoContent { + id title videoTypeData { ...VideoTypeEpisodeFullFragment } + } + fragment VideoTypeEpisodeFullFragment on VideoTypeEpisodeData { episodeNumber } + ''' + } + ) + + episodes_response = episodes_response.content.decode() + episodes_response = json.loads(episodes_response) + try: + episodes = episodes_response["data"]["seasonById"]["episodesConnection"]["edges"] + except: + episodes = [] + if len(episodes) == 0: + break + episode_after_id = None + + for episode in episodes: + episode = episode.get("node", None) + if episode is None: + continue + episode_id = episode.get("id", "").split(":")[-1] + if episode_id == "": + continue + episode_after_id = episode["id"] + + episode_index = episode["videoTypeData"]["episodeNumber"] + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + episode_url = vix_com.VIDEO_URL.format(video_id=episode_id) + episode_title = episode.get("title", None) + if episode_title in ["", None]: + episode_title = f"Id_{episode_id}" + episode_title = f'Episode_{episode_index} {episode_title}' + episode_title = get_valid_filename(episode_title) + + collection.append(BaseElement( + url=episode_url, + collection=season_title, + element=episode_title + )) + + if episode_after_id is None: + break + + if season_after_id is None: + break + return collection diff --git a/API/proxiesembed/drmproxy/services/vrt_be.py b/API/proxiesembed/drmproxy/services/vrt_be.py new file mode 100644 index 0000000..a3af168 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/vrt_be.py @@ -0,0 +1,698 @@ +import builtins +import json +import re +from os.path import join +from urllib.parse import urlparse, parse_qs, quote + +import browser_cookie3 +import requests +import xmltodict + +import utils.tools.cdm as cdm_tools +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename, clean_url + + +class vrt_be(BaseService): + DEMO_URLS = [ + "https://www.vrt.be/vrtmax/a-z/knokke-off/#afleveringen", + "https://www.vrt.be/vrtmax/a-z/doc-martin/#afleveringen", + "https://www.vrt.be/vrtmax/a-z/dag---nacht/#trailer", + "https://www.vrt.be/vrtmax/a-z/thuis/#alle-seizoenen", + "https://www.vrt.be/vrtmax/a-z/thuis/#throwbackthuis", + "https://www.vrt.be/vrtmax/a-z/fc-de-kampioenen/?seizoen=extras#afleveringen", + "https://www.vrt.be/vrtmax/a-z/postbus-x/", + "https://www.vrt.be/vrtmax/podcasts/studio-brussel/d/de-popcast-van-de-week/#afleveringen", + "https://www.vrt.be/vrtmax/luister/radio/m/mnm50~55-17/#uitzendingen", + "https://www.vrt.be/vrtmax/luister/radio/i/iedereen-klassiek~31-16/iedereen-klassiek~31-23781-0/", + "https://www.vrt.be/vrtmax/livestream/audio/klara/", + "https://www.vrt.be/vrtmax/livestream/video/ketnet/" + "https://www.vrt.be/vrtmax/livestream/video/vrt-canvas/", + "https://www.vrt.be/vrtmax/podcasts/mnm/0/22-minuten-stomme-vragen-/3/gustaph/", + "https://www.vrt.be/vrtmax/a-z/de-gruffalo/2009/de-gruffalo/", + ] + + TOKENS_URL = 'https://media-services-public.vrt.be/vualto-video-aggregator-web/rest/external/v2/tokens' + ITEMS_URL = 'https://media-services-public.vrt.be/media-aggregator/v2/media-items/{id}' + GRAPHQL_URL = 'https://www.vrt.be/vrtnu-api/graphql/public/v1' + REFRESH_URL = 'https://www.vrt.be/vrtmax/sso/refresh' + BASE_URL = 'https://www.vrt.be' + LICENSE_URL = 'https://widevine-proxy.drm.technology/proxy' + + PLAYER_TOKEN = None + PAGE_SIZE = 90 + + @staticmethod + def test_service(): + main_service.run_service(vrt_be) + + @staticmethod + def is_content_livestream(content, additional): + return "/livestream/audio/" in content or "/livestream/video/" in content + + @staticmethod + def credentials_needed(): + return { + "OPTIONAL": True, + "FIREFOX_COOKIES": True + } + + @staticmethod + def get_player_token(): + vrt_be_cookies = {} + try: + for c in browser_cookie3.firefox(domain_name='vrt.be'): + vrt_be_cookies[c.name] = c.value + except browser_cookie3.BrowserCookieError: + pass + + response = json.loads(requests.get( + vrt_be.REFRESH_URL, cookies=vrt_be_cookies + ).content.decode()) + vrt_be_cookies["vrtnu-site_profile_vt"] = response.get("tokens", {}).get("video_token", "") + + player_token = json.loads(requests.post( + vrt_be.TOKENS_URL, + json={'identityToken': vrt_be_cookies.get("vrtnu-site_profile_vt", "")} + ).content.decode())["vrtPlayerToken"] + return player_token + + @staticmethod + def initialize_service(): + if vrt_be.PLAYER_TOKEN is None: + vrt_be.PLAYER_TOKEN = vrt_be.get_player_token() + if vrt_be.PLAYER_TOKEN is None: + return None + return vrt_be + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + vrt_be.LICENSE_URL, + data=json.dumps({ + "token": additional["token"], + "drm_info": list(challenge) + }) + ) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_init_from_mpd(mpd_url): + mpd_content = requests.get(mpd_url).content.decode() + mpd_content = xmltodict.parse(mpd_content)["MPD"]["Period"] + base_url = mpd_content["BaseURL"] + if type(mpd_content["AdaptationSet"]) is not list: + mpd_content["AdaptationSet"] = [mpd_content["AdaptationSet"]] + + best_content = None + best_height = None + best_bandwidth = None + for content in mpd_content["AdaptationSet"]: + if content["@contentType"] != "video": + continue + update_content = False + + height = content.get("@maxHeight", content.get("@height", None)) + if height is None: + continue + height = int(height) + bandwidth = content.get("@maxBandwidth", content.get("@bandwidth", None)) + + if best_content is None: + update_content = True + else: + if height > best_height: + update_content = True + elif height == best_height: + if bandwidth is not None: + if best_bandwidth is None: + update_content = True + elif int(bandwidth) > int(best_bandwidth): + update_content = True + + if update_content: + best_content = content + best_height = height + best_bandwidth = bandwidth + + mpd_content = best_content + init_url = mpd_content["SegmentTemplate"]["@initialization"] + if type(mpd_content["Representation"]) is not list: + mpd_content["Representation"] = [mpd_content["Representation"]] + + best_content = None + for content in mpd_content["Representation"]: + if best_content is None: + best_content = content + continue + if int(content["@height"]) > int(best_content["@height"]): + best_content = content + continue + elif int(content["@height"]) == int(best_content["@height"]): + if int(content["@bandwidth"]) > int(best_content["@bandwidth"]): + best_content = content + continue + + init_url = init_url.replace("$RepresentationID$", best_content["@id"]) + init_url = '/'.join(mpd_url.split('/')[:-1]) + "/" + base_url + init_url + return init_url + + @staticmethod + def get_pssh_from_manifest(manifest): + return cdm_tools.get_pssh_from_init(vrt_be.get_init_from_mpd(manifest)) + + @staticmethod + def get_stream_data(url): + response = {} + action_type = None + + if "/a-z/" in url: + response = json.loads(requests.post( + vrt_be.GRAPHQL_URL, + headers={'x-vrt-client-name': 'WEB'}, + json={ + 'query': 'query VideoPage($pageId: ID!) {\n page(id: $pageId) {\n ... on EpisodePage {\n objectId\n title\n brand\n permalink\n seo {\n ...seoFragment\n __typename\n }\n socialSharing {\n ...socialSharingFragment\n __typename\n }\n trackingData {\n ...trackingDataFragment\n __typename\n }\n ldjson\n player {\n ...playerFragment\n __typename\n }\n episode {\n objectId\n title\n available\n brandLogos {\n ...brandLogosFragment\n __typename\n }\n logo\n primaryMeta {\n ...metaFragment\n __typename\n }\n secondaryMeta {\n ...metaFragment\n __typename\n }\n image {\n ...imageFragment\n __typename\n }\n playlist {\n __typename\n objectId\n activeListId\n lists {\n ... on StaticTileList {\n ...basicStaticTileListFragment\n __typename\n }\n __typename\n }\n }\n durationSeconds\n announcementValue\n name\n subtitle\n richDescription {\n __typename\n html\n }\n program {\n objectId\n link\n title\n __typename\n }\n watchAction {\n streamId\n videoId\n avodUrl\n resumePoint\n completed\n __typename\n }\n shareAction {\n title\n description\n image {\n templateUrl\n __typename\n }\n url\n __typename\n }\n favoriteAction {\n id\n title\n favorite\n programWhatsonId\n programUrl\n __typename\n }\n __typename\n }\n menu {\n ...menuFragment\n __typename\n }\n __typename\n }\n __typename\n }\n}\nfragment metaFragment on MetaDataItem {\n __typename\n type\n value\n shortValue\n longValue\n}\nfragment imageFragment on Image {\n __typename\n objectId\n alt\n title\n focalPoint\n templateUrl\n}\nfragment seoFragment on SeoProperties {\n __typename\n title\n description\n}\nfragment socialSharingFragment on SocialSharingProperties {\n __typename\n title\n description\n image {\n __typename\n objectId\n templateUrl\n }\n}\nfragment brandLogosFragment on Logo {\n colorOnColor\n height\n mono\n primary\n type\n width\n}\nfragment trackingDataFragment on PageTrackingData {\n data\n perTrigger {\n trigger\n data\n template {\n id\n __typename\n }\n __typename\n }\n}\nfragment playerFragment on MediaPlayer {\n __typename\n objectId\n expires\n image {\n ...imageFragment\n __typename\n }\n listenAction {\n __typename\n ... on LiveListenAction {\n streamId\n pageLink: livestreamPageLink\n startDate\n __typename\n }\n ... on PodcastEpisodeListenAction {\n streamId\n pageLink: podcastEpisodeLink\n resumePointId: audioId\n resumePoint\n completed\n __typename\n }\n ... on RadioEpisodeListenAction {\n streamId\n radioEpisodeId\n pageLink\n startDate\n endDate\n __typename\n }\n }\n modes {\n __typename\n active\n token {\n placeholder\n value\n __typename\n }\n }\n secondaryMeta {\n ...metaFragment\n __typename\n }\n sportBuffStreamId\n subtitle\n title\n watchAction {\n __typename\n ... on LiveWatchAction {\n streamId\n pageLink: livestreamPageLink\n startDate\n __typename\n }\n ... on EpisodeWatchAction {\n streamId\n pageLink: videoUrl\n resumePointId: videoId\n resumePoint\n completed\n avodUrl\n __typename\n }\n }\n}\nfragment menuFragment on ContainerNavigation {\n __typename\n objectId\n items {\n __typename\n objectId\n componentId\n title\n active\n }\n}\nfragment basicStaticTileListFragment on StaticTileList {\n __typename\n objectId\n listId\n displayType\n expires\n tileVariant\n tileContentType\n tileOrientation\n title\n items {\n ...tileFragment\n __typename\n }\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n}\nfragment tileFragment on Tile {\n ... on IIdentifiable {\n __typename\n objectId\n }\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n ... on ITile {\n description\n title\n active\n action {\n ...actionFragment\n __typename\n }\n actionItems {\n ...actionItemFragment\n __typename\n }\n image {\n ...imageFragment\n __typename\n }\n primaryMeta {\n ...metaFragment\n __typename\n }\n secondaryMeta {\n ...metaFragment\n __typename\n }\n tertiaryMeta {\n ...metaFragment\n __typename\n }\n indexMeta {\n __typename\n type\n value\n }\n statusMeta {\n __typename\n type\n value\n }\n labelMeta {\n __typename\n type\n value\n }\n __typename\n }\n ... on ContentTile {\n brand\n brandLogos {\n ...brandLogosFragment\n __typename\n }\n __typename\n }\n ... on BannerTile {\n compactLayout\n backgroundColor\n textTheme\n brand\n brandLogos {\n ...brandLogosFragment\n __typename\n }\n ctaText\n passUserIdentity\n titleArt {\n objectId\n templateUrl\n __typename\n }\n __typename\n }\n ... on EpisodeTile {\n description\n formattedDuration\n available\n chapterStart\n action {\n ...actionFragment\n __typename\n }\n playAction: watchAction {\n pageUrl: videoUrl\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n episode {\n __typename\n objectId\n program {\n __typename\n objectId\n link\n }\n }\n \n __typename\n }\n ... on PodcastEpisodeTile {\n formattedDuration\n available\n programLink: podcastEpisode {\n objectId\n podcastProgram {\n objectId\n link\n __typename\n }\n __typename\n }\n playAction: listenAction {\n pageUrl: podcastEpisodeLink\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n __typename\n }\n ... on PodcastProgramTile {\n link\n __typename\n }\n ... on ProgramTile {\n link\n __typename\n }\n ... on AudioLivestreamTile {\n brand\n brandsLogos {\n brand\n brandTitle\n logos {\n ...brandLogosFragment\n __typename\n }\n __typename\n }\n __typename\n }\n ... on LivestreamTile {\n description\n __typename\n }\n ... on ButtonTile {\n icon\n iconPosition\n mode\n __typename\n }\n ... on RadioEpisodeTile {\n action {\n ...actionFragment\n __typename\n }\n available\n \n formattedDuration\n ...componentTrackingDataFragment\n __typename\n }\n ... on SongTile {\n startDate\n formattedStartDate\n endDate\n __typename\n }\n ... on RadioProgramTile {\n objectId\n __typename\n }\n}\nfragment actionFragment on Action {\n __typename\n ... on FavoriteAction {\n favorite\n id\n programUrl\n programWhatsonId\n title\n __typename\n }\n ... on ListDeleteAction {\n listName\n id\n listId\n title\n __typename\n }\n ... on ListTileDeletedAction {\n listName\n id\n listId\n __typename\n }\n ... on PodcastEpisodeListenAction {\n id: audioId\n podcastEpisodeLink\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n ... on EpisodeWatchAction {\n id: videoId\n videoUrl\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n ... on LinkAction {\n id: linkId\n linkId\n link\n linkType\n openExternally\n passUserIdentity\n linkTokens {\n __typename\n placeholder\n value\n }\n __typename\n }\n ... on ShareAction {\n title\n url\n __typename\n }\n ... on SwitchTabAction {\n referencedTabId\n mediaType\n link\n __typename\n }\n ... on RadioEpisodeListenAction {\n streamId\n pageLink\n startDate\n __typename\n }\n ... on LiveListenAction {\n streamId\n livestreamPageLink\n startDate\n startOver\n endDate\n __typename\n }\n ... on LiveWatchAction {\n streamId\n livestreamPageLink\n startDate\n startOver\n endDate\n __typename\n }\n}\nfragment actionItemFragment on ActionItem {\n __typename\n objectId\n accessibilityLabel\n action {\n ...actionFragment\n __typename\n }\n active\n icon\n iconPosition\n icons {\n __typename\n position\n ... on DesignSystemIcon {\n value {\n name\n __typename\n }\n __typename\n }\n }\n mode\n objectId\n title\n}\nfragment componentTrackingDataFragment on IComponent {\n trackingData {\n data\n perTrigger {\n trigger\n data\n template {\n id\n __typename\n }\n __typename\n }\n __typename\n }\n}', + 'operationName': 'VideoPage', + 'variables': {'pageId': f'/vrtnu/{url.split("/vrtmax/")[1]}.model.json'} + } + ).content.decode()) + action_type = "watchAction" + + if "/podcasts/" in url: + response = json.loads(requests.post( + vrt_be.GRAPHQL_URL, + headers={'x-vrt-client-name': 'WEB'}, + json={ + 'query': 'query PodcastPage($pageId: ID!) {\n page(id: $pageId) {\n ... on PodcastEpisodePage {\n objectId\n permalink\n brand\n seo {\n ...seoFragment\n __typename\n }\n socialSharing {\n ...socialSharingFragment\n __typename\n }\n trackingData {\n data\n perTrigger {\n trigger\n data\n template {\n id\n __typename\n }\n __typename\n }\n __typename\n }\n ldjson\n components {\n __typename\n ... on IComponent {\n ... on PageHeader {\n objectId\n categories {\n title\n name\n category\n __typename\n }\n brandsLogos {\n brand\n brandTitle\n logos {\n mono\n primary\n type\n __typename\n }\n __typename\n }\n __typename\n }\n __typename\n }\n ... on ContainerNavigation {\n objectId\n __typename\n }\n }\n menu {\n ...menuFragment\n __typename\n }\n player {\n ...playerFragment\n __typename\n }\n podcastEpisode {\n objectId\n title\n available\n richDescription {\n __typename\n html\n }\n image {\n objectId\n templateUrl\n __typename\n }\n listenAction {\n audioId\n streamId\n publicationDate\n resumePoint\n completed\n __typename\n }\n presenters {\n name\n category\n title\n __typename\n }\n primaryMeta {\n ...metaFragment\n __typename\n }\n secondaryMeta {\n ...metaFragment\n __typename\n }\n shareAction {\n title\n description\n image {\n objectId\n templateUrl\n __typename\n }\n url\n __typename\n }\n podcastProgram {\n objectId\n title\n link\n __typename\n }\n podcastSeason {\n objectId\n title\n __typename\n }\n episodeNumberRaw\n __typename\n }\n __typename\n }\n __typename\n }\n}\nfragment menuFragment on ContainerNavigation {\n __typename\n objectId\n items {\n __typename\n objectId\n componentId\n title\n active\n }\n}\nfragment metaFragment on MetaDataItem {\n __typename\n type\n value\n shortValue\n longValue\n}\nfragment seoFragment on SeoProperties {\n __typename\n title\n description\n}\nfragment socialSharingFragment on SocialSharingProperties {\n __typename\n title\n description\n image {\n __typename\n objectId\n templateUrl\n }\n}\nfragment playerFragment on MediaPlayer {\n __typename\n objectId\n expires\n image {\n ...imageFragment\n __typename\n }\n listenAction {\n __typename\n ... on LiveListenAction {\n streamId\n pageLink: livestreamPageLink\n startDate\n __typename\n }\n ... on PodcastEpisodeListenAction {\n streamId\n pageLink: podcastEpisodeLink\n resumePointId: audioId\n resumePoint\n completed\n __typename\n }\n ... on RadioEpisodeListenAction {\n streamId\n radioEpisodeId\n pageLink\n startDate\n endDate\n __typename\n }\n }\n modes {\n __typename\n active\n token {\n placeholder\n value\n __typename\n }\n }\n secondaryMeta {\n ...metaFragment\n __typename\n }\n sportBuffStreamId\n subtitle\n title\n watchAction {\n __typename\n ... on LiveWatchAction {\n streamId\n pageLink: livestreamPageLink\n startDate\n __typename\n }\n ... on EpisodeWatchAction {\n streamId\n pageLink: videoUrl\n resumePointId: videoId\n resumePoint\n completed\n avodUrl\n __typename\n }\n }\n}\nfragment imageFragment on Image {\n __typename\n objectId\n alt\n title\n focalPoint\n templateUrl\n}', + 'operationName': 'PodcastPage', + 'variables': {'pageId': f'/vrtnu/{url.split("/vrtmax/")[1]}.model.json'} + } + ).content.decode()) + action_type = "listenAction" + + if "/livestream/audio/" in url or "/livestream/video/" in url: + response = json.loads(requests.post( + vrt_be.GRAPHQL_URL, + headers={'x-vrt-client-name': 'WEB'}, + json={ + 'query': 'query Livestream($pageId: ID!, $miniQuery: Boolean = false) {\n page(id: $pageId) {\n ... on IIdentifiable {\n __typename\n objectId\n }\n ... on IPage @skip(if: $miniQuery) {\n title\n brand\n permalink\n trackingData {\n ...trackingDataFragment\n __typename\n }\n components {\n __typename\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n ...bannerFragment\n }\n seo {\n ...seoFragment\n __typename\n }\n socialSharing {\n ...socialSharingFragment\n __typename\n }\n __typename\n }\n ... on AudioLivestreamPage {\n linkTemplate\n description\n livestream {\n objectId\n title\n presenters {\n name\n title\n category\n __typename\n }\n ... on AudioLivestream @skip(if: $miniQuery) {\n actionItems {\n ...actionItemFragment\n __typename\n }\n brandLogos {\n ...brandLogosFragment\n __typename\n }\n shareAction {\n title\n url\n __typename\n }\n primaryMeta {\n ...metaFragment\n __typename\n }\n __typename\n }\n __typename\n }\n player {\n ...playerFragment\n __typename\n }\n menu @skip(if: $miniQuery) {\n ...menuFragment\n __typename\n }\n __typename\n }\n ... on LivestreamPage {\n description\n livestream {\n objectId\n brandLogos @skip(if: $miniQuery) {\n ...brandLogosFragment\n __typename\n }\n shareAction @skip(if: $miniQuery) {\n title\n url\n __typename\n }\n title\n primaryMeta @skip(if: $miniQuery) {\n ...metaFragment\n __typename\n }\n episode @skip(if: $miniQuery) {\n ... on Episode {\n objectId\n program {\n ... on Program {\n objectId\n title\n description\n link\n __typename\n }\n __typename\n }\n __typename\n }\n __typename\n }\n __typename\n }\n player {\n ...playerFragment\n __typename\n }\n menu {\n ...menuFragment\n __typename\n }\n __typename\n }\n __typename\n }\n}\nfragment metaFragment on MetaDataItem {\n __typename\n type\n value\n shortValue\n longValue\n}\nfragment bannerFragment on Banner {\n __typename\n objectId\n brand\n countdown {\n date\n __typename\n }\n richDescription {\n __typename\n text\n }\n ctaText\n image {\n objectId\n templateUrl\n alt\n focalPoint\n __typename\n }\n title\n compactLayout\n textTheme\n backgroundColor\n style\n action {\n ...actionFragment\n __typename\n }\n actionItems {\n ...actionItemFragment\n __typename\n }\n titleArt {\n objectId\n templateUrl\n __typename\n }\n labelMeta {\n __typename\n type\n value\n }\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n}\nfragment actionFragment on Action {\n __typename\n ... on FavoriteAction {\n favorite\n id\n programUrl\n programWhatsonId\n title\n __typename\n }\n ... on ListDeleteAction {\n listName\n id\n listId\n title\n __typename\n }\n ... on ListTileDeletedAction {\n listName\n id\n listId\n __typename\n }\n ... on PodcastEpisodeListenAction {\n id: audioId\n podcastEpisodeLink\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n ... on EpisodeWatchAction {\n id: videoId\n videoUrl\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n ... on LinkAction {\n id: linkId\n linkId\n link\n linkType\n openExternally\n passUserIdentity\n linkTokens {\n __typename\n placeholder\n value\n }\n __typename\n }\n ... on ShareAction {\n title\n url\n __typename\n }\n ... on SwitchTabAction {\n referencedTabId\n mediaType\n link\n __typename\n }\n ... on RadioEpisodeListenAction {\n streamId\n pageLink\n startDate\n __typename\n }\n ... on LiveListenAction {\n streamId\n livestreamPageLink\n startDate\n startOver\n endDate\n __typename\n }\n ... on LiveWatchAction {\n streamId\n livestreamPageLink\n startDate\n startOver\n endDate\n __typename\n }\n}\nfragment actionItemFragment on ActionItem {\n __typename\n objectId\n accessibilityLabel\n action {\n ...actionFragment\n __typename\n }\n active\n icon\n iconPosition\n icons {\n __typename\n position\n ... on DesignSystemIcon {\n value {\n name\n __typename\n }\n __typename\n }\n }\n mode\n objectId\n title\n}\nfragment componentTrackingDataFragment on IComponent {\n trackingData {\n data\n perTrigger {\n trigger\n data\n template {\n id\n __typename\n }\n __typename\n }\n __typename\n }\n}\nfragment brandLogosFragment on Logo {\n colorOnColor\n height\n mono\n primary\n type\n width\n}\nfragment playerFragment on MediaPlayer {\n __typename\n objectId\n expires\n image {\n ...imageFragment\n __typename\n }\n listenAction {\n __typename\n ... on LiveListenAction {\n streamId\n pageLink: livestreamPageLink\n startDate\n __typename\n }\n ... on PodcastEpisodeListenAction {\n streamId\n pageLink: podcastEpisodeLink\n resumePointId: audioId\n resumePoint\n completed\n __typename\n }\n ... on RadioEpisodeListenAction {\n streamId\n radioEpisodeId\n pageLink\n startDate\n endDate\n __typename\n }\n }\n modes {\n __typename\n active\n token {\n placeholder\n value\n __typename\n }\n }\n secondaryMeta {\n ...metaFragment\n __typename\n }\n sportBuffStreamId\n subtitle\n title\n watchAction {\n __typename\n ... on LiveWatchAction {\n streamId\n pageLink: livestreamPageLink\n startDate\n __typename\n }\n ... on EpisodeWatchAction {\n streamId\n pageLink: videoUrl\n resumePointId: videoId\n resumePoint\n completed\n avodUrl\n __typename\n }\n }\n}\nfragment imageFragment on Image {\n __typename\n objectId\n alt\n title\n focalPoint\n templateUrl\n}\nfragment seoFragment on SeoProperties {\n __typename\n title\n description\n}\nfragment socialSharingFragment on SocialSharingProperties {\n __typename\n title\n description\n image {\n __typename\n objectId\n templateUrl\n }\n}\nfragment trackingDataFragment on PageTrackingData {\n data\n perTrigger {\n trigger\n data\n template {\n id\n __typename\n }\n __typename\n }\n}\nfragment menuFragment on ContainerNavigation {\n __typename\n objectId\n items {\n __typename\n objectId\n componentId\n title\n active\n }\n}', + 'operationName': 'Livestream', + 'variables': {'pageId': f'/vrtmax/{url.split("/vrtmax/")[1]}/'} + } + ).content.decode()) + if "/livestream/audio/" in url: + action_type = "listenAction" + else: + action_type = "watchAction" + + if "/luister/radio/" in url: + response = json.loads(requests.post( + vrt_be.GRAPHQL_URL, + headers={'x-vrt-client-name': 'WEB'}, + json={ + 'query': 'query RadioEpisodePage($pageId: ID!) {\n page(id: $pageId) {\n ... on RadioEpisodePage {\n objectId\n title\n brand\n permalink\n seo {\n ...seoFragment\n __typename\n }\n socialSharing {\n ...socialSharingFragment\n __typename\n }\n trackingData {\n ...trackingDataFragment\n __typename\n }\n header {\n title\n announcementValue\n brandsLogos {\n brandTitle\n logos {\n type\n mono\n width\n height\n __typename\n }\n __typename\n }\n __typename\n }\n menu {\n ...menuFragment\n __typename\n }\n player {\n ...playerFragment\n __typename\n }\n radioEpisode {\n objectId\n title\n richDescription {\n __typename\n html\n text\n }\n brand\n startDate\n brandLogos {\n ...brandLogosFragment\n __typename\n }\n image {\n ...imageFragment\n __typename\n }\n brand\n presenters {\n name\n category\n title\n icon\n __typename\n }\n primaryMeta {\n ...metaFragment\n __typename\n }\n secondaryMeta {\n ...metaFragment\n __typename\n }\n actionItems {\n ...actionItemFragment\n __typename\n }\n __typename\n }\n __typename\n }\n __typename\n }\n}\nfragment actionItemFragment on ActionItem {\n __typename\n objectId\n accessibilityLabel\n action {\n ...actionFragment\n __typename\n }\n active\n icon\n iconPosition\n icons {\n __typename\n position\n ... on DesignSystemIcon {\n value {\n name\n __typename\n }\n __typename\n }\n }\n mode\n objectId\n title\n}\nfragment actionFragment on Action {\n __typename\n ... on FavoriteAction {\n favorite\n id\n programUrl\n programWhatsonId\n title\n __typename\n }\n ... on ListDeleteAction {\n listName\n id\n listId\n title\n __typename\n }\n ... on ListTileDeletedAction {\n listName\n id\n listId\n __typename\n }\n ... on PodcastEpisodeListenAction {\n id: audioId\n podcastEpisodeLink\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n ... on EpisodeWatchAction {\n id: videoId\n videoUrl\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n ... on LinkAction {\n id: linkId\n linkId\n link\n linkType\n openExternally\n passUserIdentity\n linkTokens {\n __typename\n placeholder\n value\n }\n __typename\n }\n ... on ShareAction {\n title\n url\n __typename\n }\n ... on SwitchTabAction {\n referencedTabId\n mediaType\n link\n __typename\n }\n ... on RadioEpisodeListenAction {\n streamId\n pageLink\n startDate\n __typename\n }\n ... on LiveListenAction {\n streamId\n livestreamPageLink\n startDate\n startOver\n endDate\n __typename\n }\n ... on LiveWatchAction {\n streamId\n livestreamPageLink\n startDate\n startOver\n endDate\n __typename\n }\n}\nfragment imageFragment on Image {\n __typename\n objectId\n alt\n title\n focalPoint\n templateUrl\n}\nfragment seoFragment on SeoProperties {\n __typename\n title\n description\n}\nfragment socialSharingFragment on SocialSharingProperties {\n __typename\n title\n description\n image {\n __typename\n objectId\n templateUrl\n }\n}\nfragment metaFragment on MetaDataItem {\n __typename\n type\n value\n shortValue\n longValue\n}\nfragment trackingDataFragment on PageTrackingData {\n data\n perTrigger {\n trigger\n data\n template {\n id\n __typename\n }\n __typename\n }\n}\nfragment brandLogosFragment on Logo {\n colorOnColor\n height\n mono\n primary\n type\n width\n}\nfragment playerFragment on MediaPlayer {\n __typename\n objectId\n expires\n image {\n ...imageFragment\n __typename\n }\n listenAction {\n __typename\n ... on LiveListenAction {\n streamId\n pageLink: livestreamPageLink\n startDate\n __typename\n }\n ... on PodcastEpisodeListenAction {\n streamId\n pageLink: podcastEpisodeLink\n resumePointId: audioId\n resumePoint\n completed\n __typename\n }\n ... on RadioEpisodeListenAction {\n streamId\n radioEpisodeId\n pageLink\n startDate\n endDate\n __typename\n }\n }\n modes {\n __typename\n active\n token {\n placeholder\n value\n __typename\n }\n }\n secondaryMeta {\n ...metaFragment\n __typename\n }\n sportBuffStreamId\n subtitle\n title\n watchAction {\n __typename\n ... on LiveWatchAction {\n streamId\n pageLink: livestreamPageLink\n startDate\n __typename\n }\n ... on EpisodeWatchAction {\n streamId\n pageLink: videoUrl\n resumePointId: videoId\n resumePoint\n completed\n avodUrl\n __typename\n }\n }\n}\nfragment menuFragment on ContainerNavigation {\n __typename\n objectId\n items {\n __typename\n objectId\n componentId\n title\n active\n }\n}', + 'operationName': 'RadioEpisodePage', + 'variables': {'pageId': f'/vrtnu/{url.split("/vrtmax/")[1]}/'} + } + ).content.decode()) + action_type = "listenAction" + + if action_type is None: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=url, + reason="URL not supported", + solution=f"Extend the {vrt_be.__name__} service" + )) + + response = response["data"]["page"] + if response is None or response["player"][action_type] is None: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + response = response["player"] + return response[action_type]["streamId"], response["title"] + + @staticmethod + def get_video_data(source_element): + source_element.url = source_element.url.rstrip('/') + stream_id, stream_title = vrt_be.get_stream_data(source_element.url) + + response = requests.get( + vrt_be.ITEMS_URL.format(id=stream_id), + params={ + 'vrtPlayerToken': vrt_be.PLAYER_TOKEN, + 'client': 'vrtnu-web@PROD' + } + ) + + if response.status_code == 404: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + response = json.loads(response.content.decode()) + message = response.get("code", "").lower() + if "available_only" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Need Belgian IP to access content", + solution="Use a VPN" + )) + if "authentication" in message or "restricted" in message: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason='Need account for this content and/or fresh cookies', + solution=f'Sign into your account using Firefox and play a random video. ' + f'If it persists then debug the {vrt_be.__name__} service' + )) + + if len(message) > 0: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Unknown error encountered: {str(response)}", + solution=f"Debug the {vrt_be.__name__} service" + )) + + if source_element.element is None: + if response["title"] is None or len(response["title"].strip()) == 0: + response["title"] = stream_title + source_element.element = get_valid_filename(response["title"]) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + vrt_be.__name__ + ) + + manifest = None + for target in response['targetUrls']: + if "dash" in target["type"].lower(): + manifest = target["url"] + break + + pssh_value = None + if response["drm"] is not None: + pssh_value = vrt_be.get_pssh_from_manifest(manifest) + return manifest, pssh_value, {"token": response["drm"]} + + @staticmethod + def get_label_index(label): + if label is None or len(label) == 0: + return None + label = label.lower() + label = re.sub(r'\s+', ' ', label) + label = label.replace(' ', "_") + for s in [ + "seizoen_", "aflevering_", "afl\\.", "-s\\d+a", "-s\\d+-a", "-\\d+a", "-\\d+-a", + "-s\\d+a-", "-s\\d+-a-", "-\\d+a-", "-\\d+-a-", "sspecialsa" + ]: + try: + return int(re.findall(fr'{s}(\d+)', label)[0]) + except: + pass + return None + + @staticmethod + def get_episode_index(metadata, url): + for meta in metadata: + value = meta["value"].lower() + if "aflevering" in value or "afl" in value: + return vrt_be.get_label_index(meta["value"]) + + index = vrt_be.get_label_index(url) + if index is None: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=url, + reason="Failed to extract the episode index", + solution=f"Debug the {vrt_be.__name__} service" + )) + return index + + @staticmethod + def check_order(type_elements, elements): + if len(elements) < 2: + return True + + e1, e2 = elements[0:2] + if type_elements == "paginatedItems": + e1, e2 = e1["node"], e2["node"] + + e1_url = f'{vrt_be.BASE_URL}{e1["playAction"]["pageUrl"]}' + e1_index = vrt_be.get_episode_index(e1["primaryMeta"], e1_url) + e2_url = f'{vrt_be.BASE_URL}{e2["playAction"]["pageUrl"]}' + e2_index = vrt_be.get_episode_index(e2["primaryMeta"], e2_url) + return e1_index < e2_index + + @staticmethod + def clean_title(title): + title = title.lower().replace(' ', '-') + title = quote(title) + title = re.sub(r'%[0-9a-fA-F]{2}', '', title) + return title + + @staticmethod + def radio_handler(collection_name, component_id): + response = json.loads(requests.post( + vrt_be.GRAPHQL_URL, + headers={'x-vrt-client-name': 'WEB'}, + json={ + 'query': 'query component($componentId: ID!, $lazyItemCount: Int = ' + + str(vrt_be.PAGE_SIZE) + + ', $after: ID, $before: ID) {\n component(id: $componentId) {\n __typename\n ... on ContainerNavigationItem {\n __typename\n objectId\n componentId\n title\n components {\n __typename\n ... on PaginatedTileList {\n ...basicPaginatedTileListFragment\n __typename\n }\n ... on StaticTileList {\n ...basicStaticTileListFragment\n __typename\n }\n ... on ElectronicProgramGuideSchedule {\n ...epgFragment\n __typename\n }\n ... on Chat {\n __typename\n chatId\n expires\n objectId\n ...componentTrackingDataFragment\n }\n ... on Text {\n ...textFragment\n __typename\n }\n ... on PresentersList {\n __typename\n objectId\n presenters {\n title\n __typename\n }\n }\n ... on NoContent {\n ...noContentFragment\n __typename\n }\n }\n }\n }\n}\nfragment actionFragment on Action {\n __typename\n ... on FavoriteAction {\n favorite\n id\n programUrl\n programWhatsonId\n title\n __typename\n }\n ... on ListDeleteAction {\n listName\n id\n listId\n title\n __typename\n }\n ... on ListTileDeletedAction {\n listName\n id\n listId\n __typename\n }\n ... on PodcastEpisodeListenAction {\n id: audioId\n podcastEpisodeLink\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n ... on EpisodeWatchAction {\n id: videoId\n videoUrl\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n ... on LinkAction {\n id: linkId\n linkId\n link\n linkType\n openExternally\n passUserIdentity\n linkTokens {\n __typename\n placeholder\n value\n }\n __typename\n }\n ... on ShareAction {\n title\n url\n __typename\n }\n ... on SwitchTabAction {\n referencedTabId\n mediaType\n link\n __typename\n }\n ... on RadioEpisodeListenAction {\n streamId\n pageLink\n startDate\n __typename\n }\n ... on LiveListenAction {\n streamId\n livestreamPageLink\n startDate\n startOver\n endDate\n __typename\n }\n ... on LiveWatchAction {\n streamId\n livestreamPageLink\n startDate\n startOver\n endDate\n __typename\n }\n}\nfragment actionItemFragment on ActionItem {\n __typename\n objectId\n accessibilityLabel\n action {\n ...actionFragment\n __typename\n }\n active\n icon\n iconPosition\n icons {\n __typename\n position\n ... on DesignSystemIcon {\n value {\n name\n __typename\n }\n __typename\n }\n }\n mode\n objectId\n title\n}\nfragment componentTrackingDataFragment on IComponent {\n trackingData {\n data\n perTrigger {\n trigger\n data\n template {\n id\n __typename\n }\n __typename\n }\n __typename\n }\n}\nfragment noContentFragment on NoContent {\n __typename\n objectId\n title\n text\n noContentType\n actionItems {\n ...actionItemFragment\n __typename\n }\n}\nfragment tileFragment on Tile {\n ... on IIdentifiable {\n __typename\n objectId\n }\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n ... on ITile {\n description\n title\n active\n action {\n ...actionFragment\n __typename\n }\n actionItems {\n ...actionItemFragment\n __typename\n }\n image {\n ...imageFragment\n __typename\n }\n primaryMeta {\n ...metaFragment\n __typename\n }\n secondaryMeta {\n ...metaFragment\n __typename\n }\n tertiaryMeta {\n ...metaFragment\n __typename\n }\n indexMeta {\n __typename\n type\n value\n }\n statusMeta {\n __typename\n type\n value\n }\n labelMeta {\n __typename\n type\n value\n }\n __typename\n }\n ... on ContentTile {\n brand\n brandLogos {\n ...brandLogosFragment\n __typename\n }\n __typename\n }\n ... on BannerTile {\n compactLayout\n backgroundColor\n textTheme\n brand\n brandLogos {\n ...brandLogosFragment\n __typename\n }\n ctaText\n passUserIdentity\n titleArt {\n objectId\n templateUrl\n __typename\n }\n __typename\n }\n ... on EpisodeTile {\n description\n formattedDuration\n available\n chapterStart\n action {\n ...actionFragment\n __typename\n }\n playAction: watchAction {\n pageUrl: videoUrl\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n episode {\n __typename\n objectId\n program {\n __typename\n objectId\n link\n }\n }\n \n __typename\n }\n ... on PodcastEpisodeTile {\n formattedDuration\n available\n programLink: podcastEpisode {\n objectId\n podcastProgram {\n objectId\n link\n __typename\n }\n __typename\n }\n playAction: listenAction {\n pageUrl: podcastEpisodeLink\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n __typename\n }\n ... on PodcastProgramTile {\n link\n __typename\n }\n ... on ProgramTile {\n link\n __typename\n }\n ... on AudioLivestreamTile {\n brand\n brandsLogos {\n brand\n brandTitle\n logos {\n ...brandLogosFragment\n __typename\n }\n __typename\n }\n __typename\n }\n ... on LivestreamTile {\n description\n __typename\n }\n ... on ButtonTile {\n icon\n iconPosition\n mode\n __typename\n }\n ... on RadioEpisodeTile {\n action {\n ...actionFragment\n __typename\n }\n available\n \n formattedDuration\n ...componentTrackingDataFragment\n __typename\n }\n ... on SongTile {\n startDate\n formattedStartDate\n endDate\n __typename\n }\n ... on RadioProgramTile {\n objectId\n __typename\n }\n}\nfragment metaFragment on MetaDataItem {\n __typename\n type\n value\n shortValue\n longValue\n}\nfragment imageFragment on Image {\n __typename\n objectId\n alt\n title\n focalPoint\n templateUrl\n}\nfragment brandLogosFragment on Logo {\n colorOnColor\n height\n mono\n primary\n type\n width\n}\nfragment textFragment on Text {\n __typename\n objectId\n html\n}\nfragment basicPaginatedTileListFragment on PaginatedTileList {\n __typename\n objectId\n listId\n displayType\n expires\n tileVariant\n tileContentType\n tileOrientation\n title\n paginatedItems(first: $lazyItemCount, after: $after, before: $before) {\n __typename\n edges {\n __typename\n cursor\n node {\n __typename\n ...tileFragment\n }\n }\n pageInfo {\n __typename\n endCursor\n hasNextPage\n hasPreviousPage\n startCursor\n }\n }\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n}\nfragment basicStaticTileListFragment on StaticTileList {\n __typename\n objectId\n listId\n displayType\n expires\n tileVariant\n tileContentType\n tileOrientation\n title\n items {\n ...tileFragment\n __typename\n }\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n}\nfragment epgFragment on ElectronicProgramGuideSchedule {\n __typename\n objectId\n expires\n current {\n tile {\n ...tileFragment\n __typename\n }\n __typename\n }\n next {\n ...basicPaginatedTileListFragment\n __typename\n }\n previous {\n ...basicPaginatedTileListFragment\n __typename\n }\n}', + 'operationName': 'component', + 'variables': {'componentId': component_id} + } + ).content.decode()) + + response = response["data"]["component"] + episode_index = 0 + collection = [] + + for component in response.get("components", []): + if component["__typename"] == "StaticTileList": + for item in component["items"]: + episode_index += 1 + + check = check_range(False, None, episode_index) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=f'{vrt_be.BASE_URL}{item["action"]["pageLink"]}', + collection=join(join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + vrt_be.__name__ + ), collection_name), + element=f'Radio_{episode_index}' + f'_' + f'{get_valid_filename(item["title"])}' + )) + + return collection + return None + + @staticmethod + def container_navigation_handler(collection_name, container, selected_season_name, fragment, url): + collection = [] + if fragment is not None: + collection_name = join(collection_name, get_valid_filename(fragment)) + if selected_season_name is not None: + collection_name = join(collection_name, get_valid_filename(selected_season_name)) + + for i1 in container["items"]: + collection_index = vrt_be.get_label_index(i1["title"]) + if collection_index is None and vrt_be.clean_title(i1["title"]) != fragment: + continue + + if "/luister/radio/" in url and i1.get("components", None) is None: + return vrt_be.radio_handler(collection_name, i1["componentId"]) + + season_index = 0 + for c1 in i1["components"]: + seasons = [] + ignore_index = False + if "/podcasts/" in url in url: + ignore_index = True + + if len(c1.get("paginatedItems", [])) > 0: + if collection_index is None: + collection_index = vrt_be.get_label_index(c1["title"]) + if collection_index is not None: + season_index = collection_index + else: + season_index += 1 + ignore_index = True + + response = json.loads(requests.post( + vrt_be.GRAPHQL_URL, + headers={'x-vrt-client-name': 'WEB'}, + json={ + 'query': 'query PaginatedTileListPage($listId: ID!, $lazyItemCount: Int = ' + + str(vrt_be.PAGE_SIZE) + + ', $after: ID, $before: ID) {\n list(listId: $listId) {\n __typename\n ... on PaginatedTileList {\n ...paginatedTileListFragment\n __typename\n }\n ... on StaticTileList {\n ...staticTileListFragment\n __typename\n }\n }\n}\nfragment staticTileListFragment on StaticTileList {\n __typename\n objectId\n listId\n title\n description\n tileContentType\n tileOrientation\n displayType\n expires\n tileVariant\n sort {\n icon\n order\n title\n __typename\n }\n actionItems {\n ...actionItemFragment\n __typename\n }\n banner {\n actionItems {\n ...actionItemFragment\n __typename\n }\n description\n image {\n ...imageFragment\n __typename\n }\n compactLayout\n backgroundColor\n textTheme\n title\n titleArt {\n objectId\n templateUrl\n __typename\n }\n __typename\n }\n bannerSize\n items {\n ...tileFragment\n __typename\n }\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n}\nfragment actionItemFragment on ActionItem {\n __typename\n objectId\n accessibilityLabel\n action {\n ...actionFragment\n __typename\n }\n active\n icon\n iconPosition\n icons {\n __typename\n position\n ... on DesignSystemIcon {\n value {\n name\n __typename\n }\n __typename\n }\n }\n mode\n objectId\n title\n}\nfragment actionFragment on Action {\n __typename\n ... on FavoriteAction {\n favorite\n id\n programUrl\n programWhatsonId\n title\n __typename\n }\n ... on ListDeleteAction {\n listName\n id\n listId\n title\n __typename\n }\n ... on ListTileDeletedAction {\n listName\n id\n listId\n __typename\n }\n ... on PodcastEpisodeListenAction {\n id: audioId\n podcastEpisodeLink\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n ... on EpisodeWatchAction {\n id: videoId\n videoUrl\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n ... on LinkAction {\n id: linkId\n linkId\n link\n linkType\n openExternally\n passUserIdentity\n linkTokens {\n __typename\n placeholder\n value\n }\n __typename\n }\n ... on ShareAction {\n title\n url\n __typename\n }\n ... on SwitchTabAction {\n referencedTabId\n mediaType\n link\n __typename\n }\n ... on RadioEpisodeListenAction {\n streamId\n pageLink\n startDate\n __typename\n }\n ... on LiveListenAction {\n streamId\n livestreamPageLink\n startDate\n startOver\n endDate\n __typename\n }\n ... on LiveWatchAction {\n streamId\n livestreamPageLink\n startDate\n startOver\n endDate\n __typename\n }\n}\nfragment imageFragment on Image {\n __typename\n objectId\n alt\n title\n focalPoint\n templateUrl\n}\nfragment tileFragment on Tile {\n ... on IIdentifiable {\n __typename\n objectId\n }\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n ... on ITile {\n description\n title\n active\n action {\n ...actionFragment\n __typename\n }\n actionItems {\n ...actionItemFragment\n __typename\n }\n image {\n ...imageFragment\n __typename\n }\n primaryMeta {\n ...metaFragment\n __typename\n }\n secondaryMeta {\n ...metaFragment\n __typename\n }\n tertiaryMeta {\n ...metaFragment\n __typename\n }\n indexMeta {\n __typename\n type\n value\n }\n statusMeta {\n __typename\n type\n value\n }\n labelMeta {\n __typename\n type\n value\n }\n __typename\n }\n ... on ContentTile {\n brand\n brandLogos {\n ...brandLogosFragment\n __typename\n }\n __typename\n }\n ... on BannerTile {\n compactLayout\n backgroundColor\n textTheme\n brand\n brandLogos {\n ...brandLogosFragment\n __typename\n }\n ctaText\n passUserIdentity\n titleArt {\n objectId\n templateUrl\n __typename\n }\n __typename\n }\n ... on EpisodeTile {\n description\n formattedDuration\n available\n chapterStart\n action {\n ...actionFragment\n __typename\n }\n playAction: watchAction {\n pageUrl: videoUrl\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n episode {\n __typename\n objectId\n program {\n __typename\n objectId\n link\n }\n }\n \n __typename\n }\n ... on PodcastEpisodeTile {\n formattedDuration\n available\n programLink: podcastEpisode {\n objectId\n podcastProgram {\n objectId\n link\n __typename\n }\n __typename\n }\n playAction: listenAction {\n pageUrl: podcastEpisodeLink\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n __typename\n }\n ... on PodcastProgramTile {\n link\n __typename\n }\n ... on ProgramTile {\n link\n __typename\n }\n ... on AudioLivestreamTile {\n brand\n brandsLogos {\n brand\n brandTitle\n logos {\n ...brandLogosFragment\n __typename\n }\n __typename\n }\n __typename\n }\n ... on LivestreamTile {\n description\n __typename\n }\n ... on ButtonTile {\n icon\n iconPosition\n mode\n __typename\n }\n ... on RadioEpisodeTile {\n action {\n ...actionFragment\n __typename\n }\n available\n \n formattedDuration\n ...componentTrackingDataFragment\n __typename\n }\n ... on SongTile {\n startDate\n formattedStartDate\n endDate\n __typename\n }\n ... on RadioProgramTile {\n objectId\n __typename\n }\n}\nfragment metaFragment on MetaDataItem {\n __typename\n type\n value\n shortValue\n longValue\n}\nfragment componentTrackingDataFragment on IComponent {\n trackingData {\n data\n perTrigger {\n trigger\n data\n template {\n id\n __typename\n }\n __typename\n }\n __typename\n }\n}\nfragment brandLogosFragment on Logo {\n colorOnColor\n height\n mono\n primary\n type\n width\n}\nfragment paginatedTileListFragment on PaginatedTileList {\n __typename\n objectId\n listId\n actionItems {\n ...actionItemFragment\n __typename\n }\n banner {\n actionItems {\n ...actionItemFragment\n __typename\n }\n backgroundColor\n compactLayout\n description\n image {\n ...imageFragment\n __typename\n }\n titleArt {\n ...imageFragment\n __typename\n }\n textTheme\n title\n __typename\n }\n bannerSize\n displayType\n expires\n tileVariant\n paginatedItems(first: $lazyItemCount, after: $after, before: $before) {\n __typename\n edges {\n __typename\n cursor\n node {\n __typename\n ...tileFragment\n }\n }\n pageInfo {\n __typename\n endCursor\n hasNextPage\n hasPreviousPage\n startCursor\n }\n }\n sort {\n icon\n order\n title\n __typename\n }\n tileContentType\n tileOrientation\n title\n description\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n}', + 'operationName': 'PaginatedTileListPage', + 'variables': {'listId': c1["listId"]} + } + ).content.decode()) + response = response["data"]["list"] + + seasons.append((season_index, response)) + + elif len(c1.get("items", [])) > 0: + tuples = [ + (vrt_be.get_label_index(i["title"]), i) + for i in c1["items"] + ] + seasons = sorted([ + (index, item) for index, item in tuples + if index is not None], key=lambda m: m[0] + ) + [(index, item) for index, item in tuples if index is None] + + if len(seasons) == 0: + seasons = [(vrt_be.get_label_index(i1["title"]), c1)] + + for season_index, season in seasons: + if season_index is None: + if ( + selected_season_name is not None and + vrt_be.clean_title(season["title"]).startswith(selected_season_name) + ): + pass + else: + continue + if selected_season_name is not None and season_index is not None: + continue + + try: + list_id = [c for c in season["components"] if len(c.get("listId", "")) > 0][0]["listId"] + except: + list_id = season["listId"] + + if season_index is not None: + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + response = json.loads(requests.post( + vrt_be.GRAPHQL_URL, + headers={'x-vrt-client-name': 'WEB'}, + json={ + 'query': 'query ProgramSeasonEpisodeList($listId: ID!, $sort: SortInput, $lazyItemCount: Int = ' + + str(vrt_be.PAGE_SIZE) + + ', $after: ID, $before: ID) {\n list(listId: $listId, sort: $sort) {\n __typename\n ... on PaginatedTileList {\n ...paginatedTileListFragment\n __typename\n }\n ... on StaticTileList {\n ...staticTileListFragment\n __typename\n }\n }\n}\nfragment staticTileListFragment on StaticTileList {\n __typename\n objectId\n listId\n title\n description\n tileContentType\n tileOrientation\n displayType\n expires\n tileVariant\n sort {\n icon\n order\n title\n __typename\n }\n actionItems {\n ...actionItemFragment\n __typename\n }\n banner {\n actionItems {\n ...actionItemFragment\n __typename\n }\n description\n image {\n ...imageFragment\n __typename\n }\n compactLayout\n backgroundColor\n textTheme\n title\n titleArt {\n objectId\n templateUrl\n __typename\n }\n __typename\n }\n bannerSize\n items {\n ...tileFragment\n __typename\n }\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n}\nfragment actionItemFragment on ActionItem {\n __typename\n objectId\n accessibilityLabel\n action {\n ...actionFragment\n __typename\n }\n active\n icon\n iconPosition\n icons {\n __typename\n position\n ... on DesignSystemIcon {\n value {\n name\n __typename\n }\n __typename\n }\n }\n mode\n objectId\n title\n}\nfragment actionFragment on Action {\n __typename\n ... on FavoriteAction {\n favorite\n id\n programUrl\n programWhatsonId\n title\n __typename\n }\n ... on ListDeleteAction {\n listName\n id\n listId\n title\n __typename\n }\n ... on ListTileDeletedAction {\n listName\n id\n listId\n __typename\n }\n ... on PodcastEpisodeListenAction {\n id: audioId\n podcastEpisodeLink\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n ... on EpisodeWatchAction {\n id: videoId\n videoUrl\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n ... on LinkAction {\n id: linkId\n linkId\n link\n linkType\n openExternally\n passUserIdentity\n linkTokens {\n __typename\n placeholder\n value\n }\n __typename\n }\n ... on ShareAction {\n title\n url\n __typename\n }\n ... on SwitchTabAction {\n referencedTabId\n mediaType\n link\n __typename\n }\n ... on RadioEpisodeListenAction {\n streamId\n pageLink\n startDate\n __typename\n }\n ... on LiveListenAction {\n streamId\n livestreamPageLink\n startDate\n startOver\n endDate\n __typename\n }\n ... on LiveWatchAction {\n streamId\n livestreamPageLink\n startDate\n startOver\n endDate\n __typename\n }\n}\nfragment imageFragment on Image {\n __typename\n objectId\n alt\n title\n focalPoint\n templateUrl\n}\nfragment tileFragment on Tile {\n ... on IIdentifiable {\n __typename\n objectId\n }\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n ... on ITile {\n description\n title\n active\n action {\n ...actionFragment\n __typename\n }\n actionItems {\n ...actionItemFragment\n __typename\n }\n image {\n ...imageFragment\n __typename\n }\n primaryMeta {\n ...metaFragment\n __typename\n }\n secondaryMeta {\n ...metaFragment\n __typename\n }\n tertiaryMeta {\n ...metaFragment\n __typename\n }\n indexMeta {\n __typename\n type\n value\n }\n statusMeta {\n __typename\n type\n value\n }\n labelMeta {\n __typename\n type\n value\n }\n __typename\n }\n ... on ContentTile {\n brand\n brandLogos {\n ...brandLogosFragment\n __typename\n }\n __typename\n }\n ... on BannerTile {\n compactLayout\n backgroundColor\n textTheme\n brand\n brandLogos {\n ...brandLogosFragment\n __typename\n }\n ctaText\n passUserIdentity\n titleArt {\n objectId\n templateUrl\n __typename\n }\n __typename\n }\n ... on EpisodeTile {\n description\n formattedDuration\n available\n chapterStart\n action {\n ...actionFragment\n __typename\n }\n playAction: watchAction {\n pageUrl: videoUrl\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n episode {\n __typename\n objectId\n program {\n __typename\n objectId\n link\n }\n }\n \n __typename\n }\n ... on PodcastEpisodeTile {\n formattedDuration\n available\n programLink: podcastEpisode {\n objectId\n podcastProgram {\n objectId\n link\n __typename\n }\n __typename\n }\n playAction: listenAction {\n pageUrl: podcastEpisodeLink\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n __typename\n }\n ... on PodcastProgramTile {\n link\n __typename\n }\n ... on ProgramTile {\n link\n __typename\n }\n ... on AudioLivestreamTile {\n brand\n brandsLogos {\n brand\n brandTitle\n logos {\n ...brandLogosFragment\n __typename\n }\n __typename\n }\n __typename\n }\n ... on LivestreamTile {\n description\n __typename\n }\n ... on ButtonTile {\n icon\n iconPosition\n mode\n __typename\n }\n ... on RadioEpisodeTile {\n action {\n ...actionFragment\n __typename\n }\n available\n \n formattedDuration\n ...componentTrackingDataFragment\n __typename\n }\n ... on SongTile {\n startDate\n formattedStartDate\n endDate\n __typename\n }\n ... on RadioProgramTile {\n objectId\n __typename\n }\n}\nfragment metaFragment on MetaDataItem {\n __typename\n type\n value\n shortValue\n longValue\n}\nfragment componentTrackingDataFragment on IComponent {\n trackingData {\n data\n perTrigger {\n trigger\n data\n template {\n id\n __typename\n }\n __typename\n }\n __typename\n }\n}\nfragment brandLogosFragment on Logo {\n colorOnColor\n height\n mono\n primary\n type\n width\n}\nfragment paginatedTileListFragment on PaginatedTileList {\n __typename\n objectId\n listId\n actionItems {\n ...actionItemFragment\n __typename\n }\n banner {\n actionItems {\n ...actionItemFragment\n __typename\n }\n backgroundColor\n compactLayout\n description\n image {\n ...imageFragment\n __typename\n }\n titleArt {\n ...imageFragment\n __typename\n }\n textTheme\n title\n __typename\n }\n bannerSize\n displayType\n expires\n tileVariant\n paginatedItems(first: $lazyItemCount, after: $after, before: $before) {\n __typename\n edges {\n __typename\n cursor\n node {\n __typename\n ...tileFragment\n }\n }\n pageInfo {\n __typename\n endCursor\n hasNextPage\n hasPreviousPage\n startCursor\n }\n }\n sort {\n icon\n order\n title\n __typename\n }\n tileContentType\n tileOrientation\n title\n description\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n}', + 'operationName': 'ProgramSeasonEpisodeList', + 'variables': {'listId': list_id} + } + ).content.decode()) + + response = response["data"]["list"] + is_asc = None + if ignore_index: + is_asc = True + + episode_index = 0 + if response.get("paginatedItems", None) is not None: + while True: + edges = response["paginatedItems"].get("edges", []) + if is_asc is None: + is_asc = vrt_be.check_order("paginatedItems", edges) + + for edge in edges: + e = edge["node"] + if e.get("playAction", None) is None: + continue + + episode_url = f'{vrt_be.BASE_URL}{e["playAction"]["pageUrl"]}' + if ignore_index: + episode_index += 1 + else: + episode_index = vrt_be.get_episode_index(e["primaryMeta"], episode_url) + + check = check_range(False, season_index, episode_index, is_asc) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=episode_url, + collection=join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + vrt_be.__name__ + ), + collection_name if season_index is None else + join(collection_name, f'Season_{season_index}') + ), + element=f'Episode_{episode_index}' + f'_' + f'{get_valid_filename(e["title"])}' + )) + + page_info = response["paginatedItems"]["pageInfo"] + if page_info["hasNextPage"] is True: + response = json.loads(requests.post( + vrt_be.GRAPHQL_URL, + headers={'x-vrt-client-name': 'WEB'}, + json={ + 'query': 'query ProgramSeasonEpisodeList($listId: ID!, $sort: SortInput, $lazyItemCount: Int = ' + + str(vrt_be.PAGE_SIZE) + + ', $after: ID, $before: ID) {\n list(listId: $listId, sort: $sort) {\n __typename\n ... on PaginatedTileList {\n ...paginatedTileListFragment\n __typename\n }\n ... on StaticTileList {\n ...staticTileListFragment\n __typename\n }\n }\n}\nfragment staticTileListFragment on StaticTileList {\n __typename\n objectId\n listId\n title\n description\n tileContentType\n tileOrientation\n displayType\n expires\n tileVariant\n sort {\n icon\n order\n title\n __typename\n }\n actionItems {\n ...actionItemFragment\n __typename\n }\n banner {\n actionItems {\n ...actionItemFragment\n __typename\n }\n description\n image {\n ...imageFragment\n __typename\n }\n compactLayout\n backgroundColor\n textTheme\n title\n titleArt {\n objectId\n templateUrl\n __typename\n }\n __typename\n }\n bannerSize\n items {\n ...tileFragment\n __typename\n }\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n}\nfragment actionItemFragment on ActionItem {\n __typename\n objectId\n accessibilityLabel\n action {\n ...actionFragment\n __typename\n }\n active\n icon\n iconPosition\n icons {\n __typename\n position\n ... on DesignSystemIcon {\n value {\n name\n __typename\n }\n __typename\n }\n }\n mode\n objectId\n title\n}\nfragment actionFragment on Action {\n __typename\n ... on FavoriteAction {\n favorite\n id\n programUrl\n programWhatsonId\n title\n __typename\n }\n ... on ListDeleteAction {\n listName\n id\n listId\n title\n __typename\n }\n ... on ListTileDeletedAction {\n listName\n id\n listId\n __typename\n }\n ... on PodcastEpisodeListenAction {\n id: audioId\n podcastEpisodeLink\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n ... on EpisodeWatchAction {\n id: videoId\n videoUrl\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n ... on LinkAction {\n id: linkId\n linkId\n link\n linkType\n openExternally\n passUserIdentity\n linkTokens {\n __typename\n placeholder\n value\n }\n __typename\n }\n ... on ShareAction {\n title\n url\n __typename\n }\n ... on SwitchTabAction {\n referencedTabId\n mediaType\n link\n __typename\n }\n ... on RadioEpisodeListenAction {\n streamId\n pageLink\n startDate\n __typename\n }\n ... on LiveListenAction {\n streamId\n livestreamPageLink\n startDate\n startOver\n endDate\n __typename\n }\n ... on LiveWatchAction {\n streamId\n livestreamPageLink\n startDate\n startOver\n endDate\n __typename\n }\n}\nfragment imageFragment on Image {\n __typename\n objectId\n alt\n title\n focalPoint\n templateUrl\n}\nfragment tileFragment on Tile {\n ... on IIdentifiable {\n __typename\n objectId\n }\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n ... on ITile {\n description\n title\n active\n action {\n ...actionFragment\n __typename\n }\n actionItems {\n ...actionItemFragment\n __typename\n }\n image {\n ...imageFragment\n __typename\n }\n primaryMeta {\n ...metaFragment\n __typename\n }\n secondaryMeta {\n ...metaFragment\n __typename\n }\n tertiaryMeta {\n ...metaFragment\n __typename\n }\n indexMeta {\n __typename\n type\n value\n }\n statusMeta {\n __typename\n type\n value\n }\n labelMeta {\n __typename\n type\n value\n }\n __typename\n }\n ... on ContentTile {\n brand\n brandLogos {\n ...brandLogosFragment\n __typename\n }\n __typename\n }\n ... on BannerTile {\n compactLayout\n backgroundColor\n textTheme\n brand\n brandLogos {\n ...brandLogosFragment\n __typename\n }\n ctaText\n passUserIdentity\n titleArt {\n objectId\n templateUrl\n __typename\n }\n __typename\n }\n ... on EpisodeTile {\n description\n formattedDuration\n available\n chapterStart\n action {\n ...actionFragment\n __typename\n }\n playAction: watchAction {\n pageUrl: videoUrl\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n episode {\n __typename\n objectId\n program {\n __typename\n objectId\n link\n }\n }\n \n __typename\n }\n ... on PodcastEpisodeTile {\n formattedDuration\n available\n programLink: podcastEpisode {\n objectId\n podcastProgram {\n objectId\n link\n __typename\n }\n __typename\n }\n playAction: listenAction {\n pageUrl: podcastEpisodeLink\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n __typename\n }\n ... on PodcastProgramTile {\n link\n __typename\n }\n ... on ProgramTile {\n link\n __typename\n }\n ... on AudioLivestreamTile {\n brand\n brandsLogos {\n brand\n brandTitle\n logos {\n ...brandLogosFragment\n __typename\n }\n __typename\n }\n __typename\n }\n ... on LivestreamTile {\n description\n __typename\n }\n ... on ButtonTile {\n icon\n iconPosition\n mode\n __typename\n }\n ... on RadioEpisodeTile {\n action {\n ...actionFragment\n __typename\n }\n available\n \n formattedDuration\n ...componentTrackingDataFragment\n __typename\n }\n ... on SongTile {\n startDate\n formattedStartDate\n endDate\n __typename\n }\n ... on RadioProgramTile {\n objectId\n __typename\n }\n}\nfragment metaFragment on MetaDataItem {\n __typename\n type\n value\n shortValue\n longValue\n}\nfragment componentTrackingDataFragment on IComponent {\n trackingData {\n data\n perTrigger {\n trigger\n data\n template {\n id\n __typename\n }\n __typename\n }\n __typename\n }\n}\nfragment brandLogosFragment on Logo {\n colorOnColor\n height\n mono\n primary\n type\n width\n}\nfragment paginatedTileListFragment on PaginatedTileList {\n __typename\n objectId\n listId\n actionItems {\n ...actionItemFragment\n __typename\n }\n banner {\n actionItems {\n ...actionItemFragment\n __typename\n }\n backgroundColor\n compactLayout\n description\n image {\n ...imageFragment\n __typename\n }\n titleArt {\n ...imageFragment\n __typename\n }\n textTheme\n title\n __typename\n }\n bannerSize\n displayType\n expires\n tileVariant\n paginatedItems(first: $lazyItemCount, after: $after, before: $before) {\n __typename\n edges {\n __typename\n cursor\n node {\n __typename\n ...tileFragment\n }\n }\n pageInfo {\n __typename\n endCursor\n hasNextPage\n hasPreviousPage\n startCursor\n }\n }\n sort {\n icon\n order\n title\n __typename\n }\n tileContentType\n tileOrientation\n title\n description\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n}', + 'operationName': 'ProgramSeasonEpisodeList', + 'variables': {'listId': list_id, 'after': page_info["endCursor"]} + } + ).content.decode()) + response = response["data"]["list"] + continue + break + continue + + elif response.get("items", None) is not None: + if is_asc is None: + is_asc = vrt_be.check_order("items", response["items"]) + + for e in response["items"]: + if e.get("playAction", None) is None: + continue + + episode_url = f'{vrt_be.BASE_URL}{e["playAction"]["pageUrl"]}' + if ignore_index: + episode_index += 1 + else: + episode_index = vrt_be.get_episode_index(e["primaryMeta"], episode_url) + + check = check_range(False, season_index, episode_index, is_asc) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=episode_url, + collection=join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + vrt_be.__name__ + ), + collection_name if season_index is None else + join(collection_name, f'Season_{season_index}') + ), + element=f'Episode_{episode_index}' + f'_' + f'{get_valid_filename(e["title"])}' + )) + continue + + return None + return collection + + @staticmethod + def collection_handler(collection_url, season_name, fragment): + if "/a-z/" in collection_url: + response = json.loads(requests.post( + vrt_be.GRAPHQL_URL, + headers={'x-vrt-client-name': 'WEB'}, + json={ + 'query': 'query VideoProgramPage($pageId: ID!, $lazyItemCount: Int = ' + + str(vrt_be.PAGE_SIZE) + + ', $after: ID, $before: ID) {\n page(id: $pageId) {\n ... on ProgramPage {\n objectId\n permalink\n seo {\n ...seoFragment\n __typename\n }\n socialSharing {\n ...socialSharingFragment\n __typename\n }\n trackingData {\n ...trackingDataFragment\n __typename\n }\n ldjson\n components {\n __typename\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n ... on Banner {\n ...bannerFragment\n __typename\n }\n ... on PageHeader {\n ...pageHeaderFragment\n __typename\n }\n ... on ContainerNavigation {\n objectId\n navigationType\n items {\n objectId\n title\n active\n components {\n __typename\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n ... on PaginatedTileList {\n ...paginatedTileListFragment\n __typename\n }\n ... on StaticTileList {\n ...staticTileListFragment\n __typename\n }\n ... on LazyTileList {\n objectId\n title\n listId\n __typename\n }\n ... on Banner {\n ...bannerFragment\n __typename\n }\n ... on IComponent {\n ... on Text {\n ...textFragment\n __typename\n }\n ... on TagsList {\n objectId\n title\n tags {\n name\n title\n category\n __typename\n }\n __typename\n }\n ... on PresentersList {\n objectId\n title\n presenters {\n title\n type\n __typename\n }\n __typename\n }\n ... on ContainerNavigation {\n objectId\n navigationType\n items {\n objectId\n title\n components {\n __typename\n ... on Component {\n ... on PaginatedTileList {\n ...paginatedTileListFragment\n __typename\n }\n ... on StaticTileList {\n ...staticTileListFragment\n __typename\n }\n ... on LazyTileList {\n objectId\n title\n listId\n __typename\n }\n __typename\n }\n }\n __typename\n }\n __typename\n }\n __typename\n }\n }\n __typename\n }\n __typename\n }\n ...paginatedTileListFragment\n }\n __typename\n }\n __typename\n }\n}\nfragment metaFragment on MetaDataItem {\n __typename\n type\n value\n shortValue\n longValue\n}\nfragment staticTileListFragment on StaticTileList {\n __typename\n objectId\n listId\n title\n description\n tileContentType\n tileOrientation\n displayType\n expires\n tileVariant\n sort {\n icon\n order\n title\n __typename\n }\n actionItems {\n ...actionItemFragment\n __typename\n }\n banner {\n actionItems {\n ...actionItemFragment\n __typename\n }\n description\n image {\n ...imageFragment\n __typename\n }\n compactLayout\n backgroundColor\n textTheme\n title\n titleArt {\n objectId\n templateUrl\n __typename\n }\n __typename\n }\n bannerSize\n items {\n ...tileFragment\n __typename\n }\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n}\nfragment actionItemFragment on ActionItem {\n __typename\n objectId\n accessibilityLabel\n action {\n ...actionFragment\n __typename\n }\n active\n icon\n iconPosition\n icons {\n __typename\n position\n ... on DesignSystemIcon {\n value {\n name\n __typename\n }\n __typename\n }\n }\n mode\n objectId\n title\n}\nfragment actionFragment on Action {\n __typename\n ... on FavoriteAction {\n favorite\n id\n programUrl\n programWhatsonId\n title\n __typename\n }\n ... on ListDeleteAction {\n listName\n id\n listId\n title\n __typename\n }\n ... on ListTileDeletedAction {\n listName\n id\n listId\n __typename\n }\n ... on PodcastEpisodeListenAction {\n id: audioId\n podcastEpisodeLink\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n ... on EpisodeWatchAction {\n id: videoId\n videoUrl\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n ... on LinkAction {\n id: linkId\n linkId\n link\n linkType\n openExternally\n passUserIdentity\n linkTokens {\n __typename\n placeholder\n value\n }\n __typename\n }\n ... on ShareAction {\n title\n url\n __typename\n }\n ... on SwitchTabAction {\n referencedTabId\n mediaType\n link\n __typename\n }\n ... on RadioEpisodeListenAction {\n streamId\n pageLink\n startDate\n __typename\n }\n ... on LiveListenAction {\n streamId\n livestreamPageLink\n startDate\n startOver\n endDate\n __typename\n }\n ... on LiveWatchAction {\n streamId\n livestreamPageLink\n startDate\n startOver\n endDate\n __typename\n }\n}\nfragment imageFragment on Image {\n __typename\n objectId\n alt\n title\n focalPoint\n templateUrl\n}\nfragment tileFragment on Tile {\n ... on IIdentifiable {\n __typename\n objectId\n }\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n ... on ITile {\n description\n title\n active\n action {\n ...actionFragment\n __typename\n }\n actionItems {\n ...actionItemFragment\n __typename\n }\n image {\n ...imageFragment\n __typename\n }\n primaryMeta {\n ...metaFragment\n __typename\n }\n secondaryMeta {\n ...metaFragment\n __typename\n }\n tertiaryMeta {\n ...metaFragment\n __typename\n }\n indexMeta {\n __typename\n type\n value\n }\n statusMeta {\n __typename\n type\n value\n }\n labelMeta {\n __typename\n type\n value\n }\n __typename\n }\n ... on ContentTile {\n brand\n brandLogos {\n ...brandLogosFragment\n __typename\n }\n __typename\n }\n ... on BannerTile {\n compactLayout\n backgroundColor\n textTheme\n brand\n brandLogos {\n ...brandLogosFragment\n __typename\n }\n ctaText\n passUserIdentity\n titleArt {\n objectId\n templateUrl\n __typename\n }\n __typename\n }\n ... on EpisodeTile {\n description\n formattedDuration\n available\n chapterStart\n action {\n ...actionFragment\n __typename\n }\n playAction: watchAction {\n pageUrl: videoUrl\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n episode {\n __typename\n objectId\n program {\n __typename\n objectId\n link\n }\n }\n \n __typename\n }\n ... on PodcastEpisodeTile {\n formattedDuration\n available\n programLink: podcastEpisode {\n objectId\n podcastProgram {\n objectId\n link\n __typename\n }\n __typename\n }\n playAction: listenAction {\n pageUrl: podcastEpisodeLink\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n __typename\n }\n ... on PodcastProgramTile {\n link\n __typename\n }\n ... on ProgramTile {\n link\n __typename\n }\n ... on AudioLivestreamTile {\n brand\n brandsLogos {\n brand\n brandTitle\n logos {\n ...brandLogosFragment\n __typename\n }\n __typename\n }\n __typename\n }\n ... on LivestreamTile {\n description\n __typename\n }\n ... on ButtonTile {\n icon\n iconPosition\n mode\n __typename\n }\n ... on RadioEpisodeTile {\n action {\n ...actionFragment\n __typename\n }\n available\n \n formattedDuration\n ...componentTrackingDataFragment\n __typename\n }\n ... on SongTile {\n startDate\n formattedStartDate\n endDate\n __typename\n }\n ... on RadioProgramTile {\n objectId\n __typename\n }\n}\nfragment componentTrackingDataFragment on IComponent {\n trackingData {\n data\n perTrigger {\n trigger\n data\n template {\n id\n __typename\n }\n __typename\n }\n __typename\n }\n}\nfragment brandLogosFragment on Logo {\n colorOnColor\n height\n mono\n primary\n type\n width\n}\nfragment paginatedTileListFragment on PaginatedTileList {\n __typename\n objectId\n listId\n actionItems {\n ...actionItemFragment\n __typename\n }\n banner {\n actionItems {\n ...actionItemFragment\n __typename\n }\n backgroundColor\n compactLayout\n description\n image {\n ...imageFragment\n __typename\n }\n titleArt {\n ...imageFragment\n __typename\n }\n textTheme\n title\n __typename\n }\n bannerSize\n displayType\n expires\n tileVariant\n paginatedItems(first: $lazyItemCount, after: $after, before: $before) {\n __typename\n edges {\n __typename\n cursor\n node {\n __typename\n ...tileFragment\n }\n }\n pageInfo {\n __typename\n endCursor\n hasNextPage\n hasPreviousPage\n startCursor\n }\n }\n sort {\n icon\n order\n title\n __typename\n }\n tileContentType\n tileOrientation\n title\n description\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n}\nfragment pageHeaderFragment on PageHeader {\n objectId\n title\n richShortDescription {\n __typename\n html\n }\n richDescription {\n __typename\n html\n }\n announcementValue\n announcementType\n mostRelevantEpisodeTile {\n __typename\n objectId\n tile {\n ...tileFragment\n __typename\n }\n title\n }\n actionItems {\n ...actionItemFragment\n __typename\n }\n secondaryMeta {\n longValue\n shortValue\n type\n value\n __typename\n }\n image {\n objectId\n alt\n focalPoint\n templateUrl\n __typename\n }\n categories {\n category\n name\n title\n __typename\n }\n presenters {\n title\n __typename\n }\n brands {\n name\n title\n __typename\n }\n brandsLogos {\n brand\n brandTitle\n logos {\n mono\n primary\n type\n __typename\n }\n __typename\n }\n}\nfragment bannerFragment on Banner {\n __typename\n objectId\n brand\n countdown {\n date\n __typename\n }\n richDescription {\n __typename\n text\n }\n ctaText\n image {\n objectId\n templateUrl\n alt\n focalPoint\n __typename\n }\n title\n compactLayout\n textTheme\n backgroundColor\n style\n action {\n ...actionFragment\n __typename\n }\n actionItems {\n ...actionItemFragment\n __typename\n }\n titleArt {\n objectId\n templateUrl\n __typename\n }\n labelMeta {\n __typename\n type\n value\n }\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n}\nfragment textFragment on Text {\n __typename\n objectId\n html\n}\nfragment seoFragment on SeoProperties {\n __typename\n title\n description\n}\nfragment socialSharingFragment on SocialSharingProperties {\n __typename\n title\n description\n image {\n __typename\n objectId\n templateUrl\n }\n}\nfragment trackingDataFragment on PageTrackingData {\n data\n perTrigger {\n trigger\n data\n template {\n id\n __typename\n }\n __typename\n }\n}', + 'operationName': 'VideoProgramPage', + 'variables': {'pageId': f'/vrtnu/{collection_url.split("/vrtmax/")[1]}.model.json'} + } + ).content.decode()) + + elif "/podcasts/" in collection_url: + response = json.loads(requests.post( + vrt_be.GRAPHQL_URL, + headers={'x-vrt-client-name': 'WEB'}, + json={ + 'query': 'query PodcastProgramPage($pageId: ID!) {\n page(id: $pageId) {\n ... on PodcastProgramPage {\n objectId\n permalink\n seo {\n ...seoFragment\n __typename\n }\n socialSharing {\n ...socialSharingFragment\n __typename\n }\n trackingData {\n ...trackingDataFragment\n __typename\n }\n ldjson\n components {\n __typename\n ... on IComponent {\n ...pageHeaderFragment\n ... on ContainerNavigation {\n objectId\n navigationType\n items {\n objectId\n title\n active\n active\n components {\n __typename\n ... on PaginatedTileList {\n __typename\n objectId\n sort {\n order\n __typename\n }\n title\n listId\n paginatedItems(first: 20) {\n edges {\n node {\n __typename\n ...tileFragment\n }\n __typename\n }\n pageInfo {\n __typename\n endCursor\n hasNextPage\n hasPreviousPage\n startCursor\n }\n __typename\n }\n }\n ... on IComponent {\n ... on Text {\n ...textFragment\n __typename\n }\n ... on TagsList {\n objectId\n title\n tags {\n name\n title\n category\n __typename\n }\n __typename\n }\n ... on PresentersList {\n objectId\n title\n presenters {\n title\n type\n __typename\n }\n __typename\n }\n ... on ContainerNavigation {\n objectId\n navigationType\n items {\n objectId\n title\n components {\n __typename\n ... on Component {\n ... on PaginatedTileList {\n __typename\n objectId\n sort {\n order\n __typename\n }\n title\n listId\n paginatedItems(first: 20) {\n edges {\n node {\n __typename\n ...tileFragment\n }\n cursor\n __typename\n }\n pageInfo {\n __typename\n endCursor\n hasNextPage\n hasPreviousPage\n startCursor\n }\n __typename\n }\n }\n ... on LazyTileList {\n objectId\n title\n listId\n __typename\n }\n __typename\n }\n }\n __typename\n }\n __typename\n }\n __typename\n }\n }\n __typename\n }\n __typename\n }\n __typename\n }\n }\n __typename\n }\n __typename\n }\n}\nfragment tileFragment on Tile {\n ... on IIdentifiable {\n __typename\n objectId\n }\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n ... on ITile {\n description\n title\n active\n action {\n ...actionFragment\n __typename\n }\n actionItems {\n ...actionItemFragment\n __typename\n }\n image {\n ...imageFragment\n __typename\n }\n primaryMeta {\n ...metaFragment\n __typename\n }\n secondaryMeta {\n ...metaFragment\n __typename\n }\n tertiaryMeta {\n ...metaFragment\n __typename\n }\n indexMeta {\n __typename\n type\n value\n }\n statusMeta {\n __typename\n type\n value\n }\n labelMeta {\n __typename\n type\n value\n }\n __typename\n }\n ... on ContentTile {\n brand\n brandLogos {\n ...brandLogosFragment\n __typename\n }\n __typename\n }\n ... on BannerTile {\n compactLayout\n backgroundColor\n textTheme\n brand\n brandLogos {\n ...brandLogosFragment\n __typename\n }\n ctaText\n passUserIdentity\n titleArt {\n objectId\n templateUrl\n __typename\n }\n __typename\n }\n ... on EpisodeTile {\n description\n formattedDuration\n available\n chapterStart\n action {\n ...actionFragment\n __typename\n }\n playAction: watchAction {\n pageUrl: videoUrl\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n episode {\n __typename\n objectId\n program {\n __typename\n objectId\n link\n }\n }\n \n __typename\n }\n ... on PodcastEpisodeTile {\n formattedDuration\n available\n programLink: podcastEpisode {\n objectId\n podcastProgram {\n objectId\n link\n __typename\n }\n __typename\n }\n playAction: listenAction {\n pageUrl: podcastEpisodeLink\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n __typename\n }\n ... on PodcastProgramTile {\n link\n __typename\n }\n ... on ProgramTile {\n link\n __typename\n }\n ... on AudioLivestreamTile {\n brand\n brandsLogos {\n brand\n brandTitle\n logos {\n ...brandLogosFragment\n __typename\n }\n __typename\n }\n __typename\n }\n ... on LivestreamTile {\n description\n __typename\n }\n ... on ButtonTile {\n icon\n iconPosition\n mode\n __typename\n }\n ... on RadioEpisodeTile {\n action {\n ...actionFragment\n __typename\n }\n available\n \n formattedDuration\n ...componentTrackingDataFragment\n __typename\n }\n ... on SongTile {\n startDate\n formattedStartDate\n endDate\n __typename\n }\n ... on RadioProgramTile {\n objectId\n __typename\n }\n}\nfragment metaFragment on MetaDataItem {\n __typename\n type\n value\n shortValue\n longValue\n}\nfragment actionFragment on Action {\n __typename\n ... on FavoriteAction {\n favorite\n id\n programUrl\n programWhatsonId\n title\n __typename\n }\n ... on ListDeleteAction {\n listName\n id\n listId\n title\n __typename\n }\n ... on ListTileDeletedAction {\n listName\n id\n listId\n __typename\n }\n ... on PodcastEpisodeListenAction {\n id: audioId\n podcastEpisodeLink\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n ... on EpisodeWatchAction {\n id: videoId\n videoUrl\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n ... on LinkAction {\n id: linkId\n linkId\n link\n linkType\n openExternally\n passUserIdentity\n linkTokens {\n __typename\n placeholder\n value\n }\n __typename\n }\n ... on ShareAction {\n title\n url\n __typename\n }\n ... on SwitchTabAction {\n referencedTabId\n mediaType\n link\n __typename\n }\n ... on RadioEpisodeListenAction {\n streamId\n pageLink\n startDate\n __typename\n }\n ... on LiveListenAction {\n streamId\n livestreamPageLink\n startDate\n startOver\n endDate\n __typename\n }\n ... on LiveWatchAction {\n streamId\n livestreamPageLink\n startDate\n startOver\n endDate\n __typename\n }\n}\nfragment actionItemFragment on ActionItem {\n __typename\n objectId\n accessibilityLabel\n action {\n ...actionFragment\n __typename\n }\n active\n icon\n iconPosition\n icons {\n __typename\n position\n ... on DesignSystemIcon {\n value {\n name\n __typename\n }\n __typename\n }\n }\n mode\n objectId\n title\n}\nfragment imageFragment on Image {\n __typename\n objectId\n alt\n title\n focalPoint\n templateUrl\n}\nfragment componentTrackingDataFragment on IComponent {\n trackingData {\n data\n perTrigger {\n trigger\n data\n template {\n id\n __typename\n }\n __typename\n }\n __typename\n }\n}\nfragment brandLogosFragment on Logo {\n colorOnColor\n height\n mono\n primary\n type\n width\n}\nfragment seoFragment on SeoProperties {\n __typename\n title\n description\n}\nfragment socialSharingFragment on SocialSharingProperties {\n __typename\n title\n description\n image {\n __typename\n objectId\n templateUrl\n }\n}\nfragment textFragment on Text {\n __typename\n objectId\n html\n}\nfragment pageHeaderFragment on PageHeader {\n objectId\n title\n richShortDescription {\n __typename\n html\n }\n richDescription {\n __typename\n html\n }\n announcementValue\n announcementType\n mostRelevantEpisodeTile {\n __typename\n objectId\n tile {\n ...tileFragment\n __typename\n }\n title\n }\n actionItems {\n ...actionItemFragment\n __typename\n }\n secondaryMeta {\n longValue\n shortValue\n type\n value\n __typename\n }\n image {\n objectId\n alt\n focalPoint\n templateUrl\n __typename\n }\n categories {\n category\n name\n title\n __typename\n }\n presenters {\n title\n __typename\n }\n brands {\n name\n title\n __typename\n }\n brandsLogos {\n brand\n brandTitle\n logos {\n mono\n primary\n type\n __typename\n }\n __typename\n }\n}\nfragment trackingDataFragment on PageTrackingData {\n data\n perTrigger {\n trigger\n data\n template {\n id\n __typename\n }\n __typename\n }\n}', + 'operationName': 'PodcastProgramPage', + 'variables': {'pageId': f'/vrtnu/{collection_url.split("/vrtmax/")[1]}.model.json'} + } + ).content.decode()) + + elif "/luister/radio/" in collection_url: + response = json.loads(requests.post( + vrt_be.GRAPHQL_URL, + headers={'x-vrt-client-name': 'WEB'}, + json={ + 'query': 'query RadioProgramPage($pageId: ID!) {\n page(id: $pageId) {\n __typename\n ... on RadioProgramPage {\n __typename\n objectId\n title\n brand\n permalink\n seo {\n ...seoFragment\n __typename\n }\n socialSharing {\n ...socialSharingFragment\n __typename\n }\n trackingData {\n ...trackingDataFragment\n __typename\n }\n components {\n __typename\n ... on PageHeader {\n ...pageHeaderFragment\n __typename\n }\n ... on ContainerNavigation {\n __typename\n objectId\n navigationType\n items {\n __typename\n objectId\n componentId\n title\n active\n }\n }\n }\n }\n }\n}\nfragment metaFragment on MetaDataItem {\n __typename\n type\n value\n shortValue\n longValue\n}\nfragment actionItemFragment on ActionItem {\n __typename\n objectId\n accessibilityLabel\n action {\n ...actionFragment\n __typename\n }\n active\n icon\n iconPosition\n icons {\n __typename\n position\n ... on DesignSystemIcon {\n value {\n name\n __typename\n }\n __typename\n }\n }\n mode\n objectId\n title\n}\nfragment actionFragment on Action {\n __typename\n ... on FavoriteAction {\n favorite\n id\n programUrl\n programWhatsonId\n title\n __typename\n }\n ... on ListDeleteAction {\n listName\n id\n listId\n title\n __typename\n }\n ... on ListTileDeletedAction {\n listName\n id\n listId\n __typename\n }\n ... on PodcastEpisodeListenAction {\n id: audioId\n podcastEpisodeLink\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n ... on EpisodeWatchAction {\n id: videoId\n videoUrl\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n ... on LinkAction {\n id: linkId\n linkId\n link\n linkType\n openExternally\n passUserIdentity\n linkTokens {\n __typename\n placeholder\n value\n }\n __typename\n }\n ... on ShareAction {\n title\n url\n __typename\n }\n ... on SwitchTabAction {\n referencedTabId\n mediaType\n link\n __typename\n }\n ... on RadioEpisodeListenAction {\n streamId\n pageLink\n startDate\n __typename\n }\n ... on LiveListenAction {\n streamId\n livestreamPageLink\n startDate\n startOver\n endDate\n __typename\n }\n ... on LiveWatchAction {\n streamId\n livestreamPageLink\n startDate\n startOver\n endDate\n __typename\n }\n}\nfragment imageFragment on Image {\n __typename\n objectId\n alt\n title\n focalPoint\n templateUrl\n}\nfragment tileFragment on Tile {\n ... on IIdentifiable {\n __typename\n objectId\n }\n ... on IComponent {\n ...componentTrackingDataFragment\n __typename\n }\n ... on ITile {\n description\n title\n active\n action {\n ...actionFragment\n __typename\n }\n actionItems {\n ...actionItemFragment\n __typename\n }\n image {\n ...imageFragment\n __typename\n }\n primaryMeta {\n ...metaFragment\n __typename\n }\n secondaryMeta {\n ...metaFragment\n __typename\n }\n tertiaryMeta {\n ...metaFragment\n __typename\n }\n indexMeta {\n __typename\n type\n value\n }\n statusMeta {\n __typename\n type\n value\n }\n labelMeta {\n __typename\n type\n value\n }\n __typename\n }\n ... on ContentTile {\n brand\n brandLogos {\n ...brandLogosFragment\n __typename\n }\n __typename\n }\n ... on BannerTile {\n compactLayout\n backgroundColor\n textTheme\n brand\n brandLogos {\n ...brandLogosFragment\n __typename\n }\n ctaText\n passUserIdentity\n titleArt {\n objectId\n templateUrl\n __typename\n }\n __typename\n }\n ... on EpisodeTile {\n description\n formattedDuration\n available\n chapterStart\n action {\n ...actionFragment\n __typename\n }\n playAction: watchAction {\n pageUrl: videoUrl\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n episode {\n __typename\n objectId\n program {\n __typename\n objectId\n link\n }\n }\n \n __typename\n }\n ... on PodcastEpisodeTile {\n formattedDuration\n available\n programLink: podcastEpisode {\n objectId\n podcastProgram {\n objectId\n link\n __typename\n }\n __typename\n }\n playAction: listenAction {\n pageUrl: podcastEpisodeLink\n resumePointProgress\n resumePointTotal\n completed\n __typename\n }\n __typename\n }\n ... on PodcastProgramTile {\n link\n __typename\n }\n ... on ProgramTile {\n link\n __typename\n }\n ... on AudioLivestreamTile {\n brand\n brandsLogos {\n brand\n brandTitle\n logos {\n ...brandLogosFragment\n __typename\n }\n __typename\n }\n __typename\n }\n ... on LivestreamTile {\n description\n __typename\n }\n ... on ButtonTile {\n icon\n iconPosition\n mode\n __typename\n }\n ... on RadioEpisodeTile {\n action {\n ...actionFragment\n __typename\n }\n available\n \n formattedDuration\n ...componentTrackingDataFragment\n __typename\n }\n ... on SongTile {\n startDate\n formattedStartDate\n endDate\n __typename\n }\n ... on RadioProgramTile {\n objectId\n __typename\n }\n}\nfragment componentTrackingDataFragment on IComponent {\n trackingData {\n data\n perTrigger {\n trigger\n data\n template {\n id\n __typename\n }\n __typename\n }\n __typename\n }\n}\nfragment brandLogosFragment on Logo {\n colorOnColor\n height\n mono\n primary\n type\n width\n}\nfragment seoFragment on SeoProperties {\n __typename\n title\n description\n}\nfragment socialSharingFragment on SocialSharingProperties {\n __typename\n title\n description\n image {\n __typename\n objectId\n templateUrl\n }\n}\nfragment trackingDataFragment on PageTrackingData {\n data\n perTrigger {\n trigger\n data\n template {\n id\n __typename\n }\n __typename\n }\n}\nfragment pageHeaderFragment on PageHeader {\n objectId\n title\n richShortDescription {\n __typename\n html\n }\n richDescription {\n __typename\n html\n }\n announcementValue\n announcementType\n mostRelevantEpisodeTile {\n __typename\n objectId\n tile {\n ...tileFragment\n __typename\n }\n title\n }\n actionItems {\n ...actionItemFragment\n __typename\n }\n secondaryMeta {\n longValue\n shortValue\n type\n value\n __typename\n }\n image {\n objectId\n alt\n focalPoint\n templateUrl\n __typename\n }\n categories {\n category\n name\n title\n __typename\n }\n presenters {\n title\n __typename\n }\n brands {\n name\n title\n __typename\n }\n brandsLogos {\n brand\n brandTitle\n logos {\n mono\n primary\n type\n __typename\n }\n __typename\n }\n}', + 'operationName': 'RadioProgramPage', + 'variables': {'pageId': f'/vrtnu/{collection_url.split("/vrtmax/")[1]}/'} + } + ).content.decode()) + else: + return None + + response = response["data"]["page"]["components"] + try: + collection_name = [c for c in response if c["__typename"] == "PageHeader"][0]["title"] + except: + collection_name = clean_url(collection_url).rstrip("/").split("/")[-1] + collection_name = get_valid_filename(collection_name) + + for c1 in response: + if c1["__typename"] == "PaginatedTileList": + c1["components"] = [c1] + return vrt_be.container_navigation_handler( + collection_name, {"items": [c1]}, + season_name, fragment, collection_url + ) + + if c1["__typename"] == "ContainerNavigation": + if fragment is None: + return None + return vrt_be.container_navigation_handler( + collection_name, c1, season_name, + fragment, collection_url + ) + + return None + + @staticmethod + def get_collection_elements(collection_url): + collection_url = collection_url.rstrip('/') + if "/vrtmax/" not in collection_url: + return None + + fragment = None + if "#" in collection_url: + fragment = urlparse(collection_url).fragment + collection_url = collection_url.split(f'#{fragment}')[0].rstrip("/") + + season_name = None + if "?" in collection_url and "seizoen=" in collection_url: + season_name = parse_qs(urlparse(collection_url).query)["seizoen"][0] + if "seizoen-" in season_name.lower(): + return None + collection_url = collection_url.split('?')[0].rstrip("/") + + for p, i in [ + ("/a-z/", 0), ("/podcasts/", 2), ("/livestream/audio/", -1), + ("/livestream/video/", -1), ("/luister/radio/", 1) + ]: + if p in collection_url: + if 0 <= i == collection_url.split(p)[1].count("/"): + return vrt_be.collection_handler(collection_url, season_name, fragment) + return [BaseElement(url=collection_url)] + return None diff --git a/API/proxiesembed/drmproxy/services/vtmgo_be.py b/API/proxiesembed/drmproxy/services/vtmgo_be.py new file mode 100644 index 0000000..453224d --- /dev/null +++ b/API/proxiesembed/drmproxy/services/vtmgo_be.py @@ -0,0 +1,406 @@ +import builtins +import json +import re +from os.path import join + +import browser_cookie3 +import requests +from bs4 import BeautifulSoup + +from utils.constants.macros import USER_ERROR, ERR_MSG, APP_ERROR, REQUESTS_TIMEOUT +from utils.main_service import main_service +from utils.structs import BaseElement, CustomException, BaseService +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename, get_ext_from_url, clean_url + + +class vtmgo_be(BaseService): + DEMO_URLS = [ + "https://www.vtmgo.be/vtmgo/boer-zkt-vrouw~78ede068-635f-4307-a8e0-fd157b79f40a", + "https://www.vtmgo.be/vtmgo/familie~96a49148-59f6-420c-9b90-8b058760c467", + "https://www.vtmgo.be/vtmgo/burger-house~ef4b0fde-2281-42a6-99c0-8230b7f1fc0c", + "https://www.vtmgo.be/vtmgo/aspe~e892cf10-5100-42ce-8d59-6b5c03cc2b96", + 'https://www.vtmgo.be/vtmgo/afspelen/571cfea2-0b01-4f39-bfe9-622020d641ad', + "https://www.vtmgo.be/vtmgo/afspelen/44ad5dfb-f745-4577-9a90-530774ce7132", + "https://www.vtmgo.be/vtmgo/afspelen/82098a6b-05cf-4123-a00f-a3d5046e866f", + "https://www.vtmgo.be/vtmgo/live-kijken", + "https://www.vtmgo.be/vtmgo/live-kijken/vtm4", + "https://www.vtmgo.be/vtmgo/live-kijken/qmusic", + ] + + CONFIG_URL = 'https://videoplayer-service.dpgmedia.net/play-config/{content_id}' + VIDEO_URL = "https://www.vtmgo.be/vtmgo/afspelen/{video_id}" + BASE_URL = "https://www.vtmgo.be/vtmgo" + + LOGIN_COOKIES = None + USER_AGENT = None + POPCORN_SDK = '8' + + @staticmethod + def test_service(): + main_service.run_service(vtmgo_be) + + @staticmethod + def is_content_livestream(content, additional): + return "/live-kijken/" in content and "/afspelen/" not in content + + @staticmethod + def credentials_needed(): + return {"FIREFOX_COOKIES": True} + + @staticmethod + def get_login_cookies(): + cookie_dict = {} + for c in browser_cookie3.firefox(domain_name='vtmgo.be'): + cookie_dict[c.name] = c.value + + try: + assert len(cookie_dict.keys()) > 0 + assert cookie_dict["lfvp_auth_token"] is not None + return cookie_dict + except: + return None + + @staticmethod + def get_site_data(site_url, is_livestream): + with requests.Session() as session: + response = session.get( + site_url, cookies=vtmgo_be.LOGIN_COOKIES, allow_redirects=False + ).content.decode() + + try: + api_key = re.search(r'apiKey: "([^"]*)"', response).group(1) + except: + api_key = None + + try: + token = re.search(r'token: "([^"]*)"', response).group(1) + except: + token = None + + if is_livestream: + for r1, r2 in [(r"playerData\s*=", "assetId"), (r"channel\s*:", "id")]: + try: + content_id = re.search(r1 + "[^{}]+{([^{}]+)}", response).group(1) + content_id = re.search(r2 + "[^\"']+[\"']([^\"']+)[\"']", content_id).group(1) + assert len(content_id) > 0 + break + except: + content_id = None + else: + content_id = re.search(r"/afspelen/([^/?]*)", site_url).group(1) + return api_key, token, content_id + + @staticmethod + def initialize_service(): + if vtmgo_be.USER_AGENT is None: + vtmgo_be.USER_AGENT = builtins.CONFIG["USER_AGENT"] + + if vtmgo_be.LOGIN_COOKIES is None: + vtmgo_be.LOGIN_COOKIES = vtmgo_be.get_login_cookies() + if vtmgo_be.LOGIN_COOKIES is None: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=f'from {vtmgo_be.__name__}', + reason='Need account for this service', + solution='Sign into your account using Firefox' + )) + + return vtmgo_be + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + additional["license_url"], data=challenge, + headers={"x-dt-auth-token": additional["auth_token"]} + ) + licence.raise_for_status() + return json.loads(licence.content.decode())["license"] + + @staticmethod + def get_video_data(source_element): + is_livestream = "/live-kijken/" in source_element.url and "/afspelen/" not in source_element.url + api_key, bearer_token, content_id = vtmgo_be.get_site_data(source_element.url, is_livestream) + if bearer_token is None: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}/{APP_ERROR}', + url=source_element.url, + reason='This content is no longer available or refresh the site cookies or VPN issues (Belgium)', + solution='Do not attempt to download it or sign into your account using Firefox and play a ' + 'random video or fix your VPN. If it persists then debug the service' + )) + if api_key is None: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}/{APP_ERROR}', + url=f'from {vtmgo_be.__name__}', + reason='Refresh the site cookies', + solution='Sign into your account using Firefox and play a random video. ' + 'If it persists then debug the service' + )) + + try: + response = requests.post( + vtmgo_be.CONFIG_URL.format(content_id=content_id), + json={'deviceType': 'web', 'zone': 'vtmgo'}, + headers={ + 'User-Agent': vtmgo_be.USER_AGENT, + 'x-api-key': api_key, + 'popcorn-sdk-version': vtmgo_be.POPCORN_SDK, + 'authorization': f'Bearer {bearer_token}' + }, + timeout=REQUESTS_TIMEOUT + ) + + if response.status_code == 403: + raise + except: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Timeout most likely due to fake user agent", + solution='Use your real user agent' + )) + + response = json.loads(response.content.decode()) + if response.get("code", None) == 103 and "available" in response.get("type", "").lower(): + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Can't download paid content", + solution='Do not attempt to download it' + )) + if response.get("code", None) == 104 and "found" in response.get("type", "").lower(): + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="This content is no longer available", + solution='Do not attempt to download it' + )) + + response = response["video"] + if source_element.element is None: + metadata = response.get("metadata", {}) + source_element.element = get_valid_filename(( + f'{metadata.get("program", {}).get("title", "Livestream" if is_livestream else "Movie")}' + f'_' + f'{metadata.get("title", source_element.url.split("/")[-1] if is_livestream else content_id)}' + )) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + vtmgo_be.__name__ + ) + + additional = {} + manifest = None + is_drm = True + for stream in response["streams"]: + if stream["type"] != "dash" or ".mpd" not in stream["url"]: + continue + manifest = stream["url"] + + drm = stream.get("drm", None) + if drm is None: + is_drm = False + break + + for k in drm: + if "widevine" in k.lower(): + drm = drm[k] + break + + additional["license_url"] = drm["licenseUrl"] + additional["auth_token"] = drm["drmtoday"]["authToken"] + break + + subtitles = [] + index = 0 + for subtitle in response.get("subtitles", []): + index += 1 + srt_ext = get_ext_from_url(subtitle["url"]) + + subtitles.append((False, BaseElement( + url=subtitle["url"], + collection=join(source_element.collection, source_element.element), + element=f'subtitle_{index}_{subtitle["language"]}{srt_ext}' + ))) + additional["SUBTITLES"] = subtitles + + try: + if not is_drm: + raise + pssh_value = str(min(re.findall( + r']*>(.*?)', + requests.get(manifest).content.decode() + ), key=len)) + except: + pssh_value = None + return manifest, pssh_value, additional + + @staticmethod + def get_episode_index(label): + if label is None or len(label) == 0: + return None + label = label.lower() + label = re.sub(r'\s+', ' ', label) + label = label.replace(' ', "_") + for r in ["aflevering_(\\d+)", "(\\d+)\\.", "-_(\\d+)", "\\d+"]: + try: + return int(re.findall(r, label)[0]) + except: + pass + return None + + @staticmethod + def handle_live_list(collection_url): + collection = [] + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + vtmgo_be.__name__ + ), + get_valid_filename(collection_url.split("/")[-1] + " livestreams") + ) + + with requests.Session() as session: + response = session.get(collection_url, cookies=vtmgo_be.LOGIN_COOKIES).content.decode() + livestreams = re.findall(r'href="([^"]+vtmgo.be/vtmgo/live-kijken/[^"]+)"', response) + if len(livestreams) == 0: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}/{APP_ERROR}', + url=f'from {vtmgo_be.__name__}', + reason='Refresh the site cookies', + solution='Sign into your account using Firefox and play a random video. ' + 'If it persists then debug the service' + )) + + live_index = 0 + for livestream in livestreams: + live_index += 1 + check = check_range(False, None, live_index) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=livestream, + collection=collection_title, + element=get_valid_filename(f"Channel {live_index} {livestream.split('/')[-1]}") + )) + return collection + + @staticmethod + def get_collection_elements(collection_url): + if "/afspelen/" in collection_url or "/live-kijken/" in collection_url: + return [BaseElement(url=collection_url)] + if clean_url(collection_url).rstrip("/").endswith("/live-kijken"): + return vtmgo_be.handle_live_list(collection_url) + + if collection_url.split(vtmgo_be.BASE_URL)[1].count("/") == 1 and "~" in collection_url: + collection = [] + series_id = collection_url.split("~")[1] + response = requests.get(collection_url, cookies=vtmgo_be.LOGIN_COOKIES).content.decode() + + matches = re.findall(r'"detail__title"[^>]*>([^<]+) 0: + collection_name = matches[0] + else: + collection_name = series_id + collection_name = get_valid_filename(collection_name) + + matches = re.findall(fr'href="({collection_url}/seizoen-\d+)["#]', response) + matches = [(m, int(m.split("/seizoen-")[1])) for m in matches] + matches = sorted(matches, key=lambda m: m[1]) + + indexes = [] + seasons = [] + for season_url, season_index in matches: + if season_index in indexes: + continue + indexes.append(season_index) + seasons.append((season_url, season_index)) + + for season_url, season_index in seasons: + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + response = requests.get(season_url, cookies=vtmgo_be.LOGIN_COOKIES).content.decode() + soup = BeautifulSoup(response, 'html5lib') + episodes_soup = soup.find_all(attrs={'class': 'detail__season'})[0] + episodes_soup = episodes_soup.find_all(attrs={'class': 'list__item'}) + + episodes = [] + for episode_soup in episodes_soup: + episode_soup = episode_soup.find_all(attrs={'class': 'media'}) + if len(episode_soup) == 0: + continue + episode_soup = episode_soup[0] + + episode_name = episode_soup.find_all(attrs={'class': 'media__title'})[0] + try: + temp_url = episode_name.find_all(attrs={'id': True})[0]['id'] + temp_url = temp_url[temp_url.index("-") + 1:] + temp_url = vtmgo_be.VIDEO_URL.format(video_id=temp_url) + except: + temp_url = None + + try: + temp_name = episode_name.find_all('span')[0].find(text=True, recursive=False).strip() + assert len(temp_name) > 0 + except: + temp_name = None + + if temp_name is None: + episode_name = episode_name.find(text=True, recursive=False).strip() + else: + episode_name = temp_name + episode_index = vtmgo_be.get_episode_index(episode_name) + + try: + episode_url = episode_soup.find_all(attrs={'class': 'media__figure-link'})[0] + episode_url = episode_url["href"] + assert "/afspelen/" in episode_url + except: + episode_url = temp_url + episodes.append((episode_url, episode_name, episode_index)) + + episodes = sorted(episodes, key=lambda m: m[2]) + index = 0 + duplicates = [] + for episode_url, episode_name, episode_index in episodes: + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + if episode_url is None: + continue + + if episode_name in duplicates: + index += 1 + index_name = "_" + str(index) + else: + duplicates.append(episode_name) + index_name = "" + + collection.append(BaseElement( + url=episode_url, + collection=join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + vtmgo_be.__name__ + ), + join(collection_name, f'Season_{season_index}') + ), + element=f"Episode_{episode_index}" + f"_" + f"{get_valid_filename(episode_name)}" + f"{index_name}" + )) + + return collection + return None diff --git a/API/proxiesembed/drmproxy/services/watch_blaze_tv.py b/API/proxiesembed/drmproxy/services/watch_blaze_tv.py new file mode 100644 index 0000000..fef7def --- /dev/null +++ b/API/proxiesembed/drmproxy/services/watch_blaze_tv.py @@ -0,0 +1,248 @@ +import builtins +import json +import re +from os.path import join + +import requests +from bs4 import BeautifulSoup + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import clean_url, get_valid_filename + + +class watch_blaze_tv(BaseService): + DEMO_URLS = [ + "https://watch.blaze.tv/watch/replay/38169103", + "https://watch.blaze.tv/watch/replay/94743/karens-big-idea", + "https://watch.blaze.tv/live/553", + "https://watch.blaze.tv/live/1235", + "https://watch.blaze.tv/series/Ancient+Aliens", + "https://watch.blaze.tv/shows/6cf0dc93-baf5-11ea-9b31-0626f8704156/hardcore-pawn", + "https://watch.blaze.tv/page/catchup", + ] + + STREAM_URL = '{stream_type}/stream/{stream_id}' + GUIDE_URL = 'https://watch.blaze.tv/guide' + + PLATFORM = "chrome" + API_KEY = None + + @staticmethod + def test_service(): + main_service.run_service(watch_blaze_tv) + + @staticmethod + def is_content_livestream(content, additional): + return "/live/" in content + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def set_endpoints(): + js_dict = json.loads(re.findall( + r'config[^={]*=[^{]*({.*?});', + requests.get(watch_blaze_tv.GUIDE_URL).content.decode(), + flags=re.DOTALL + )[0])["api"] + + watch_blaze_tv.API_KEY = js_dict["key"] + js_dict = js_dict["endpoints"] + + stream_url = js_dict["streams"] + js_dict["internal"].replace("https://", "") + stream_url += watch_blaze_tv.STREAM_URL + watch_blaze_tv.STREAM_URL = stream_url + + @staticmethod + def initialize_service(): + if watch_blaze_tv.API_KEY is None: + watch_blaze_tv.set_endpoints() + return watch_blaze_tv + + @staticmethod + def get_keys(challenge, additional): + raise Exception( + f'{BaseService.get_keys.__name__} must not be called ' + f'for the {watch_blaze_tv.__name__} service' + ) + + @staticmethod + def get_video_data(source_element): + if "/watch/" in source_element.url: + search = re.search(r'/watch/([^/]+)/([^/]+)', source_element.url) + stream_type = search.group(1) + if stream_type in ["vod"]: + stream_type = "replay" + stream_id = search.group(2) + else: + search = re.search(r'/live/([^/]+)', source_element.url) + stream_type = "live" + stream_id = search.group(1) + + response = requests.post( + watch_blaze_tv.STREAM_URL.format( + stream_type=stream_type, + stream_id=stream_id + ), + params={ + 'key': watch_blaze_tv.API_KEY, + 'platform': watch_blaze_tv.PLATFORM + } + ) + + response = response.content.decode() + if response == "api-streams": + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="Invalid stream type", + solution="Write a valid URL" + )) + + response = json.loads(response) + err_msg = response.get("response", {}).get("error", "").lower() + if "not found" in err_msg: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + response = response.get("response", {}) + has_drm = response.get("drm", False) is True + if has_drm: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Widevine DRM not supported", + solution=f"Extend the {watch_blaze_tv.__name__} service" + )) + + if source_element.element is None: + video_title = f'{stream_type}_{source_element.url.split("/")[-1]}' + source_element.element = get_valid_filename(video_title) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + watch_blaze_tv.__name__ + ) + return response["stream"], None, {} + + @staticmethod + def get_collection_elements(collection_url): + collection_url = clean_url(collection_url) + if "/watch/" in collection_url or "/live/" in collection_url: + return [BaseElement(url=collection_url)] + + if "/catchup" not in collection_url: + if "/shows/" not in collection_url and "/series/" not in collection_url: + return None + + collection = [] + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + watch_blaze_tv.__name__ + ), + get_valid_filename(collection_url.split("/")[-1]) + ) + + response = requests.get(collection_url) + response = response.content.decode() + if ">errors_geo_title<" in response.lower(): + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="Need British IP to access content", + solution="Use a VPN" + )) + + soup = BeautifulSoup(response, 'html5lib') + a_nodes = soup.find_all('a', href=True) + a_nodes = [a for a in a_nodes if "/watch/" in a["href"]] + + if "/page/catchup" in collection_url: + video_index = 0 + for a_node in a_nodes: + video_index += 1 + + check = check_range(False, None, video_index) + if check is True: + continue + elif check is False: + return collection + + video_title = a_node["href"].split("/")[-1] + collection.append(BaseElement( + url=a_node["href"], + collection=collection_title, + element=f'Video_{video_index}_{get_valid_filename(video_title)}' + )) + return collection + + episodes = [] + for a_node in a_nodes: + episode_title = a_node.text + if episode_title is None: + episode_title = "" + episode_title = episode_title.strip() + if len(episode_title) == 0: + episode_title = a_node["href"].split("/")[-1] + + episodes.append((a_node["href"], episode_title)) + episodes = list(reversed(episodes)) + + spans = soup.find_all('span', {"data-content-type": "season-episode"}) + contents = [] + + for span in spans: + span_text = re.findall(r"S\d+:E\d+", span.text, flags=re.IGNORECASE) + if len(span_text) == 0: + continue + + span_text = span_text[0].split(":") + try: + season_index = int(span_text[0][1:]) + episode_index = int(span_text[1][1:]) + except: + continue + + episode = episodes.pop() + found = False + for c_s, c_e in contents: + if c_s == season_index: + c_e.append((episode_index, episode)) + found = True + break + + if not found: + contents.append((season_index, [(episode_index, episode)])) + + contents = sorted(contents, key=lambda ct: ct[0]) + for season_index, episodes in contents: + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + episodes = sorted(episodes, key=lambda ep: ep[0]) + for episode_index, episode in episodes: + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=episode[0], + collection=join(collection_title, f'Season_{season_index}'), + element=f'Episode_{episode_index}_{get_valid_filename(episode[1])}' + )) + + return collection diff --git a/API/proxiesembed/drmproxy/services/watch_globaltv_com.py b/API/proxiesembed/drmproxy/services/watch_globaltv_com.py new file mode 100644 index 0000000..2c6db00 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/watch_globaltv_com.py @@ -0,0 +1,522 @@ +import base64 +import builtins +import json +import re +from os.path import join + +import requests +import xmltodict + +import utils.tools.cdm as cdm_tools +from utils.constants.macros import ERR_MSG, USER_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, CustomException, BaseService +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename, get_ext_from_url + + +class watch_globaltv_com(BaseService): + DEMO_URLS = [ + "https://watch.globaltv.com/series/f7a04c78-c1ff-11ee-ac50-0242ac110005/collection/4f809a02-caa1-11ee-abe3-0242ac110004/", + "https://watch.globaltv.com/series/411617347723/collection/650085443998/", + "https://watch.globaltv.com/series/820ad6e2-b6fe-11ee-bea3-0242ac110003/collection/1440eb0a-b6ff-11ee-8cba-0242ac110005/", + "https://watch.globaltv.com/series/32666602/collection/1054443075512/", + "https://watch.globaltv.com/series/a0bc9542-4e3d-11ed-9b84-0242ac110005/collection/0d98f950-4fae-11ed-a560-0242ac110002/", + "https://watch.globaltv.com/video/1467928131832", + "https://watch.globaltv.com/video/f3c5743c-c13e-11ee-8217-0242ac110002", + "https://watch.globaltv.com/video/23f22e48-5499-11ed-98d3-0242ac110004", + "https://watch.globaltv.com/movie/LIFE0056486710000000", + "https://watch.globaltv.com/movie/WNET0056532040000500", + "https://watch.globaltv.com/movie/LIFE0055278970000000", + "https://watch.globaltv.com/series/32666562/episode/GLOB0053686160000000", + "https://watch.globaltv.com/series/852506179691/episode/HGTV0054879080000000", + "https://watch.globaltv.com/series/759427139648/episode/HGTV0055596150000100", + "https://watch.globaltv.com/channel/215422c9-d1b9-4009-aaca-32e403f22b01", + "https://watch.globaltv.com/channel/6bfb7f13-9d9d-4211-9c50-fb56330e4ccd", + "https://watch.globaltv.com/channel/8970c668-40cd-4ca9-8c4d-25fd04f619b5", + ] + + SIGN_URL = 'https://global.corusappservices.com/authorization/untrusted/sign' + AUTHENTICATE_URL = 'https://global.corusappservices.com/authentication/authenticate' + AUTHORIZE_RESOURCE_URL = 'https://global.corusappservices.com/authorization/authorizeresource' + GET_STREAM_URL = 'https://global.corusappservices.com/media/getstream' + CONTAINER_URL = 'https://globalcontent.corusappservices.com/api/container/v1/' + BASE_URL = "https://watch.globaltv.com/" + VIDEO_URL = BASE_URL + 'video/{guid}' + EPISODE_URL = BASE_URL + 'series/{series_guid}/episode/{episode_guid}' + LICENSE_URL = "https://global.corusappservices.com/authorization/widevine/getresourcekey" + + USER_AGENT = None + SESSION_DATA = None + APP_ID = None + PAGE_LIMIT = 100 + + @staticmethod + def test_service(): + main_service.run_service(watch_globaltv_com) + + @staticmethod + def is_content_livestream(content, additional): + return "/channel/" in content + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def get_session_data(): + response = requests.post( + watch_globaltv_com.SIGN_URL, + headers={'User-Agent': watch_globaltv_com.USER_AGENT}, + json={ + 'path': '/authentication/authenticate', + 'data': { + 'transaction_type': 'authenticate', + 'authenticator_id': 'anonymous', + 'application_id': watch_globaltv_com.APP_ID, + 'platform_id': 'web_widevine' + } + } + ) + response = json.loads(response.content.decode())["data"]["session_data"] + + response = json.loads(base64.b64decode(json.loads(requests.post( + watch_globaltv_com.AUTHENTICATE_URL, + headers={'User-Agent': watch_globaltv_com.USER_AGENT}, + json={'session_data': response} + ).content.decode())["session_data"].split(".")[1] + "==").decode()) + return response + + @staticmethod + def get_application_id(): + main_js = re.findall( + r'src="(/static/js/main.*?\.js)"', + requests.get(watch_globaltv_com.BASE_URL).content.decode() + )[0] + return re.findall( + r'application_id:"(.*?)"', + requests.get(f'{watch_globaltv_com.BASE_URL}{main_js}').content.decode() + )[0] + + @staticmethod + def initialize_service(): + if watch_globaltv_com.USER_AGENT is None: + watch_globaltv_com.USER_AGENT = builtins.CONFIG["USER_AGENT"] + if watch_globaltv_com.APP_ID is None: + watch_globaltv_com.APP_ID = watch_globaltv_com.get_application_id() + if watch_globaltv_com.SESSION_DATA is None: + watch_globaltv_com.SESSION_DATA = watch_globaltv_com.get_session_data() + return watch_globaltv_com + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + watch_globaltv_com.LICENSE_URL, json={ + 'license_request_data': list(challenge), + 'authorization_token': additional["auth_token"] + } + ) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_init_from_mpd(mpd_url): + mpd_content = requests.get(mpd_url).content.decode() + mpd_content = xmltodict.parse(mpd_content)["MPD"]["Period"] + base_url = mpd_content["BaseURL"] + if type(mpd_content["AdaptationSet"]) is not list: + mpd_content["AdaptationSet"] = [mpd_content["AdaptationSet"]] + + best_content = None + best_height = None + best_bandwidth = None + for content in mpd_content["AdaptationSet"]: + if content["@contentType"] != "video": + continue + update_content = False + + height = content.get("@maxHeight", content.get("@height", None)) + if height is None: + continue + height = int(height) + bandwidth = content.get("@maxBandwidth", content.get("@bandwidth", None)) + + if best_content is None: + update_content = True + else: + if height > best_height: + update_content = True + elif height == best_height: + if bandwidth is not None: + if best_bandwidth is None: + update_content = True + elif int(bandwidth) > int(best_bandwidth): + update_content = True + + if update_content: + best_content = content + best_height = height + best_bandwidth = bandwidth + + mpd_content = best_content + init_url = mpd_content["SegmentTemplate"]["@initialization"] + if type(mpd_content["Representation"]) is not list: + mpd_content["Representation"] = [mpd_content["Representation"]] + + best_content = None + for content in mpd_content["Representation"]: + if best_content is None: + best_content = content + continue + if int(content["@height"]) > int(best_content["@height"]): + best_content = content + continue + elif int(content["@height"]) == int(best_content["@height"]): + if int(content["@bandwidth"]) > int(best_content["@bandwidth"]): + best_content = content + continue + + init_url = init_url.replace("$RepresentationID$", best_content["@id"]) + init_url = '/'.join(mpd_url.split('/')[:-1]) + "/" + base_url + init_url + return init_url + + @staticmethod + def get_pssh_from_manifest(manifest): + return cdm_tools.get_pssh_from_init(watch_globaltv_com.get_init_from_mpd(manifest)) + + @staticmethod + def get_manifest(source_url, content_id): + response = json.loads(requests.post( + watch_globaltv_com.SIGN_URL, + headers={'User-Agent': watch_globaltv_com.USER_AGENT}, + json={ + 'path': '/authorization/authorizeresource', + 'data': { + 'duid': watch_globaltv_com.SESSION_DATA['duid'], + 'puid': watch_globaltv_com.SESSION_DATA['puid'], + 'resource_id': content_id + } + } + ).content.decode())["data"]["session_data"] + + response = json.loads(base64.b64decode(json.loads(requests.post( + watch_globaltv_com.AUTHORIZE_RESOURCE_URL, + headers={'User-Agent': watch_globaltv_com.USER_AGENT}, + json={'session_data': response} + ).content.decode())["session_data"].split(".")[1] + "==").decode()) + if response["status"] == '401': + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_url, + reason="Need Canadian IP to access content", + solution="Use a VPN" + )) + + if response["status"] == "413": + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_url, + reason="The content isn't available without a TV provider account", + solution="Do not attempt to download it" + )) + response = response["data"]["authorization_token"] + + auth_token = response + response = json.loads(base64.b64decode(json.loads(requests.post( + watch_globaltv_com.GET_STREAM_URL, + json={ + 'authorization_token': response, + 'platform': 'web_widevine' + } + ).content.decode())["session_data"].split(".")[1] + "==").decode()) + return response["resources"]["streaming_url"], auth_token + + @staticmethod + def get_video_data(source_element): + content_id = None + for p in ["/episode/", "/channel/", "/movie/", "/video/"]: + try: + if p in source_element.url: + content_id = re.search(fr"{p}([^/]+)", source_element.url).group(1) + break + except: + pass + + response = json.loads(requests.get( + watch_globaltv_com.CONTAINER_URL, + params={"guid": content_id, "limit": '1'}, + headers={'User-Agent': watch_globaltv_com.USER_AGENT} + ).content.decode()) + + if response.get("count", None) == 0: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available anymore", + solution="Do not attempt to download it" + )) + + response = [r for r in response["results"] if r.get("guid", "") == content_id][0] + resources = response.get("resources", []) + response = response["data"] + + if source_element.element is None: + element_name = ( + f'{response.get("show_title", "")}' + f'_' + f'{response.get("title", "")}' + ) + element_name = get_valid_filename(element_name) + + if element_name is None or len(element_name) == 1: + element_name = content_id + source_element.element = element_name + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + watch_globaltv_com.__name__ + ) + + manifest, auth_token = watch_globaltv_com.get_manifest(source_element.url, content_id) + pssh_value = watch_globaltv_com.get_pssh_from_manifest(manifest) + + subtitles = [] + index = 0 + for resource in resources: + resource_type = resource.get("type", "").lower() + if "subtitle" in resource_type or "caption" in resource_type: + if "http" in resource.get("uri", "").lower(): + index += 1 + srt_url = resource["uri"] + srt_ext = get_ext_from_url(srt_url) + + subtitles.append((False, BaseElement( + url=srt_url, + collection=join(source_element.collection, source_element.element), + element=f'subtitle_{index}{srt_ext}' + ))) + return manifest, pssh_value, { + "auth_token": auth_token, + "SUBTITLES": subtitles + } + + @staticmethod + def get_collection_elements(collection_url): + if "/channel/" in collection_url or ("/series/" in collection_url and "/episode/" in collection_url): + return [BaseElement(url=collection_url)] + if "/movie/" in collection_url or "/video/" in collection_url: + return [BaseElement(url=collection_url)] + + if "/series/" in collection_url and "/collection/" in collection_url: + collection = [] + series_id = re.search(r"/series/([^/]+)", collection_url).group(1) + collection_id = re.search(r"/collection/([^/]+)", collection_url).group(1) + + season_response = json.loads(requests.get( + watch_globaltv_com.CONTAINER_URL, + params={"guid": series_id, "limit": '1'}, + headers={'User-Agent': watch_globaltv_com.USER_AGENT} + ).content.decode()) + + if season_response.get("count", None) == 0: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="The series isn't available anymore", + solution="Do not attempt to download it" + )) + + season_response = [r for r in season_response["results"] if r.get("guid", "") == series_id][0] + collection_name = season_response.get("label", None) + if collection_name is None: + collection_name = series_id + + season_response = json.loads(requests.get( + watch_globaltv_com.CONTAINER_URL, + params={ + "parent": series_id, "type": "collection", + "limit": watch_globaltv_com.PAGE_LIMIT + }, + headers={'User-Agent': watch_globaltv_com.USER_AGENT} + ).content.decode()) + + is_series = False + found = False + default_ordering = "reference_date" + while True: + for season_result in season_response.get("results", []): + if season_result.get("guid", "") != collection_id: + continue + + season_data = season_result.get('data', {}) + season_name = season_result.get('label', season_data.get('title', '')) + if "episodes" == season_name.lower(): + is_series = True + if len(season_name) == 0: + season_name = collection_id + + default_ordering = season_data.get("default_ordering", default_ordering) + collection_name += f'_{season_name}' + found = True + break + + if found: + break + season_next = season_response.get('next', None) + if season_next is None: + break + season_response = json.loads(requests.get( + season_next, headers={'User-Agent': watch_globaltv_com.USER_AGENT} + ).content.decode()) + + if not found: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=collection_url, + reason="The collection isn't available or isn't supported", + solution=f"Make sure you wrote a valid URL or extend the {watch_globaltv_com.__name__} service" + )) + collection_name = get_valid_filename(collection_name) + + for t in ["season", "media", "episode"]: + if not is_series and t == "season": + continue + if is_series and t != "season": + continue + + season_response = json.loads(requests.get( + watch_globaltv_com.CONTAINER_URL, + params={ + "parent": collection_id, + "limit": watch_globaltv_com.PAGE_LIMIT, + "type": t, + # "ordering": f'{"reference_date" if is_series else "order"}' + "ordering": f'{default_ordering if is_series else "order"}' + }, + headers={'User-Agent': watch_globaltv_com.USER_AGENT} + ).content.decode()) + + if season_response["count"] > 0: + break + + content_index = 0 + if is_series: + if season_response["count"] == 0: + season_response = json.loads(requests.get( + watch_globaltv_com.CONTAINER_URL, + params={ + "parent": collection_id, + "limit": watch_globaltv_com.PAGE_LIMIT, + "ordering": default_ordering + }, + headers={'User-Agent': watch_globaltv_com.USER_AGENT} + ).content.decode()) + is_series = False + + while True: + for content_result in season_response.get("results", []): + if content_result.get("guid", None) is None: + continue + if not is_series: + if content_result.get("type", "").lower() not in ["media", "episode"]: + continue + + content_index += 1 + check = check_range(False, None, content_index) + if check is True: + continue + elif check is False: + return collection + + content_guid = content_result["guid"] + content_data = content_result.get('data', {}) + content_name = content_data.get("title", None) + if content_name is None: + content_name = content_result.get("label", None) + if content_name is None: + content_name = content_guid + content_name = get_valid_filename(content_name) + + collection.append(BaseElement( + url=watch_globaltv_com.VIDEO_URL.format(guid=content_guid), + collection=join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + watch_globaltv_com.__name__ + ), + collection_name + ), + element=f'{content_index}_{content_name}' + )) + continue + + if content_result.get("type", "").lower() != "season": + continue + season_result = content_result + season_guid = season_result["guid"] + + season_data = season_result.get('data', {}) + if season_data.get("season_number", None) is None: + continue + season_index = season_data["season_number"] + check = check_range(True, int(season_index), None) + if check in [True, False]: + continue + + episode_response = json.loads(requests.get( + watch_globaltv_com.CONTAINER_URL, + params={ + "parent": season_guid, "type": "episode", + "limit": watch_globaltv_com.PAGE_LIMIT, + "ordering": 'reference_date' + }, + headers={'User-Agent': watch_globaltv_com.USER_AGENT} + ).content.decode()) + + while True: + for episode_result in episode_response.get("results", []): + if episode_result.get("guid", None) is None: + continue + episode_guid = episode_result["guid"] + + episode_data = episode_result.get('data', {}) + if episode_data.get("episode_number", None) is None: + continue + episode_index = episode_data["episode_number"] + check = check_range(False, int(season_index), int(episode_index)) + if check in [True, False]: + continue + + collection.append(BaseElement( + url=watch_globaltv_com.EPISODE_URL.format( + series_guid=series_id, + episode_guid=episode_guid + ), + collection=join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + watch_globaltv_com.__name__ + ), + join(str(collection_name), "Season_" + season_index) + ), + element=f'Episode_{episode_index}' + f'_' + f'{get_valid_filename(episode_data.get("title", episode_guid))}' + )) + + episode_next = episode_response.get('next', None) + if episode_next is None: + break + episode_response = json.loads(requests.get( + episode_next, headers={'User-Agent': watch_globaltv_com.USER_AGENT} + ).content.decode()) + + season_next = season_response.get('next', None) + if season_next is None: + break + season_response = json.loads(requests.get( + season_next, headers={'User-Agent': watch_globaltv_com.USER_AGENT} + ).content.decode()) + + return collection + return None diff --git a/API/proxiesembed/drmproxy/services/watch_shortly_film.py b/API/proxiesembed/drmproxy/services/watch_shortly_film.py new file mode 100644 index 0000000..6218feb --- /dev/null +++ b/API/proxiesembed/drmproxy/services/watch_shortly_film.py @@ -0,0 +1,366 @@ +import builtins +import json +from os.path import join +from urllib.parse import parse_qs, urlparse + +import requests + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR, CACHE_DIR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.cdm import get_pssh_from_cenc_pssh +from utils.tools.common import get_valid_filename, clean_url, dict_to_file, file_to_dict + + +class watch_shortly_film(BaseService): + DEMO_URLS = [ + "https://watch.shortly.film/play/f-for-freaks", + "https://watch.shortly.film/play/the-virus", + "https://watch.shortly.film/tag/11-15-min_23192C", + "https://watch.shortly.film/search?q=horror", + "https://watch.shortly.film/search?q=uk", + ] + + ASSET_URL = 'https://exposure.api.redbee.live/v1/customer/ShortlyFilm/businessunit/ShortlyOTT/content/asset/{asset_id}' + PLAY_URL = 'https://exposure.api.redbee.live/v2/customer/ShortlyFilm/businessunit/ShortlyOTT/entitlement/{asset_id}/play' + LOGIN_URL = 'https://exposure.api.redbee.live/v3/customer/ShortlyFilm/businessunit/ShortlyOTT/auth/login' + TAG_SEARCH_URL = 'https://exposure.api.redbee.live/v1/customer/ShortlyFilm/businessunit/ShortlyOTT/content/asset' + QUERY_SEARCH_URL = 'https://exposure.api.redbee.live/v3/customer/ShortlyFilm/businessunit/ShortlyOTT/content/search/query/{query}' + VIDEO_URL = 'https://watch.shortly.film/play/{asset_id}' + + EMAIL = "YOUR_EMAIL" + PASSWORD = "YOUR_PASSWORD" + BEARER_TOKEN = None + CACHE_FILE = None + PAGE_SIZE = 50 + + @staticmethod + def test_service(): + main_service.run_service(watch_shortly_film) + + @staticmethod + def credentials_needed(): + return { + "EMAIL": watch_shortly_film.EMAIL, + "PASSWORD": watch_shortly_film.PASSWORD + } + + @staticmethod + def get_bearer_token(): + try: + return file_to_dict(watch_shortly_film.CACHE_FILE)["bearer_token"] + except: + pass + + class_name = watch_shortly_film.__name__.replace("_", ".") + credentials = builtins.CONFIG["SERVICE_CREDENTIALS"][class_name] + try: + assert type(credentials["EMAIL"]) is str + assert type(credentials["PASSWORD"]) is str + except: + return None + + response = requests.post( + watch_shortly_film.LOGIN_URL, + json={ + 'username': credentials["EMAIL"], + 'password': credentials["PASSWORD"], + 'device': {'deviceId': 'deviceId'} + } + ) + + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + message = response.get("message", "").lower() + if status_code == 401 and message == "incorrect_credentials": + return None + + bearer_token = response["sessionToken"] + dict_to_file(watch_shortly_film.CACHE_FILE, {"bearer_token": bearer_token}) + return bearer_token + + @staticmethod + def initialize_service(): + if watch_shortly_film.CACHE_FILE is None: + watch_shortly_film.CACHE_FILE = join(CACHE_DIR, f'{watch_shortly_film.__name__}.json') + if builtins.CONFIG.get("FRESH", False) is True: + dict_to_file(watch_shortly_film.CACHE_FILE, {}) + + if watch_shortly_film.BEARER_TOKEN is None: + watch_shortly_film.BEARER_TOKEN = watch_shortly_film.get_bearer_token() + if watch_shortly_film.BEARER_TOKEN is None: + return None + return watch_shortly_film + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + additional["license_url"], + data=challenge + ) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_video_data(source_element): + asset_id = source_element.url.split("/")[-1] + response = requests.get(watch_shortly_film.ASSET_URL.format(asset_id=asset_id)) + + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + message = response.get("message", "").lower() + + if status_code == 404 and "unknown_asset" in message: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + if source_element.element is None: + title = None + localized = response.get("localized", []) + localized = list(filter(lambda lc: lc.get("locale", "").lower() in ["en"], localized)) + if len(localized) > 0: + localized = localized[0] + title = localized.get("title", localized.get("sortingTitle", "")) + + if title in [None, ""]: + title = response.get("originalTitle", None) + if title in [None, ""]: + title = f'Film_{asset_id}' + source_element.element = get_valid_filename(title) + + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + watch_shortly_film.__name__ + ) + + asset_id = response["assetId"] + response = requests.get( + watch_shortly_film.PLAY_URL.format(asset_id=asset_id), + params={'supportedFormats': 'dash', 'supportedDrms': 'widevine'}, + headers={'authorization': f'Bearer {watch_shortly_film.BEARER_TOKEN}'} + ) + + status_code = response.status_code + response = response.content.decode() + response = json.loads(response) + message = response.get("message", "").lower() + + if status_code == 401 and "session_token" in message: + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Can't access the video content because the cached token expired", + solution=f'Delete the {watch_shortly_film.CACHE_FILE} cache manually or add the parameter --fresh to your command' + )) + + response = response["formats"][0] + manifest = response["mediaLocator"] + license_url = response.get("drm", {}).get("com.widevine.alpha", {}).get("licenseServerUrl", None) + pssh_value = None + + if license_url is not None: + manifest_content = requests.get(manifest).content.decode() + try: + pssh_value = get_pssh_from_cenc_pssh(manifest_content) + except: + pssh_value = None + + if pssh_value is None: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Manifest format not supported: {manifest}. Can't extract pssh", + solution=f"Extend the {watch_shortly_film.__name__} service" + )) + + return manifest, pssh_value, {"license_url": license_url} + + @staticmethod + def get_tags(collection_url, search_query=None): + if search_query is None: + search_query = {} + + tag = search_query.get("tag_id", None) + collection_title = search_query.get("collection_title", None) + collection = search_query.get("collection", None) + video_index = search_query.get("video_index", None) + visited = search_query.get("visited", None) + + if tag is None: + tag = collection_url.split("/")[-1] + tag = f'tags.other:{tag}' + collection_title = f'Tag_{tag}' + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + watch_shortly_film.__name__ + ), + get_valid_filename(collection_title) + ) + collection = [] + video_index = 0 + visited = [] + + page = 0 + while True: + page += 1 + response = requests.get( + watch_shortly_film.TAG_SEARCH_URL, + params={ + 'pageSize': watch_shortly_film.PAGE_SIZE, + 'fieldSet': 'ALL', 'pageNumber': page, + 'query': tag + } + ) + + response = response.content.decode() + response = json.loads(response) + videos = response.get("items", []) + if len(videos) == 0: + break + + for video in videos: + try: + asset_id = video["slugs"][0] + assert len(asset_id) > 0 + except: + asset_id = video["assetId"] + + if asset_id in visited: + continue + visited.append(asset_id) + + video_index += 1 + check = check_range(False, None, video_index) + if check is True: + continue + elif check is False: + return collection + video_url = watch_shortly_film.VIDEO_URL.format(asset_id=asset_id) + + video_title = None + localized = video.get("localized", []) + localized = list(filter(lambda lc: lc.get("locale", "").lower() in ["en"], localized)) + if len(localized) > 0: + localized = localized[0] + video_title = localized.get("title", localized.get("sortingTitle", "")) + + if video_title in [None, ""]: + video_title = video.get("originalTitle", None) + if video_title in [None, ""]: + video_title = asset_id + video_title = get_valid_filename(f'Film_{video_index}_{video_title}') + + collection.append(BaseElement( + url=video_url, + collection=collection_title, + element=video_title + )) + + return collection + + @staticmethod + def get_search(collection_url): + params_dict = parse_qs(urlparse(collection_url).query) + query = params_dict["q"][0] + if query in ["", None]: + return [] + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + watch_shortly_film.__name__ + ), + get_valid_filename(f'Search_{query}') + ) + + response = requests.get( + watch_shortly_film.QUERY_SEARCH_URL.format(query=query), + params={ + 'fieldSet': 'ALL', 'locale': 'en', + 'types': 'MOVIE,TV_SHOW,EPISODE,TV_CHANNEL,LIVE_EVENT,EVENT', + 'schemes': ['other', 'genre', 'category'] + } + ) + + response = response.content.decode() + response = json.loads(response) + videos = response.get("assetHits", {}).get("items", []) + + video_index = 0 + collection = [] + visited = [] + for video in videos: + video = video["asset"] + try: + asset_id = video["slugs"][0] + assert len(asset_id) > 0 + except: + asset_id = video["assetId"] + + if asset_id in visited: + continue + visited.append(asset_id) + + video_index += 1 + check = check_range(False, None, video_index) + if check is True: + continue + elif check is False: + return collection + + video_url = watch_shortly_film.VIDEO_URL.format(asset_id=asset_id) + video_title = None + localized = video.get("localized", []) + localized = list(filter(lambda lc: lc.get("locale", "").lower() in ["en"], localized)) + if len(localized) > 0: + localized = localized[0] + video_title = localized.get("title", localized.get("sortingTitle", "")) + + if video_title in [None, ""]: + video_title = video.get("originalTitle", None) + if video_title in [None, ""]: + video_title = asset_id + video_title = get_valid_filename(f'Film_{video_index}_{video_title}') + + collection.append(BaseElement( + url=video_url, + collection=collection_title, + element=video_title + )) + + tag_ids = [t["tag"]["tagId"] for t in response.get("tagHits", {}).get("items", [])] + if len(tag_ids) == 0: + return collection + + tag_ids = " OR ".join(tag_ids) + collection = watch_shortly_film.get_tags( + collection_url, + search_query={ + "tag_id": f'tags.tagId:{tag_ids}', + "collection_title": collection_title, + "collection": collection, + "video_index": video_index, + "visited": visited + } + ) + return collection + + @staticmethod + def get_collection_elements(collection_url): + if "/search?q=" in collection_url: + return watch_shortly_film.get_search(collection_url) + collection_url = clean_url(collection_url) + + if "/play/" in collection_url: + return [BaseElement(url=collection_url)] + if "/tag/" in collection_url: + return watch_shortly_film.get_tags(collection_url) + return None diff --git a/API/proxiesembed/drmproxy/services/watch_tbn_uk.py b/API/proxiesembed/drmproxy/services/watch_tbn_uk.py new file mode 100644 index 0000000..95304a6 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/watch_tbn_uk.py @@ -0,0 +1,227 @@ +import builtins +import json +import re +from os.path import join + +import requests +from bs4 import BeautifulSoup + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService, CustomException +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename, clean_url + + +class watch_tbn_uk(BaseService): + DEMO_URLS = [ + "https://watch.tbn.uk/watch/replay/19118141/john-mcginley", + "https://watch.tbn.uk/watch/vod/52157303/identity-and-belonging", + "https://watch.tbn.uk/live/1197", + "https://watch.tbn.uk/shows/c171a631-ca92-4715-9df4-51567542481c/the-sessions-with-cynthia-garrett", + "https://watch.tbn.uk/shows/906eb770-23de-4fc7-a369-e87167a5256d/praise-uk", + ] + + STREAM_URL = '/api/{stream_type}/stream/{stream_id}' + BASE_URL = "https://watch.tbn.uk" + + API_KEY = None + + @staticmethod + def test_service(): + main_service.run_service(watch_tbn_uk) + + @staticmethod + def is_content_livestream(content, additional): + return "/live/" in content + + @staticmethod + def get_additional_params(additional): + return [("MUXER", lambda s: s.format(args="mkv:muxer=mkvmerge"))] + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def set_api_info(): + response = requests.get(watch_tbn_uk.BASE_URL) + response = response.content.decode() + response = re.findall(r'config[^=]*=[^{]*({[^;]+});', response) + response = json.loads(response[0])["api"] + + watch_tbn_uk.API_KEY = response["key"] + response = response["endpoints"] + watch_tbn_uk.STREAM_URL = response["streams"] + watch_tbn_uk.STREAM_URL + + @staticmethod + def initialize_service(): + if watch_tbn_uk.API_KEY is None: + watch_tbn_uk.set_api_info() + return watch_tbn_uk + + @staticmethod + def get_keys(challenge, additional): + raise Exception( + f'{BaseService.get_keys.__name__} must not be called ' + f'for the {watch_tbn_uk.__name__} service' + ) + + @staticmethod + def get_video_data(source_element): + response = requests.get(source_element.url) + response_html = response.content.decode() + response = re.findall(r'data-uvid="([^"]+)"', response_html) + if len(response) == 0: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + stream_id = response[0] + response = re.findall(r'this.url.params[^=]*=[^{]*({[^}]+})', response_html) + if len(response) == 0: + response = re.findall(r'programme[^{]*({[^}]+})', response_html) + response = re.findall(r"type[^:]*:[^']*'([^']+)'", response[0]) + stream_type = response[0].lower() + + response = requests.post( + watch_tbn_uk.STREAM_URL.format(stream_type=stream_type, stream_id=stream_id), + params={'key': watch_tbn_uk.API_KEY, 'platform': 'chrome'} + ) + response = response.content.decode() + response = json.loads(response).get("response", {}) + if "not found" in response.get("error", "").lower(): + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't available", + solution="Do not attempt to download it" + )) + + if response.get("drm", False) is True: + raise CustomException(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Widevine DRM not supported", + solution=f"Extend the {watch_tbn_uk.__name__} service" + )) + + manifest = response.get("stream", "") + if manifest in ["", None]: + response = response["ads"] + manifest = response["prefix"] + response["session"] + manifest = requests.post(manifest) + manifest = manifest.content.decode() + manifest = json.loads(manifest) + manifest = response["prefix"] + manifest["manifestUrl"] + + if source_element.element is None: + response_html = BeautifulSoup(response_html, 'html5lib') + try: + title = response_html.title.text + assert len(title) > 0 + except: + title = f'Video_{source_element.url.split("/")[-1]}' + source_element.element = get_valid_filename(title) + + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + watch_tbn_uk.__name__ + ) + + return manifest, None, {} + + @staticmethod + def get_collection_elements(collection_url): + collection_url = clean_url(collection_url) + for f in ["vod", "replay"]: + if f"/watch/{f}/" in collection_url: + return [BaseElement(url=collection_url)] + if "/live/" in collection_url: + return [BaseElement(url=collection_url)] + if "/shows/" not in collection_url: + return None + + response = requests.get(collection_url) + response = response.content.decode() + + try: + collection_title = re.findall(r'"af_content"[^:]*:[^"]*"([^"]+)"', response) + collection_title = collection_title[0] + assert len(collection_title) > 0 + except: + collection_title = collection_url.split("/")[-1] + collection_title = join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + watch_tbn_uk.__name__ + ), + get_valid_filename(collection_title) + ) + + response_soup = BeautifulSoup(response, 'html5lib') + card_nodes = response_soup.find_all('div', class_=lambda c: c and "card-body" in c) + seasons = {} + for card_node in card_nodes: + try: + card_title = card_node.find(class_=lambda c: c and "card-title" in c) + card_title = card_title.find("a", attrs={"href": True}) + episode_url = card_title["href"] + assert len(episode_url) > 0 + + season_index = card_node.find("span", attrs={"data-content-type": "season"}) + season_index = season_index.get_text().strip() + season_index = re.search(r'season\s*(\d+)', season_index, flags=re.IGNORECASE) + season_index = int(season_index.group(1)) + + episode_index = card_node.find("span", attrs={"data-content-type": "episode"}) + episode_index = episode_index.get_text().strip() + episode_index = re.search(r'episode\s*(\d+)', episode_index, flags=re.IGNORECASE) + episode_index = int(episode_index.group(1)) + except: + continue + + try: + episode_title = card_title.get_text().strip() + assert len(episode_title) > 0 + except: + episode_title = episode_url.split("/")[-1] + episode_title = f'Episode_{episode_index}_{episode_title}' + + if seasons.get(season_index, None) is None: + seasons[season_index] = [] + seasons[season_index].append((episode_index, { + "title": episode_title, + "url": episode_url + })) + + collection = [] + for season_index, episodes in sorted(seasons.items()): + check = check_range(True, season_index, None) + if check is True: + continue + elif check is False: + return collection + + if len(episodes) == 0: + continue + episodes = sorted(episodes, key=lambda e: e[0]) + + for episode_index, episode in episodes: + check = check_range(False, season_index, episode_index) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=episode["url"], + collection=join(collection_title, f'Season_{season_index}'), + element=get_valid_filename(episode["title"]) + )) + + return collection diff --git a/API/proxiesembed/drmproxy/services/wittytv_it.py b/API/proxiesembed/drmproxy/services/wittytv_it.py new file mode 100644 index 0000000..3b40365 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/wittytv_it.py @@ -0,0 +1,222 @@ +import builtins +import json +import re +from os.path import join +from urllib.parse import urlencode, urlparse, urlunparse, parse_qs + +import requests + +from utils.main_service import main_service +from utils.structs import BaseElement, BaseService +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename + + +class wittytv_it(BaseService): + DEMO_URLS = [ + "https://www.wittytv.it/?trasmissioni=cat-originals&category_name=google-bar", + "https://www.wittytv.it/?trasmissioni=cat-amici&category_name=clip", + "https://www.wittytv.it/?trasmissioni=cat-amici&category_name=le-puntate", + "https://www.wittytv.it/tu-si-que-vales/prima-puntata-sabato-18-settembre/", + "https://www.wittytv.it/ce-posta-per-te/quarta-puntata-sabato-3-febbraio/", + "https://www.wittytv.it/maurizio-costanzo-show/ultima-puntata-venerdi-25-novembre/", + "https://www.wittytv.it/uomini-e-donne/lunedi-11-marzo-2", + "https://www.wittytv.it/uomini-e-donne/venerdi-8-marzo-2/", + "https://www.wittytv.it/uomini-e-donne/esterna-di-ida-e-pierpaolo-8-marzo/", + ] + + LOGIN_URL = "https://api-ott-prod-fe.mediaset.net/PROD/play/idm/anonymous/login/v2.0" + ACCOUNT_URL = "http://access.auth.theplatform.com/data/Account/{a_id}" + PLAYBACK_URL = 'https://api-ott-prod-fe.mediaset.net/PROD/play/playback/check/v2.0' + PROGRAM_URL = 'https://feed.entertainment.tv.theplatform.eu/f/-/mediaset-prod-ext-programs-v2/guid/-/{guid}' + QUERY_URL = 'https://www.wittytv.it/wp-admin/admin-ajax.php?action=load_more&query[category_name]={category_name}&query[trasmissioni]={broadcast}&query[paged]={page}' + MEDIASET_URL = 'https://mediasetinfinity.mediaset.it' + LICENSE_URL = 'https://widevine.entitlement.theplatform.eu/wv/web/ModularDrm/getRawWidevineLicense' + + USER_AGENT = None + BEARER_TOKEN = None + RES_PRIORITY = ["hd", "hr", "sd"] + + @staticmethod + def test_service(): + main_service.run_service(wittytv_it) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def get_bearer_token(): + return json.loads(requests.post( + wittytv_it.LOGIN_URL, json={'client_id': 'client_id', 'appName': 'embed//mediasetplay-embed'} + ).content.decode())["response"]["beToken"] + + @staticmethod + def initialize_service(): + if wittytv_it.USER_AGENT is None: + wittytv_it.USER_AGENT = builtins.CONFIG["USER_AGENT"] + if wittytv_it.BEARER_TOKEN is None: + wittytv_it.BEARER_TOKEN = wittytv_it.get_bearer_token() + return wittytv_it + + @staticmethod + def get_keys(challenge, additional): + licence = requests.post( + wittytv_it.LICENSE_URL, data=challenge, + params={ + 'releasePid': additional['release_pid'], + 'account': wittytv_it.ACCOUNT_URL.format(a_id=additional["account"]), + 'schema': '1.0', 'token': wittytv_it.BEARER_TOKEN + } + ) + licence.raise_for_status() + return licence.content + + @staticmethod + def get_manifest_info(manifest, formats, manifest_info): + try: + raise + return manifest, str(min(re.findall( + r'(.+?)', + requests.get(f"{manifest}?formats={formats}").content.decode() + ), key=len)) + except: + pass + matches = re.findall(r'= 300: + raise + except: + continue + try: + return temp_url, str(min(re.findall( + r'(.+?)', response.content.decode() + ), key=len)) + except: + return temp_url, None + return None, None + + @staticmethod + def get_video_data(source_element): + content_id = re.search( + r'guIDcurrentGlobal\s*=\s*"([^"]+)"', + requests.get(source_element.url).content.decode() + ).group(1) + + if source_element.element is None: + content_info = json.loads(requests.get( + wittytv_it.PROGRAM_URL.format(guid=content_id), + headers={'User-Agent': wittytv_it.USER_AGENT} + ).content.decode()) + + title = content_info.get("title", None) + if title is None: + title = content_id + title = get_valid_filename(title) + + program = content_info.get("mediasetprogram$brandTitle", None) + if program is None: + program = content_info.get("mediasetprogram$auditelBrandName", None) + if program is None: + program = content_info.get("mediasetprogram$tvLinearSeasonTitle", None) + program = get_valid_filename(program) + if program is None: + program = "" + source_element.element = f'{program}_{title}' + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + wittytv_it.__name__ + ) + + response = json.loads(requests.post( + wittytv_it.PLAYBACK_URL, json={'contentId': content_id, 'streamType': 'VOD'}, + headers={ + 'User-Agent': wittytv_it.USER_AGENT, + 'Authorization': f'Bearer {wittytv_it.BEARER_TOKEN}' + } + ).content.decode())["response"]["mediaSelector"] + + manifest = response.pop("url") + response["auth"] = wittytv_it.BEARER_TOKEN + manifest_info = f"{manifest}?{urlencode(response)}" + manifest_info = requests.get(manifest_info, headers={ + 'Accept': 'application/json, text/plain, */*', + 'Origin': wittytv_it.MEDIASET_URL, + 'Referer': wittytv_it.MEDIASET_URL, + 'User-Agent': wittytv_it.USER_AGENT + }).content.decode() + + manifest, pssh_value = wittytv_it.get_manifest_info(manifest, response["formats"], manifest_info) + return manifest, pssh_value, { + "release_pid": re.search(r"\|pid=(.*?)\|", manifest_info).group(1), + "account": re.search(r"aid=(.*?)\|", manifest_info).group(1) + } + + @staticmethod + def get_collection_elements(collection_url): + if "trasmissioni=" in collection_url and "category_name=" in collection_url: + collection = [] + params_dict = parse_qs(urlparse(collection_url).query) + broadcast = params_dict["trasmissioni"][0] + category_name = params_dict["category_name"][0] + collection_name = get_valid_filename(broadcast) + + page = 0 + episode_index = 0 + urls = [] + while True: + page += 1 + episodes = json.loads(requests.get(wittytv_it.QUERY_URL.format( + category_name=category_name, + broadcast=broadcast, + page=str(page) + )).content.decode())["data"] + if len(episodes) == 0: + break + + for episode in episodes: + if episode["link"] in urls: + continue + + episode_index += 1 + check = check_range(False, None, episode_index) + if check is True: + continue + elif check is False: + return collection + + collection.append(BaseElement( + url=episode["link"], + collection=join(join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + wittytv_it.__name__ + ), collection_name), + element=f'{episode_index}_{get_valid_filename(episode["title"])}' + )) + urls.append(episode["link"]) + return collection + + if collection_url.split("wittytv.it")[1].count("/") >= 2: + return [BaseElement(url=collection_url)] + return None diff --git a/API/proxiesembed/drmproxy/services/zee5_com.py b/API/proxiesembed/drmproxy/services/zee5_com.py new file mode 100644 index 0000000..dcaa648 --- /dev/null +++ b/API/proxiesembed/drmproxy/services/zee5_com.py @@ -0,0 +1,285 @@ +import builtins +import json +import re +import time +from os.path import join + +import requests + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR +from utils.main_service import main_service +from utils.structs import BaseElement, CustomException, BaseService +from utils.tools.args import check_range +from utils.tools.common import get_valid_filename, get_country_code + + +class zee5_com(BaseService): + DEMO_URLS = [ + "https://www.zee5.com/global/tv-shows/details/sa-re-ga-ma-pa-2023/0-6-4z5416889", + "https://www.zee5.com/global/web-series/details/united-kacche/0-6-4z5327133", + "https://www.zee5.com/global/kids/kids-shows/sa-re-ga-ma-pa-lil-champs-2020/0-6-2526", + "https://www.zee5.com/global/kids/kids-shows/sa-re-ga-ma-pa-lil-champs-2019/0-6-1317/sa-re-ga-ma-pa-lil-champs-2019-episode-5-february-23-2019-full-episode/0-1-179578", + "https://www.zee5.com/global/kids/kids-shows/sa-re-ga-ma-pa-lil-champs-2020/0-6-2526/musician-pyarelal-sharma-graces-the-show-sa-re-ga-ma-pa-lil-champs-2020/0-1-manual_6g16vpetmim0", + "https://www.zee5.com/global/tv-shows/details/pyar-ka-pehla-naam-radha-mohan/0-6-4z5130241/latest", + "https://www.zee5.com/global/tv-shows/details/navri-mile-hitlerla/0-6-4z5521328/latest", + "https://www.zee5.com/global/tv-shows/details/pavitra-rishta/0-6-133/episode-1189-pavitra-rishta/0-1-manual_1ej5qfm3eg8g", + "https://www.zee5.com/global/tv-shows/details/veera/0-6-4z5521331/ramachandran-disbelieves-raghavan/0-1-6z5536732", + "https://www.zee5.com/global/web-series/details/maya-bazaar-for-sale/0-6-4z5387149/who-let-the-cow-out/0-1-6z5395324", + "https://www.zee5.com/global/web-series/details/united-kacche/0-6-4z5327133/pehli-job-dusra-pyaar/0-1-6z5335305", + "https://www.zee5.com/global/movies/details/the-long-drive/0-0-1z520799", + "https://www.zee5.com/global/movies/details/kaagaz/0-0-1z536625", + ] + + CONTENT_URL = 'https://spapi.zee5.com/singlePlayback/getDetails/secure?content_id={content_id}&show_id={show_id}&device_id=device_id&platform_name=desktop_web&country={country_code}&check_parental_control=false' + CONTENT_SHOW_URL = 'https://gwapi.zee5.com/content/tvshow/{content_id}' + LICENSE_URL = "https://spapi.zee5.com/widevine/getLicense" + BASE_URL = "https://www.zee5.com/global" + + COUNTRY_CODE = None + PAGE_LIMIT = 100 + ACCESS_TOKEN = None + LICENSE_RETRIES = 3 + + @staticmethod + def test_service(): + main_service.run_service(zee5_com) + + @staticmethod + def credentials_needed(): + return {"NONE_NEEDED": True} + + @staticmethod + def initialize_service(): + if zee5_com.ACCESS_TOKEN is None: + zee5_com.ACCESS_TOKEN = zee5_com.get_access_token() + if zee5_com.COUNTRY_CODE is None: + zee5_com.COUNTRY_CODE = get_country_code() + + if zee5_com.COUNTRY_CODE is None: + raise CustomException(ERR_MSG.format( + type=f'{APP_ERROR}', + url=f'from the {zee5_com.__name__} service', + reason="Failed to obtain the country code", + solution="Fix the code responsible for obtaining the country code" + )) + else: + zee5_com.COUNTRY_CODE = zee5_com.COUNTRY_CODE.upper() + return zee5_com + + @staticmethod + def get_keys(challenge, additional): + licence = None + for i in range(1, zee5_com.LICENSE_RETRIES + 1): + try: + licence = requests.post( + zee5_com.LICENSE_URL, data=challenge, headers={ + 'nl': additional["nl"], + 'customdata': additional["custom_data"], + } + ) + licence.raise_for_status() + break + except Exception as e: + response = e.response + if response.status_code == 403: + if i < zee5_com.LICENSE_RETRIES: + time.sleep(1) + continue + raise e + return licence.content + + @staticmethod + def get_access_token(): + for s in ['"platform_token":{"token":', '"platformToken":']: + try: + return re.search( + rf'{s}"(.*?)"', + requests.get(zee5_com.BASE_URL).content.decode() + ).group(1) + except: + pass + return None + + @staticmethod + def get_video_data(source_element): + if "/movies/" in source_element.url: + show_id = None + content_id = re.search(r'/global/[^/]+/[^/]+/[^/]+/([^/]+)', source_element.url).group(1) + content_url = zee5_com.CONTENT_URL.replace("&show_id={show_id}", "") + else: + show_id = re.search(r'/global/[^/]+/[^/]+/[^/]+/([^/]+)/', source_element.url).group(1) + + if "latest" in source_element.url.split("/")[-1]: + content_id = show_id + content_url = zee5_com.CONTENT_URL.replace("&show_id={show_id}", "&is_latest=1") + else: + content_id = re.search(r'/global/[^/]+/[^/]+/[^/]+/[^/]+/[^/]+/([^/]+)$', source_element.url).group(1) + content_url = zee5_com.CONTENT_URL + + manifest, response = None, {} + try: + response = json.loads(requests.post( + content_url.format(content_id=content_id, show_id=show_id, country_code=zee5_com.COUNTRY_CODE), + json={ + 'x-access-token': zee5_com.ACCESS_TOKEN, + 'X-Z5-Guest-Token': '00000000-0000-0000-0000-00000000' + } + ).content.decode()) + + manifest = None + is_hls = False + for details in response: + try: + manifest = response[details]["video_url"]["mpd"] + except: + pass + + if manifest is None: + try: + manifest = response[details]["hls_token"] + is_hls = True + except: + pass + + if not is_hls: + manifest = manifest.split("?")[0] + manifest = re.sub(r'-\w+\.mpd', '.mpd', manifest) + except: + pass + + if manifest is None: + raise CustomException(ERR_MSG.format( + type=f'{USER_ERROR}', + url=source_element.url, + reason="The content isn't found, needs account, or isn't available in your region", + solution="Do not attempt to download it or use a VPN with a different country" + )) + + if source_element.element is None: + element_name = response.get("assetDetails", {}).get("title", None) + if element_name is None: + element_name = response.get("assetDetails", {}).get("original_title", None) + if element_name is None: + element_name = content_id + source_element.element = get_valid_filename(element_name) + if source_element.collection is None: + source_element.collection = join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + zee5_com.__name__ + ) + + try: + pssh_value = str(min(re.findall( + r']*>(.*?)', + requests.get(manifest).content.decode() + ), key=len)) + except: + return manifest, None, {} + return manifest, pssh_value, { + "nl": response["keyOsDetails"]["nl"], + "custom_data": response["keyOsDetails"]["sdrm"] + } + + @staticmethod + def get_collection_elements(collection_url): + if "/cricket" in collection_url: + return None + if "/latest" in collection_url: + return [BaseElement(url=collection_url)] + + try: + section = re.search(r'(/global/[^/]+/[^/]+/)', collection_url).group(1) + except: + return None + if "movies" in section: + is_series = False + else: + rest_url = collection_url.split(section)[1] + if rest_url.count("/") > 1: + is_series = False + else: + is_series = True + + if not is_series: + return [BaseElement(url=collection_url)] + else: + collection = [] + content_id = re.search(r'/global/[^/]+/[^/]+/[^/]+/([^/]+)', collection_url).group(1) + response = requests.get( + zee5_com.CONTENT_SHOW_URL.format(content_id=content_id), + headers={'x-access-token': zee5_com.ACCESS_TOKEN} + ).content.decode() + + if ">access denied<" in response.lower(): + raise CustomException(ERR_MSG.format( + type=USER_ERROR, + url=collection_url, + reason='You requested too much content recently', + solution='Wait 10 minutes' + )) + + response = json.loads(response) + season_id = response["season_details"]["id"] + + season_title = response.get("title", None) + if season_title is None: + season_title = season_id + season_title = get_valid_filename(season_title) + + content_url = zee5_com.CONTENT_SHOW_URL.replace("{content_id}", "") + page = 1 + is_asc = None + compare = [] + + while True: + current_page = json.loads(requests.get( + content_url, headers={'x-access-token': zee5_com.ACCESS_TOKEN}, + params={ + 'type': 'episode', 'translation': 'en', + 'season_id': season_id, 'page': str(page), + 'limit': f'{zee5_com.PAGE_LIMIT}' + } + ).content.decode()) + + for episode in current_page["episode"]: + episode_index = episode["episode_number"] + if len(compare) < 2: + compare.append(int(episode_index)) + elif is_asc is None and len(compare) >= 2: + is_asc = compare[0] < compare[1] + + if is_asc is None: + check = check_range(False, None, episode_index) + if check in [True, False]: + continue + else: + check = check_range(False, None, episode_index, is_asc) + if check is True: + continue + elif check is False: + return collection + + episode_id = episode["id"] + episode_title = episode.get("title", None) + if episode_title is None: + episode_title = episode.get("original_title", None) + if episode_title is None: + episode_title = episode_id + episode_title = get_valid_filename(episode_title) + + collection.append(BaseElement( + url=f'{zee5_com.BASE_URL}/{episode["web_url"]}', + collection=join( + join( + str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), + zee5_com.__name__ + ), + f"Series_{season_title}" + ), + element=f"Episode_{episode_index}_{episode_title}" + )) + + page += 1 + if current_page.get("next_episode_api", None) is None: + break + return collection diff --git a/API/proxiesembed/drmproxy/utils/__init__.py b/API/proxiesembed/drmproxy/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/API/proxiesembed/drmproxy/utils/constants/__init__.py b/API/proxiesembed/drmproxy/utils/constants/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/API/proxiesembed/drmproxy/utils/constants/configuration.py b/API/proxiesembed/drmproxy/utils/constants/configuration.py new file mode 100644 index 0000000..d7178b4 --- /dev/null +++ b/API/proxiesembed/drmproxy/utils/constants/configuration.py @@ -0,0 +1,64 @@ +from os.path import join + +from utils.constants.macros import DEFAULT_OUTPUT_MEDIA, TERMINAL_DIR +from utils.constants.portable import CMD_JOIN, CMD_DELETE, CMD_SCRIPT_EXT + +save_dir = join("[!collection!]", "[!element!]") +mkvmerge = join(TERMINAL_DIR, f"mkvmerge.{CMD_SCRIPT_EXT}") +ffmpeg = join(TERMINAL_DIR, f"ffmpeg.{CMD_SCRIPT_EXT}") +TOOL_PARAMS = { + "BASE": f'N_m3u8DL-RE "[!manifest!]" [!keys!] --tmp-dir "[!TMP_PATH!]" --save-dir "{save_dir}" --save-name "content"', + "VOD": '-sv best -sa best -da id=audio_div -ss all -mt --check-segments-count false --no-log', + "LIVESTREAM": '--live-pipe-mux --live-record-limit 00:02:00', + "OTHERS": { + "HEADER": '--header "{key}:{value}"', + "BASE_URL": '--base-url "{value}"', + "KEY": { + 'PARAM': '--key {value}', + 'EXTRA': '--use-shaka-packager' + }, + "AES": { + "KEY": "--custom-hls-key {value}", + "IV": "--custom-hls-iv {value}" + }, + "MUXER": "-M format={args}", + "VIDEO_RES": { + "BEST": "-sv best", + "CUSTOM": '-sv res="{width}x{height}"' + }, + "ARGUMENT": "{value}" + }, + "EXTRA_CMDS": f'{CMD_JOIN} "{mkvmerge}" "{save_dir}.mkv" "{save_dir}" true {CMD_JOIN} {CMD_DELETE} "[!TMP_PATH!]"', + "PROCESS_CMDS": { + "CONCAT": f'"{ffmpeg}" "{save_dir}.mkv" "{save_dir}" "{mkvmerge}" true' + } +} + +TOOL_PARAMS_BASIC = { + "BASE": f'N_m3u8DL-RE "[!manifest!]" [!keys!] --save-dir "[!collection!]" --save-name "[!element!]"', + "VOD": '', + "LIVESTREAM": '', + "OTHERS": TOOL_PARAMS["OTHERS"], + "EXTRA_CMDS": "", + "PROCESS_CMDS": {} +} + +DEFAULT_CONFIG = { + "CDM_WVD_FILE_PATH": None, + "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 Edg/123.0.0.0", + "NUMBER_OF_THREADS": { + "DATA_SCRAPER": 5, + "MEDIA_DOWNLOADER": 3 + }, + "DOWNLOAD_COMMANDS": { + "OUTPUT_MEDIA_PATH": DEFAULT_OUTPUT_MEDIA, + "WAIT_BEFORE_DOWNLOADING": True, + "ADDITIONAL_SUBS": True, + "TOOL_PARAMETERS": { + "VOD": TOOL_PARAMS["VOD"], + "LIVESTREAM": TOOL_PARAMS["LIVESTREAM"] + } + }, + "SERVICE_CREDENTIALS": {}, + "WARN_EXTERNAL_TOOLS": True +} diff --git a/API/proxiesembed/drmproxy/utils/constants/macros.py b/API/proxiesembed/drmproxy/utils/constants/macros.py new file mode 100644 index 0000000..5bfa168 --- /dev/null +++ b/API/proxiesembed/drmproxy/utils/constants/macros.py @@ -0,0 +1,38 @@ +import os +from os.path import join + +DEFAULT_DEBUG_MODE = False + +APP_NAME = "widefrog" +APP_VERSION = "3.2.0" +APP_DIR = f"app_files" +CACHE_DIR = join(APP_DIR, "services_cache") + +CONFIG_FILE = join(APP_DIR, "config.json") +for d in [APP_DIR, CACHE_DIR]: + if not os.path.exists(d): + os.makedirs(d) + +DEFAULT_OUTPUT_MEDIA = "media" +TERMINAL_DIR = "terminal" + +TMP_TOOLS_PATH = "tmp" +TMP_RAND_LEN = 7 +REQUESTS_TIMEOUT = 8 + +DEFAULT_INPUT_FILE = join(APP_DIR, "input.txt") +DEFAULT_OUTPUT_CMD = join(APP_DIR, "cmds.txt") +DEFAULT_OUTPUT_CMD_FAIL = join(APP_DIR, "cmds_failed.txt") +CMD_BATCH_SIZE = 3 + +DEFAULT_WVD_PATH = "YOUR_WVD_FILE_PATH" +APP_ERROR = "[APP_ERROR]" +USER_ERROR = "[USER_ERROR]" +ERR_MSG = "{type} Failed to download: {url}. Reason: {reason}. Solution: {solution}." +INF_MSG = "[INFO] {msg}" +WARN_MSG = "[WARNING] {msg}" + +EXTERNAL_TOOLS = ["N_m3u8DL-RE", "mp4decrypt", "shaka-packager", "ffmpeg", "mkvmerge"] + +WIDEVINE_SCHEME_ID = "EDEF8BA9-79D6-4ACE-A3C8-27DCD51D21ED" +PLAYREADY_SCHEME_ID = "9A04F079-9840-4286-AB92-E65BE0885F95" diff --git a/API/proxiesembed/drmproxy/utils/constants/portable.py b/API/proxiesembed/drmproxy/utils/constants/portable.py new file mode 100644 index 0000000..3112130 --- /dev/null +++ b/API/proxiesembed/drmproxy/utils/constants/portable.py @@ -0,0 +1,114 @@ +import os +import platform +import shutil +import subprocess +from functools import partial + +SUPPORTED_OS = ['windows', 'linux', 'darwin'] +SUPPORTED_ARCHITECTURES = ['64bit'] +CURRENT_OS = platform.system().lower() +CURRENT_ARCHITECTURE = platform.architecture()[0].lower() +IS_SUPPORTED_OS = CURRENT_OS in SUPPORTED_OS and 'ANDROID_ARGUMENT' not in os.environ +IS_SUPPORTED_SYSTEM = IS_SUPPORTED_OS and CURRENT_ARCHITECTURE in SUPPORTED_ARCHITECTURES + +SUPPORTED_LINUX_TERMINALS = [ + "gnome-terminal --wait -- {shell} -c '{command}'", + "xterm -e {shell} -c '{command}'", "konsole -e {shell} -c '{command}'", + "urxvt -e {shell} -c '{command}'", "alacritty -e {shell} -c '{command}'" +] +SUPPORTED_LINUX_SHELLS = [ + "bash", "sh", "zsh", "dash", "ksh", "fish", + "tcsh", "csh", "ash", "mksh", "sash" +] + + +class EnvironmentConstants: + _initialized = False + IS_SUPPORTED = None + TERMINAL_CHOSEN = "" + SHELL_CHOSEN = "" + ERROR_MESSAGE = "" + INFO_MESSAGE = "" + + @staticmethod + def initialize_once(): + if EnvironmentConstants._initialized is True: + return + EnvironmentConstants._initialized = True + if not IS_SUPPORTED_SYSTEM: + EnvironmentConstants.IS_SUPPORTED = False + return + + if CURRENT_OS == "linux": + for terminal in SUPPORTED_LINUX_TERMINALS: + if shutil.which(terminal.split(" ")[0]): + EnvironmentConstants.TERMINAL_CHOSEN = terminal + break + for shell in SUPPORTED_LINUX_SHELLS: + if shutil.which(shell): + EnvironmentConstants.SHELL_CHOSEN = shell + break + + EnvironmentConstants.IS_SUPPORTED = ( + len(EnvironmentConstants.TERMINAL_CHOSEN) > 0 and + len(EnvironmentConstants.SHELL_CHOSEN) > 0 + ) + if EnvironmentConstants.TERMINAL_CHOSEN == "": + EnvironmentConstants.ERROR_MESSAGE = ( + f"The Linux system doesn't use any of the supported Linux terminals: " + f"{str([s.split(' ')[0] for s in SUPPORTED_LINUX_TERMINALS])}. Install one of them." + ) + elif EnvironmentConstants.SHELL_CHOSEN == "": + EnvironmentConstants.ERROR_MESSAGE = ( + f"The Linux system doesn't use any of the supported Linux shells: " + f"{str(SUPPORTED_LINUX_SHELLS)}. Install one of them." + ) + else: + EnvironmentConstants.INFO_MESSAGE = ( + f"Linux detected. Chosen terminal: {EnvironmentConstants.TERMINAL_CHOSEN.split(' ')[0]}. " + f"Chosen shell: {EnvironmentConstants.SHELL_CHOSEN}." + ) + + elif CURRENT_OS == "darwin": + EnvironmentConstants.IS_SUPPORTED = False + EnvironmentConstants.ERROR_MESSAGE = "MacOS detected." + + else: # elif CURRENT_OS == "windows": + EnvironmentConstants.IS_SUPPORTED = True + + +CMD_JOIN = ";" +CMD_JOIN_ADJUST = "\\" +CMD_DELETE = 'rm -rf' +CMD_SCRIPT_EXT = 'sh' +IS_FILE_EXECUTABLE = lambda s: os.access(s, os.X_OK) +TERMINAL_CLOSE = 'exit' + +EnvironmentConstants.initialize_once() + +if CURRENT_OS == "linux": + terminal_open = partial( + EnvironmentConstants.TERMINAL_CHOSEN.format, + shell=EnvironmentConstants.SHELL_CHOSEN + ) + cmd_adjust = lambda cmd_input: cmd_input.replace('"', '\\"') \ + if '"' in terminal_open(command="") and "'" in terminal_open(command="") else cmd_input + TERMINAL_LAUNCH = lambda cmd_input: \ + subprocess.check_output(terminal_open(command=cmd_adjust(cmd_input)), shell=True) + +elif CURRENT_OS == "darwin": + TERMINAL_LAUNCH = None + +else: # elif CURRENT_OS == "windows": + CMD_JOIN = "&" + CMD_JOIN_ADJUST = "^" + CMD_DELETE = 'rd /s /q' + CMD_SCRIPT_EXT = 'bat' + IS_FILE_EXECUTABLE = lambda s: True + + terminal_open = partial('start /wait cmd /k "{command}"'.format) + TERMINAL_LAUNCH = lambda cmd_input: \ + subprocess.check_output(terminal_open(command=cmd_input), shell=True) + +CMD_ADJUST = CMD_JOIN_ADJUST +CMD_JOIN_ADJUST = f'{CMD_JOIN_ADJUST}{CMD_JOIN}' diff --git a/API/proxiesembed/drmproxy/utils/main_service.py b/API/proxiesembed/drmproxy/utils/main_service.py new file mode 100644 index 0000000..ec84c22 --- /dev/null +++ b/API/proxiesembed/drmproxy/utils/main_service.py @@ -0,0 +1,501 @@ +import builtins +import concurrent +import os +import platform +import re +import subprocess +from concurrent.futures import ThreadPoolExecutor +from os.path import join + +import requests + +import utils.tools.common as common_tools +import utils.tools.service as service_tools +from utils.constants.macros import INF_MSG, ERR_MSG, USER_ERROR, APP_ERROR, CMD_BATCH_SIZE, WARN_MSG, \ + DEFAULT_OUTPUT_CMD, DEFAULT_OUTPUT_CMD_FAIL, TMP_TOOLS_PATH, APP_VERSION +from utils.constants.portable import TERMINAL_CLOSE, CMD_JOIN_ADJUST, CMD_JOIN, TERMINAL_LAUNCH, CURRENT_OS, \ + CURRENT_ARCHITECTURE +from utils.structs import CustomException, BaseElement +from utils.tools.cdm import init_cdm, close_cdm + + +class main_service: + CURRENT_TASK = 0 + TOTAL_TASKS = 0 + + @staticmethod + def update_task(incr=1): + main_service.CURRENT_TASK += incr + print(INF_MSG.format( + msg=f"Current progress: [{main_service.CURRENT_TASK}/{main_service.TOTAL_TASKS}]") + ) + + @staticmethod + def save_subtitles(subtitles): + for is_manifest, subtitle in subtitles: + if not is_manifest: + if not os.path.exists(subtitle.collection): + os.makedirs(subtitle.collection) + + response = requests.get(subtitle.url) + if response.status_code == 200: + with open(join(subtitle.collection, subtitle.element), 'wb') as file: + file.write(response.content) + + @staticmethod + def get_keys(service, pssh, additional): + cdm, cdm_session_id, challenge = init_cdm(pssh) + if cdm is None: + return [] + + return close_cdm( + cdm, cdm_session_id, + service.get_keys(challenge, additional.get(pssh, additional)) + ) + + @staticmethod + def get_download_command(service, source_element): + wait_flag = builtins.CONFIG["DOWNLOAD_COMMANDS"].get("WAIT_BEFORE_DOWNLOADING", None) + is_basic = builtins.CONFIG.get("BASIC", False) is True + use_adjust = False + + try: + manifest, pssh, additional = service.get_video_data(source_element) + if type(manifest) is not list: + manifest = [(manifest, None)] + if len(manifest) == 0: + manifest = [(None, None)] + if type(pssh) is not list: + pssh = [pssh] + if len(pssh) == 0: + pssh = [None] + + if len([m for m in manifest if m[0] not in [None, ""]]) == 0: + raise Exception("No manifest found") + + if wait_flag is not None and builtins.CONFIG["NUMBER_OF_THREADS"]["MEDIA_DOWNLOADER"] > 1: + use_adjust = True + temp_manifest = [] + for m in manifest: + temp_manifest.append((m[0].replace(CMD_JOIN, CMD_JOIN_ADJUST), m[1])) + manifest = temp_manifest + except CustomException as e: + if builtins.CONFIG["DEBUG_MODE"]: + raise e + print(str(e)) + return None, None + except Exception as e: + if builtins.CONFIG["DEBUG_MODE"]: + raise e + print(ERR_MSG.format( + type=f'{USER_ERROR}/{APP_ERROR}', + url=source_element.url, + reason="Failed to extract content data", + solution=f"Make sure you can play the content. If you can, then debug the {service.__name__} service" + )) + return None, None + + is_hls_aes = additional.get("AES", None) is not None + keys = [] + + if not is_hls_aes: + try: + keys = [] + for p in pssh: + if p is None: + continue + keys += main_service.get_keys(service, p, additional) + keys = list(set(keys)) + except CustomException as e: + if builtins.CONFIG["DEBUG_MODE"]: + raise e + print(str(e)) + return None, None + except Exception as e: + if builtins.CONFIG["DEBUG_MODE"]: + raise e + print(ERR_MSG.format( + type=f'{USER_ERROR}/{APP_ERROR}', + url=source_element.url, + reason="Something went wrong with the license call", + solution=f"Make sure you can play the content and/or change your VPN IP. Additionally, wait a few minutes and/or replace your CDM with a fresh one. If the issue persists, then debug the {service.__name__} service" + )) + return None, None + + if builtins.CONFIG["DOWNLOAD_COMMANDS"].get("ADDITIONAL_SUBS", True) is True: + main_service.save_subtitles(additional.get("SUBTITLES", [])) + + if not is_hls_aes and len(keys) == 0 and len([p for p in pssh if p is not None]) > 0: + print(ERR_MSG.format( + type=USER_ERROR, + url=source_element.url, + reason="Need emulated L3 CDM (in WVD format)", + solution=f"Search and read the forum" + )) + return None, None + + dwn_cmds = [] + for manifest_url, manifest_name in manifest: + if manifest_name not in ["", None]: + element_path = manifest_name + collection_path = join(source_element.collection, source_element.element) + else: + element_path = source_element.element + collection_path = source_element.collection + + template_cmd = None + is_livestream = False + try: + template_cmd = builtins.CONFIG["DOWNLOAD_COMMANDS"]["TOOL_PARAMETERS"] + dwn_cmd = template_cmd["BASE"] + dwn_cmd += " " + common_tools.adjust_parameters(use_adjust, template_cmd["VOD"]) + + is_livestream = service.is_content_livestream(source_element.url, additional) + if is_livestream: + dwn_cmd += " " + common_tools.adjust_parameters(use_adjust, template_cmd["LIVESTREAM"]) + + if not is_hls_aes and (wait_flag is not None or is_basic): + if template_cmd["OTHERS"].get("VIDEO_RES", None) is not None: + if template_cmd["OTHERS"]["VIDEO_RES"]["BEST"] in dwn_cmd or is_basic: + if keys is not None and len(keys) > 0: + try: + best_res = service.get_best_decryptable_video(manifest_url, keys) + except Exception as e: + if builtins.CONFIG["DEBUG_MODE"]: + raise e + print(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason=f"Failed to get the best decryptable video resolution for manifest: {manifest_url} and keys: {str(keys)}", + solution=f"Debug the {service.__name__} service" + )) + return None, None + + if best_res is not None: + if is_basic: + dwn_cmd += " " + template_cmd["OTHERS"]["VIDEO_RES"]["CUSTOM"].format( + width=str(best_res[0]), height=str(best_res[1]) + ) + else: + dwn_cmd = dwn_cmd.replace( + template_cmd["OTHERS"]["VIDEO_RES"]["BEST"], + template_cmd["OTHERS"]["VIDEO_RES"]["CUSTOM"].format( + width=str(best_res[0]), height=str(best_res[1]) + ) + ) + + dwn_cmd += " " + " ".join([ + lmb(template_cmd['OTHERS'][name]) + for (name, lmb) in service.get_additional_params(additional) + ]) + dwn_cmd += " " + template_cmd["EXTRA_CMDS"] + except Exception as e: + if builtins.CONFIG["DEBUG_MODE"]: + raise e + dwn_cmd = "" + + if dwn_cmd is None or len(dwn_cmd.strip()) == 0: + print(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason="Need download tool parameters to be well defined", + solution=f"Define them" + )) + return None, None + + dwn_cmd = dwn_cmd.replace("[!manifest!]", manifest_url) + if not is_hls_aes: + use_shaka = len(keys) > 0 and is_livestream and additional.get("USE_SHAKA", True) is True + if len(keys) > 0 and additional.get("FORCE_SHAKA", False) is True: + use_shaka = True + + dwn_cmd = dwn_cmd.replace("[!keys!]", " ".join([ + template_cmd["OTHERS"]["KEY"]["PARAM"].format(value=k) + for k in keys + ]) + (f' {template_cmd["OTHERS"]["KEY"]["EXTRA"]}' if use_shaka else "")) + else: + aes_params = [] + for param in ["KEY", "IV"]: + if additional["AES"].get(param, None) is not None: + aes_params.append(template_cmd["OTHERS"]["AES"][param].format( + value=additional["AES"][param] + )) + dwn_cmd = dwn_cmd.replace("[!keys!]", " ".join(aes_params)) + + dwn_cmd = dwn_cmd.replace("[!collection!]", collection_path) + dwn_cmd = dwn_cmd.replace("[!element!]", element_path) + dwn_cmd = dwn_cmd.replace("[!TMP_PATH!]", join( + join(str(builtins.CONFIG["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]), TMP_TOOLS_PATH), + common_tools.rand_str() + )) + + if wait_flag is None: + dwn_cmd = re.sub(r'\s+', ' ', dwn_cmd) + dwn_cmds.append(dwn_cmd) + + proc_cmds = [] + if len(dwn_cmds) > 1: + try: + proc_cmd = builtins.CONFIG["DOWNLOAD_COMMANDS"]["TOOL_PARAMETERS"] + proc_cmd = proc_cmd["PROCESS_CMDS"].get("CONCAT", "") + proc_cmd = proc_cmd.replace("[!collection!]", source_element.collection) + proc_cmd = proc_cmd.replace("[!element!]", source_element.element) + proc_cmds.append(proc_cmd) + except Exception as e: + if builtins.CONFIG["DEBUG_MODE"]: + raise e + return dwn_cmds, proc_cmds + + @staticmethod + def get_download_commands(source_elements): + download_commands = [] + process_commands = [] + failures = [] + + for source_element in source_elements: + if not common_tools.is_http_url(source_element.url): + download_commands.append(source_element.url) + continue + + failures.append(source_element.url) + service = service_tools.get_service(source_element.url) + if service is None: + continue + + try: + dl_cmds, pr_cmds = main_service.get_download_command(service, source_element) + if type(dl_cmds) is not list: + dl_cmds = [dl_cmds] + if len([dw for dw in dl_cmds if dw not in ["", None]]) == 0: + continue + if type(pr_cmds) is not list: + pr_cmds = [pr_cmds] + pr_cmds = [prc for prc in pr_cmds if prc not in ["", None]] + + download_commands.extend(dl_cmds) + failures.pop() + process_commands.extend(pr_cmds) + main_service.update_task() + except Exception as e: + if builtins.CONFIG["DEBUG_MODE"]: + raise e + print(ERR_MSG.format( + type=APP_ERROR, + url=source_element.url, + reason="Failed to extract content data", + solution=f"Debug the {service.__name__} service" + )) + return download_commands, failures, process_commands + + @staticmethod + def get_collections_elements(collection_urls): + collections_elements = [] + failures = [] + + for collection_url in collection_urls: + if not common_tools.is_http_url(collection_url): + collections_elements.append(BaseElement(url=collection_url)) + continue + + failures.append(collection_url) + service = service_tools.get_service(collection_url) + if service is None: + continue + + try: + collection = service.get_collection_elements(collection_url) + if collection is None: + print(ERR_MSG.format( + type=USER_ERROR, + url=collection_url, + reason="URL not supported", + solution=f"Extend the {service.__name__} service" + )) + continue + + collections_elements.append(collection) + failures.pop() + main_service.update_task() + except CustomException as e: + if builtins.CONFIG["DEBUG_MODE"]: + raise e + print(str(e)) + continue + except Exception as e: + if builtins.CONFIG["DEBUG_MODE"]: + raise e + print(ERR_MSG.format( + type=APP_ERROR, + url=collection_url, + reason="Failed to extract collection data", + solution=f"Debug the {service.__name__} service" + )) + continue + return collections_elements, failures, [] + + @staticmethod + def initialize_services(source_urls): + print(INF_MSG.format(msg="Starting the service initialization stage.")) + main_service.CURRENT_TASK = 0 + failures = [] + + sites = [] + for source_url in source_urls: + site = common_tools.get_base_url(source_url) + if site not in sites: + sites.append(site) + main_service.TOTAL_TASKS = len(sites) + + valid_urls = [] + bad_urls = [] + for source_url in source_urls: + if not common_tools.is_http_url(source_url): + valid_urls.append(source_url) + continue + + failures.append(source_url) + site = common_tools.get_base_url(source_url) + if site in bad_urls: + continue + + if service_tools.get_service(source_url) is not None: + valid_urls.append(source_url) + failures.pop() + else: + bad_urls.append(site) + + if site in sites: + sites.remove(site) + main_service.update_task() + return valid_urls, failures + + @staticmethod + def get_download_commands_parallel(source_urls): + source_urls, failures = main_service.initialize_services(source_urls) + proc_commands = [] + + lst = source_urls + for job in [main_service.get_collections_elements, main_service.get_download_commands]: + main_service.CURRENT_TASK = 0 + main_service.TOTAL_TASKS = len(lst) + if job == main_service.get_collections_elements: + print(INF_MSG.format(msg="Starting the collections extraction stage.")) + else: + print(INF_MSG.format(msg="Starting the media data extraction stage.")) + + nr_workers = builtins.CONFIG["NUMBER_OF_THREADS"]["DATA_SCRAPER"] + chunks = common_tools.split_list_chunks(lst, nr_workers) + with concurrent.futures.ThreadPoolExecutor(max_workers=nr_workers) as executor: + futures = [executor.submit(job, batch) for batch in chunks] + for _ in concurrent.futures.as_completed(futures): + pass + + results = ([], [], []) + for future in futures: + success, fail, proc = future.result() + results[0].extend(success) + results[1].extend(fail) + results[2].extend(proc) + + lst = common_tools.flatten_list(results[0]) + failures.extend(results[1]) + proc_commands.extend(results[2]) + return results[0], failures, proc_commands + + @staticmethod + def run_commands(commands, multiple_terminals): + for i in range(0, len(commands), CMD_BATCH_SIZE): + batch = commands[i:i + CMD_BATCH_SIZE] + + if multiple_terminals: + command = f" {CMD_JOIN} ".join(batch + [TERMINAL_CLOSE]) + TERMINAL_LAUNCH(command) + main_service.update_task(len(batch)) + + else: + for command in batch: + subprocess.run(command, shell=True) + main_service.update_task() + + @staticmethod + def run_commands_parallel(commands): + main_service.CURRENT_TASK = 0 + main_service.TOTAL_TASKS = len(commands) + nr_workers = builtins.CONFIG["NUMBER_OF_THREADS"]["MEDIA_DOWNLOADER"] + if nr_workers == 1: + main_service.run_commands(commands, False) + return + + chunks = common_tools.split_list_chunks(commands, nr_workers) + with concurrent.futures.ThreadPoolExecutor(max_workers=nr_workers) as executor: + futures = [executor.submit(main_service.run_commands, batch, True) for batch in chunks] + for _ in concurrent.futures.as_completed(futures): + pass + + @staticmethod + def run_service(demo_urls): + print(INF_MSG.format(msg=f"Current app version: {APP_VERSION}")) + print(INF_MSG.format(msg=f"Running on: {CURRENT_OS}/{CURRENT_ARCHITECTURE}/python {platform.python_version()}")) + if type(demo_urls) is not list: + demo_urls = demo_urls.DEMO_URLS + + dwn_cmds, failed_cmds, proc_cmds = main_service.get_download_commands_parallel(demo_urls) + print(INF_MSG.format(msg="Finished generating the download commands.")) + + common_tools.list_to_file(DEFAULT_OUTPUT_CMD_FAIL, failed_cmds) + if len(failed_cmds) > 0: + print(WARN_MSG.format( + msg=f'Saved the failed URLs to {DEFAULT_OUTPUT_CMD_FAIL}' + )) + if dwn_cmds is None or len(dwn_cmds) == 0: + print(WARN_MSG.format(msg="No download commands have been generated.")) + return + + common_tools.list_to_file(DEFAULT_OUTPUT_CMD, dwn_cmds) + print(INF_MSG.format( + msg=f'Saved the generated download commands to {DEFAULT_OUTPUT_CMD}' + )) + + wait_flag = builtins.CONFIG["DOWNLOAD_COMMANDS"].get("WAIT_BEFORE_DOWNLOADING", None) + if wait_flag is None: + print(INF_MSG.format(msg="Skipping the downloading stage.")) + if len(proc_cmds) > 0: + print(INF_MSG.format(msg="Skipping the processing stage.")) + return + + if wait_flag is True: + while True: + answer = input(INF_MSG.format( + msg=f"If you used a VPN, turn it off to avoid wasting data " + f"for the downloading stage. Also you may edit the {DEFAULT_OUTPUT_CMD} " + f"file if necessary. Type yes when ready: " + )) + if answer is None: + continue + + answer = answer.lower().strip() + answer = re.sub(r"\s+", "", answer) + for c in "yes": + answer = re.sub(fr"{c}+", c, answer) + + if len(answer) == 0: + continue + + if answer != "yes": + print(INF_MSG.format(msg="Cancelling the downloading stage.")) + return + break + + dwn_cmds = common_tools.file_to_list(DEFAULT_OUTPUT_CMD) + if dwn_cmds is None or len(dwn_cmds) == 0: + print(WARN_MSG.format(msg="No download commands have been found.")) + return + + print(INF_MSG.format(msg="Starting the downloading stage.")) + main_service.run_commands_parallel(dwn_cmds) + print(INF_MSG.format(msg="SUCCESS! Finished downloading.")) + + if len(proc_cmds) > 0: + print(INF_MSG.format(msg="Starting the processing stage.")) + main_service.run_commands_parallel(proc_cmds) + print(INF_MSG.format(msg="SUCCESS! Finished processing.")) diff --git a/API/proxiesembed/drmproxy/utils/pssh_box/__init__.py b/API/proxiesembed/drmproxy/utils/pssh_box/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/API/proxiesembed/drmproxy/utils/pssh_box/pssh_box.py b/API/proxiesembed/drmproxy/utils/pssh_box/pssh_box.py new file mode 100644 index 0000000..ce18ffc --- /dev/null +++ b/API/proxiesembed/drmproxy/utils/pssh_box/pssh_box.py @@ -0,0 +1,444 @@ +#!/usr/bin/python +# Copyright 2016 Google LLC. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""A utility to parse and generate PSSH boxes.""" + +# This file itself is considered an invalid module name because of the dash in +# the filename: pssh_box.py +# pylint: disable=invalid-name + +from __future__ import print_function + +import argparse +import base64 +import itertools +import os +import struct +import sys + + +def to_code_point(value): + """ + Return the unicode code point with `int` passthrough + """ + if isinstance(value, int): + return value + + return ord(value) + + +_script_dir = os.path.dirname(os.path.realpath(__file__)) + +# pylint: disable=wrong-import-position +from utils.pssh_box import widevine_pssh_data_pb2 + +COMMON_SYSTEM_ID = base64.b16decode('1077EFECC0B24D02ACE33C1E52E2FB4B') +WIDEVINE_SYSTEM_ID = base64.b16decode('EDEF8BA979D64ACEA3C827DCD51D21ED') +PLAYREADY_SYSTEM_ID = base64.b16decode('9A04F07998404286AB92E65BE0885F95') + + +class BinaryReader(object): + """A helper class used to read binary data from an binary string.""" + + def __init__(self, data, little_endian): + self.data = data + self.little_endian = little_endian + self.position = 0 + + def has_data(self): + """Returns whether the reader has any data left to read.""" + return self.position < len(self.data) + + def read_bytes(self, count): + """Reads the given number of bytes into an array.""" + if len(self.data) < self.position + count: + raise Exception('Invalid PSSH box, not enough data') + ret = self.data[self.position:self.position + count] + self.position += count + return ret + + def read_int(self, size): + """Reads an integer of the given size (in bytes).""" + data = self.read_bytes(size) + ret = 0 + for i in range(0, size): + if self.little_endian: + ret |= (to_code_point(data[i]) << (8 * i)) + else: + ret |= (to_code_point(data[i]) << (8 * (size - i - 1))) + return ret + + +class Pssh(object): + """Defines a PSSH box and related functions.""" + + def __init__(self, version, system_id, key_ids, pssh_data): + """Parses a PSSH box from the given data. + + Args: + version: The version number of the box + system_id: A binary string of the System ID + key_ids: An array of binary strings for the key IDs + pssh_data: A binary string of the PSSH data + """ + self.version = version + self.system_id = system_id + self.key_ids = key_ids or [] + self.pssh_data = pssh_data or '' + + def binary_string(self): + """Converts the PSSH box to a binary string.""" + ret = b'pssh' + _create_bin_int(self.version << 24) + ret += self.system_id + if self.version == 1: + ret += _create_bin_int(len(self.key_ids)) + for key in self.key_ids: + ret += key + ret += _create_bin_int(len(self.pssh_data)) + ret += self.pssh_data + return _create_bin_int(len(ret) + 4) + ret + + def human_string(self): + """Converts the PSSH box to a human readable string.""" + system_name = '' + convert_data = None + if self.system_id == WIDEVINE_SYSTEM_ID: + system_name = 'Widevine' + convert_data = _parse_widevine_data + elif self.system_id == PLAYREADY_SYSTEM_ID: + system_name = 'PlayReady' + convert_data = _parse_playready_data + elif self.system_id == COMMON_SYSTEM_ID: + system_name = 'Common' + + lines = [ + 'PSSH Box v%d' % self.version, + ' System ID: %s %s' % (system_name, _create_uuid(self.system_id)) + ] + if self.version == 1: + lines.append(' Key IDs (%d):' % len(self.key_ids)) + lines.extend([' ' + _create_uuid(key) for key in self.key_ids]) + + lines.append(' PSSH Data (size: %d):' % len(self.pssh_data)) + if self.pssh_data: + if convert_data: + lines.append(' ' + system_name + ' Data:') + try: + extra = convert_data(self.pssh_data) + lines.extend([' ' + x for x in extra]) + # pylint: disable=broad-except + except Exception as e: + lines.append(' ERROR: ' + str(e)) + else: + lines.extend([ + ' Raw Data (base64):', + ' ' + base64.b64encode(self.pssh_data) + ]) + + return '\n'.join(lines) + + +def _split_list_on(elems, sep): + """Splits the given list on the given separator.""" + return [list(g) for k, g in itertools.groupby(elems, lambda x: x == sep) + if not k] + + +def _create_bin_int(value): + """Creates a binary string as 4-byte array from the given integer.""" + return struct.pack('>i', value) + + +def _create_uuid(data): + """Creates a human readable UUID string from the given binary string.""" + ret = base64.b16encode(data).decode().lower() + return (ret[:8] + '-' + ret[8:12] + '-' + ret[12:16] + '-' + ret[16:20] + + '-' + ret[20:]) + + +def _generate_widevine_data(key_ids, content_id, provider, protection_scheme): + """Generate widevine pssh data.""" + wv = widevine_pssh_data_pb2.WidevinePsshData() + wv.key_id.extend(key_ids) + if provider: + wv.provider = provider + if content_id: + wv.content_id = content_id + # 'cenc' is the default, so omitted to save bytes. + if protection_scheme and protection_scheme != 'cenc': + try: + wv.protection_scheme = struct.unpack('>L', protection_scheme.encode())[0] + except: + wv.protection_scheme = protection_scheme + return wv.SerializeToString() + + +def _parse_widevine_data(data): + """Parses Widevine PSSH box from the given binary string.""" + wv = widevine_pssh_data_pb2.WidevinePsshData() + wv.ParseFromString(data) + + ret = [] + if wv.key_id: + ret.append('Key IDs (%d):' % len(wv.key_id)) + ret.extend([' ' + _create_uuid(x) for x in wv.key_id]) + + if wv.HasField('provider'): + ret.append('Provider: ' + wv.provider) + if wv.HasField('content_id'): + ret.append('Content ID: ' + base64.b16encode(wv.content_id).decode()) + if wv.HasField('policy'): + ret.append('Policy: ' + wv.policy) + if wv.HasField('crypto_period_index'): + ret.append('Crypto Period Index: %d' % wv.crypto_period_index) + if wv.HasField('protection_scheme'): + protection_scheme = struct.pack('>L', wv.protection_scheme) + ret.append('Protection Scheme: %s' % protection_scheme) + + return ret + + +def _parse_playready_data(data): + """Parses PlayReady PSSH data from the given binary string.""" + reader = BinaryReader(data, little_endian=True) + size = reader.read_int(4) + if size != len(data): + raise Exception('Length incorrect') + + ret = [] + count = reader.read_int(2) + while count > 0: + count -= 1 + record_type = reader.read_int(2) + record_len = reader.read_int(2) + record_data = reader.read_bytes(record_len) + + ret.append('Record (size %d):' % record_len) + if record_type == 1: + xml = record_data.decode('utf-16 LE') + ret.extend([ + ' Record Type: Rights Management Header (1)', + ' Record XML:', + ' ' + xml + ]) + elif record_type == 3: + ret.extend([ + ' Record Type: License Store (1)', + ' License Data:', + ' ' + base64.b64encode(record_data) + ]) + else: + raise Exception('Invalid record type %d' % record_type) + + if reader.has_data(): + raise Exception('Extra data after records') + + return ret + + +def _parse_boxes(data): + """Parses one or more PSSH boxes for the given binary data.""" + reader = BinaryReader(data, little_endian=False) + boxes = [] + while reader.has_data(): + start = reader.position + size = reader.read_int(4) + + box_type = reader.read_bytes(4) + if box_type != b'pssh': + raise Exception( + 'Invalid box type 0x%s, not \'pssh\'' % box_type.encode('hex')) + + version_and_flags = reader.read_int(4) + version = version_and_flags >> 24 + if version > 1: + raise Exception('Invalid PSSH version %d' % version) + + system_id = reader.read_bytes(16) + + key_ids = [] + if version == 1: + count = reader.read_int(4) + while count > 0: + key = reader.read_bytes(16) + key_ids.append(key) + count -= 1 + + pssh_data_size = reader.read_int(4) + pssh_data = reader.read_bytes(pssh_data_size) + + if start + size != reader.position: + raise Exception('Box size does not match size of data') + + pssh = Pssh(version, system_id, key_ids, pssh_data) + boxes.append(pssh) + return boxes + + +def _create_argument_parser(): + """Creates an argument parser.""" + + def hex_16_bytes(string): + if not string or len(string) != 32: + raise argparse.ArgumentTypeError( + 'Must be a 32-character hex string, %d given' % len(string)) + return base64.b16decode(string.upper()) + + def hex_bytes(string): + return base64.b16decode(string.upper()) + + parser = argparse.ArgumentParser( + formatter_class=argparse.RawDescriptionHelpFormatter, + usage='[--base64 | --hex | --human] options [-- options [-- ...]', + epilog="""\ +This utility can be used to generate one or more PSSH boxes. This is done by +passing a system ID and either --key-id or --pssh-data. Multiple boxes can be +generated by separating boxes with --. Using --key-id will generate v1 pssh +boxes, if none are given, it will generate v0. + +You can also import PSSH boxes using --from-base64 and --from-hex. These must +be valid PSSH boxes, but can be multiple concatenated together. These arguments +can appear anywhere in the string. If it appears 'inside' another definition, +it will appear before the generated one. + +An alternative to --pssh-data is to generate Widevine PSSH data. This is only +valid with --widevine-system-id. Passing --content-id will make it generate +Widevine PSSH data instead. You can optionally add --provider and/or +--protection-scheme. It will generate a v0 PSSH box for compatibility +reasons.""") + + formats = parser.add_mutually_exclusive_group() + formats.add_argument('--base64', + dest='format', + action='store_const', + const='base64', + help='Output base64 encoded') + formats.add_argument('--hex', + dest='format', + action='store_const', + const='hex', + help='Output hexadecimal encoded') + formats.add_argument('--human', + dest='format', + action='store_const', + const='human', + help='Output a human readable string') + + inputs = parser.add_mutually_exclusive_group() + inputs.add_argument('--from-base64', + metavar='', + dest='input', + type=base64.b64decode, + help='Parse the given base64 encoded PSSH box') + inputs.add_argument('--from-hex', + metavar='', + dest='input', + type=hex_bytes, + help='Parse the given hexadecimal encoded PSSH box') + + system_ids = parser.add_mutually_exclusive_group() + system_ids.add_argument('--system-id', + metavar='', + dest='system_id', + type=hex_16_bytes, + help='Sets the system ID') + system_ids.add_argument('--common-system-id', + dest='system_id', + action='store_const', + const=COMMON_SYSTEM_ID, + help='Use the Common system ID') + system_ids.add_argument('--widevine-system-id', + dest='system_id', + action='store_const', + const=WIDEVINE_SYSTEM_ID, + help='Use the Widevine system ID') + + extra = parser.add_argument_group() + extra.add_argument('--key-id', + metavar='', + action='append', + type=hex_16_bytes, + help='Adds a key ID (can appear multiple times)') + extra.add_argument('--pssh-data', + metavar='', + type=base64.b64decode, + help='Sets the extra data') + extra.add_argument('--content-id', + metavar='', + type=hex_bytes, + help='Sets the content ID of the Widevine PSSH data') + extra.add_argument('--provider', + metavar='', + help='Sets the provider of the Widevine PSSH data') + extra.add_argument('--protection-scheme', + choices=['cenc', 'cbcs', 'cens', 'cbc1'], + help='Set the protection scheme of the Widevine PSSH data') + + return parser + + +def main(all_args): + boxes = [] + output_format = None + parser = _create_argument_parser() + if not all_args: + parser.print_help() + sys.exit(1) + arg_groups = _split_list_on(all_args, '--') + for args in arg_groups: + ns = parser.parse_args(args) + + if ns.format: + if output_format: + raise Exception('Can only specify one of: --base64, --hex, --human') + else: + output_format = ns.format + + if ns.input: + boxes.extend(_parse_boxes(ns.input)) + + pssh_data = ns.pssh_data + if pssh_data and ns.content_id: + raise Exception('Cannot specify both --pssh-data and --content-id') + if ns.protection_scheme: + if ns.system_id != WIDEVINE_SYSTEM_ID: + raise Exception( + '--protection-scheme only valid with Widevine system ID') + if ns.content_id: + if ns.system_id != WIDEVINE_SYSTEM_ID: + raise Exception('--content-id only valid with Widevine system ID') + + # Ignore if we have no data. + if not pssh_data and not ns.key_id and not ns.system_id: + continue + if not ns.system_id: + raise Exception('System ID is required') + if ns.system_id == WIDEVINE_SYSTEM_ID: + # Always generate version 0 for Widevine for backward compatibility. + version = 0 + if not pssh_data: + if not ns.key_id and not ns.content_id: + raise Exception('Widevine system needs key-id or content-id or both') + pssh_data = _generate_widevine_data(ns.key_id, ns.content_id, + ns.provider, ns.protection_scheme) + else: + version = 1 if ns.key_id else 0 + boxes.append(Pssh(version, ns.system_id, ns.key_id, pssh_data)) + + if output_format == 'human' or not output_format: + for box in boxes: + print(box.human_string()) + else: + box_data = b''.join([x.binary_string() for x in boxes]) + if output_format == 'hex': + print(base64.b16encode(box_data).decode()) + else: + print(base64.b64encode(box_data).decode()) + + +if __name__ == '__main__': + main(sys.argv[1:]) diff --git a/API/proxiesembed/drmproxy/utils/pssh_box/widevine_pssh_data_pb2.py b/API/proxiesembed/drmproxy/utils/pssh_box/widevine_pssh_data_pb2.py new file mode 100644 index 0000000..ceb1dd1 --- /dev/null +++ b/API/proxiesembed/drmproxy/utils/pssh_box/widevine_pssh_data_pb2.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: widevine_pssh_data.proto +# Protobuf Python Version: 4.25.2 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n\x18widevine_pssh_data.proto\x12\x0bshaka.media\"\x8f\x02\n\x10WidevinePsshData\x12:\n\talgorithm\x18\x01 \x01(\x0e\x32\'.shaka.media.WidevinePsshData.Algorithm\x12\x0e\n\x06key_id\x18\x02 \x03(\x0c\x12\x10\n\x08provider\x18\x03 \x01(\t\x12\x12\n\ncontent_id\x18\x04 \x01(\x0c\x12\x0e\n\x06policy\x18\x06 \x01(\t\x12\x1b\n\x13\x63rypto_period_index\x18\x07 \x01(\r\x12\x17\n\x0fgrouped_license\x18\x08 \x01(\x0c\x12\x19\n\x11protection_scheme\x18\t \x01(\r\"(\n\tAlgorithm\x12\x0f\n\x0bUNENCRYPTED\x10\x00\x12\n\n\x06\x41\x45SCTR\x10\x01\"G\n\x0eWidevineHeader\x12\x0f\n\x07key_ids\x18\x02 \x03(\t\x12\x10\n\x08provider\x18\x03 \x01(\t\x12\x12\n\ncontent_id\x18\x04 \x01(\x0c') + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'widevine_pssh_data_pb2', _globals) +if _descriptor._USE_C_DESCRIPTORS == False: + DESCRIPTOR._options = None + _globals['_WIDEVINEPSSHDATA']._serialized_start = 42 + _globals['_WIDEVINEPSSHDATA']._serialized_end = 313 + _globals['_WIDEVINEPSSHDATA_ALGORITHM']._serialized_start = 273 + _globals['_WIDEVINEPSSHDATA_ALGORITHM']._serialized_end = 313 + _globals['_WIDEVINEHEADER']._serialized_start = 315 + _globals['_WIDEVINEHEADER']._serialized_end = 386 +# @@protoc_insertion_point(module_scope) diff --git a/API/proxiesembed/drmproxy/utils/structs.py b/API/proxiesembed/drmproxy/utils/structs.py new file mode 100644 index 0000000..dc2bce0 --- /dev/null +++ b/API/proxiesembed/drmproxy/utils/structs.py @@ -0,0 +1,56 @@ +class BaseElement: + def __init__(self, url=None, collection=None, element=None, additional=None): + self.url = url + self.collection = collection + self.element = element + self.additional = additional + + def copy(self, base_element): + self.url = base_element.url + self.collection = base_element.collection + self.element = base_element.element + self.additional = base_element.additional + + +class CustomException(Exception): + def __init__(self, message): + super().__init__(message) + + +class BaseService: + + @staticmethod + def test_service(): + raise NotImplementedError(f'{BaseService.test_service.__name__} must be implemented') + + @staticmethod + def is_content_livestream(content, additional): + return False + + @staticmethod + def get_additional_params(additional): + return [("MUXER", lambda s: s.format(args="mkv"))] + + @staticmethod + def credentials_needed(): + raise NotImplementedError(f'{BaseService.credentials_needed.__name__} must be implemented') + + @staticmethod + def initialize_service(): + raise NotImplementedError(f'{BaseService.initialize_service.__name__} must be implemented') + + @staticmethod + def get_best_decryptable_video(manifest, keys): + return None + + @staticmethod + def get_keys(challenge, additional): + raise NotImplementedError(f'{BaseService.get_keys.__name__} must be implemented') + + @staticmethod + def get_video_data(source_element): + raise NotImplementedError(f'{BaseService.get_video_data.__name__} must be implemented') + + @staticmethod + def get_collection_elements(collection_url): + raise NotImplementedError(f'{BaseService.get_collection_elements.__name__} must be implemented') diff --git a/API/proxiesembed/drmproxy/utils/tools/__init__.py b/API/proxiesembed/drmproxy/utils/tools/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/API/proxiesembed/drmproxy/utils/tools/args.py b/API/proxiesembed/drmproxy/utils/tools/args.py new file mode 100644 index 0000000..1d008b1 --- /dev/null +++ b/API/proxiesembed/drmproxy/utils/tools/args.py @@ -0,0 +1,383 @@ +import builtins +import json +import os +import re +import shutil + +import browser_cookie3 + +from utils.constants.configuration import TOOL_PARAMS, TOOL_PARAMS_BASIC, DEFAULT_CONFIG +from utils.constants.macros import APP_NAME, DEFAULT_INPUT_FILE, WARN_MSG, CONFIG_FILE, EXTERNAL_TOOLS, TERMINAL_DIR, \ + INF_MSG, DEFAULT_WVD_PATH, APP_VERSION +from utils.constants.portable import IS_SUPPORTED_SYSTEM, CURRENT_OS, SUPPORTED_OS, SUPPORTED_ARCHITECTURES, \ + CURRENT_ARCHITECTURE, \ + EnvironmentConstants, IS_SUPPORTED_OS, CMD_SCRIPT_EXT, IS_FILE_EXECUTABLE +from utils.tools.cdm import search_cdm_wvd +from utils.tools.common import file_to_list, dict_to_file, is_http_url +from utils.tools.service import get_all_services, get_all_services_classes + + +def check_query_args(args): + try: + # raise + query_str = [] + for a in args: + if "--query=" in a: + query_str = a.split("=")[1].split(":") + break + except: + return { + "MIN": {"COLLECTION": None, "ELEMENT": None}, + "MAX": {"COLLECTION": None, "ELEMENT": None} + } + + query = {} + for m in [(0, "MIN"), (2, "MAX")]: + query[m[1]] = {} + for i in [(0, "COLLECTION"), (1, "ELEMENT")]: + try: + query[m[1]][i[1]] = float(query_str[m[0] + i[0]]) + except: + query[m[1]][i[1]] = None + + if 1 <= len(query_str) <= 2: + query["MAX"]["COLLECTION"] = query["MIN"]["COLLECTION"] + if len(query_str) == 2: + query["MAX"]["ELEMENT"] = query["MIN"]["ELEMENT"] + return query + + +def check_help_args(args): + if "--help" in args: + return ( + "--help\nShows help\n\n" + "--usage\nShows usage examples\n\n" + "--config\nExplains the config properties.\n\n" + "--version\nDisplays the current app version.\n\n" + "--services\nDisplays all available services\n\n" + "--format=SERVICE_NAME\nDisplays example URLs for a service\n\n" + "--query=collection1_index:element1_index:collection2_index:element2_index\nDownloads only an interval from a content collection\n\n" + "--debug\nDisplays the exact error and where it happened so you can properly debug the app\n\n" + "--basic\nNo downloads are launched and only basic shareable commands are generated (*won't work for all services because of URL parameters)\n\n" + "--fresh\nDeletes the cache and gets new information for relevant services\n\n" + f"Make sure you edit the {CONFIG_FILE} file according to your needs." + ) + + if "--config" in args: + return ( + "Config properties:\n" + "CDM_WVD_FILE_PATH: the path to your local cdm in wvd format (can be set as relative or absolute)\n" + "USER_AGENT: the user agent of your browser (some services need a real user agent)\n" + "NUMBER_OF_THREADS: the properties related to the number of threads used by the program\n" + "\tDATA_SCRAPER: during the data scraping stage (for high values, some services will temporarily block you)\n" + "\tMEDIA_DOWNLOADER: during the download stage (the number of terminals that will be opened)\n\n" + + "DOWNLOAD_COMMANDS: the properties related to the downloading stage\n" + "\tOUTPUT_MEDIA_PATH: the path to your media download directory (can be set as relative or absolute)\n" + "\tWAIT_BEFORE_DOWNLOADING: boolean flag that is used to pause between the data scraping and the downloading stages " + "(if set to null then the downloading stage is skipped and only basic unshareable commands are generated). It " + "is recommended to be set to true if using a VPN or if you want to edit the generated commands\n" + "\tADDITIONAL_SUBS: boolean flag that is used to download subtitles that aren't part of the manifest\n" + "\tTOOL_PARAMETERS: additional parameters for N_m3u8DL-RE\n" + "\t\tVOD: parameters used for all types of content (vod/livestream)\n" + "\t\tLIVESTREAM: parameters used only for livestreams\n\n" + + "SERVICE_CREDENTIALS: the credentials used by the services\n" + "\tOPTIONAL: the service uses credentials but those are optional (some content won't be downloaded however)\n" + "\tFIREFOX_COOKIES: the service uses existing cookies provided by Firefox\n\n" + + "WARN_EXTERNAL_TOOLS: boolean flag that is used to warn the user if any external tools are not properly installed. It " + "is recommended to be left as it is and to be not changed manually" + ) + + if "--usage" in args: + return ( + "Usage examples:\n" + f'python {APP_NAME}.py "CONTENT_URL"\n' + "Downloads from URL.\n\n" + f'python {APP_NAME}.py "LOCAL_FILE_PATH"\n' + "Downloads from a local file that contains a list of URLs. Each URL is on a newline.\n\n" + f'python {APP_NAME}.py "CONTENT" --query=1:2:3:4\n' + "Downloads the content found in the interval, collection 1, element 2, collection 3, element 4.\n\n" + f'python {APP_NAME}.py "CONTENT" --query=1:2::\n' + "Downloads the content starting from collection 1 element 2.\n\n" + f'python {APP_NAME}.py "CONTENT" --query=::3:4\n' + "Downloads the content up to collection 3, element 4.\n\n" + f'python {APP_NAME}.py "CONTENT" --query=1:2\n' + "Downloads the content collection 1, element 2 only.\n\n" + f'python {APP_NAME}.py "CONTENT" --query=1\n' + "Downloads the content collection 1 only.\n\n" + f'python {APP_NAME}.py "CONTENT" --query=:2::4\n' + "Downloads the content found in the interval, element 2, element 4 (useful when the collection isn't ordered).\n\n" + f'python {APP_NAME}.py "CONTENT" --query=1::3:\n' + "Downloads the content found in the interval, collection 1, collection 3.\n\n" + f'python {APP_NAME}.py --format=aloula.sa\n' + "Displays example URLs for the aloula.sa service.\n\n" + f'python {APP_NAME}.py --format=all\n' + "Displays example URLs for all services.\n\n" + ) + + if "--version" in args: + return f"Current app version: {APP_VERSION}" + + if "--services" in args: + all_services = list(get_all_services().keys()) + all_services = sorted(all_services) + return ( + "Available services:\n" + "\n".join(all_services) + "\n\n" + + "Number of available services: " + str(len(all_services)) + ) + + try: + for a in args: + if "--format=" in a: + service = a.split("=")[1] + if service == "all": + message = "" + for s in get_all_services_classes(): + service_name = s.__name__.replace('_', '.') + if service_name.startswith("."): + service_name = service_name[1:] + + message += ( + f"Allowed format for {service_name}:\n" + + "\n".join(s.DEMO_URLS) + "\n\n" + ) + return message + + return "Allowed format:\n" + "\n".join(get_all_services()[service].DEMO_URLS) + except: + return "The requested service is not available" + return None + + +def check_input_args(args): + try: + for a in args: + if a.startswith("--"): + continue + if is_http_url(a): + return [a] + return file_to_list(a) + return file_to_list(DEFAULT_INPUT_FILE) + except: + return [] + + +def check_tool_args(tool_args): + try: + bad_args = re.findall(r'--\S+', tool_args["BASE"]) + [ + "-M ", "--mux-after-done", "--append-url-params" + ] + for arg in bad_args: + if arg in tool_args["VOD"] or arg in tool_args["LIVESTREAM"]: + return bad_args + except: + pass + return [] + + +def check_config_basic(config, arguments): + if not IS_SUPPORTED_SYSTEM or "--basic" in arguments: + if "--basic" in arguments: + config["BASIC"] = True + elif not IS_SUPPORTED_OS: + detected_os = CURRENT_OS + if 'ANDROID_ARGUMENT' in os.environ: + detected_os = 'Android' + + print(WARN_MSG.format( + msg=f"OS is not supported for launching the download commands. " + f"Detected OS: {detected_os}. " + f"Allowed OS: {SUPPORTED_OS}." + )) + elif CURRENT_ARCHITECTURE not in SUPPORTED_ARCHITECTURES: + print(WARN_MSG.format( + msg=f"OS architecture is not supported for launching the download commands. " + f"Detected architecture: {CURRENT_ARCHITECTURE}. " + f"Allowed architectures: {SUPPORTED_ARCHITECTURES}." + )) + + config["DOWNLOAD_COMMANDS"]["WAIT_BEFORE_DOWNLOADING"] = None + + elif not EnvironmentConstants.IS_SUPPORTED: + if config["NUMBER_OF_THREADS"]["MEDIA_DOWNLOADER"] != 1: + config["NUMBER_OF_THREADS"]["MEDIA_DOWNLOADER"] = 1 + + print(WARN_MSG.format( + msg=f"Environment is not supported for launching multiple terminal windows. " + f"{EnvironmentConstants.ERROR_MESSAGE} " + f"Lowering the number of threads for MEDIA_DOWNLOADER to 1..." + )) + dict_to_file(CONFIG_FILE, config) + + if config["NUMBER_OF_THREADS"]["MEDIA_DOWNLOADER"] > 1: + if len(EnvironmentConstants.INFO_MESSAGE) > 0: + print(INF_MSG.format(msg=EnvironmentConstants.INFO_MESSAGE)) + + if config["DOWNLOAD_COMMANDS"].get("WAIT_BEFORE_DOWNLOADING", None) is None: + config["DOWNLOAD_COMMANDS"]["TOOL_PARAMETERS"] = TOOL_PARAMS_BASIC + else: + if config["WARN_EXTERNAL_TOOLS"] is True: + config["WARN_EXTERNAL_TOOLS"] = not check_external_tools(config) + if not config["WARN_EXTERNAL_TOOLS"]: + dict_to_file(CONFIG_FILE, config) + + config["DOWNLOAD_COMMANDS"]["TOOL_PARAMETERS"] = TOOL_PARAMS + return config + + +def get_config(arguments): + try: + file_opened = False + with open(CONFIG_FILE, 'r') as json_file: + file_opened = True + config = json.load(json_file) + + for k in ["VOD", "LIVESTREAM"]: + v = config["DOWNLOAD_COMMANDS"]["TOOL_PARAMETERS"][k] + assert type(v) is str + TOOL_PARAMS[k] = v + + assert type(config["CDM_WVD_FILE_PATH"]) is str + assert type(config["USER_AGENT"]) is str + assert type(config["NUMBER_OF_THREADS"]["DATA_SCRAPER"]) is int + assert type(config["NUMBER_OF_THREADS"]["MEDIA_DOWNLOADER"]) is int + assert type(config["WARN_EXTERNAL_TOOLS"]) is bool + assert type(config["DOWNLOAD_COMMANDS"]["OUTPUT_MEDIA_PATH"]) is str + + config = check_config_basic(config, arguments) + return config + except Exception as e: + if file_opened: + print(WARN_MSG.format( + msg=f"Failed to load {CONFIG_FILE}. Reason (not a valid JSON file): {str(e)}. Resetting file..." + )) + + DEFAULT_CONFIG["CDM_WVD_FILE_PATH"] = search_cdm_wvd() + config = DEFAULT_CONFIG + + for py_file in get_all_services_classes(): + credentials = getattr(py_file, "credentials_needed")() + if credentials.get("NONE_NEEDED", False) is True: + continue + + name = py_file.__name__.replace("_", ".") + if name[0] == ".": + name = name[1:] + config["SERVICE_CREDENTIALS"][name] = credentials + + dict_to_file(CONFIG_FILE, config) + config = check_config_basic(config, arguments) + return config + + +def check_range(is_collection, collection_index, element_index, is_asc=True): + config_query = builtins.CONFIG["QUERY"] + + if is_collection: + if type(config_query["MIN"]["COLLECTION"]) in [int, float]: + if collection_index < config_query["MIN"]["COLLECTION"]: + return is_asc + if type(config_query["MAX"]["COLLECTION"]) in [int, float]: + if collection_index > config_query["MAX"]["COLLECTION"]: + return not is_asc + else: + if collection_index is not None: + if type(config_query["MIN"]["COLLECTION"]) in [int, float]: + if type(config_query["MIN"]["ELEMENT"]) in [int, float]: + if config_query["MIN"]["COLLECTION"] == collection_index: + if element_index < config_query["MIN"]["ELEMENT"]: + return is_asc + if type(config_query["MAX"]["COLLECTION"]) in [int, float]: + if type(config_query["MAX"]["ELEMENT"]) in [int, float]: + if config_query["MAX"]["COLLECTION"] == collection_index: + if element_index > config_query["MAX"]["ELEMENT"]: + return not is_asc + else: + if type(config_query["MIN"]["ELEMENT"]) in [int, float]: + if element_index < config_query["MIN"]["ELEMENT"]: + return is_asc + if type(config_query["MAX"]["ELEMENT"]) in [int, float]: + if element_index > config_query["MAX"]["ELEMENT"]: + return not is_asc + return None + + +def check_external_tools(config): + try: + for tool in EXTERNAL_TOOLS: + tool_path = shutil.which(tool) + + if tool_path is None: + print(WARN_MSG.format( + msg=f"External tool is not installed: {tool}. " + f"Download commands may not be launched properly." + )) + return False + if not IS_FILE_EXECUTABLE(tool_path): + print(WARN_MSG.format( + msg=f"External tool can't be executed: {tool}. Insufficient privileges. " + f"Download commands may not be launched properly." + )) + return False + + ext = CMD_SCRIPT_EXT + if not ext.startswith('.'): + ext = '.' + ext + + try: + scripts = [script for script in [ + os.path.join(TERMINAL_DIR, script) for script in os.listdir(TERMINAL_DIR) + ] if os.path.isfile(script) and script.endswith(ext)] + except FileNotFoundError: + print(WARN_MSG.format( + msg=f"The folder {TERMINAL_DIR} is missing. " + f"Download commands won't be launched properly." + )) + return False + + if len(scripts) == 0: + print(WARN_MSG.format( + msg=f"The folder {TERMINAL_DIR} doesn't contain the necessary scripts. " + f"Download commands won't be launched properly." + )) + return False + + for script in scripts: + if not IS_FILE_EXECUTABLE(script): + print(WARN_MSG.format( + msg=f"Terminal script can't be executed: {script}. Insufficient privileges. " + f"Download commands won't be launched properly." + )) + return False + + try: + if config["CDM_WVD_FILE_PATH"] in [DEFAULT_WVD_PATH, ""]: + raise FileNotFoundError + + with open(config["CDM_WVD_FILE_PATH"], 'r') as _: + pass + except FileNotFoundError: + print(WARN_MSG.format( + msg=f"The CDM WVD file path is not configured correctly. " + f"Services that require a CDM won't work." + )) + return False + + try: + browser_cookie3.firefox(domain_name='') + except browser_cookie3.BrowserCookieError: + print(WARN_MSG.format( + msg=f"Firefox browser is not installed. " + f"Services that require browser cookies won't work as intended." + )) + return False + return True + + except Exception as e: + print(WARN_MSG.format( + msg=f"Can't check if the external tools are installed. Reason: {str(e)}. " + f"Download commands may not be launched properly." + )) + return False diff --git a/API/proxiesembed/drmproxy/utils/tools/cdm.py b/API/proxiesembed/drmproxy/utils/tools/cdm.py new file mode 100644 index 0000000..f253d71 --- /dev/null +++ b/API/proxiesembed/drmproxy/utils/tools/cdm.py @@ -0,0 +1,94 @@ +import base64 +import builtins +import os +import re + +import requests +from pywidevine import PSSH, Cdm, Device + +from utils.constants.macros import DEFAULT_WVD_PATH, PLAYREADY_SCHEME_ID + + +def search_cdm_wvd(): + for wvd_file in os.listdir("."): + if not wvd_file.endswith(".wvd"): + continue + return wvd_file + return DEFAULT_WVD_PATH + + +def init_cdm(pssh_value): + try: + if pssh_value is None: + raise + device = Device.load(builtins.CONFIG["CDM_WVD_FILE_PATH"]) + assert device.security_level == 3 + except: + return None, None, None + + pssh_value = PSSH(pssh_value) + if pssh_value.system_id == PSSH.SystemId.PlayReady: + pssh_value.to_widevine() + + cdm = Cdm.from_device(device) + cdm_session_id = cdm.open() + challenge = cdm.get_license_challenge(cdm_session_id, pssh_value) + return cdm, cdm_session_id, challenge + + +def close_cdm(cdm, cdm_session_id, response): + cdm.parse_license(cdm_session_id, response) + keys = [] + for key in cdm.get_keys(cdm_session_id): + if "CONTENT" in key.type: + keys += [f"{key.kid.hex}:{key.key.hex()}"] + cdm.close(cdm_session_id) + return keys + + +def get_pssh_from_init(init_url): + content = requests.get(init_url).content + offsets = [] + offset = 0 + + while True: + offset = content.find(b'pssh', offset) + if offset == -1: + break + + size = int.from_bytes(content[offset - 4:offset], byteorder='big') + pssh_offset = offset - 4 + + offsets.append(content[pssh_offset:pssh_offset + size]) + offset += size + + pssh_list = [base64.b64encode(wv_offset).decode() for wv_offset in offsets] + for pssh in pssh_list: + if 70 < len(pssh) < 190: + return pssh + return None + + +def get_pssh_from_default_kid(manifest_content, xml_node="cenc:default_KID", default_kid=None): + if default_kid is None: + default_kid = re.search(fr'{xml_node}="([a-fA-F0-9-]+)"', manifest_content).group(1) + default_kid = default_kid.replace('-', '') + pssh = f'000000387073736800000000edef8ba979d64acea3c827dcd51d21ed000000181210{default_kid}48e3dc959b06' + pssh = base64.b64encode(bytes.fromhex(pssh)).decode() + return pssh + + +def get_pssh_from_cenc_pssh(manifest_content, xml_node="cenc:pssh"): + return str(min(re.findall( + fr'<[^<>]*{xml_node}[^<>]*>(.*?)]*{xml_node}[^<>]*>', + manifest_content + ), key=len)) + + +def get_pssh_from_playready(manifest_content): + psshs = re.findall( + fr'"]*"[^<>"]*{PLAYREADY_SCHEME_ID}[^<>"]*"[^<>]*>(.*?)', + manifest_content, + re.DOTALL | re.IGNORECASE + ) + return str(min(psshs, key=len)) diff --git a/API/proxiesembed/drmproxy/utils/tools/common.py b/API/proxiesembed/drmproxy/utils/tools/common.py new file mode 100644 index 0000000..96371fa --- /dev/null +++ b/API/proxiesembed/drmproxy/utils/tools/common.py @@ -0,0 +1,208 @@ +import json +import os +import random +import re +import string +from math import ceil +from urllib.parse import urlparse, parse_qs, urlencode, urlunparse + +import numpy as np +import requests +import unicodedata +from unidecode import unidecode + +from utils.constants.macros import TMP_RAND_LEN, CONFIG_FILE +from utils.constants.portable import CMD_ADJUST + + +def split_list_chunks(lst, chunks): + chunks = [list(c) for c in np.array_split(lst, chunks)] + return [c for c in chunks if len(c) > 0] + + +def flatten_list(lst): + if len(lst) > 0 and type(lst[0]) is list: + lst = [_ for r in lst for _ in r] + return lst + + +def get_base_url(url): + parsed_url = urlparse(url) + domain_parts = parsed_url.netloc.split('.') + if 'www' in domain_parts[0]: + return '.'.join(domain_parts[1:]) + return parsed_url.netloc + + +def file_to_list(file_path): + with open(file_path, 'r') as file: + lines = file.readlines() + lines = [line.strip() for line in lines] + lines = [line for line in lines if len(line) > 0] + return list(dict.fromkeys(lines)) + + +def list_to_file(file_path, l): + with open(file_path, 'w') as file: + for e in l: + file.write(e + '\n') + + +def rand_str(rand_len=TMP_RAND_LEN): + return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(rand_len)) + + +def get_width_res_from_height(height): + width = (height * 16) / 9 + return int(ceil(width)) + + +LATIN_LETTERS = {} + + +def is_latin_char(character): + try: + return LATIN_LETTERS[character] + except KeyError: + return LATIN_LETTERS.setdefault(character, 'LATIN' in unicodedata.name(character)) + + +def has_only_roman_chars(input_string): + if input_string is None or type(input_string) is not str: + return False + return all( + is_latin_char(character) + for character in input_string + if character.isalpha() + ) + + +def get_valid_filename(name): + if name is None or len(name) == 0: + return None + try: + temp_name = unidecode(name) + if temp_name is not None and len(temp_name) > 0: + name = temp_name + except: + pass + + s = str(name).strip() + s = re.sub(r'\s+', ' ', s) + s = s.replace(" ", "_") + s = re.sub(r"(?u)[^-\w.]", "", s) + s = re.sub(r'_+', '_', s) + s = re.sub(r'\.+', '', s) + + if s in {"", ".", ".."}: + return None + return s + + +def get_ext_from_url(url): + try: + _, url_ext = os.path.splitext(os.path.basename(urlparse(url).path)) + return url_ext + except: + return "" + + +def get_last_path(url): + if url is None or len(url) == 0: + return None + + for p in reversed(url.split("/")): + if len(p) == 0: + continue + return p + return None + + +def remove_last_path_segment(url): + url = url.rstrip("/") + parsed_url = urlparse(url) + + path_segments = parsed_url.path.rstrip('/').split('/') + if len(path_segments) > 1: + new_path = '/'.join(path_segments[:-1]) + else: + new_path = '' + + new_url = urlunparse(parsed_url._replace(path=new_path)) + return new_url + + +def get_nr_paths(url): + if url is None or len(url) == 0: + return 0 + + count = 0 + for p in url.split("/"): + if len(p) == 0: + continue + count += 1 + return count + + +def dict_to_file(file, d): + if file != CONFIG_FILE: + with open(file, 'w') as f: + f.write(json.dumps(d)) + else: + with open(file, 'w') as json_file: + json.dump(d, json_file, indent=4) + + +def file_to_dict(file): + try: + with open(file, 'r') as f: + return json.loads(f.read()) + except: + return {} + + +def update_url_params(url, new_params): + parsed_url = urlparse(url) + query_params = parse_qs(parsed_url.query) + + for key, value in new_params.items(): + query_params[key] = [str(value)] + + updated_query = urlencode(query_params, doseq=True) + updated_url = urlunparse(( + parsed_url.scheme, parsed_url.netloc, parsed_url.path, + parsed_url.params, updated_query, parsed_url.fragment + )) + return updated_url + + +def get_public_ip(): + try: + return requests.get('https://checkip.amazonaws.com').text.strip().split(",")[-1] + except: + return None + + +def get_country_code(): + try: + response = requests.get(f"https://ip2c.org/{get_public_ip()}") + return response.text.split(";")[1] + except: + return None + + +def is_http_url(u): + return ( + u is not None and len(u) > 0 and + (u.startswith("https://") or u.startswith("http://")) + ) + + +def clean_url(url): + return url.split("?")[0].split("#")[0].rstrip("/") + + +def adjust_parameters(use_adjust, params): + if not use_adjust: + return params + return params.replace("|", f'{CMD_ADJUST}|') diff --git a/API/proxiesembed/drmproxy/utils/tools/service.py b/API/proxiesembed/drmproxy/utils/tools/service.py new file mode 100644 index 0000000..683f001 --- /dev/null +++ b/API/proxiesembed/drmproxy/utils/tools/service.py @@ -0,0 +1,87 @@ +import builtins +import importlib +import os + +from utils.constants.macros import ERR_MSG, USER_ERROR, APP_ERROR, CONFIG_FILE, APP_DIR, WARN_MSG +from utils.structs import CustomException +from utils.tools.common import get_base_url + + +def get_all_services_classes(): + import services + py_files = [] + for py_file in os.listdir(os.path.dirname(services.__file__)): + if not py_file.endswith(".py") or py_file == "__init__.py": + continue + + py_file = py_file[:-3] + try: + py_files.append(getattr(importlib.import_module(f"services.{py_file}"), py_file)) + except Exception as e: + try: + check_debug = builtins.CONFIG["DEBUG_MODE"] + except: + check_debug = False + if check_debug: + raise e + + service_name = py_file.replace('_', '.') + if service_name.startswith("."): + service_name = service_name[1:] + + print(WARN_MSG.format( + msg=f"The service {service_name} cannot be used because " + f"it is not properly implemented, has package errors or has syntax errors. After fixing the issue " + f"delete the {APP_DIR} folder." + )) + return py_files + + +def get_service(content_url): + base_url = get_base_url(content_url) + service = builtins.SERVICES.get(base_url, None) + if service is None: + print(ERR_MSG.format( + type=USER_ERROR, + url=content_url, + reason=f"No service available for {base_url}", + solution=f"Implement it" + )) + return None + + try: + service_name = service.__name__ + service = service.initialize_service() + if service is None: + print(ERR_MSG.format( + type=f'{USER_ERROR}/{APP_ERROR}', + url=content_url, + reason=f"Failed to initialize the {service_name} service", + solution=f"Check the service credentials in the {CONFIG_FILE} file. " + f"If you are sure everything is right then debug the service" + )) + return service + except CustomException as e: + if builtins.CONFIG["DEBUG_MODE"]: + raise e + print(str(e)) + except Exception as e: + if builtins.CONFIG["DEBUG_MODE"]: + raise e + print(ERR_MSG.format( + type=APP_ERROR, + url=content_url, + reason=f"Failed to initialize the {service.__name__} service", + solution=f"Debug the service" + )) + return None + + +def get_all_services(): + services = {} + for py_file in get_all_services_classes(): + name = py_file.__name__.replace("_", ".") + if name[0] == ".": + name = name[1:] + services[name] = py_file + return services diff --git a/API/proxiesembed/drmproxy/widefrog.py b/API/proxiesembed/drmproxy/widefrog.py new file mode 100644 index 0000000..499453f --- /dev/null +++ b/API/proxiesembed/drmproxy/widefrog.py @@ -0,0 +1,124 @@ +import builtins +import os +import sys + +from utils.constants.macros import CONFIG_FILE, INF_MSG, DEFAULT_DEBUG_MODE +from utils.main_service import main_service +from utils.tools.args import get_config, check_query_args, check_help_args, check_input_args, check_tool_args +from utils.tools.service import get_all_services + + +def test_service(): + main_service.run_service( + # _35mm_online.DEMO_URLS + + # adtv_ae.DEMO_URLS + + # adultswim_com.DEMO_URLS + + # aloula_sa.DEMO_URLS + + # app_nzrplus_com.DEMO_URLS + + # auvio_rtbf_be.DEMO_URLS + + # canalplus_com.DEMO_URLS + + # cbs_com.DEMO_URLS + + # cda_pl.DEMO_URLS + + # channel4_com.DEMO_URLS + + # cineverse_com.DEMO_URLS + + # docplus_com.DEMO_URLS + + # eurovisionsport_com.DEMO_URLS + + # fifa_com.DEMO_URLS + + # filmzie_com.DEMO_URLS + + # france_tv.DEMO_URLS + + # goplay_be.DEMO_URLS + + # joyn_de.DEMO_URLS + + # kanopy_com.DEMO_URLS + + # kijk_nl.DEMO_URLS + + # m6_fr.DEMO_URLS + + # maoriplus_co_nz.DEMO_URLS + + # mediasetinfinity_mediaset_it.DEMO_URLS + + # midnightpulp_com.DEMO_URLS + + # mtv_fi.DEMO_URLS + + # nba_com.DEMO_URLS + + # nemzetiarchivum_hu.DEMO_URLS + + # netflix_com.DEMO_URLS + + # ninateka_pl.DEMO_URLS + + # npo_nl.DEMO_URLS + + # pianogroove_com.DEMO_URLS + + # play_tv3_lt.DEMO_URLS + + # play_tv3_lv.DEMO_URLS + + # play_virginmediatelevision_ie.DEMO_URLS + + # play_xumo_com.DEMO_URLS + + # player_pl.DEMO_URLS + + # plus_fifa_com.DEMO_URLS + + # plus_rtl_de.DEMO_URLS + + # ptvflix_org.DEMO_URLS + + # rakuten_tv.DEMO_URLS + + # rmcbfmplay_com.DEMO_URLS + + # rsi_ch.DEMO_URLS + + # rtlplay_be.DEMO_URLS + + # rtp_pt.DEMO_URLS + + # rts_ch.DEMO_URLS + + # rtve_es.DEMO_URLS + + # rugbypass_tv.DEMO_URLS + + # shahid_mbc_net.DEMO_URLS + + # stirr_com.DEMO_URLS + + # tf1_fr.DEMO_URLS + + # tg4_ie.DEMO_URLS + + # threenow_co_nz.DEMO_URLS + + # tv5mondeplus_com.DEMO_URLS + + # uefa_tv.DEMO_URLS + + # veeps_com.DEMO_URLS + + # video_telequebec_tv.DEMO_URLS + + # viki_com.DEMO_URLS + + # viu_com.DEMO_URLS + + # vix_com.DEMO_URLS + + # vrt_be.DEMO_URLS + + # vtmgo_be.DEMO_URLS + + # watch_blaze_tv.DEMO_URLS + + # watch_globaltv_com.DEMO_URLS + + # watch_shortly_film.DEMO_URLS + + # watch_tbn_uk.DEMO_URLS + + # wittytv_it.DEMO_URLS + + # zee5_com.DEMO_URLS + + [] + ) + sys.exit(0) + + +def first_setup(arguments): + is_first = not os.path.exists(CONFIG_FILE) + builtins.CONFIG = get_config(arguments) + builtins.CONFIG["QUERY"] = check_query_args(arguments) + + if "--debug" in arguments: + builtins.CONFIG["DEBUG_MODE"] = True + else: + builtins.CONFIG["DEBUG_MODE"] = DEFAULT_DEBUG_MODE + if "--fresh" in arguments: + builtins.CONFIG["FRESH"] = True + + builtins.SERVICES = get_all_services() + return is_first + + +if __name__ == '__main__': + args = sys.argv[1:] + response = check_help_args(args) + if response is not None and len(response) > 0: + print(response) + sys.exit(0) + + if first_setup(args): + print(INF_MSG.format( + msg=f"The {CONFIG_FILE} file was created. Edit the file and run the program." + )) + sys.exit(0) + + bad_args = check_tool_args(builtins.CONFIG["DOWNLOAD_COMMANDS"]["TOOL_PARAMETERS"]) + if len(bad_args) > 0: + print("Those arguments are not allowed: ", ", ".join(bad_args)) + sys.exit(0) + + # test_service() + + response = check_input_args(args) + if len(response) == 0: + sys.exit(0) + main_service.run_service(response) diff --git a/API/proxiesembed/requirements.txt b/API/proxiesembed/requirements.txt new file mode 100644 index 0000000..c782ce8 --- /dev/null +++ b/API/proxiesembed/requirements.txt @@ -0,0 +1,27 @@ +aiohttp==3.11.18 +aiohttp-socks==0.9.1 +aiofiles==24.1.0 +beautifulsoup4==4.12.2 +lxml==5.3.0 +requests==2.31.0 +requests[socks] +cloudscraper==1.2.71 +pycryptodome +aiomysql==0.2.0 +python-dotenv==1.0.1 + +# WideFrog DRM integration dependencies +browser_cookie3 +numpy +pycountry +Unidecode +xmltodict +curl_cffi +chompjs +isodate +python-slugify +cryptography +m3u8 +pywidevine +protobuf +html5lib \ No newline at end of file diff --git a/API/proxiesembed/server.py b/API/proxiesembed/server.py new file mode 100644 index 0000000..1d20c8a --- /dev/null +++ b/API/proxiesembed/server.py @@ -0,0 +1,4263 @@ +#!/usr/bin/env python3 +""" +Python Proxy Server - Ultra High Performance Version +Optimized for massive concurrent connections and high-load streaming +""" + +import asyncio +import aiohttp +import json +import base64 +import re +import urllib.parse +from urllib.parse import urlparse, urljoin +from aiohttp import web, ClientTimeout, TCPConnector +from aiohttp.web import Request, Response +import logging +import sys +from typing import Optional, Dict, Any, Tuple, Set +from dataclasses import dataclass +from functools import lru_cache +import codecs +import time +import hashlib +from bs4 import BeautifulSoup +from datetime import datetime, timezone +import ssl +import random +from aiohttp_socks import ProxyConnector +from collections import OrderedDict +import gc +import binascii +from string import ascii_letters, digits +from Crypto.Cipher import AES +from Crypto.Util.Padding import unpad +import aiomysql +import os +import builtins +import traceback +from concurrent.futures import ThreadPoolExecutor +from dotenv import load_dotenv + +# Load local .env from proxiesembed folder +load_dotenv(os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env')) + +# --------------------------------------------------------------------------- +# WideFrog / DRM Proxy integration +# --------------------------------------------------------------------------- +# Add drmproxy directory to sys.path so we can import widefrog utilities +_DRMPROXY_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'drmproxy') +if _DRMPROXY_DIR not in sys.path: + sys.path.insert(0, _DRMPROXY_DIR) + +# Thread pool for blocking widefrog calls +_DRM_EXECUTOR = ThreadPoolExecutor(max_workers=4, thread_name_prefix='drm') + +# Try to import widefrog utilities (optional — server starts without them) +_WIDEFROG_AVAILABLE = False +try: + from utils.constants.macros import CONFIG_FILE, DEFAULT_DEBUG_MODE + from utils.structs import BaseElement + from utils.tools.args import get_config as wf_get_config + from utils.tools.cdm import init_cdm, close_cdm + from utils.tools.common import get_base_url as wf_get_base_url + from utils.tools.service import get_service, get_all_services + import requests as sync_requests # Used by widefrog extraction (sync) + _WIDEFROG_AVAILABLE = True + logger_early = logging.getLogger(__name__) + logger_early.info('[DRM] WideFrog utilities loaded successfully') +except ImportError as _wf_err: + logger_early = logging.getLogger(__name__) + logger_early.warning(f'[DRM] WideFrog utilities not available: {_wf_err}') + + +def _init_widefrog(): + """Initialise widefrog config (once, thread-safe). + + Widefrog uses relative paths (app_files/config.json, *.wvd) so we + must chdir to the drmproxy directory before calling its functions. + """ + if not _WIDEFROG_AVAILABLE: + return + if hasattr(builtins, 'CONFIG'): + return + # Switch CWD to drmproxy/ so relative paths (config.json, .wvd) resolve + _prev_cwd = os.getcwd() + os.chdir(_DRMPROXY_DIR) + try: + args = [] + builtins.CONFIG = wf_get_config(args) + builtins.CONFIG['QUERY'] = { + 'MIN': {'COLLECTION': None, 'ELEMENT': None}, + 'MAX': {'COLLECTION': None, 'ELEMENT': None}, + } + builtins.CONFIG['DEBUG_MODE'] = DEFAULT_DEBUG_MODE + builtins.SERVICES = get_all_services() + builtins.CONFIG['DOWNLOAD_COMMANDS']['WAIT_BEFORE_DOWNLOADING'] = None + + # Convert CDM .wvd path to absolute so it works from any CWD later + wvd_path = builtins.CONFIG.get('CDM_WVD_FILE_PATH', '') + if wvd_path and not os.path.isabs(wvd_path): + abs_wvd = os.path.join(_DRMPROXY_DIR, wvd_path) + if os.path.isfile(abs_wvd): + builtins.CONFIG['CDM_WVD_FILE_PATH'] = abs_wvd + finally: + os.chdir(_prev_cwd) + + +# --------------------------------------------------------------------------- +# SOCKS5H proxy session for france.tv extraction (NOT for streaming) +# --------------------------------------------------------------------------- +def _build_ftv_proxy_session(): + """Create a requests.Session pre-configured with a SOCKS5H proxy. + + This session is used ONLY for extraction/API calls to france.tv + (page download, manifest fetch, DRM token, auth). + The actual video streaming goes through separate aiohttp sessions WITHOUT proxy. + """ + proxies_list = json.loads(os.environ.get('PROXIES_SOCKS5_JSON', '[]')) + if not proxies_list: + return None + # Pick a random proxy from the list + import random as _rand + proxy = _rand.choice(proxies_list) + auth = proxy.get('auth', '') + host = proxy.get('host', '') + port = proxy.get('port', '') + ptype = proxy.get('type', 'socks5h') + proxy_url = f"{ptype}://{auth}@{host}:{port}" if auth else f"{ptype}://{host}:{port}" + sess = sync_requests.Session() + sess.proxies = { + 'http': proxy_url, + 'https': proxy_url, + } + sess.headers.update({ + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' + '(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36', + 'Accept': '*/*', + 'Accept-Language': 'fr-FR,fr;q=0.9,en;q=0.5', + }) + logging.getLogger(__name__).info(f'[france.tv] Proxy session created: {ptype}://{host}:{port}') + return sess + +if _WIDEFROG_AVAILABLE: + _FTV_PROXY_SESSION = _build_ftv_proxy_session() + # Expose via builtins so france_tv.py service can use it + builtins.FTV_PROXY_SESSION = _FTV_PROXY_SESSION +else: + _FTV_PROXY_SESSION = None + builtins.FTV_PROXY_SESSION = None + + +# --------------------------------------------------------------------------- +# france.tv authentication +# --------------------------------------------------------------------------- +_FRANCETV_SESSION_LOCK = None # Will be a threading.Lock, lazily created +_FRANCETV_CREDENTIALS = { + 'email': os.environ.get('FRANCETV_EMAIL', ''), + 'password': os.environ.get('FRANCETV_PASSWORD', ''), +} + + +def _francetv_authenticate() -> dict: + """Authenticate with france.tv and return session cookies. + + Flow: + 1. GET /api/auth/csrf/ → csrfToken + 2. POST /api/auth/callback/credentials/ → session cookie in Set-Cookie + Stores cookies in builtins.FRANCETV_COOKIES for the france_tv service to use. + """ + if not _FRANCETV_CREDENTIALS['email'] or not _FRANCETV_CREDENTIALS['password']: + raise ValueError('france.tv credentials not configured (set FRANCETV_EMAIL and FRANCETV_PASSWORD in .env)') + + import threading + global _FRANCETV_SESSION_LOCK + if _FRANCETV_SESSION_LOCK is None: + _FRANCETV_SESSION_LOCK = threading.Lock() + + # If we already have valid cookies, return them + existing = getattr(builtins, 'FRANCETV_COOKIES', None) + if existing and existing.get('_expires', 0) > time.time(): + return existing + + with _FRANCETV_SESSION_LOCK: + # Double-check after acquiring lock + existing = getattr(builtins, 'FRANCETV_COOKIES', None) + if existing and existing.get('_expires', 0) > time.time(): + return existing + + _log = logging.getLogger(__name__) + _log.info('[france.tv] Authenticating...') + + try: + # Use proxied session if available, otherwise create a plain one + if _FTV_PROXY_SESSION: + sess = sync_requests.Session() + sess.proxies = dict(_FTV_PROXY_SESSION.proxies) + else: + sess = sync_requests.Session() + sess.headers.update({ + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' + '(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36', + 'Accept': '*/*', + 'Accept-Language': 'fr-FR,fr;q=0.9,en;q=0.5', + }) + + # Step 1: Get CSRF token + csrf_resp = sess.get('https://www.france.tv/api/auth/csrf/', timeout=15) + csrf_resp.raise_for_status() + csrf_token = csrf_resp.json().get('csrfToken', '') + if not csrf_token: + raise ValueError('Empty CSRF token') + _log.info(f'[france.tv] Got CSRF token: {csrf_token[:16]}...') + + # Step 2: POST credentials + login_resp = sess.post( + 'https://www.france.tv/api/auth/callback/credentials/', + data={ + 'email': _FRANCETV_CREDENTIALS['email'], + 'password': _FRANCETV_CREDENTIALS['password'], + 'rememberMe': 'true', + 'redirect': 'false', + 'csrfToken': csrf_token, + 'callbackUrl': 'https://www.france.tv/connexion/?callbackUrl=https%3A%2F%2Fwww.france.tv%2Frecherche%2F', + 'json': 'true', + }, + timeout=15, + ) + login_resp.raise_for_status() + + # Step 3: Extract session cookie from response + cookies_dict = {} + for cookie in sess.cookies: + cookies_dict[cookie.name] = cookie.value + + # Look for the session token in Set-Cookie headers + session_token = None + for cookie_name in ('__Secure-next-auth.session-token', 'next-auth.session-token'): + if cookie_name in cookies_dict: + session_token = cookies_dict[cookie_name] + break + + if not session_token: + _log.warning(f'[france.tv] Auth succeeded but no session token found. Cookies: {list(cookies_dict.keys())}') + else: + _log.info(f'[france.tv] Authenticated! Session token: {session_token[:30]}...') + + # Store all cookies + expiry (30 days, matching Expires header) + cookies_dict['_expires'] = time.time() + (30 * 24 * 3600) + builtins.FRANCETV_COOKIES = cookies_dict + + return cookies_dict + + except Exception as e: + _log.error(f'[france.tv] Authentication failed: {e}') + # Return empty cookies on failure (extraction will work without auth for non-premium content) + empty = {'_expires': time.time() + 300} # Retry in 5 min + builtins.FRANCETV_COOKIES = empty + return empty + + +# DRM manifest cache (module-level, shared) — TTL 10 min +_drm_manifest_cache: Dict[str, dict] = {} +_DRM_CACHE_TTL = 600 # 10 minutes + + +def _extract_manifest_sync(content_url: str) -> dict: + """Synchronous extraction using widefrog (runs in executor thread). + + All widefrog calls happen inside drmproxy/ CWD so that relative + paths (config, .wvd, service caches) resolve correctly. + """ + if not _WIDEFROG_AVAILABLE: + raise RuntimeError('WideFrog utilities are not installed on this server') + + if content_url in _drm_manifest_cache: + entry = _drm_manifest_cache[content_url] + if time.time() - entry.get('_cached_at', 0) < _DRM_CACHE_TTL: + return entry + del _drm_manifest_cache[content_url] + + # Switch CWD to drmproxy/ for the entire extraction + _prev_cwd = os.getcwd() + os.chdir(_DRMPROXY_DIR) + try: + return _extract_manifest_sync_inner(content_url) + finally: + os.chdir(_prev_cwd) + + +def _extract_manifest_sync_inner(content_url: str) -> dict: + """Inner extraction logic (called with CWD = drmproxy/).""" + _init_widefrog() + + # Pre-authenticate for france.tv URLs + if 'france.tv' in content_url.lower(): + try: + _francetv_authenticate() + except Exception as e: + logging.getLogger(__name__).warning(f'[france.tv] Pre-auth failed: {e}') + + service = get_service(content_url) + if service is None: + raise ValueError(f'No service found for URL: {content_url}') + + source_element = BaseElement(url=content_url) + manifest, pssh, additional = service.get_video_data(source_element) + + if not isinstance(manifest, list): + manifest = [(manifest, None)] + if len(manifest) == 0: + manifest = [(None, None)] + if not isinstance(pssh, list): + pssh = [pssh] + + manifest_url = None + for m_url, _ in manifest: + if m_url: + manifest_url = m_url + break + if manifest_url is None: + raise ValueError('No manifest URL could be extracted') + + manifest_type = 'unknown' + ml = manifest_url.split('?')[0].lower() + if '.m3u8' in ml or 'm3u8' in manifest_url.lower(): + manifest_type = 'hls' + elif '.mpd' in ml or 'mpd' in manifest_url.lower(): + manifest_type = 'dash' + elif '.ism' in ml: + manifest_type = 'smooth' + else: + try: + resp = sync_requests.get(manifest_url, timeout=10) + body = resp.text[:500].lower() + if '#extm3u' in body: + manifest_type = 'hls' + elif ' str: + """Build a proxy URL for DRM resources.""" + return f"{route}?url={urllib.parse.quote(target_url, safe='')}" + + +def _drm_resolve_url(base_url: str, relative: str) -> str: + if relative.startswith('http://') or relative.startswith('https://'): + return relative + return urljoin(base_url, relative) + + +def _drm_make_base_proxy_url(original_base_url: str) -> str: + """Encode a base URL into a path-based proxy prefix for DASH.""" + b = base64.urlsafe_b64encode(original_base_url.encode()).decode().rstrip('=') + return f"/drm/b/{b}/" + + +def _drm_rewrite_m3u8(content: str, base_url: str) -> str: + """Rewrite HLS manifest URLs to go through /drm/ proxy.""" + lines = content.split('\n') + result = [] + for line in lines: + stripped = line.strip() + if not stripped: + result.append(line) + continue + if stripped.startswith('#'): + def _rw_uri(m): + uri = m.group(1) + absolute = _drm_resolve_url(base_url, uri) + return f'URI="{_drm_proxy_url(absolute)}"' + rewritten = re.sub(r'URI="([^"]*)"', _rw_uri, stripped, flags=re.IGNORECASE) + rewritten = re.sub(r"URI='([^']*)'", _rw_uri, rewritten, flags=re.IGNORECASE) + rewritten = re.sub( + r"\bURI=([^\"'\s,][^,\s]*)", + _rw_uri, + rewritten, + flags=re.IGNORECASE, + ) + result.append(rewritten) + else: + absolute = _drm_resolve_url(base_url, stripped) + result.append(_drm_proxy_url(absolute)) + return '\n'.join(result) + + +def _drm_rewrite_mpd(content: str, base_url: str) -> str: + """Rewrite DASH MPD manifest URLs to go through /drm/ proxy.""" + has_base_url = bool(re.search(r']*>', content, re.IGNORECASE)) + + if has_base_url: + def _rw_baseurl(m): + url = m.group(1).strip() + if url and (url.startswith('http://') or url.startswith('https://')): + resolved = url if url.endswith('/') else url + '/' + return f'{_drm_make_base_proxy_url(resolved)}' + elif url: + absolute = _drm_resolve_url(base_url, url) + if not absolute.endswith('/'): + absolute += '/' + return f'{_drm_make_base_proxy_url(absolute)}' + return m.group(0) + content = re.sub(r'(.*?)', _rw_baseurl, content, flags=re.DOTALL) + else: + proxy_base = _drm_make_base_proxy_url(base_url) + content = re.sub( + r'(]*>)', + rf'\1\n {proxy_base}', + content, + count=1, + ) + + for attr in ['media', 'initialization']: + def _rw_attr(m, attr_name=attr): + url = m.group(1) + if url.startswith('http://') or url.startswith('https://'): + return f'{attr_name}="{_drm_proxy_url(url)}"' + return m.group(0) + content = re.sub( + rf'{attr}="(https?://[^"]*)"', + _rw_attr, + content, + flags=re.IGNORECASE, + ) + + return content + + +# Try to use uvloop for better async performance (Linux/Mac) +try: + import uvloop + asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) + print("[PERF] uvloop enabled for better async performance") +except ImportError: + pass + +# Optimize garbage collection for high-throughput +gc.set_threshold(50000, 500, 100) + +# Configuration +PORT = 25569 +PROXY_BASE = os.environ.get("PROXY_BASE") +VIP_CACHE_TTL = 300 # Cache VIP check results for 5 minutes + +# MySQL configuration — same env vars as Node.js backend (API/.env) +DB_CONFIG = { + 'host': os.environ.get('DB_HOST'), + 'port': int(os.environ.get('DB_PORT')), + 'user': os.environ.get('DB_USER'), + 'password': os.environ.get('DB_PASSWORD'), + 'db': os.environ.get('DB_NAME'), + 'minsize': 2, + 'maxsize': 20, + 'autocommit': True, +} + +# Proxies SOCKS5H configuration +PROXIES = json.loads(os.environ.get('PROXIES_SOCKS5_JSON', '[]')) + +SIBNET_PROXY_CONFIG = json.loads(os.environ.get('SIBNET_PROXY_SOCKS5_JSON', '{"type":"socks5h"}')) + +DEEPBRID_API_KEY = os.environ.get('DEEPBRID_API_KEY', '') + +DEBRID_PROVIDERS = frozenset({'deepbrid'}) + +SIBNET_PROXY = PROXIES[0] if len(PROXIES) > 0 else None +VIDMOLY_PROXY = PROXIES[1] if len(PROXIES) > 1 else (PROXIES[0] if len(PROXIES) > 0 else None) + +# Logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) +logging.getLogger('aiohttp.access').setLevel(logging.INFO) + +# Filter to suppress HTTP/2 connection attempts (PRI/Upgrade errors) +class HTTP2NoiseFilter(logging.Filter): + """Filter out HTTP/2 connection preface errors from bots/scanners""" + def filter(self, record): + if record.levelno >= logging.ERROR: + msg = str(record.getMessage()).lower() + if 'pri/upgrade' in msg or 'pause on pri' in msg: + return False + # Also filter BadHttpMessage for empty/malformed requests + if hasattr(record, 'exc_info') and record.exc_info: + exc_type = record.exc_info[0] + if exc_type and 'BadHttpMessage' in str(exc_type): + exc_msg = str(record.exc_info[1]).lower() if record.exc_info[1] else '' + if 'pri/upgrade' in exc_msg or 'pause on pri' in exc_msg: + return False + return True + +# Apply filter to aiohttp.server logger +aiohttp_server_logger = logging.getLogger('aiohttp.server') +aiohttp_server_logger.addFilter(HTTP2NoiseFilter()) + +# URL encoding key +URL_ENCODE_KEY = b"ce1f909bbd8b8fa6bdd29035f75ccd1a284fae92a12ff64580008dd0de6e7bc8" + +# Known video extensions (immutable tuple for performance) +KNOWN_EXTENSIONS = ('.mp4', '.m3u8', '.ts', '.m4s', '.mpd', '.webm', '.mkv', '.avi', '.mov') + +# CORS headers constant - MINIMIZED for bandwidth savings +CORS_HEADERS = { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'GET, OPTIONS', + 'Access-Control-Allow-Headers': 'Range, Content-Type, Accept, x-access-key', + 'Access-Control-Expose-Headers': 'Content-Length, Content-Range, Accept-Ranges' +} + + +def _safe_stream_response(status, headers): + """Create StreamResponse with Content-Type in headers only. + + aiohttp 3.11 removed the content_type keyword argument. + Content-Type must be set via the headers dict directly. + """ + return web.StreamResponse(status=status, headers=headers) + + +def _safe_response(body=b'', status=200, headers=None): + """Create Response with Content-Type in headers only. + + aiohttp 3.11 removed the content_type keyword argument. + Content-Type must be set via the headers dict directly. + """ + if headers is None: + headers = {} + return web.Response(body=body, status=status, headers=headers) + + +# Problematic SSL domains +PROBLEMATIC_DOMAINS = frozenset([ + 'vidzy.org', 'v4.vidzy.org', 'v3.vidzy.org', 'v2.vidzy.org', 'v1.vidzy.org', + 'bandwidth.com', 'edgeon-bandwidth.com', 'familyrestream.com', '6522236688.shop', + '1396168994.live', 'vuunov.1396168994.live' +]) + +# AES decryption constants for seekstreaming (embed4me) +SEEKSTREAMING_AES_KEY = b"kiemtienmua911ca" +SEEKSTREAMING_AES_IV = b"1234567890oiuytr" + +# Chunk sizes - OPTIMIZED for high-throughput streaming +CHUNK_TS = 32768 # 32KB for TS segments (doubled for speed) +CHUNK_MP4 = 131072 # 128KB for MP4 streaming (doubled) +CHUNK_DEFAULT = 65536 # 64KB default (doubled) +CHUNK_M3U8 = 16384 # 16KB for M3U8 playlists +CHUNK_LARGE = 262144 # 256KB for large files + +# High-load optimization constants +MAX_CONCURRENT_REQUESTS = 0 # No limit +KEEPALIVE_TIMEOUT = 300 # 5 min keepalive +DNS_CACHE_TTL = 600 # 10 min DNS cache +SOCKET_READ_BUFFER = 262144 # 256KB socket buffer +CONNECTION_TIMEOUT = 15 # 15s connection timeout + +M3U8_CACHE_TTL = 5 # Cache live M3U8 playlists for 5s (reduces re-fetches) +M3U8_VOD_CACHE_TTL = 120 # Cache VOD M3U8 playlists for 2min + +# Dispatcharr-style segment buffer constants +SEGMENT_CACHE_TTL = 20 # Keep segments for 20s (≈2 manifest cycles) +SEGMENT_CACHE_MAX_ENTRIES = 200 # Max cached segments +SEGMENT_CACHE_MAX_BYTES = 150 * 1024 * 1024 # 150 MB max memory for segment cache +SEGMENT_MAX_SIZE = 15 * 1024 * 1024 # Don't cache segments > 15 MB + + +class RequestCoalescer: + """ + Deduplicates identical concurrent upstream requests. + If 50 clients request the same M3U8 playlist at the same time, + only ONE upstream fetch is made, and all 50 get the same result. + + For M3U8 requests: stores (status, body_bytes, headers_dict) tuples. + The first request performs the actual fetch; concurrent duplicates await + the same future and receive a clone of the response. + """ + __slots__ = ('_pending',) + + def __init__(self): + self._pending: Dict[str, asyncio.Future] = {} + + async def get_or_fetch(self, key: str, fetch_coro): + """Return cached future result or start a new fetch. + + Returns a tuple (is_coalesced: bool, result). + is_coalesced=True means this caller piggy-backed on another request. + """ + if key in self._pending: + result = await self._pending[key] + return (True, result) + + future = asyncio.get_event_loop().create_future() + self._pending[key] = future + + try: + result = await fetch_coro + future.set_result(result) + return (False, result) + except Exception as e: + future.set_exception(e) + raise + finally: + self._pending.pop(key, None) + + +class TTLCache: + """Simple TTL cache with O(1) operations""" + __slots__ = ('_cache', '_maxsize', '_ttl') + + def __init__(self, maxsize: int = 1000, ttl: int = 3600): + self._cache: OrderedDict = OrderedDict() + self._maxsize = maxsize + self._ttl = ttl + + def get(self, key: str) -> Optional[Any]: + if key not in self._cache: + return None + data, timestamp = self._cache[key] + if time.time() - timestamp > self._ttl: + del self._cache[key] + return None + # Move to end for LRU + self._cache.move_to_end(key) + return data + + def set(self, key: str, value: Any) -> None: + if key in self._cache: + del self._cache[key] + elif len(self._cache) >= self._maxsize: + self._cache.popitem(last=False) + self._cache[key] = (value, time.time()) + + def clear_expired(self) -> None: + now = time.time() + expired = [k for k, (_, ts) in self._cache.items() if now - ts > self._ttl] + for k in expired: + del self._cache[k] + + +class SegmentBuffer: + """Dispatcharr-style in-memory segment buffer. + + Caches TS/M4S segments so that N clients watching the same live channel + share a SINGLE upstream fetch per segment. Segments are evicted by: + - TTL expiration (SEGMENT_CACHE_TTL) + - Entry count (SEGMENT_CACHE_MAX_ENTRIES) + - Total memory (SEGMENT_CACHE_MAX_BYTES) + + Thread-safe within a single asyncio event loop (no locks needed). + """ + __slots__ = ('_cache', '_total_bytes', '_ttl', '_max_entries', '_max_bytes') + + def __init__(self, ttl: int = SEGMENT_CACHE_TTL, + max_entries: int = SEGMENT_CACHE_MAX_ENTRIES, + max_bytes: int = SEGMENT_CACHE_MAX_BYTES): + # key -> (data: bytes, timestamp: float, size: int) + self._cache: OrderedDict = OrderedDict() + self._total_bytes = 0 + self._ttl = ttl + self._max_entries = max_entries + self._max_bytes = max_bytes + + def get(self, key: str) -> Optional[bytes]: + """Return cached segment data or None.""" + if key not in self._cache: + return None + data, ts, size = self._cache[key] + if time.time() - ts > self._ttl: + self._cache.pop(key) + self._total_bytes -= size + return None + self._cache.move_to_end(key) + return data + + def put(self, key: str, data: bytes) -> None: + """Cache a segment. Evicts oldest entries if limits exceeded.""" + size = len(data) + if size > SEGMENT_MAX_SIZE: + return # Don't cache oversized segments + + # Remove existing entry if present + if key in self._cache: + _, _, old_size = self._cache.pop(key) + self._total_bytes -= old_size + + # Evict expired entries first + self._evict_expired() + + # Evict oldest until under memory limit + while self._total_bytes + size > self._max_bytes and self._cache: + _, (_, _, evicted_size) = self._cache.popitem(last=False) + self._total_bytes -= evicted_size + + # Evict oldest until under entry count limit + while len(self._cache) >= self._max_entries and self._cache: + _, (_, _, evicted_size) = self._cache.popitem(last=False) + self._total_bytes -= evicted_size + + self._cache[key] = (data, time.time(), size) + self._total_bytes += size + + def _evict_expired(self) -> None: + now = time.time() + while self._cache: + key, (_, ts, size) = next(iter(self._cache.items())) + if now - ts > self._ttl: + self._cache.popitem(last=False) + self._total_bytes -= size + else: + break # OrderedDict is sorted by insertion, oldest first + + @property + def stats(self) -> Dict[str, Any]: + return { + 'entries': len(self._cache), + 'total_bytes': self._total_bytes, + 'total_mb': round(self._total_bytes / (1024 * 1024), 1), + } + + +def encode_url(url: str) -> str: + """Encode URL with XOR + Base64, preserving file extension""" + if not url: + return url + + parsed = urlparse(url) + path_lower = parsed.path.lower() + file_ext = next((ext for ext in KNOWN_EXTENSIONS if ext in path_lower), '') + + url_bytes = url.encode('utf-8') + key_len = len(URL_ENCODE_KEY) + # Fast XOR using bytearray instead of generator + buf = bytearray(len(url_bytes)) + for i in range(len(url_bytes)): + buf[i] = url_bytes[i] ^ URL_ENCODE_KEY[i % key_len] + encoded = base64.urlsafe_b64encode(buf).decode('utf-8').rstrip('=') + + return encoded + file_ext if file_ext else encoded + + +def decode_url(encoded: str) -> str: + """Decode XOR + Base64 encoded URL""" + if not encoded: + return encoded + + try: + clean_encoded = encoded + for ext in KNOWN_EXTENSIONS: + if encoded.lower().endswith(ext): + clean_encoded = encoded[:-len(ext)] + break + + padding_needed = (4 - len(clean_encoded) % 4) % 4 + decoded_bytes = base64.urlsafe_b64decode(clean_encoded + '=' * padding_needed) + + key_len = len(URL_ENCODE_KEY) + # Fast XOR using bytearray instead of generator + buf = bytearray(len(decoded_bytes)) + for i in range(len(decoded_bytes)): + buf[i] = decoded_bytes[i] ^ URL_ENCODE_KEY[i % key_len] + return buf.decode('utf-8') + except Exception as e: + logger.warning(f"Failed to decode URL: {e}") + return encoded + + +@dataclass(frozen=True) +class ContentType: + """Detected content type info""" + is_m3u8: bool = False + is_mp4: bool = False + is_ts: bool = False + is_mpd: bool = False + is_m4s: bool = False + + +def detect_content_type(url: str, accept_header: str = '') -> ContentType: + """Detect content type from URL and Accept header""" + url_lower = url.lower() + accept_lower = accept_header.lower() + + # Treat .txt files that look like M3U8 (usually from specialized providers) as M3U8 for proxy purposes + is_m3u8 = ('.m3u8' in url_lower or + 'application/vnd.apple.mpegurl' in accept_lower or + 'application/x-mpegurl' in accept_lower or + ('.txt' in url_lower and 'application/vnd.apple.mpegurl' in accept_lower) or + ('.txt' in url_lower and ('index-' in url_lower or 'master' in url_lower))) # Heuristic for the .txt m3u8 case + + return ContentType( + is_m3u8=is_m3u8, + is_mp4='.mp4' in url_lower or 'video/mp4' in accept_lower, + is_ts='.ts' in url_lower or 'video/mp2t' in accept_lower, + is_mpd='.mpd' in url_lower or 'application/dash+xml' in accept_lower, + is_m4s='.m4s' in url_lower + ) + + +class ProxyServer: + # Compiled regex patterns (class-level for sharing) + RE_BANDWIDTH = re.compile(r'bandwidth\.com|edgeon-bandwidth\.com', re.IGNORECASE) + RE_VIDZY = re.compile(r'vidzy\.org|v\d+\.vidzy\.org', re.IGNORECASE) + RE_FSVID = re.compile(r'fsvid\.lol', re.IGNORECASE) + RE_SIBNET = re.compile(r'sibnet\.ru|dv\d+\.sibnet\.ru', re.IGNORECASE) + RE_VMWESA = re.compile(r'vmwesa\.online|vidmoly|getromes\.space', re.IGNORECASE) + RE_FAMILYRESTREAM = re.compile(r'familyrestream\.com', re.IGNORECASE) + RE_SOSPLAY = re.compile(r'srvagu|6522236688\.shop|vuunov|1396168994\.live', re.IGNORECASE) + RE_WITV = re.compile(r'lansdrud\.space', re.IGNORECASE) + RE_UQLOAD_EMBED = re.compile(r'uqload\.(cx|com|net|bz)/(embed-)?[^/]+\.html', re.IGNORECASE) + RE_UQLOAD = re.compile(r'uqload\.(cx|com|bz|net|org|to|io|co)', re.IGNORECASE) + RE_NIGGAFLIX = re.compile(r'cdn\.niggaflix\.xyz', re.IGNORECASE) + RE_DROPCDN = re.compile(r'dropcdn', re.IGNORECASE) + RE_SERVERSICURO = re.compile(r'serversicuro', re.IGNORECASE) + RE_MERI = re.compile(r'merichunidya\.com', re.IGNORECASE) + # Streaming CDN patterns: numeric domains, epic*, quest*, hero*, etc. + RE_NUMERIC_CDN = re.compile(r'([a-z0-9]+\.\d+\.net|epicquest|questher|hero.*\.com|trainer\.net|dishtrainer)', re.IGNORECASE) + RE_DOODSTREAM = re.compile(r'd0000d\.com|doodstream\.com|dood\.(cx|la|pm|sh|so|to|watch|wf|yt|re)|cloudatacdn\.com|dsvplay\.com|doply\.net', re.IGNORECASE) + RE_DOODSTREAM_PASS = re.compile(r'/pass_md5/[\w-]+/(?P[\w-]+)') + RE_SEEKSTREAMING = re.compile(r'embed4me\.com|lpayer\.embed4me\.com|servicecatalog\.site|embedseek\.com', re.IGNORECASE) + RE_RANGE = re.compile(r'bytes=(\d+)-(\d*)') + RE_M3U8_URI_DQ = re.compile(r'URI="([^"]+)"', re.IGNORECASE) + RE_M3U8_URI_SQ = re.compile(r"URI='([^']+)'", re.IGNORECASE) + RE_M3U8_URI_UQ = re.compile(r"\bURI=([^\"'\s,][^,\s]*)", re.IGNORECASE) + RE_M3U8_HTTP = re.compile(r'^https?://', re.IGNORECASE) + + def __init__(self): + # High-performance application configuration + self.app = web.Application( + client_max_size=0, # No request size limit + handler_args={ + 'tcp_keepalive': True, + } + ) + + # TTL Caches - Sized based on observed usage patterns + self.voe_cache = TTLCache(maxsize=1000, ttl=7200) + self.fsvid_cache = TTLCache(maxsize=500, ttl=60) + self.vidzy_cache = TTLCache(maxsize=1500, ttl=7200) # Was saturating at 554/500 + self.vidmoly_cache = TTLCache(maxsize=500, ttl=600) + self.sibnet_cache = TTLCache(maxsize=500, ttl=7200) + self.uqload_cache = TTLCache(maxsize=2500, ttl=7200) # Was saturating at 1003/500 + self.uqload_mp4_cache = TTLCache(maxsize=2500, ttl=7200) + self.doodstream_cache = TTLCache(maxsize=500, ttl=3600) # 1h - doodstream links expire + self.seekstreaming_cache = TTLCache(maxsize=500, ttl=7200) # 2h - embed4me/seekstreaming + self.vip_cache = TTLCache(maxsize=5000, ttl=VIP_CACHE_TTL) # VIP access key verification cache + self.m3u8_response_cache = TTLCache(maxsize=2000, ttl=M3U8_CACHE_TTL) # Short-lived M3U8 response cache + self.m3u8_vod_cache = TTLCache(maxsize=1000, ttl=M3U8_VOD_CACHE_TTL) # Longer-lived VOD M3U8 cache + self.cache_duration = 300 # 5 minutes + + # Request coalescer - deduplicates identical concurrent requests + self.coalescer = RequestCoalescer() + + # Dispatcharr-style segment buffer - caches TS/M4S segments in memory + # so N clients watching the same channel share ONE upstream fetch + self.segment_buffer = SegmentBuffer() + + # SSL context for problematic domains + self.ssl_context = ssl.create_default_context() + self.ssl_context.check_hostname = False + self.ssl_context.verify_mode = ssl.CERT_NONE + + self.setup_routes() + self.setup_cors() + + # Sessions container + self.sessions = {} + + # MySQL pool (initialized async in start_server) + self.mysql_pool = None + + # Performance metrics + self._request_count = 0 + self._active_streams = 0 + self._bandwidth_saved = 0 # Track bytes saved by compression/caching + self._cache_hits = 0 + self._coalesced_requests = 0 + self._coalesced_segments = 0 + self._segment_cache_hits = 0 + + async def _init_mysql(self): + """Initialize the MySQL connection pool for direct VIP verification""" + try: + self.mysql_pool = await aiomysql.create_pool( + host=DB_CONFIG['host'], + port=DB_CONFIG['port'], + user=DB_CONFIG['user'], + password=DB_CONFIG['password'], + db=DB_CONFIG['db'], + minsize=DB_CONFIG['minsize'], + maxsize=DB_CONFIG['maxsize'], + autocommit=DB_CONFIG['autocommit'], + charset='utf8mb4', + ) + # Test connection + async with self.mysql_pool.acquire() as conn: + async with conn.cursor() as cur: + await cur.execute('SELECT 1') + logger.info('✅ MySQL connection pool created (VIP verification)') + except Exception as e: + logger.error(f'❌ MySQL connection error: {e}') + self.mysql_pool = None + + async def _init_sessions(self): + """Initialize persistent sessions - OPTIMIZED FOR HIGH LOAD""" + + # Shared connector settings for maximum performance + base_connector_args = { + 'limit': 0, # NO CONNECTION LIMIT + 'limit_per_host': 0, # NO PER-HOST LIMIT + 'keepalive_timeout': KEEPALIVE_TIMEOUT, + 'enable_cleanup_closed': True, + 'ttl_dns_cache': DNS_CACHE_TTL, + 'force_close': False, # Reuse connections aggressively + 'use_dns_cache': True, + } + + # Normal Session - Maximum performance + self.sessions['normal'] = aiohttp.ClientSession( + connector=TCPConnector( + ssl=True, + **base_connector_args + ), + timeout=ClientTimeout(total=None), # No global timeout + read_bufsize=SOCKET_READ_BUFFER, + ) + + # No SSL Session - For problematic domains + self.sessions['no_ssl'] = aiohttp.ClientSession( + connector=TCPConnector( + ssl=self.ssl_context, + **base_connector_args + ), + timeout=ClientTimeout(total=None), + read_bufsize=SOCKET_READ_BUFFER, + ) + + # Proxy Sessions - Optimized for SOCKS5 + for i, proxy in enumerate(PROXIES): + if proxy and proxy.get('host') and proxy.get('port'): + connector = self._create_socks5_connector(proxy) + self.sessions[f'proxy_{i}'] = aiohttp.ClientSession( + connector=connector, + timeout=ClientTimeout(total=None), + read_bufsize=SOCKET_READ_BUFFER, + ) + + # Sibnet Specific Session + if SIBNET_PROXY_CONFIG and SIBNET_PROXY_CONFIG.get('host') and SIBNET_PROXY_CONFIG.get('port'): + sibnet_connector = self._create_socks5_connector(SIBNET_PROXY_CONFIG) + self.sessions['sibnet'] = aiohttp.ClientSession( + connector=sibnet_connector, + timeout=ClientTimeout(total=None), + read_bufsize=SOCKET_READ_BUFFER, + ) + else: + self.sessions['sibnet'] = self.sessions['normal'] + + @staticmethod + def _is_francetv_url(url: str) -> bool: + """Detect URLs that require a French IP (france.tv CDN domains).""" + try: + host = urllib.parse.urlparse(url).hostname or '' + return host.endswith('.ftven.fr') or host.endswith('.francetv.fr') or host.endswith('.france.tv') + except Exception: + return False + + def _get_session(self, service: str, url: str, use_proxy: Optional[int] = None) -> aiohttp.ClientSession: + """Get appropriate session for request. + + Args: + use_proxy: If set, force use of proxy_{N} session (0=first SOCKS5, 1=second, etc.) + """ + # Explicit proxy override from use_proxy parameter + if use_proxy is not None: + key = f'proxy_{use_proxy}' + if key in self.sessions: + return self.sessions[key] + # Fallback: try proxy_0 if requested index doesn't exist + logger.warning(f'Requested proxy_{use_proxy} not available, falling back') + return self.sessions.get('proxy_0', self.sessions['normal']) + + if service == 'bandwidth': + return self.sessions.get('proxy_0', self.sessions['normal']) + elif service == 'vmwesa': + return self.sessions.get('proxy_1', self.sessions.get('proxy_0', self.sessions['normal'])) + elif service == 'sibnet': + return self.sessions.get('sibnet', self.sessions['normal']) + + # France.tv CDN needs French proxy + if self._is_francetv_url(url): + return self.sessions.get('proxy_0', self.sessions['normal']) + + # Check SSL + if self._should_disable_ssl(url): + return self.sessions['no_ssl'] + + return self.sessions['normal'] + + def _make_cors_response(self, body: bytes = b'', status: int = 200, + headers: Optional[Dict] = None, content_type: str = None) -> Response: + """Create response with CORS headers""" + resp_headers = dict(CORS_HEADERS) + if headers: + resp_headers.update(headers) + if content_type: + resp_headers['Content-Type'] = content_type + return _safe_response(body, status, resp_headers) + + def _prepare_stream_headers(self, upstream_headers: Dict, content_type: str = None, + include_range: bool = False, range_info: Dict = None) -> Dict: + """Prepare headers for streaming response""" + excluded = frozenset(['transfer-encoding', 'connection', 'content-encoding']) + headers = {k: v for k, v in upstream_headers.items() if k.lower() not in excluded} + headers.update(CORS_HEADERS) + + if content_type: + headers['Content-Type'] = content_type + + if include_range and range_info: + if 'content_range' in range_info: + headers['Content-Range'] = range_info['content_range'] + if 'content_length' in range_info: + headers['Content-Length'] = range_info['content_length'] + headers['Accept-Ranges'] = 'bytes' + + return headers + + async def _stream_response(self, request: Request, upstream_response, + headers: Dict, chunk_size: int = CHUNK_DEFAULT) -> Response: + """ + ULTRA-OPTIMIZED streaming response handler for high load + Features: + - Adaptive chunk sizing based on transfer speed + - Minimal overhead with direct buffer writes + - Graceful connection handling + - Zero-copy when possible + """ + resp = _safe_stream_response(upstream_response.status, headers) + + # Track active streams for metrics + self._active_streams += 1 + + try: + await resp.prepare(request) + except (ConnectionResetError, ConnectionAbortedError): + self._active_streams -= 1 + return resp + + try: + async for chunk in upstream_response.content.iter_chunked(chunk_size): + try: + await resp.write(chunk) + except (ConnectionResetError, ConnectionAbortedError, BrokenPipeError, OSError): + # Client disconnected - normal for video seeking + break + + # Finalize response + try: + await resp.write_eof() + except (ConnectionResetError, ConnectionAbortedError, BrokenPipeError, RuntimeError, OSError): + pass + + except asyncio.CancelledError: + pass + except Exception as e: + err_str = str(e).lower() + if 'closing transport' not in err_str and 'connection reset' not in err_str: + logger.debug(f'Stream ended: {type(e).__name__}') + finally: + self._active_streams -= 1 + + return resp + + async def _stream_response_fast(self, request: Request, upstream_response, + headers: Dict, chunk_size: int = CHUNK_LARGE) -> Response: + """ + FASTEST streaming for large files (MP4, large TS files) + Uses maximum chunk size and minimal processing + """ + resp = _safe_stream_response(upstream_response.status, headers) + self._active_streams += 1 + + try: + await resp.prepare(request) + except (ConnectionResetError, ConnectionAbortedError): + self._active_streams -= 1 + return resp + + try: + # Stream with maximum chunk size for throughput + async for chunk in upstream_response.content.iter_any(): + try: + await resp.write(chunk) + except (ConnectionResetError, ConnectionAbortedError, BrokenPipeError, OSError): + break + + try: + await resp.write_eof() + except: + pass + + except asyncio.CancelledError: + pass + except: + pass + finally: + self._active_streams -= 1 + + return resp + + async def _stream_response_with_prefix(self, request: Request, upstream_response, + headers: Dict, prefix: bytes, + chunk_size: int = CHUNK_DEFAULT) -> Response: + """Stream response after consuming a small probe prefix from upstream.""" + resp = _safe_stream_response(upstream_response.status, headers) + self._active_streams += 1 + + try: + await resp.prepare(request) + except (ConnectionResetError, ConnectionAbortedError): + self._active_streams -= 1 + return resp + + try: + if prefix: + await resp.write(prefix) + + async for chunk in upstream_response.content.iter_chunked(chunk_size): + try: + await resp.write(chunk) + except (ConnectionResetError, ConnectionAbortedError, BrokenPipeError, OSError): + break + + try: + await resp.write_eof() + except: + pass + + except asyncio.CancelledError: + pass + except: + pass + finally: + self._active_streams -= 1 + + return resp + + async def _handle_m3u8_response(self, response, target_url: str, headers: Dict, + is_bandwidth: bool = False, is_sosplay: bool = False, + is_witv: bool = False, custom_headers: Optional[Dict] = None, + request: Request = None, use_proxy: Optional[int] = None, + raw_body: Optional[bytes] = None) -> Optional[Response]: + """Handle M3U8 content rewriting with compression, caching, and ETag support""" + content = raw_body if raw_body is not None else await response.read() + try: + text_content = content.decode('utf-8') + if self._is_valid_m3u8(text_content): + modified_content = await self._rewrite_m3u8_urls( + text_content, target_url, is_bandwidth, is_sosplay, is_witv, custom_headers, + use_proxy=use_proxy + ) + response_body = modified_content.encode('utf-8') + original_size = len(response_body) + + headers['Content-Type'] = 'application/vnd.apple.mpegurl' + headers.pop('Content-Length', None) + headers.pop('content-length', None) + + # Determine if VOD (has ENDLIST) for cache duration + is_vod = '#EXT-X-ENDLIST' in text_content + if is_vod: + headers['Cache-Control'] = f'public, max-age={M3U8_VOD_CACHE_TTL}' + else: + headers['Cache-Control'] = 'no-cache' # Live playlists must not be stale + + # ETag support - allows 304 Not Modified responses + etag = hashlib.md5(response_body).hexdigest() + headers['ETag'] = f'"{etag}"' + + if request: + if_none_match = request.headers.get('If-None-Match', '') + if if_none_match == f'"{etag}"': + self._cache_hits += 1 + self._bandwidth_saved += original_size + return _safe_response(b'', 304, headers) + + headers['Content-Length'] = str(original_size) + return _safe_response(response_body, response.status, headers) + except UnicodeDecodeError: + pass + + # Content is NOT valid M3U8 (HTML error page, empty body, binary, etc.) + # Return a clear error so the player fails fast instead of retrying forever. + body_text = content.decode('utf-8', errors='replace') if content else '(empty)' + logger.warning(f"[PROXY] M3U8 URL returned non-M3U8 content (status={response.status}, len={len(content)}): {target_url} — body preview: {body_text[:200]}") + error_headers = dict(CORS_HEADERS) + error_headers['Cache-Control'] = 'no-cache' + return web.json_response( + { + 'error': 'Invalid stream: upstream did not return valid M3U8 content', + 'upstream_status': response.status, + 'upstream_url': target_url, + 'upstream_body': body_text[:2000] + }, + status=502, + headers=error_headers + ) + + def setup_cors(self): + """Configure CORS middleware""" + @web.middleware + async def cors_handler(request: Request, handler): + if request.method == 'OPTIONS': + return web.Response(headers=CORS_HEADERS) + response = await handler(request) + for k, v in CORS_HEADERS.items(): + response.headers[k] = v + + return response + + self.app.middlewares.append(cors_handler) + + def _should_disable_ssl(self, url: str) -> bool: + """Check if SSL verification should be disabled""" + try: + domain = urlparse(url).netloc.lower() + if domain in PROBLEMATIC_DOMAINS: + return True + return any(kw in domain for kw in ('edgeon-bandwidth', 'vidzy')) + except: + return False + + def _get_random_proxy(self) -> Dict: + return random.choice(PROXIES) + + def _create_socks5_connector(self, proxy: Dict) -> ProxyConnector: + """Create SOCKS5 connector with connection pooling""" + return ProxyConnector.from_url( + f"socks5://{proxy['auth']}@{proxy['host']}:{proxy['port']}", + rdns=True, + limit=0 + ) + + def setup_routes(self): + """Configure server routes""" + # Global proxy (fallback) + self.app.router.add_get('/proxy', self.proxy_handler) + self.app.router.add_get('/proxy/{path:.*}', self.proxy_handler) + + # Extraction endpoints + self.app.router.add_get('/api/voe/m3u8', self.voe_m3u8_handler) + self.app.router.add_get('/api/extract-fsvid', self.fsvid_extract_handler) + self.app.router.add_get('/api/extract-vidzy', self.vidzy_extract_handler) + self.app.router.add_get('/api/extract-vidmoly', self.vidmoly_extract_handler) + self.app.router.add_get('/api/extract-sibnet', self.sibnet_extract_handler) + self.app.router.add_get('/api/extract-uqload', self.uqload_extract_handler) + self.app.router.add_get('/api/extract-doodstream', self.doodstream_extract_handler) + self.app.router.add_get('/api/extract-seekstreaming', self.seekstreaming_extract_handler) + + # Service-specific proxy routes (dedicated headers, no regex detection needed) + self.app.router.add_get('/voe-proxy', self.voe_proxy_handler) + self.app.router.add_get('/fsvid-proxy', self.fsvid_proxy_handler) + self.app.router.add_get('/vidzy-proxy', self.vidzy_proxy_handler) + self.app.router.add_get('/vidmoly-proxy', self.vidmoly_proxy_handler) + self.app.router.add_get('/sibnet-proxy', self.sibnet_proxy_handler) + self.app.router.add_get('/uqload-proxy', self.uqload_proxy_handler) + self.app.router.add_get('/doodstream-proxy', self.doodstream_proxy_handler) + self.app.router.add_get('/seekstreaming-proxy', self.seekstreaming_proxy_handler) + self.app.router.add_get('/cinep-proxy', self.cinep_proxy_handler) + # DRM Proxy routes (widefrog integration, API-only) + self.app.router.add_get('/drm/extract', self.drm_extract_handler) + self.app.router.add_post('/drm/extract', self.drm_extract_handler) + self.app.router.add_get('/drm/manifest', self.drm_manifest_handler) + self.app.router.add_get('/drm/resource', self.drm_resource_handler) + self.app.router.add_get('/drm/b/{base_b64}/{subpath:.*}', self.drm_base_resource_handler) + + # Deepbrid routes + self.app.router.add_post('/api/debrid/unlock', self.debrid_unlock_handler) + + # System + self.app.router.add_get('/health', self.health_handler) + self.app.router.add_get('/stats', self.stats_handler) + + def _extract_debrid_error_message(self, payload: Dict[str, Any], fallback: str) -> str: + """Normalize provider-specific error payloads.""" + error = payload.get('error') + if isinstance(error, dict): + message = error.get('message') + if isinstance(message, str) and message.strip(): + return message + elif isinstance(error, str) and error.strip(): + return error + + message = payload.get('message') + if isinstance(message, str) and message.strip(): + return message + + return fallback + + def _parse_deepbrid_filesize(self, size_str: Any) -> int: + """Convert Deepbrid human-readable sizes to bytes.""" + size_text = str(size_str or '').strip().upper() + try: + if 'GB' in size_text: + return int(float(size_text.replace(' GB', '').replace('GB', '')) * 1073741824) + if 'MB' in size_text: + return int(float(size_text.replace(' MB', '').replace('MB', '')) * 1048576) + if 'KB' in size_text: + return int(float(size_text.replace(' KB', '').replace('KB', '')) * 1024) + if size_text.isdigit(): + return int(size_text) + except (ValueError, TypeError): + return 0 + return 0 + + async def _unlock_with_deepbrid(self, link: str, password: str) -> Response: + """Unlock a link via Deepbrid.""" + if not DEEPBRID_API_KEY: + return web.json_response({'status': 'error', 'error': 'Service de debridage non configure'}, status=503) + + headers = { + 'Authorization': f'Bearer {DEEPBRID_API_KEY}', + } + form_data = aiohttp.FormData() + form_data.add_field('link', link) + if password: + form_data.add_field('pass', password) + + async with aiohttp.ClientSession() as session: + async with session.post( + 'https://www.deepbrid.com/api/v1/generate/link', + headers=headers, + data=form_data, + timeout=ClientTimeout(total=30) + ) as resp: + result = await resp.json(content_type=None) + + if result.get('error') == 0 and result.get('link'): + return web.json_response({ + 'status': 'success', + 'data': { + 'link': result.get('link', ''), + 'filename': result.get('filename', ''), + 'filesize': self._parse_deepbrid_filesize(result.get('size', '')), + 'host': result.get('hoster', ''), + } + }) + + error_msg = self._extract_debrid_error_message(result, 'Erreur lors du debridage') + return web.json_response({'status': 'error', 'error': error_msg}, status=400) + + async def debrid_unlock_handler(self, request: Request) -> Response: + """Unlock a link via the selected debrid provider.""" + if not await self._check_vip(request): + return self._vip_denied_response() + try: + data = await request.json() + link = data.get('link', '').strip() + password = data.get('password', '').strip() + provider = str(data.get('provider', 'deepbrid')).strip().lower() or 'deepbrid' + + if not link: + return web.json_response({'status': 'error', 'error': 'Lien manquant'}, status=400) + + if provider not in DEBRID_PROVIDERS: + return web.json_response({'status': 'error', 'error': 'Provider de debridage invalide'}, status=400) + + return await self._unlock_with_deepbrid(link, password) + + + except asyncio.TimeoutError: + return web.json_response({'status': 'error', 'error': 'Timeout lors du débridage'}, status=504) + except Exception as e: + logger.error(f'[DEBRID] Error unlocking link: {e}') + return web.json_response({'status': 'error', 'error': 'Erreur interne du serveur'}, status=500) + + async def health_handler(self, request: Request) -> Response: + """Quick health check endpoint""" + return web.json_response({ + "status": "ok", + "message": "Ultra High Performance Proxy Server", + "active_streams": self._active_streams + }) + + async def stats_handler(self, request: Request) -> Response: + """Detailed performance statistics endpoint""" + import gc + + # Collect cache stats + cache_stats = { + 'voe_cache': f"{len(self.voe_cache._cache)}/{self.voe_cache._maxsize}", + 'fsvid_cache': f"{len(self.fsvid_cache._cache)}/{self.fsvid_cache._maxsize}", + 'vidzy_cache': f"{len(self.vidzy_cache._cache)}/{self.vidzy_cache._maxsize}", + 'vidmoly_cache': f"{len(self.vidmoly_cache._cache)}/{self.vidmoly_cache._maxsize}", + 'sibnet_cache': f"{len(self.sibnet_cache._cache)}/{self.sibnet_cache._maxsize}", + 'uqload_cache': f"{len(self.uqload_cache._cache)}/{self.uqload_cache._maxsize}", + 'uqload_mp4_cache': f"{len(self.uqload_mp4_cache._cache)}/{self.uqload_mp4_cache._maxsize}", + 'doodstream_cache': f"{len(self.doodstream_cache._cache)}/{self.doodstream_cache._maxsize}", + 'seekstreaming_cache': f"{len(self.seekstreaming_cache._cache)}/{self.seekstreaming_cache._maxsize}", + 'vip_cache': f"{len(self.vip_cache._cache)}/{self.vip_cache._maxsize}", + 'm3u8_response_cache': f"{len(self.m3u8_response_cache._cache)}/{self.m3u8_response_cache._maxsize}", + 'm3u8_vod_cache': f"{len(self.m3u8_vod_cache._cache)}/{self.m3u8_vod_cache._maxsize}", + } + + # Session stats + session_stats = {} + for name, session in self.sessions.items(): + if hasattr(session, 'connector') and session.connector: + connector = session.connector + session_stats[name] = { + 'limit': connector.limit, + 'limit_per_host': connector.limit_per_host, + } + + return web.json_response({ + "status": "ok", + "performance": { + "total_requests": self._request_count, + "active_streams": self._active_streams, + "bandwidth_saved_bytes": self._bandwidth_saved, + "bandwidth_saved_mb": round(self._bandwidth_saved / (1024 * 1024), 2), + "cache_hits": self._cache_hits, + "coalesced_requests": self._coalesced_requests, + "coalesced_segments": self._coalesced_segments, + "segment_cache_hits": self._segment_cache_hits, + "segment_buffer": self.segment_buffer.stats, + "gc_threshold": gc.get_threshold(), + "gc_count": gc.get_count(), + }, + "caches": cache_stats, + "sessions": session_stats, + "config": { + "chunk_ts": CHUNK_TS, + "chunk_mp4": CHUNK_MP4, + "chunk_default": CHUNK_DEFAULT, + "chunk_large": CHUNK_LARGE, + "keepalive_timeout": KEEPALIVE_TIMEOUT, + "dns_cache_ttl": DNS_CACHE_TTL, + "socket_read_buffer": SOCKET_READ_BUFFER, + } + }) + + def _detect_service(self, url: str) -> str: + """Detect which service the URL belongs to""" + if self.RE_BANDWIDTH.search(url): + return 'bandwidth' + if self.RE_VIDZY.search(url): + return 'vidzy' + if self.RE_FSVID.search(url): + return 'fsvid' + if self.RE_SIBNET.search(url): + return 'sibnet' + if self.RE_VMWESA.search(url): + return 'vmwesa' + if self.RE_FAMILYRESTREAM.search(url): + return 'familyrestream' + if self.RE_SOSPLAY.search(url): + return 'sosplay' + if self.RE_WITV.search(url): + return 'witv' + if self.RE_UQLOAD_EMBED.search(url): + return 'uqload_embed' + if self.RE_DOODSTREAM.search(url): + return 'doodstream' + if self.RE_SEEKSTREAMING.search(url): + return 'seekstreaming' + return 'generic' + + async def proxy_handler(self, request: Request) -> Response: + """Main proxy handler - optimized""" + try: + if request.method == 'OPTIONS': + return web.Response(headers=CORS_HEADERS) + + # Extract target URL + path = request.match_info.get('path', '') + if path: + decoded_path = decode_url(path) + target_url = decoded_path if decoded_path.startswith(('http://', 'https://')) else urllib.parse.unquote(path) + else: + target_url = request.query.get('url', '') + if not target_url: + return web.json_response({'error': 'No URL provided'}, status=400) + + # Parse use_proxy parameter (0=first SOCKS5, 1=second, etc.) + use_proxy_param = request.query.get('use_proxy') + use_proxy = int(use_proxy_param) if use_proxy_param is not None and use_proxy_param.isdigit() else None + + # Reconstruct split query parameters (handles unencoded URLs) + query_params = [] + for k, v in request.query.items(): + if k not in ('url', 'headers', 'referer', 'origin', 'user_agent', 'user-agent', 'sosplay', 'use_proxy'): + query_params.append((k, v)) + + if query_params: + target_url += ('&' if '?' in target_url else '?') + urllib.parse.urlencode(query_params) + + # Parse and clean URL + parsed_target = urlparse(target_url) + + # Check for sosplay mode (forces streaming CDN headers) + sosplay_mode = request.query.get('sosplay', '').lower() == 'true' + + # Extract custom headers + custom_headers = {} + headers_param = request.query.get('headers') + if not headers_param and parsed_target.query: + url_params = urllib.parse.parse_qs(parsed_target.query) + headers_param = url_params.get('headers', [None])[0] + + if headers_param: + try: + custom_headers = json.loads(headers_param) + except Exception as e: + logger.error(f"Failed to parse custom headers: {e}, param: {headers_param}") + pass + + shortcut_headers = {} + shortcut_header_map = { + 'referer': 'Referer', + 'origin': 'Origin', + 'user_agent': 'User-Agent', + 'user-agent': 'User-Agent', + } + for query_key, header_key in shortcut_header_map.items(): + shortcut_value = request.query.get(query_key) + if shortcut_value: + shortcut_headers[header_key] = shortcut_value + + if shortcut_headers: + custom_headers = {**custom_headers, **shortcut_headers} + + # Clean proxy-specific params from target URL + proxy_params = {'headers', 'referer', 'origin', 'user_agent', 'user-agent', 'url', 'sosplay', 'use_proxy'} + if parsed_target.query: + existing_params = urllib.parse.parse_qs(parsed_target.query, keep_blank_values=True) + for p in proxy_params: + existing_params.pop(p, None) + + if existing_params: + query_parts = [f'{k}={v[0] if isinstance(v, list) and len(v) == 1 else v}' + for k, vals in existing_params.items() + for v in (vals if isinstance(vals, list) else [vals])] + target_url = f"{parsed_target.scheme}://{parsed_target.netloc}{parsed_target.path}" + if query_parts: + target_url += '?' + '&'.join(query_parts) + + # Fix recursive proxy + target_url = re.sub(r'localhost(:\d+)?/proxy/', '', target_url, flags=re.IGNORECASE) + + if not target_url.startswith(('http://', 'https://')): + target_url = 'https://' + target_url + + # Fix malformed URLs with multiple slashes (e.g., https:////domain.com -> https://domain.com) + target_url = re.sub(r'^(https?:)/{2,}', r'\1//', target_url) + + # Validate URL before making request + try: + validated_parsed = urlparse(target_url) + if not validated_parsed.netloc: + return web.json_response({'error': 'Invalid URL: missing domain'}, status=400, headers=CORS_HEADERS) + + # Check domain label length (DNS limit is 63 chars per label) + domain_labels = validated_parsed.netloc.split('.') + for label in domain_labels: + # Remove port if present + label_clean = label.split(':')[0] if ':' in label else label + if len(label_clean) > 63: + return web.json_response({'error': f'Invalid URL: domain label too long ({len(label_clean)} > 63 chars)'}, status=400, headers=CORS_HEADERS) + + # Test IDNA encoding to catch issues early + validated_parsed.netloc.encode('idna') + except UnicodeError as e: + logger.warning(f'Invalid URL encoding rejected: {e}') + return web.json_response({'error': f'Invalid URL encoding: {str(e)}'}, status=400, headers=CORS_HEADERS) + except Exception as e: + logger.warning(f'URL validation failed: {e}') + return web.json_response({'error': f'Invalid URL: {str(e)}'}, status=400, headers=CORS_HEADERS) + + # Detect content type + content = detect_content_type(target_url, request.headers.get('accept', '')) + is_bandwidth = 'edgeon-bandwidth.com' in target_url.lower() + + # Prepare headers + headers = self._prepare_headers(target_url, request) + if custom_headers: + headers.update(self._normalize_custom_headers(custom_headers)) + headers = self._ensure_origin_matches_referer(headers) + + # Range header + range_header = request.headers.get('range') or request.headers.get('Range') + if range_header and content.is_mp4: + headers['Range'] = range_header + + # Configure timeout based on content type and service + service = self._detect_service(target_url) + + # Debug logs (use DEBUG level to avoid I/O overhead on every request) + if logger.isEnabledFor(logging.DEBUG): + logger.debug(f"Target URL: {target_url}") + logger.debug(f"Custom Headers: {custom_headers}") + logger.debug(f"Final Headers: {headers}") + + # Override service detection if sosplay mode is enabled + if sosplay_mode: + service = 'sosplay_cdn' + + if content.is_m3u8: + # M3U8 playlists ALWAYS get a total timeout — they are small files. + # Without this, sosplay/witv M3U8 requests could hang forever. + timeout = ClientTimeout(total=30, connect=10, sock_read=20) + elif content.is_mp4 and range_header: + timeout = ClientTimeout(total=None, connect=10, sock_read=30) + elif content.is_mp4: + timeout = ClientTimeout(total=60, connect=10, sock_read=30) + elif content.is_ts or content.is_m4s: + # TS/M4S segments need longer timeouts for slow servers + timeout = ClientTimeout(total=None, connect=10, sock_read=60) + elif service in ('familyrestream', 'fsvid', 'sosplay', 'witv'): + # Streaming services need longer timeouts for non-playlist content + timeout = ClientTimeout(total=None, connect=15, sock_read=60) + else: + # Unknown content: use no total timeout so live IPTV streams + # (extensionless URLs) are not killed after 15s. + # sock_read guards against truly dead connections. + timeout = ClientTimeout(total=None, connect=10, sock_read=30) + + # Route to service handler + + return await self._handle_service_request( + request, target_url, headers, timeout, content, + service, range_header, is_bandwidth, sosplay_mode, custom_headers, + use_proxy=use_proxy + ) + + except Exception as error: + logger.exception('Proxy error') + return web.json_response( + { + 'error': 'Proxy error', + 'exception': type(error).__name__, + 'message': str(error) or None, + 'details': repr(error), + }, + status=500, + headers=CORS_HEADERS, + ) + + async def _fetch_m3u8_upstream(self, target_url: str, headers: Dict, + timeout: ClientTimeout, content: ContentType, + service: str, is_bandwidth: bool, + sosplay_mode: bool, custom_headers: Optional[Dict], + request: Request, use_proxy: Optional[int], + session) -> Tuple[int, bytes, Dict[str, str], Optional[str]]: + """Fetch an M3U8 playlist upstream and return serialisable result. + + Returns (status, body, headers_dict, redirect_location_or_None). + This method is designed to be wrapped by RequestCoalescer so that + concurrent identical requests only perform ONE upstream fetch. + """ + async with session.request('GET', target_url, headers=headers, + timeout=timeout, + allow_redirects=False) as response: + resp_headers = self._prepare_stream_headers(response.headers) + + # Redirects + if 300 <= response.status < 400: + location = response.headers.get('location') or response.headers.get('Location') + if location: + abs_location = location + if not abs_location.startswith(('http://', 'https://')): + abs_location = urljoin(target_url, abs_location) + encoded_location = encode_url(abs_location) + query_parts = [] + if custom_headers: + query_parts.append('headers=' + urllib.parse.quote(json.dumps(custom_headers))) + if use_proxy is not None: + query_parts.append(f'use_proxy={use_proxy}') + suffix = ('?' + '&'.join(query_parts)) if query_parts else '' + proxied_location = f"/proxy/{encoded_location}{suffix}" + return (response.status, b'', {**CORS_HEADERS, 'Cache-Control': 'no-cache'}, proxied_location) + + # Upstream HTTP errors + if response.status >= 400: + err_body = await response.read() + err_text = err_body.decode('utf-8', errors='replace') if err_body else '(empty)' + logger.warning(f"[PROXY] Upstream HTTP {response.status} for {target_url} — headers_sent: {headers} — body: {err_text[:200]}") + body = json.dumps({ + 'error': f'Upstream HTTP error: {response.status}', + 'upstream_status': response.status, + 'upstream_url': target_url, + 'upstream_body': err_text[:2000] + }).encode() + return (response.status, body, {**CORS_HEADERS, 'Content-Type': 'application/json'}, None) + + # Read M3U8 body (small file, safe to buffer fully) + m3u8_probe = await response.content.read(2048) + if m3u8_probe and self._is_valid_m3u8(m3u8_probe.decode('utf-8', errors='ignore')): + rest = await response.content.read(10 * 1024 * 1024) + raw_body = m3u8_probe + rest + m3u8_resp = await self._handle_m3u8_response( + response, target_url, resp_headers, is_bandwidth, + is_sosplay=(service in ('sosplay', 'sosplay_cdn') or sosplay_mode), + is_witv=(service == 'witv'), + custom_headers=custom_headers, + request=request, + use_proxy=use_proxy, + raw_body=raw_body + ) + if m3u8_resp is not None: + return (m3u8_resp.status, m3u8_resp.body, dict(m3u8_resp.headers), None) + return (502, json.dumps({ + 'error': 'Failed to process M3U8 stream', + 'upstream_url': target_url + }).encode(), {**CORS_HEADERS, 'Content-Type': 'application/json'}, None) + + # Not a valid M3U8 despite URL/content-type — return probe bytes + # so caller can fall back to streaming + return (-1, m3u8_probe or b'', dict(resp_headers), None) + + async def _fetch_segment_upstream(self, target_url: str, headers: Dict, + timeout: ClientTimeout, session, + custom_headers: Optional[Dict], + use_proxy: Optional[int]) -> Tuple[int, bytes, Dict[str, str], Optional[str]]: + """Fetch a TS/M4S segment upstream and return buffered result. + + Returns (status, body_bytes, headers_dict, redirect_location_or_None). + Designed to be wrapped by RequestCoalescer so N concurrent requests + for the same segment only perform ONE upstream fetch (Dispatcharr-style). + """ + async with session.request('GET', target_url, headers=headers, + timeout=timeout, + allow_redirects=False) as response: + resp_headers = self._prepare_stream_headers(response.headers) + + # Redirects — rewrite location through proxy + if 300 <= response.status < 400: + location = response.headers.get('location') or response.headers.get('Location') + if location: + abs_location = location + if not abs_location.startswith(('http://', 'https://')): + abs_location = urljoin(target_url, abs_location) + encoded_location = encode_url(abs_location) + query_parts = [] + if custom_headers: + query_parts.append('headers=' + urllib.parse.quote(json.dumps(custom_headers))) + if use_proxy is not None: + query_parts.append(f'use_proxy={use_proxy}') + suffix = ('?' + '&'.join(query_parts)) if query_parts else '' + proxied_location = f"/proxy/{encoded_location}{suffix}" + return (response.status, b'', {**CORS_HEADERS, 'Cache-Control': 'no-cache'}, proxied_location) + + # Upstream errors + if response.status >= 400: + err_body = await response.read() + err_text = err_body.decode('utf-8', errors='replace') if err_body else '(empty)' + logger.warning(f"[PROXY] Upstream HTTP {response.status} for segment {target_url} — headers_sent: {headers}") + body = json.dumps({ + 'error': f'Upstream HTTP error: {response.status}', + 'upstream_status': response.status, + }).encode() + return (response.status, body, {**CORS_HEADERS, 'Content-Type': 'application/json'}, None) + + # Buffer the full segment (live TS segments are typically 1-8 MB) + body = await response.read() + return (response.status, body, dict(resp_headers), None) + + async def _handle_service_request(self, request: Request, target_url: str, + headers: Dict, timeout: ClientTimeout, + content: ContentType, service: str, + range_header: Optional[str], is_bandwidth: bool, + sosplay_mode: bool = False, + custom_headers: Optional[Dict] = None, + use_proxy: Optional[int] = None) -> Response: + """ + ULTRA-OPTIMIZED service request handler for high load + Features: + - Uses fast streaming for large files + - Minimal logging overhead + - Request counting for metrics + - Optimized error handling + - M3U8 request coalescing (identical concurrent requests → single upstream fetch) + """ + + self._request_count += 1 + + # Get session - already optimized for pooling + session = self._get_session(service, target_url, use_proxy=use_proxy) + + # Handle UQLOAD embed specially + if service == 'uqload_embed': + return await self._handle_uqload_embed(request, target_url, headers, timeout, range_header, session) + + # Service-specific headers (minimal overhead) + # Note: If custom_headers is provided (from embed extraction), they are already merged in proxy_handler + # so we don't need sosplay_cdn special handling anymore + + if service == 'familyrestream': + headers = { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/114.0.0.0 Safari/537.36', + 'Accept': '*/*, application/vnd.apple.mpegurl', + 'Connection': 'keep-alive' + } + if range_header: + headers['Range'] = range_header + + elif service == 'sosplay': + headers = { + 'User-Agent': headers.get('User-Agent', 'Mozilla/5.0 Chrome/120.0.0.0'), + 'Accept': '*/*', + 'Referer': 'https://notoriousleash.net/', + 'Origin': 'https://notoriousleash.net', + 'Connection': 'keep-alive' + } + + elif service == 'witv': + headers = { + 'User-Agent': 'Mozilla/5.0 Chrome/120.0.0.0', + 'Accept': '*/*', + 'Accept-Language': 'fr-FR,fr;q=0.9', + 'Accept-Encoding': 'identity', + 'Origin': 'https://witv.website', + 'Referer': 'https://witv.website/', + 'Sec-Fetch-Mode': 'cors', + 'Connection': 'keep-alive' + } + + if custom_headers: + headers.update(self._normalize_custom_headers(custom_headers)) + + headers = self._ensure_origin_matches_referer(headers) + + try: + # ── M3U8 cache + coalescing path ────────────────────────────── + # 1. Check server-side M3U8 cache (VOD=120s, live=5s) + # 2. If miss, coalesce concurrent fetches (1 upstream for N clients) + # 3. Store result in appropriate cache + if content.is_m3u8: + cache_key = target_url + + # 1. Check caches (VOD first — longer TTL, more likely hit) + cached = self.m3u8_vod_cache.get(cache_key) or self.m3u8_response_cache.get(cache_key) + if cached is not None: + self._cache_hits += 1 + status, body, resp_hdrs, redirect_loc = cached + if redirect_loc: + return web.Response( + status=status, + headers={**resp_hdrs, 'Location': redirect_loc}, + ) + return web.Response(body=body, status=status, headers=resp_hdrs) + + # 2. Coalesce concurrent requests (1 fetch for N clients) + coalesce_key = target_url + is_coalesced, result = await self.coalescer.get_or_fetch( + coalesce_key, + self._fetch_m3u8_upstream( + target_url, headers, timeout, content, service, + is_bandwidth, sosplay_mode, custom_headers, request, + use_proxy, session + ) + ) + status, body, resp_hdrs, redirect_loc = result + + if is_coalesced: + self._coalesced_requests += 1 + if logger.isEnabledFor(logging.DEBUG): + logger.debug(f"[COALESCE] M3U8 piggy-backed for {target_url}") + + # 3. Store in cache (skip errors and non-M3U8 probes) + if status == 200 and body: + if b'#EXT-X-ENDLIST' in body: + self.m3u8_vod_cache.set(cache_key, result) + else: + self.m3u8_response_cache.set(cache_key, result) + + # status == -1 means probe showed it's not a real M3U8 + # (binary IPTV stream with wrong Content-Type). + # Fall through to generic path which opens its own request. + if status != -1: + if redirect_loc: + return web.Response( + status=status, + headers={**resp_hdrs, 'Location': redirect_loc}, + ) + return web.Response(body=body, status=status, headers=resp_hdrs) + + # ── TS/M4S segment coalescing + cache (Dispatcharr-style) ───── + # N clients watching the same live channel request the same segments. + # 1. Check in-memory SegmentBuffer (instant, no upstream fetch) + # 2. If miss, coalesce concurrent requests (1 fetch for N clients) + # 3. Store result in SegmentBuffer for next clients + if content.is_ts or content.is_m4s: + is_ts = content.is_ts + ct = 'video/mp2t' if is_ts else 'video/iso.segment' + seg_headers = { + **CORS_HEADERS, + 'Content-Type': ct, + 'Cache-Control': 'public, max-age=86400, immutable', + 'Accept-Ranges': 'bytes', + } + + # 1. Check segment buffer cache + cached_data = self.segment_buffer.get(target_url) + if cached_data is not None: + self._segment_cache_hits += 1 + self._cache_hits += 1 + seg_headers['Content-Length'] = str(len(cached_data)) + seg_headers['X-Segment-Cache'] = 'HIT' + return web.Response(body=cached_data, status=200, headers=seg_headers) + + # 2. Coalesce concurrent requests + coalesce_key = f"seg:{target_url}" + is_coalesced, result = await self.coalescer.get_or_fetch( + coalesce_key, + self._fetch_segment_upstream( + target_url, headers, timeout, session, + custom_headers, use_proxy + ) + ) + status, body, resp_hdrs, redirect_loc = result + + if is_coalesced: + self._coalesced_segments += 1 + + # Handle redirect + if redirect_loc: + return web.Response( + status=status, + headers={**resp_hdrs, 'Location': redirect_loc}, + ) + + # Handle error + if status >= 400: + return web.Response(body=body, status=status, headers=resp_hdrs) + + # 3. Store in segment buffer for next clients + if status == 200 and body: + self.segment_buffer.put(target_url, body) + + seg_headers.update(resp_hdrs) + seg_headers['Content-Type'] = ct + seg_headers['Content-Length'] = str(len(body)) + seg_headers['X-Segment-Cache'] = 'COALESCED' if is_coalesced else 'MISS' + return web.Response(body=body, status=status, headers=seg_headers) + + # ── Generic (non-M3U8, non-segment) path ───────────────────── + # We must not auto-follow redirects here. + # If upstream returns 302/301, we forward that status + Location back to the client. + allow_redirects = False + + async with session.request('GET', target_url, headers=headers, + timeout=timeout, + allow_redirects=allow_redirects) as response: + + resp_headers = self._prepare_stream_headers(response.headers) + response_content_type = (response.headers.get('Content-Type') or '').lower() + is_m3u8_response = ( + 'mpegurl' in response_content_type + or str(response.url).lower().split('?', 1)[0].endswith('.m3u8') + ) + + # Pass through redirects (302/301/307/308, etc.) while keeping the client inside the proxy. + # This is important for some providers that redirect to a different CDN hostname. + if 300 <= response.status < 400: + location = response.headers.get('location') or response.headers.get('Location') + if location: + try: + abs_location = location + if not abs_location.startswith(('http://', 'https://')): + abs_location = urljoin(target_url, abs_location) + + encoded_location = encode_url(abs_location) + query_parts = [] + if custom_headers: + query_parts.append('headers=' + urllib.parse.quote(json.dumps(custom_headers))) + if use_proxy is not None: + query_parts.append(f'use_proxy={use_proxy}') + suffix = ('?' + '&'.join(query_parts)) if query_parts else '' + proxied_location = f"/proxy/{encoded_location}{suffix}" + except Exception as e: + logger.warning(f"[PROXY] Failed to rewrite redirect Location: {e}") + proxied_location = location + + return web.Response( + status=response.status, + headers={ + **CORS_HEADERS, + 'Location': proxied_location, + 'Cache-Control': 'no-cache', + }, + ) + + # Fail fast on upstream HTTP errors to avoid hanging streams on player side + if response.status >= 400: + err_body = await response.read() + err_text = err_body.decode('utf-8', errors='replace') if err_body else '(empty)' + logger.warning(f"[PROXY] Upstream HTTP {response.status} for {target_url} — headers_sent: {headers} — body: {err_text[:200]}") + return web.json_response( + { + 'error': f'Upstream HTTP error: {response.status}', + 'upstream_status': response.status, + 'upstream_url': target_url, + 'upstream_body': err_text[:2000] + }, + status=response.status, + headers=CORS_HEADERS + ) + + # M3U8 detected by content-type (not by URL — those went through coalescer above) + if is_m3u8_response: + m3u8_probe = await response.content.read(2048) + if m3u8_probe and self._is_valid_m3u8(m3u8_probe.decode('utf-8', errors='ignore')): + rest = await response.content.read(10 * 1024 * 1024) + raw_body = m3u8_probe + rest + m3u8_resp = await self._handle_m3u8_response( + response, target_url, resp_headers, is_bandwidth, + is_sosplay=(service in ('sosplay', 'sosplay_cdn') or sosplay_mode), + is_witv=(service == 'witv'), + custom_headers=custom_headers, + request=request, + use_proxy=use_proxy, + raw_body=raw_body + ) + if m3u8_resp is not None: + return m3u8_resp + body_text = raw_body.decode('utf-8', errors='replace') if raw_body else '(empty)' + logger.error(f"[PROXY] BUG: _handle_m3u8_response returned None for {target_url}") + return web.json_response( + { + 'error': 'Failed to process M3U8 stream', + 'upstream_status': response.status, + 'upstream_url': target_url, + 'upstream_body': body_text[:2000] + }, + status=502, headers=CORS_HEADERS + ) + + # Content-Type says M3U8 but content is binary (live IPTV TS stream + # with wrong Content-Type) — stream directly instead of buffering + if m3u8_probe: + return await self._stream_response_with_prefix(request, response, resp_headers, m3u8_probe, CHUNK_DEFAULT) + return await self._stream_response(request, response, resp_headers, CHUNK_DEFAULT) + + # TS/M4S segments are handled above via coalescer + buffer. + # They only reach here if content detection missed them (shouldn't happen). + + # MPD handling - small file + if content.is_mpd: + body = await response.read() + resp_headers['Content-Type'] = 'application/dash+xml' + resp_headers['Cache-Control'] = 'public, max-age=5' + resp_headers['Content-Length'] = str(len(body)) + return _safe_response(body, response.status, resp_headers) + + # MP4 handling - use FASTEST streaming for large files + if content.is_mp4: + resp_headers['Accept-Ranges'] = 'bytes' + resp_headers['Cache-Control'] = 'public, max-age=7200' + resp_headers['Content-Type'] = 'video/mp4' + + if response.status == 206: + if 'content-range' in response.headers: + resp_headers['Content-Range'] = response.headers['content-range'] + if 'content-length' in response.headers: + resp_headers['Content-Length'] = response.headers['content-length'] + + # Use fast streaming for maximum throughput + return await self._stream_response_fast(request, response, resp_headers, CHUNK_LARGE) + + # Extensionless playlists: probe first bytes to detect "#EXTM3U" + probe = await response.content.read(2048) + if probe: + probe_text = probe.decode('utf-8', errors='ignore') + if self._is_valid_m3u8(probe_text): + raw_body = probe + await response.content.read(10 * 1024 * 1024) + m3u8_resp = await self._handle_m3u8_response( + response, target_url, resp_headers, is_bandwidth, + is_sosplay=(service == 'sosplay' or service == 'sosplay_cdn' or sosplay_mode), + is_witv=(service == 'witv'), + custom_headers=custom_headers, + request=request, + use_proxy=use_proxy, + raw_body=raw_body + ) + if m3u8_resp is not None: + return m3u8_resp + body_text = raw_body.decode('utf-8', errors='replace') if raw_body else '(empty)' + logger.error(f"[PROXY] BUG: _handle_m3u8_response returned None for {target_url}") + return web.json_response( + { + 'error': 'Failed to process M3U8 stream', + 'upstream_status': response.status, + 'upstream_url': target_url, + 'upstream_body': body_text[:2000] + }, + status=502, headers=CORS_HEADERS + ) + + return await self._stream_response_with_prefix(request, response, resp_headers, probe, CHUNK_DEFAULT) + + # Default streaming + return await self._stream_response(request, response, resp_headers, CHUNK_DEFAULT) + + except asyncio.TimeoutError as e: + return web.json_response( + { + 'error': 'Timeout', + 'exception': type(e).__name__, + 'message': str(e) or None, + 'upstream_url': target_url, + }, + status=504, + headers=CORS_HEADERS, + ) + except aiohttp.ClientError as e: + return web.json_response( + { + 'error': 'Upstream request failed', + 'exception': type(e).__name__, + 'message': str(e) or None, + 'details': repr(e), + 'upstream_url': target_url, + }, + status=502, + headers=CORS_HEADERS, + ) + except Exception as e: + logger.exception('[PROXY] Unexpected error while streaming') + return web.json_response( + { + 'error': 'Unexpected proxy error', + 'exception': type(e).__name__, + 'message': str(e) or None, + 'details': repr(e), + 'upstream_url': target_url, + }, + status=500, + headers=CORS_HEADERS, + ) + + async def _handle_uqload_embed(self, request: Request, target_url: str, + headers: Dict, timeout: ClientTimeout, + range_header: Optional[str], session: aiohttp.ClientSession) -> Response: + """Handle UQLOAD embed URLs by extracting and streaming MP4""" + try: + cache_key = hashlib.md5(target_url.encode()).hexdigest() + mp4_url = self.uqload_mp4_cache.get(cache_key) + + if not mp4_url: + mp4_url = await self._extract_uqload_mp4_url(target_url) + self.uqload_mp4_cache.set(cache_key, mp4_url) + + mp4_headers = self._prepare_headers(mp4_url, request) + mp4_headers.update({ + 'Accept': '*/*', + 'Accept-Encoding': 'identity;q=1, *;q=0', + 'Referer': 'https://uqload.bz/', + 'Origin': 'https://uqload.bz' + }) + + if not range_header: + # HEAD request for metadata + async with session.request('HEAD', mp4_url, headers=mp4_headers, + timeout=ClientTimeout(total=10)) as resp: + resp_headers = self._prepare_stream_headers(resp.headers, 'video/mp4') + resp_headers['Accept-Ranges'] = 'bytes' + return _safe_response(b'', 200, resp_headers) + else: + mp4_headers['Range'] = range_header + async with session.request('GET', mp4_url, headers=mp4_headers, + timeout=ClientTimeout(total=None, connect=10, sock_read=30)) as resp: + resp_headers = self._prepare_stream_headers(resp.headers, 'video/mp4') + resp_headers['Accept-Ranges'] = 'bytes' + + if resp.status == 206 and 'content-range' in resp.headers: + resp_headers['Content-Range'] = resp.headers['content-range'] + + return await self._stream_response(request, resp, resp_headers, CHUNK_MP4) + + except Exception as e: + logger.error(f'[UQLOAD] Error: {e}') + return web.json_response({'error': str(e)}, status=500, headers=CORS_HEADERS) + + def _normalize_custom_headers(self, custom_headers: Optional[Dict]) -> Dict[str, str]: + """Normalize custom headers passed through /proxy?headers=...""" + if not custom_headers: + return {} + + normalized = {} + header_aliases = { + 'accept': 'Accept', + 'accept-language': 'Accept-Language', + 'host': 'Host', + 'origin': 'Origin', + 'range': 'Range', + 'referer': 'Referer', + 'user-agent': 'User-Agent', + } + + for key, value in custom_headers.items(): + if value is None: + continue + + key_str = str(key).strip() + if not key_str: + continue + + canonical_key = header_aliases.get( + key_str.lower(), + '-'.join(part[:1].upper() + part[1:] for part in key_str.split('-') if part) + ) + normalized[canonical_key] = str(value).strip() + + return normalized + + def _ensure_origin_matches_referer(self, headers: Dict[str, str]) -> Dict[str, str]: + """Keep Origin aligned with Referer for embed-protected CDNs.""" + referer = headers.get('Referer') + if not referer: + return headers + + try: + parsed = urlparse(referer) + if not parsed.scheme or not parsed.netloc: + return headers + referer_origin = f"{parsed.scheme}://{parsed.netloc}" + except Exception: + return headers + + current_origin = headers.get('Origin') + if current_origin != referer_origin: + if current_origin: + logger.info(f"[PROXY] Adjusting Origin to match Referer: {current_origin} -> {referer_origin}") + headers['Origin'] = referer_origin + + return headers + + def _prepare_headers(self, target_url: str, request: Request) -> Dict[str, str]: + """Prepare headers for proxy request""" + try: + parsed = urlparse(target_url) + referer_origin = f"{parsed.scheme}://{parsed.netloc}" + target_host = parsed.netloc + except: + referer_origin = 'https://vmwesa.online' + target_host = 'vmwesa.online' + + # Service-specific headers + if self.RE_NIGGAFLIX.search(target_url): + return { + 'Accept': '*/*', + 'Accept-Language': 'en-US,en;q=0.5', + 'Connection': 'keep-alive', + 'Host': target_host, + 'Origin': 'https://rivestream.org', + 'Referer': 'https://rivestream.org/', + 'User-Agent': 'Mozilla/5.0 Firefox/141.0' + } + + if self.RE_VMWESA.search(target_url): + return { + 'Accept': '*/*', + 'Host': target_host, + 'Origin': 'https://vidmoly.net', + 'Referer': 'https://vidmoly.net/', + 'User-Agent': 'Mozilla/5.0 Chrome/143.0.0.0' + } + + if self.RE_DROPCDN.search(target_url): + return { + 'Accept': '*/*', + 'Host': target_host, + 'Origin': 'https://dropload.tv', + 'Referer': 'https://dropload.tv/', + 'User-Agent': 'Mozilla/5.0 Chrome/139.0.0.0' + } + + if self.RE_SERVERSICURO.search(target_url): + return { + 'Accept': '*/*', + 'Host': target_host, + 'Origin': 'https://supervideo.cc', + 'Referer': 'https://supervideo.cc/', + 'User-Agent': 'Mozilla/5.0 Chrome/139.0.0.0' + } + + if self.RE_FSVID.search(target_url): + return { + 'Accept': 'application/vnd.apple.mpegurl,*/*', + 'Host': target_host, + 'Origin': 'https://fsvid.lol', + 'Referer': 'https://fsvid.lol/', + 'User-Agent': 'Mozilla/5.0 Chrome/139.0.0.0' + } + + if self.RE_SIBNET.search(target_url): + return {'Accept': '*/*'} + + if self.RE_UQLOAD.search(target_url): + return { + 'Accept': '*/*', + 'Accept-Encoding': 'identity;q=1, *;q=0', + 'Host': target_host, + 'Referer': 'https://uqload.bz/', + 'User-Agent': 'Mozilla/5.0 Chrome/142.0.0.0' + } + + if self.RE_VIDZY.search(target_url): + return { + 'Accept': 'application/vnd.apple.mpegurl,*/*', + 'Host': target_host, + 'Origin': 'https://vidzy.org', + 'Referer': 'https://vidzy.org/', + 'User-Agent': 'Mozilla/5.0 Chrome/141.0.0.0' + } + + if self.RE_BANDWIDTH.search(target_url): + return { + 'Accept': '*/*', + 'Host': target_host, + 'Origin': 'https://voe.sx', + 'Referer': 'https://voe.sx/', + 'User-Agent': 'Mozilla/5.0 Chrome/143.0.0.0' + } + + if self.RE_MERI.search(target_url): + return { + 'Accept': '*/*', + 'Host': target_host, + 'Referer': 'https://hoca6.com', + 'Origin': 'https://hoca6.com', + 'User-Agent': 'Mozilla/5.0 Chrome/120.0.0.0' + } + + if self.RE_DOODSTREAM.search(target_url): + return { + 'Accept': '*/*', + 'Accept-Encoding': 'identity;q=1, *;q=0', + 'Host': target_host, + 'Referer': 'https://d0000d.com/', + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36', + 'Connection': 'keep-alive' + } + + if self.RE_SEEKSTREAMING.search(target_url): + return { + 'Accept': '*/*', + 'Host': target_host, + 'Referer': 'https://lpayer.embed4me.com/', + 'Origin': 'https://lpayer.embed4me.com', + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36' + } + + # Numeric CDN domains (e.g., 8nwwqrar.12703830.net) - used by various streaming services + if self.RE_NUMERIC_CDN.search(target_url): + return { + 'Accept': '*/*', + 'Accept-Language': 'en-US,en;q=0.9', + 'Host': target_host, + 'Origin': 'https://dishtrainer.net', + 'Referer': 'https://dishtrainer.net/', + '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' + } + + # Default headers + user_agent = request.headers.get('user-agent', 'Mozilla/5.0 Chrome/120.0.0.0') + url_lower = target_url.lower() + + if 'ios' in url_lower or 'iphone' in url_lower: + user_agent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_0) Safari/604.1' + elif 'android' in url_lower: + user_agent = 'Mozilla/5.0 (Linux; Android 10) Chrome/120.0.0.0 Mobile' + + headers = { + 'Accept': '*/*', + 'Connection': 'keep-alive', + # 'Host': target_host, # Let aiohttp handle Host automatically to avoid conflicts + 'User-Agent': user_agent, + 'Sec-Fetch-Dest': 'video', + 'Sec-Fetch-Mode': 'no-cors', + 'Sec-Fetch-Site': 'cross-site', + # Allow upstream compression for text content (M3U8/MPD) to save proxy<->upstream bandwidth + # Binary streams (.ts, .mp4, .m4s) are already compressed so 'identity' is fine + 'Accept-Encoding': 'gzip, deflate' if any(ext in url_lower for ext in ('.m3u8', '.mpd', '.html')) else 'identity', + } + + if 'range' in request.headers: + headers['Range'] = request.headers['range'] + + return headers + + def _is_valid_m3u8(self, content: str) -> bool: + """Check if content is valid M3U8""" + content_lower = content.lower() + return ('#extm3u' in content_lower or '#ext-x-version' in content_lower) and not content.strip().startswith('<') + + async def _rewrite_m3u8_urls(self, content: str, base_url: str, + is_bandwidth: bool = False, is_sosplay: bool = False, + is_witv: bool = False, custom_headers: Optional[Dict] = None, + use_proxy: Optional[int] = None) -> str: + """Rewrite URLs in M3U8 content to use proxy""" + base_url_dir = base_url.rsplit('/', 1)[0] + '/' + + # Extract query params from base URL (for auth tokens like s= and e=) + parsed_base = urlparse(base_url) + base_query = parsed_base.query # e.g., "s=xxx&e=yyy" + + # Pre-encode headers for segment URLs if provided + encoded_headers = None + if custom_headers: + encoded_headers = urllib.parse.quote(json.dumps(custom_headers)) + + # Build use_proxy query suffix for segment URLs + use_proxy_suffix = f'use_proxy={use_proxy}' if use_proxy is not None else None + + def to_absolute(url: str) -> str: + if not url or url.startswith(('http://', 'https://')): + return url + return urljoin(base_url_dir, url) + + def proxify_url(url: str) -> str: + abs_url = to_absolute(url) + if not abs_url or '/proxy/' in abs_url: + return url if not abs_url else abs_url + + # If segment URL has no query params but base URL does, inherit them + # This handles auth tokens for HLS segments + if base_query and '?' not in abs_url: + # Check if it's a segment file (ts, m4s, etc.) + url_lower = abs_url.lower() + if any(ext in url_lower for ext in ('.ts', '.m4s', '.aac', '.mp4', '.fmp4')): + abs_url = f"{abs_url}?{base_query}" + + # Build proxy URL with headers if available + encoded_url = encode_url(abs_url) + + # Build query parts for segment proxy URL + query_parts = [] + if encoded_headers: + query_parts.append(f'headers={encoded_headers}') + if use_proxy_suffix: + query_parts.append(use_proxy_suffix) + + # Pass custom headers (embed referer/origin) and proxy choice to segment URLs + if query_parts: + return f"/proxy/{encoded_url}?{'&'.join(query_parts)}" + + return f"/proxy/{encoded_url}" + + # Use pre-compiled patterns for speed + re_uri_dq = self.RE_M3U8_URI_DQ + re_uri_sq = self.RE_M3U8_URI_SQ + re_uri_uq = self.RE_M3U8_URI_UQ + re_http = self.RE_M3U8_HTTP + + def rewrite_line(line: str) -> str: + trimmed = line.strip() + if not trimmed: + return line + + # Tag lines with URI attributes (pre-compiled regex) + if trimmed.startswith('#'): + line = re_uri_dq.sub(lambda m: f'URI="{proxify_url(m.group(1).strip())}"', line) + line = re_uri_sq.sub(lambda m: f'URI="{proxify_url(m.group(1).strip())}"', line) + line = re_uri_uq.sub(lambda m: f'URI="{proxify_url(m.group(1).strip())}"', line) + return line + + # URL lines (pre-compiled regex) + if re_http.match(trimmed): + return proxify_url(trimmed) + + return proxify_url(to_absolute(trimmed)) + + return '\n'.join(rewrite_line(line) for line in content.split('\n')) + + # ===== VIP Verification ===== + + async def _check_vip(self, request: Request) -> bool: + """Verify VIP access key directly against MySQL access_keys table. + Returns True if VIP, False otherwise. Results are cached for VIP_CACHE_TTL seconds.""" + raw_key = request.headers.get('x-access-key', '') + + if not raw_key or not raw_key.strip(): + return False + + access_key = raw_key.strip() + + # Fix encoding: aiohttp uses Python's surrogateescape for non-ASCII header bytes. + # Byte 0xe9 (é in Latin-1) becomes surrogate \udce9. We recover the original bytes + # with surrogateescape, then decode as Latin-1 to get the proper Unicode character. + try: + raw_bytes = access_key.encode('utf-8', 'surrogateescape') + access_key = raw_bytes.decode('latin-1') + except (UnicodeDecodeError, UnicodeEncodeError): + pass + + # Check cache first + cached = self.vip_cache.get(access_key) + if cached is not None: + return cached + + # Query MySQL directly + try: + if not self.mysql_pool: + return False + + async with self.mysql_pool.acquire() as conn: + async with conn.cursor() as cur: + await cur.execute( + 'SELECT key_value, active, expires_at FROM access_keys WHERE key_value = %s LIMIT 1', + (access_key,) + ) + row = await cur.fetchone() + + + if not row: + self.vip_cache.set(access_key, False) + return False + + key_value, active, expires_at = row + + # Key must be active + if not active: + self.vip_cache.set(access_key, False) + return False + + # Check expiration (if set) + if expires_at is not None: + now = datetime.now(timezone.utc) + if isinstance(expires_at, datetime): + # MySQL returns naive datetimes (no tz) – assume UTC + if expires_at.tzinfo is None: + expires_at = expires_at.replace(tzinfo=timezone.utc) + if expires_at < now: + self.vip_cache.set(access_key, False) + return False + else: + # expires_at might be a string + try: + exp = datetime.fromisoformat(str(expires_at)) + if exp.tzinfo is None: + exp = exp.replace(tzinfo=timezone.utc) + if exp < now: + self.vip_cache.set(access_key, False) + return False + except (ValueError, TypeError): + pass + + # Key is valid + self.vip_cache.set(access_key, True) + return True + + except Exception as e: + logger.warning(f'[VIP] MySQL verification error: {e}') + # DB error — deny by default for security + return False + + def _vip_denied_response(self) -> Response: + """Return 403 response for non-VIP users""" + return web.json_response( + {'error': 'VIP access required', 'code': 'VIP_REQUIRED'}, + status=403, + headers=CORS_HEADERS + ) + + # ===== Extraction Handlers ===== + + async def voe_m3u8_handler(self, request: Request) -> Response: + """VOE M3U8 extraction with caching""" + if not await self._check_vip(request): + return self._vip_denied_response() + try: + encoded_url = request.query.get('url') + if not encoded_url: + return web.json_response({'error': 'URL required'}, status=400) + + try: + url = base64.b64decode(encoded_url).decode('utf-8') + except: + return web.json_response({'error': 'Invalid URL'}, status=400) + + cache_key = hashlib.md5(url.encode()).hexdigest() + cached = self.voe_cache.get(cache_key) + if cached: + resp = web.json_response(cached) + resp.headers['X-Cache'] = 'HIT' + return resp + + headers = { + 'User-Agent': 'Mozilla/5.0 Chrome/139.0.0.0', + 'Referer': 'https://voe.sx/', + } + + html, _ = await self._fetch_with_redirects(url, headers, timeout_seconds=5) + json_content = self._extract_json_from_html(html) + + if not json_content or not isinstance(json_content, list): + return web.json_response({'error': 'Content not found'}, status=404) + + decrypted = self._decrypt_voe_data(json_content[0]) + if not decrypted: + return web.json_response({'error': 'Decryption failed'}, status=500) + + source_url = decrypted.get('source', '') + if '.m3u8' in source_url: + result = {'source': f"{PROXY_BASE}/voe-proxy?url={urllib.parse.quote(source_url)}"} + else: + result = {'decrypted': decrypted} + + self.voe_cache.set(cache_key, result) + resp = web.json_response(result) + resp.headers['X-Cache'] = 'MISS' + return resp + + except asyncio.TimeoutError: + return web.json_response({'error': 'Timeout'}, status=504) + except Exception as e: + return web.json_response({'error': str(e)}, status=500) + + async def _fetch_with_redirects(self, url: str, headers: Dict, max_redirects: int = 3, + use_proxy: bool = True, specific_proxy: Dict = None, + timeout_seconds: int = 10) -> Tuple[str, str]: + """Follow redirects and return final HTML content""" + # Determine session based on proxy args (legacy support for dict args) + session = self.sessions['normal'] + if use_proxy: + if specific_proxy and specific_proxy == SIBNET_PROXY: + session = self.sessions['proxy_0'] + elif specific_proxy and specific_proxy == VIDMOLY_PROXY: + session = self.sessions['proxy_1'] + else: + session = self.sessions['proxy_0'] # Default proxy + + timeout = ClientTimeout(total=timeout_seconds) + + current_url = url + async with session.request('GET', current_url, headers=headers, + timeout=timeout) as response: + html = await response.text() + + for _ in range(max_redirects): + if re.search(r'type=["\']\s*application/json\s*["\']', html) and ']*content=["\'][^;]+;\s*url=([^"\']+)', + r'https?://[a-z0-9.-]+/e/[a-z0-9]+' + ]: + match = re.search(pattern, html, re.IGNORECASE) + if match: + target = match.group(1) if match.lastindex else match.group(0) + break + + if not target: + break + + try: + abs_url = target if target.startswith('http') else urljoin(current_url, target) + async with session.request('GET', abs_url, headers={**headers, 'Referer': current_url}, + timeout=timeout) as resp: + html = await resp.text() + current_url = abs_url + except: + break + + return html, current_url + + def _extract_json_from_html(self, html: str) -> Optional[list]: + """Extract obfuscated JSON from HTML""" + match = re.search(r']*type=["\']?\s*application/json\s*["\']?[^>]*>\s*([\s\S]*?)\s*', html, re.IGNORECASE) + if match: + try: + parsed = json.loads(match.group(1).strip()) + if isinstance(parsed, list) and parsed and isinstance(parsed[0], str): + return parsed + except: + pass + + match = re.search(r'\[\s*"(?:[^"\\]|\\.){100,}"\s*\]', html) + if match: + try: + return json.loads(match.group(0)) + except: + pass + return None + + def _decrypt_voe_data(self, encrypted: str) -> Optional[Dict]: + """Decrypt VOE.SX data""" + try: + step1 = codecs.encode(encrypted, 'rot13') + for sym in ['@$', '^^', '~@', '%?', '*~', '!!', '#&']: + step1 = step1.replace(sym, '') + + padding = (4 - len(step1) % 4) % 4 + step2 = base64.b64decode(step1 + '=' * padding).decode('utf-8') + step3 = ''.join(chr(ord(c) - 3) for c in step2)[::-1] + + padding = (4 - len(step3) % 4) % 4 + step4 = base64.b64decode(step3 + '=' * padding).decode('utf-8') + + return json.loads(step4) + except Exception as e: + logger.error(f'VOE decryption error: {e}') + return None + + async def fsvid_extract_handler(self, request: Request) -> Response: + """FSVID M3U8 extraction""" + if not await self._check_vip(request): + return self._vip_denied_response() + try: + url = request.query.get('url') + if not url or 'fsvid.lol' not in url: + return web.json_response({'error': 'Invalid URL'}, status=400) + + cache_key = hashlib.md5(url.encode()).hexdigest() + cached = self.fsvid_cache.get(cache_key) + if cached: + resp = web.json_response(cached) + resp.headers['X-Cache'] = 'HIT' + return resp + + headers = { + 'accept': 'text/html,*/*', + 'referer': 'https://fsmirror46.lol/', + 'user-agent': 'Mozilla/5.0 Chrome/140.0.0.0' + } + + + async with self.sessions['normal'].request('GET', url, headers=headers, + timeout=ClientTimeout(total=8)) as response: + if response.status != 200: + return web.json_response({'error': 'Fetch failed'}, status=500) + + html = await response.text(encoding='utf-8') + + # Regex au lieu de BeautifulSoup — bien plus léger + script_match = re.search(r"eval\(function\(p,a,c,k,e,d\)\{.*?\}\('(.+?)',\d+,\d+,'[^']+'\.", html, re.DOTALL) + + if not script_match: + return web.json_response({'error': 'Script not found'}, status=404) + + deobfuscated = self._deobfuscate_fsvid_script(script_match.group(0)) + + # Try multiple patterns — videojs uses sources:[{src:"..."}] + m3u8_match = None + for pattern in [ + r'src:\s*["\']([^"\']+\.m3u8[^"\']*)["\']', + r'file:\s*["\']([^"\']+\.m3u8[^"\']*)["\']', + r'sources:\s*\[\s*\{[^}]*?["\']([^"\']+\.m3u8[^"\']*)["\']', + r'["\']([^"\']*\.m3u8[^"\']*)["\']', + ]: + m3u8_match = re.search(pattern, deobfuscated) + if m3u8_match: + break + + if not m3u8_match: + return web.json_response({'error': 'M3U8 not found'}, status=404) + + result = { + 'm3u8Url': f"{PROXY_BASE}/fsvid-proxy?url={urllib.parse.quote(m3u8_match.group(1))}", + 'source': 'fsvid' + } + + self.fsvid_cache.set(cache_key, result) + resp = web.json_response(result) + resp.headers['X-Cache'] = 'MISS' + return resp + + except Exception as e: + return web.json_response({'error': str(e)}, status=500) + + def _deobfuscate_fsvid_script(self, script: str) -> str: + """Deobfuscate packed JavaScript""" + match = re.search(r"eval\(function\(p,a,c,k,e,d\)\{.*?\}\('(.+?)',(\d+),(\d+),'(.+?)'\.", script, re.DOTALL) + if not match: + raise ValueError('Pattern not found') + + p, a, c, k_str = match.group(1), int(match.group(2)), int(match.group(3)), match.group(4) + k = k_str.split('|') + + def to_base(num: int, base: int) -> str: + chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + if num == 0: + return chars[0] + result = "" + while num > 0: + result = chars[num % base] + result + num //= base + return result + + result = p + while c > 0: + c -= 1 + if c < len(k) and k[c]: + result = re.sub(r'\b' + re.escape(to_base(c, a)) + r'\b', k[c], result) + + return result + + async def vidzy_extract_handler(self, request: Request) -> Response: + """VIDZY M3U8 extraction""" + if not await self._check_vip(request): + return self._vip_denied_response() + try: + url = request.query.get('url') + if not url or 'vidzy' not in url.lower(): + return web.json_response({'error': 'Invalid URL'}, status=400) + + cache_key = hashlib.md5(url.encode()).hexdigest() + cached = self.vidzy_cache.get(cache_key) + if cached: + resp = web.json_response(cached) + resp.headers['X-Cache'] = 'HIT' + return resp + + headers = { + 'accept': 'text/html,*/*', + 'referer': 'https://vidzy.org/', + 'user-agent': 'Mozilla/5.0 Chrome/140.0.0.0' + } + + + async with self.sessions['no_ssl'].request('GET', url, headers=headers, + timeout=ClientTimeout(total=8)) as response: + if response.status != 200: + return web.json_response({'error': 'Fetch failed'}, status=500) + + html = await response.text() + soup = BeautifulSoup(html, 'html.parser') + + script = next((s for s in soup.find_all('script') + if s.string and 'eval(function' in s.string), None) + + if not script: + return web.json_response({'error': 'Script not found'}, status=404) + + deobfuscated = self._deobfuscate_fsvid_script(script.string) + + # Try multiple M3U8 patterns + for pattern in [ + r'file:\s*["\']([^"\']+\.m3u8[^"\']*)["\']', + r'sources:\s*\[["\']([^"\']+\.m3u8[^"\']*)["\']', + r'["\']([^"\']*\.m3u8[^"\']*)["\']' + ]: + m3u8_match = re.search(pattern, deobfuscated) + if m3u8_match: + break + + if not m3u8_match: + return web.json_response({'error': 'M3U8 not found'}, status=404) + + result = { + 'm3u8Url': f"{PROXY_BASE}/vidzy-proxy?url={urllib.parse.quote(m3u8_match.group(1))}", + 'source': 'vidzy' + } + + self.vidzy_cache.set(cache_key, result) + resp = web.json_response(result) + resp.headers['X-Cache'] = 'MISS' + return resp + + except Exception as e: + return web.json_response({'error': str(e)}, status=500) + + async def vidmoly_extract_handler(self, request: Request) -> Response: + """VIDMOLY M3U8 extraction""" + if not await self._check_vip(request): + return self._vip_denied_response() + try: + url = request.query.get('url') + if not url or 'vidmoly' not in url.lower(): + return web.json_response({'error': 'Invalid URL'}, status=400) + + cache_key = hashlib.md5(url.encode()).hexdigest() + cached = self.vidmoly_cache.get(cache_key) + if cached: + resp = web.json_response(cached) + resp.headers['X-Cache'] = 'HIT' + return resp + + headers = { + 'accept': 'text/html,*/*', + 'referer': 'https://voirdrama.to/', + 'user-agent': 'Mozilla/5.0 Chrome/143.0.0.0' + } + + html, _ = await self._fetch_with_redirects(url, headers, use_proxy=True, + specific_proxy=VIDMOLY_PROXY) + + # Try multiple patterns + source_url = None + for pattern in [ + r'sources:\s*\[\s*{\s*file:\s*["\']([^"\']+)["\']', + r'file:\s*["\']([^"\']+\.m3u8[^"\']*)["\']', + r'https?://[^\s"\'<>]+\.m3u8[^\s"\'<>]*' + ]: + match = re.search(pattern, html, re.IGNORECASE) + if match: + source_url = match.group(1) if match.lastindex else match.group(0) + break + + if not source_url: + return web.json_response({'error': 'M3U8 not found'}, status=404) + + result = { + 'sourceUrl': f"{PROXY_BASE}/vidmoly-proxy?url={urllib.parse.quote(source_url)}", + 'source': 'vidmoly' + } + + self.vidmoly_cache.set(cache_key, result) + resp = web.json_response(result) + resp.headers['X-Cache'] = 'MISS' + return resp + + except Exception as e: + return web.json_response({'error': str(e)}, status=500) + + async def sibnet_extract_handler(self, request: Request) -> Response: + """SIBNET extraction""" + if not await self._check_vip(request): + return self._vip_denied_response() + try: + url = request.query.get('url') + if not url or 'sibnet.ru' not in url.lower(): + return web.json_response({'error': 'Invalid URL'}, status=400) + + cache_key = hashlib.md5(url.encode()).hexdigest() + cached = self.sibnet_cache.get(cache_key) + if cached: + resp = web.json_response(cached) + resp.headers['X-Cache'] = 'HIT' + return resp + + headers = { + 'accept': 'text/html,*/*', + 'referer': 'https://video.sibnet.ru/', + 'user-agent': 'Mozilla/5.0 Chrome/140.0.0.0' + } + + # Use SIBNET proxy + session = self.sessions.get('sibnet', self.sessions['normal']) + timeout = ClientTimeout(total=15) + + async with session.get(url, headers=headers, timeout=timeout) as response: + if response.status != 200: + return web.json_response({'error': 'Fetch failed'}, status=500) + html = await response.text() + + soup = BeautifulSoup(html, 'html.parser') + body_scripts = soup.find('body').find_all('script') if soup.find('body') else [] + + if len(body_scripts) < 22: + return web.json_response({'error': 'Script not found'}, status=404) + + script_content = body_scripts[21].string or '' + mp4_match = re.search(r'player\.src\(\[\{\s*src:\s*["\']([^"\']+\.mp4[^"\']*)["\']', script_content) + + if not mp4_match: + mp4_match = re.search(r'player\.src\(\[\{\s*src:\s*["\']([^"\']+\.mp4[^"\']*)["\']', html) + + if not mp4_match: + return web.json_response({'error': 'MP4 not found'}, status=404) + + mp4_url = f"https://video.sibnet.ru{mp4_match.group(1)}" + + # Follow redirect to get final URL + mp4_headers = { + 'accept': '*/*', + 'referer': 'https://video.sibnet.ru/', + 'user-agent': 'Mozilla/5.0 Chrome/140.0.0.0' + } + + # Continue using same session + async with session.get(mp4_url, headers=mp4_headers, + allow_redirects=False, timeout=timeout) as resp: + if resp.status in [301, 302, 303, 307, 308]: + location = resp.headers.get('Location', '') + if location.startswith('//'): + location = 'https:' + location + elif not location.startswith('http'): + location = 'https://' + location + + result = { + 'sourceUrl': f"{PROXY_BASE}/sibnet-proxy?url={urllib.parse.quote(location)}", + 'source': 'sibnet' + } + + self.sibnet_cache.set(cache_key, result) + resp = web.json_response(result) + resp.headers['X-Cache'] = 'MISS' + return resp + + return web.json_response({'error': 'Expected redirect'}, status=500) + + except Exception as e: + return web.json_response({'error': str(e)}, status=500) + + def _validate_uqload_url(self, url: str) -> str: + """Validate and format UQLOAD URL""" + if not url or len(url) < 12: + raise ValueError('Invalid URL') + + parts = url.split('/') + base = '/'.join(parts[:-1]) or 'https://uqload.bz' + video_id = parts[-1] + + if '.html' not in video_id: + video_id += '.html' + if 'embed-' not in video_id: + video_id = 'embed-' + video_id + + full_url = f'{base}/{video_id}' + if 'uqload' not in full_url: + raise ValueError('Invalid UQLOAD URL') + + return full_url + + async def _extract_uqload_mp4_url(self, embed_url: str) -> str: + """Extract MP4 URL from UQLOAD embed""" + validated = self._validate_uqload_url(embed_url) + urls = [validated, validated.replace('embed-', '')] + + headers = { + 'User-Agent': 'Mozilla/5.0 Chrome/91.0.0.0', + 'Accept': 'text/html,*/*' + } + + html = None + for url in urls: + try: + # UQLOAD generic fetch -> normal session + async with self.sessions['normal'].request('GET', url, headers=headers, + timeout=ClientTimeout(total=5)) as resp: + if resp.status == 200: + html = await resp.text() + break + except: + continue + + if not html: + raise ValueError('No content from UQLOAD') + + if 'File was deleted' in html: + raise ValueError('Video deleted') + + matches = re.findall(r'https?://.+/v\.mp4', html) + if not matches: + raise ValueError('MP4 URL not found') + + return matches[0] + + async def uqload_extract_handler(self, request: Request) -> Response: + """UQLOAD extraction""" + if not await self._check_vip(request): + return self._vip_denied_response() + try: + url = request.query.get('url') + if not url or 'uqload' not in url.lower(): + return web.json_response({'error': 'Invalid URL'}, status=400) + + cache_key = hashlib.md5(url.encode()).hexdigest() + cached = self.uqload_cache.get(cache_key) + if cached: + resp = web.json_response(cached) + resp.headers['X-Cache'] = 'HIT' + return resp + + validated = self._validate_uqload_url(url) + mp4_url = await self._extract_uqload_mp4_url(validated) + + if not mp4_url: + return web.json_response({'error': 'Extraction failed'}, status=404) + + result = { + 'url': f"{PROXY_BASE}/uqload-proxy?url={urllib.parse.quote(mp4_url)}", + 'source': 'uqload' + } + + self.uqload_cache.set(cache_key, result) + resp = web.json_response(result) + resp.headers['X-Cache'] = 'MISS' + return resp + + except Exception as e: + return web.json_response({'error': str(e)}, status=500) + + # ===== DoodStream Extraction ===== + + def _extract_doodstream_video_url(self, html_content: str, original_url: str) -> Optional[str]: + """Extract video URL from DoodStream HTML page""" + parsed_url = urlparse(original_url) + domain = f"{parsed_url.scheme}://{parsed_url.netloc}" + + pattern_match = self.RE_DOODSTREAM_PASS.search(html_content) + if not pattern_match: + return None + + pass_md5_url = pattern_match.group(0) + token = pattern_match.group("token") + + return domain, pass_md5_url, token + + async def doodstream_extract_handler(self, request: Request) -> Response: + """DoodStream extraction handler""" + if not await self._check_vip(request): + return self._vip_denied_response() + try: + url = request.query.get('url') + if not url: + return web.json_response({'error': 'Missing url parameter'}, status=400, headers=CORS_HEADERS) + + cache_key = hashlib.md5(url.encode()).hexdigest() + cached = self.doodstream_cache.get(cache_key) + if cached: + self._cache_hits += 1 + resp = web.json_response(cached) + resp.headers['X-Cache'] = 'HIT' + return resp + + # Step 1: Fetch the embed page + headers = { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36', + 'Referer': 'https://d0000d.com/', + } + + # Use proxy_1 (SOCKS5 2) instead of no_ssl + session = self.sessions.get('proxy_1', self.sessions.get('proxy_0', self.sessions['normal'])) + timeout = ClientTimeout(total=10) + + async with session.get(url, headers=headers, timeout=timeout) as response: + if response.status != 200: + return web.json_response({'error': f'Failed to fetch page: {response.status}'}, status=502, headers=CORS_HEADERS) + html_content = await response.text() + + # Step 2: Extract pass_md5 URL and token + extracted = self._extract_doodstream_video_url(html_content, url) + if not extracted: + return web.json_response({'error': 'Could not extract video URL', 'details': 'Regex match failed check server logs'}, status=404, headers=CORS_HEADERS) + + domain, pass_md5_url, token = extracted + + # Step 3: Call pass_md5 endpoint to get base URL + pass_headers = { + 'Referer': domain, + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36', + } + + async with session.get(f"{domain}{pass_md5_url}", headers=pass_headers, timeout=timeout) as response: + base_url = await response.text() + + # Step 4: Build final video URL + random_str = ''.join(random.choices(ascii_letters + digits, k=10)) + expiry = int(time.time() * 1000) + video_url = f"{base_url}{random_str}?token={token}&expiry={expiry}" + + result = { + 'url': f"{PROXY_BASE}/doodstream-proxy?url={urllib.parse.quote(video_url)}", + 'source': 'doodstream' + } + + self.doodstream_cache.set(cache_key, result) + resp = web.json_response(result) + resp.headers['X-Cache'] = 'MISS' + return resp + + except asyncio.TimeoutError: + return web.json_response({'error': 'Timeout'}, status=504, headers=CORS_HEADERS) + except Exception as e: + return web.json_response({'error': str(e)}, status=500, headers=CORS_HEADERS) + + # ===== SeekStreaming (Embed4me) Extraction ===== + + def _decrypt_seekstreaming_data(self, hex_str: str) -> Optional[str]: + """Decrypt AES-CBC encrypted data from seekstreaming/embed4me API""" + try: + + + hex_str = hex_str.strip().replace('"', '') + data = binascii.unhexlify(hex_str) + cipher = AES.new(SEEKSTREAMING_AES_KEY, AES.MODE_CBC, SEEKSTREAMING_AES_IV) + decrypted = unpad(cipher.decrypt(data), AES.block_size) + return decrypted.decode('utf-8') + except Exception as e: + logger.error(f'[SEEKSTREAMING] Decryption error: {e}') + return None + + async def seekstreaming_extract_handler(self, request: Request) -> Response: + """SeekStreaming (embed4me) extraction handler - accepts full URL""" + if not await self._check_vip(request): + return self._vip_denied_response() + try: + url = request.query.get('url') + if not url: + return web.json_response({'error': 'Missing url parameter'}, status=400, headers=CORS_HEADERS) + + # Decode %23 -> # so fragment-based IDs are properly extracted + url = urllib.parse.unquote(url) + + # Extract video ID from URL (e.g., https://lpayer.embed4me.com/#xv8jw -> xv8jw) + video_id = None + if '#' in url: + video_id = url.split('#')[-1].strip() + elif '/embed/' in url.lower(): + video_id = url.rstrip('/').split('/')[-1].strip() + else: + # Try to get ID from the last path segment or fragment + try: + parsed = urlparse(url) + if parsed.fragment: + video_id = parsed.fragment.strip() + elif parsed.path and parsed.path != '/': + video_id = parsed.path.rstrip('/').split('/')[-1].strip() + except: + pass + + if not video_id: + error_msg = 'Could not extract video ID from URL' + if 'embedseek.com' in url or 'embed4me.com' in url: + error_msg += '. If the URL uses a hash (#), ensure it is URL-encoded (%23) in your request.' + return web.json_response({'error': error_msg}, status=400, headers=CORS_HEADERS) + + cache_key = hashlib.md5(video_id.encode()).hexdigest() + cached = self.seekstreaming_cache.get(cache_key) + if cached: + self._cache_hits += 1 + resp = web.json_response(cached) + resp.headers['X-Cache'] = 'HIT' + return resp + + # Call embed4me/embedseek API (dynamic domain) + try: + parsed_url = urlparse(url) + api_domain = parsed_url.netloc + if not api_domain: + api_domain = 'lpayer.embed4me.com' + except: + api_domain = 'lpayer.embed4me.com' + + api_url = f"https://{api_domain}/api/v1/video?id={video_id}&w=1920&h=1080&r=" + headers = { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36', + 'Accept': '*/*', + 'Accept-Language': 'en-US,en;q=0.5', + 'Referer': f'https://{api_domain}/', + 'Origin': f'https://{api_domain}', + } + + session = self.sessions['normal'] + timeout = ClientTimeout(total=10) + + async with session.get(api_url, headers=headers, timeout=timeout) as response: + if response.status != 200: + return web.json_response({'error': f'API error: {response.status}'}, status=502, headers=CORS_HEADERS) + encrypted_text = await response.text() + + # Decrypt the response + decrypted_raw = self._decrypt_seekstreaming_data(encrypted_text) + if not decrypted_raw: + return web.json_response({'error': 'AES decryption failed'}, status=500, headers=CORS_HEADERS) + + data = json.loads(decrypted_raw) + + # Extract URLs + raw_cf = data.get('cf', '') + raw_source = data.get('source', '') + + result = { + 'source': 'seekstreaming' + } + + # Pass the correct origin/referer to the proxy + proxy_queries = f"&referer=https%3A//{api_domain}/&origin=https%3A//{api_domain}" + + if raw_cf: + result['url'] = f"{PROXY_BASE}/seekstreaming-proxy?url={urllib.parse.quote(raw_cf)}{proxy_queries}" + if raw_source: + result['ip_url'] = f"{PROXY_BASE}/seekstreaming-proxy?url={urllib.parse.quote(raw_source)}{proxy_queries}" + + if not raw_cf and not raw_source: + return web.json_response({'error': 'No video source found'}, status=404, headers=CORS_HEADERS) + + self.seekstreaming_cache.set(cache_key, result) + resp = web.json_response(result) + resp.headers['X-Cache'] = 'MISS' + return resp + + except asyncio.TimeoutError: + return web.json_response({'error': 'Timeout'}, status=504, headers=CORS_HEADERS) + except Exception as e: + logger.error(f'[SEEKSTREAMING] Error: {e}') + return web.json_response({'error': str(e)}, status=500, headers=CORS_HEADERS) + + # ===== Service-Specific Proxy Routes ===== + + def _rewrite_m3u8_for_service(self, content: str, base_url: str, proxy_route: str, extra_query: str = '') -> str: + """Rewrite M3U8 URLs to go through a service-specific proxy route""" + base_url_dir = base_url.rsplit('/', 1)[0] + '/' + + parsed_base = urlparse(base_url) + base_query = parsed_base.query + + def to_absolute(url: str) -> str: + if not url or url.startswith(('http://', 'https://')): + return url + return urljoin(base_url_dir, url) + + def proxify(url: str) -> str: + abs_url = to_absolute(url) + if not abs_url: + return url + # Inherit auth query params from base URL for segments + if base_query and '?' not in abs_url: + url_lower = abs_url.lower() + if any(ext in url_lower for ext in ('.ts', '.m4s', '.aac', '.mp4', '.fmp4', '.key')): + abs_url = f"{abs_url}?{base_query}" + + # Append extra query params (referer, origin, etc.) + suffix = f"&{extra_query}" if extra_query else "" + return f"{proxy_route}?url={urllib.parse.quote(abs_url)}{suffix}" + + re_uri_dq = self.RE_M3U8_URI_DQ + re_uri_sq = self.RE_M3U8_URI_SQ + re_uri_uq = self.RE_M3U8_URI_UQ + re_http = self.RE_M3U8_HTTP + + def rewrite_line(line: str) -> str: + trimmed = line.strip() + if not trimmed: + return line + if trimmed.startswith('#'): + line = re_uri_dq.sub(lambda m: f'URI="{proxify(m.group(1).strip())}"', line) + line = re_uri_sq.sub(lambda m: f'URI="{proxify(m.group(1).strip())}"', line) + line = re_uri_uq.sub(lambda m: f'URI="{proxify(m.group(1).strip())}"', line) + return line + if re_http.match(trimmed): + return proxify(trimmed) + return proxify(to_absolute(trimmed)) + + return '\n'.join(rewrite_line(l) for l in content.split('\n')) + + async def _service_proxy(self, request: Request, service_name: str, + default_headers: Dict, session_key: str = 'normal', + proxy_route: str = None) -> Response: + """ + Generic service-specific proxy handler. + Each service route calls this with its own headers and session. + No regex detection needed - the route itself identifies the service. + """ + if request.method == 'OPTIONS': + return web.Response(headers=CORS_HEADERS) + + target_url = request.query.get('url') + if not target_url: + return web.json_response({'error': 'Missing url parameter'}, status=400, headers=CORS_HEADERS) + + self._request_count += 1 + + # Build headers with correct Host + headers = dict(default_headers) + try: + parsed = urlparse(target_url) + headers['Host'] = parsed.netloc + except: + pass + + # Range support + range_header = request.headers.get('range') or request.headers.get('Range') + if range_header: + headers['Range'] = range_header + + # Capture extra query params (referer, origin) to pass to rewritten segments + extra_params = [] + for k, v in request.query.items(): + if k != 'url': + extra_params.append(f"{k}={urllib.parse.quote(v)}") + extra_query = "&".join(extra_params) + + # Detect content type + content = detect_content_type(target_url, request.headers.get('accept', '')) + + # Timeouts based on content + if content.is_mp4 and range_header: + timeout = ClientTimeout(total=None, connect=10, sock_read=30) + elif content.is_mp4: + timeout = ClientTimeout(total=60, connect=10, sock_read=30) + elif content.is_ts or content.is_m4s: + timeout = ClientTimeout(total=None, connect=10, sock_read=60) + elif content.is_m3u8: + timeout = ClientTimeout(total=30, connect=10, sock_read=20) + else: + timeout = ClientTimeout(total=30, connect=10, sock_read=20) + + if session_key in self.sessions: + session = self.sessions[session_key] + actual_session_key = session_key + else: + session = self.sessions['normal'] + actual_session_key = 'normal' + logger.warning(f'[{service_name.upper()}-PROXY] âš  Session "{session_key}" introuvable, fallback sur "normal" (sans proxy) ! Vérifier PROXIES_SOCKS5_JSON') + route = proxy_route or f'/{service_name}-proxy' + + logger.info(f'[{service_name.upper()}-PROXY] → session={actual_session_key} url={target_url} headers={headers}') + + try: + # ── Segment cache check (before upstream request) ── + if content.is_ts or content.is_m4s: + cached_data = self.segment_buffer.get(target_url) + if cached_data is not None: + self._segment_cache_hits += 1 + self._cache_hits += 1 + ct = 'video/mp2t' if content.is_ts else 'video/iso.segment' + return web.Response(body=cached_data, status=200, headers={ + **CORS_HEADERS, + 'Content-Type': ct, + 'Cache-Control': 'public, max-age=86400, immutable', + 'Accept-Ranges': 'bytes', + 'Content-Length': str(len(cached_data)), + 'X-Segment-Cache': 'HIT', + }) + + async with session.get(target_url, headers=headers, timeout=timeout) as response: + resp_headers = self._prepare_stream_headers(response.headers) + + # Pass through redirects while keeping the client inside this service proxy route + if 300 <= response.status < 400: + location = response.headers.get('location') or response.headers.get('Location') + if location: + try: + abs_location = location + if not abs_location.startswith(('http://', 'https://')): + abs_location = urljoin(target_url, abs_location) + suffix = f"&{extra_query}" if extra_query else '' + proxied_location = f"{route}?url={urllib.parse.quote(abs_location)}{suffix}" + except Exception as e: + logger.warning(f'[{service_name.upper()}-PROXY] Failed to rewrite redirect Location: {e}') + proxied_location = location + + return web.Response( + status=response.status, + headers={ + **CORS_HEADERS, + 'Location': proxied_location, + 'Cache-Control': 'no-cache', + }, + ) + + # Convert upstream HTTP failures to error for consistent client handling + if response.status >= 400: + err_body = await response.read() + err_text = err_body.decode('utf-8', errors='replace') if err_body else '(empty)' + logger.warning(f'[{service_name.upper()}-PROXY] Upstream HTTP {response.status} for {target_url} — body: {err_text[:200]}') + return web.json_response( + { + 'error': f'Upstream HTTP error: {response.status}', + 'upstream_status': response.status, + 'upstream_url': target_url, + 'upstream_body': err_text[:2000] + }, + status=response.status, + headers=CORS_HEADERS + ) + + # M3U8 - rewrite URLs to go through same service proxy + if content.is_m3u8: + body = await response.read() + try: + text = body.decode('utf-8') + if self._is_valid_m3u8(text): + rewritten = self._rewrite_m3u8_for_service(text, target_url, route, extra_query) + resp_body = rewritten.encode('utf-8') + resp_headers['Content-Type'] = 'application/vnd.apple.mpegurl' + resp_headers.pop('Content-Length', None) + resp_headers.pop('content-length', None) + + is_vod = '#EXT-X-ENDLIST' in text + resp_headers['Cache-Control'] = f'public, max-age={M3U8_VOD_CACHE_TTL}' if is_vod else 'no-cache' + resp_headers['Content-Length'] = str(len(resp_body)) + return _safe_response(resp_body, response.status, resp_headers) + + # Not valid M3U8 — return error so player fails fast + logger.warning(f'[{service_name.upper()}-PROXY] M3U8 URL returned non-M3U8 content (status={response.status}): {target_url} — preview: {text[:200]}') + return web.json_response( + { + 'error': 'Invalid stream: upstream did not return valid M3U8 content', + 'upstream_status': response.status, + 'upstream_url': target_url, + 'upstream_body': text[:2000] + }, + status=502, headers=CORS_HEADERS + ) + + except UnicodeDecodeError: + pass + # Binary/non-decodable body for an M3U8 URL — return error + body_text = body.decode('utf-8', errors='replace')[:2000] if body else '(empty)' + logger.warning(f'[{service_name.upper()}-PROXY] M3U8 URL returned non-text content: {target_url}') + return web.json_response( + { + 'error': 'Invalid stream: non-text response for M3U8 URL', + 'upstream_status': response.status, + 'upstream_url': target_url, + 'upstream_body': body_text + }, + status=502, headers=CORS_HEADERS + ) + + # TS segments — buffer + cache (shared with main proxy segment buffer) + if content.is_ts: + body = await response.read() + if response.status == 200 and body: + self.segment_buffer.put(target_url, body) + resp_headers['Content-Type'] = 'video/mp2t' + resp_headers['Cache-Control'] = 'public, max-age=86400, immutable' + resp_headers['Accept-Ranges'] = 'bytes' + resp_headers['Content-Length'] = str(len(body)) + resp_headers['X-Segment-Cache'] = 'MISS' + return web.Response(body=body, status=response.status, headers=resp_headers) + + # M4S segments — buffer + cache (shared with main proxy segment buffer) + if content.is_m4s: + body = await response.read() + if response.status == 200 and body: + self.segment_buffer.put(target_url, body) + resp_headers['Content-Type'] = 'video/iso.segment' + resp_headers['Cache-Control'] = 'public, max-age=86400, immutable' + resp_headers['Content-Length'] = str(len(body)) + resp_headers['X-Segment-Cache'] = 'MISS' + return web.Response(body=body, status=response.status, headers=resp_headers) + + # MP4 + if content.is_mp4: + resp_headers['Accept-Ranges'] = 'bytes' + resp_headers['Content-Type'] = 'video/mp4' + resp_headers['Cache-Control'] = 'public, max-age=7200' + if response.status == 206 and 'content-range' in response.headers: + resp_headers['Content-Range'] = response.headers['content-range'] + if 'content-length' in response.headers: + resp_headers['Content-Length'] = response.headers['content-length'] + return await self._stream_response_fast(request, response, resp_headers, CHUNK_LARGE) + + # MPD + if content.is_mpd: + body = await response.read() + resp_headers['Content-Type'] = 'application/dash+xml' + resp_headers['Content-Length'] = str(len(body)) + return _safe_response(body, response.status, resp_headers) + + # Default streaming + return await self._stream_response(request, response, resp_headers, CHUNK_DEFAULT) + + except asyncio.TimeoutError as e: + return web.json_response( + { + 'error': 'Timeout', + 'exception': type(e).__name__, + 'message': str(e) or None, + 'upstream_url': target_url, + }, + status=504, + headers=CORS_HEADERS, + ) + except aiohttp.ClientError as e: + return web.json_response( + { + 'error': 'Upstream request failed', + 'exception': type(e).__name__, + 'message': str(e) or None, + 'details': repr(e), + 'upstream_url': target_url, + }, + status=502, + headers=CORS_HEADERS, + ) + except Exception as e: + logger.exception(f'[{service_name.upper()}-PROXY] Unexpected error') + return web.json_response( + { + 'error': 'Unexpected proxy error', + 'exception': type(e).__name__, + 'message': str(e) or None, + 'details': repr(e), + 'upstream_url': target_url, + }, + status=500, + headers=CORS_HEADERS, + ) + + # --- Service proxy thin wrappers --- + + async def voe_proxy_handler(self, request: Request) -> Response: + """VOE / bandwidth CDN proxy""" + return await self._service_proxy(request, 'voe', { + 'Accept': '*/*', + 'Origin': 'https://voe.sx', + 'Referer': 'https://voe.sx/', + 'User-Agent': 'Mozilla/5.0 Chrome/143.0.0.0' + }, session_key='proxy_0') + + async def fsvid_proxy_handler(self, request: Request) -> Response: + """FSVID proxy""" + return await self._service_proxy(request, 'fsvid', { + 'Accept': 'application/vnd.apple.mpegurl,*/*', + 'Origin': 'https://fsvid.lol', + 'Referer': 'https://fsvid.lol/', + 'User-Agent': 'Mozilla/5.0 Chrome/139.0.0.0' + }) + + async def vidzy_proxy_handler(self, request: Request) -> Response: + """Vidzy proxy""" + return await self._service_proxy(request, 'vidzy', { + 'Accept': 'application/vnd.apple.mpegurl,*/*', + 'Origin': 'https://vidzy.org', + 'Referer': 'https://vidzy.org/', + 'User-Agent': 'Mozilla/5.0 Chrome/141.0.0.0' + }, session_key='no_ssl') + + async def vidmoly_proxy_handler(self, request: Request) -> Response: + """Vidmoly proxy""" + return await self._service_proxy(request, 'vidmoly', { + 'Accept': '*/*', + 'Origin': 'https://vidmoly.net', + 'Referer': 'https://vidmoly.net/', + 'User-Agent': 'Mozilla/5.0 Chrome/143.0.0.0' + }, session_key='proxy_1') + + async def sibnet_proxy_handler(self, request: Request) -> Response: + """Sibnet proxy""" + return await self._service_proxy(request, 'sibnet', { + 'Accept': '*/*', + 'User-Agent': 'Mozilla/5.0 Chrome/140.0.0.0' + }, session_key='sibnet') + + async def uqload_proxy_handler(self, request: Request) -> Response: + """Uqload proxy""" + return await self._service_proxy(request, 'uqload', { + 'Accept': '*/*', + 'Accept-Encoding': 'identity;q=1, *;q=0', + 'Referer': 'https://uqload.bz/', + 'User-Agent': 'Mozilla/5.0 Chrome/142.0.0.0' + }) + + async def doodstream_proxy_handler(self, request: Request) -> Response: + """DoodStream proxy — robust streaming with SOCKS5 retry on connection drop. + Unlike the generic _service_proxy, this handler automatically resumes + the upstream download via Range headers when the SOCKS5 tunnel drops, + so the client receives the full file without interruption. + """ + if request.method == 'OPTIONS': + return web.Response(headers=CORS_HEADERS) + + target_url = request.query.get('url') + if not target_url: + return web.json_response({'error': 'Missing url parameter'}, status=400, headers=CORS_HEADERS) + + self._request_count += 1 + + # -- Build upstream headers ------------------------------------------------ + up_headers = { + 'Accept': '*/*', + 'Accept-Encoding': 'identity;q=1, *;q=0', + 'Referer': 'https://d0000d.com/', + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36', + 'Connection': 'keep-alive', + } + try: + up_headers['Host'] = urlparse(target_url).netloc + except Exception: + pass + + # Forward client Range header + client_range = request.headers.get('range') or request.headers.get('Range') + if client_range: + up_headers['Range'] = client_range + + # No sock_read timeout — SOCKS5 tunnels can stall briefly during large transfers + timeout = ClientTimeout(total=None, connect=15, sock_read=None) + session = self.sessions.get('proxy_1', self.sessions['normal']) + + MAX_RETRIES = 5 + + try: + # -- First upstream request -------------------------------------------- + async with session.get(target_url, headers=up_headers, timeout=timeout) as first_resp: + # Prepare response headers for the client + resp_headers = self._prepare_stream_headers(first_resp.headers) + resp_headers['Accept-Ranges'] = 'bytes' + resp_headers['Content-Type'] = 'video/mp4' + resp_headers['Cache-Control'] = 'public, max-age=7200' + + if first_resp.status == 206 and 'content-range' in first_resp.headers: + resp_headers['Content-Range'] = first_resp.headers['content-range'] + if 'content-length' in first_resp.headers: + resp_headers['Content-Length'] = first_resp.headers['content-length'] + + # Determine total file size (needed for retry Range headers) + total_size = None + cr = first_resp.headers.get('content-range', '') + if '/' in cr: + try: + total_size = int(cr.split('/')[-1]) + except (ValueError, IndexError): + pass + if total_size is None and 'content-length' in first_resp.headers: + try: + total_size = int(first_resp.headers['content-length']) + except (ValueError, IndexError): + pass + + # Figure out the absolute start byte so retries can resume correctly + range_start = 0 + if client_range: + try: + range_start = int(client_range.split('=')[1].split('-')[0]) + except Exception: + pass + + # -- Begin streaming to client ------------------------------------- + resp = _safe_stream_response(first_resp.status, resp_headers) + self._active_streams += 1 + try: + await resp.prepare(request) + except (ConnectionResetError, ConnectionAbortedError): + self._active_streams -= 1 + return resp + + bytes_sent = 0 + upstream_ok = True + try: + async for chunk in first_resp.content.iter_any(): + try: + await resp.write(chunk) + bytes_sent += len(chunk) + except (ConnectionResetError, ConnectionAbortedError, BrokenPipeError, OSError): + # Client disconnected — nothing to retry + self._active_streams -= 1 + return resp + except (aiohttp.ClientError, aiohttp.ClientPayloadError, asyncio.TimeoutError, OSError) as exc: + logger.warning(f'[DOODSTREAM-PROXY] Upstream dropped at {bytes_sent} bytes: {exc}') + upstream_ok = False + except Exception as exc: + logger.warning(f'[DOODSTREAM-PROXY] Upstream error at {bytes_sent} bytes: {exc}') + upstream_ok = False + + # -- Retry loop (runs only when upstream dropped) ---------------------- + if not upstream_ok: + current_pos = range_start + bytes_sent + for attempt in range(1, MAX_RETRIES + 1): + if total_size is not None and current_pos >= total_size: + break # We actually got everything + + retry_headers = dict(up_headers) + if total_size: + retry_headers['Range'] = f'bytes={current_pos}-{total_size - 1}' + else: + retry_headers['Range'] = f'bytes={current_pos}-' + + await asyncio.sleep(min(1.0 * attempt, 3.0)) # back-off + + try: + async with session.get(target_url, headers=retry_headers, timeout=timeout) as retry_resp: + if retry_resp.status not in (200, 206): + logger.warning(f'[DOODSTREAM-PROXY] Retry {attempt} status {retry_resp.status}') + continue + try: + async for chunk in retry_resp.content.iter_any(): + try: + await resp.write(chunk) + bytes_sent += len(chunk) + current_pos += len(chunk) + except (ConnectionResetError, ConnectionAbortedError, BrokenPipeError, OSError): + self._active_streams -= 1 + return resp + except (aiohttp.ClientError, aiohttp.ClientPayloadError, asyncio.TimeoutError, OSError) as exc: + logger.warning(f'[DOODSTREAM-PROXY] Retry {attempt} dropped at +{bytes_sent} bytes: {exc}') + continue + except Exception as exc: + logger.warning(f'[DOODSTREAM-PROXY] Retry {attempt} error: {exc}') + continue + + # If we reached here the retry stream finished normally + if total_size is None or current_pos >= total_size: + break + except (aiohttp.ClientError, asyncio.TimeoutError) as exc: + logger.warning(f'[DOODSTREAM-PROXY] Retry {attempt} connect failed: {exc}') + continue + + # -- Finalise ---------------------------------------------------------- + try: + await resp.write_eof() + except Exception: + pass + self._active_streams -= 1 + return resp + + except asyncio.TimeoutError: + return web.json_response({'error': 'Timeout'}, status=504, headers=CORS_HEADERS) + except aiohttp.ClientError as exc: + return web.json_response({'error': str(exc)}, status=502, headers=CORS_HEADERS) + except Exception as exc: + logger.error(f'[DOODSTREAM-PROXY] Fatal: {exc}') + return web.json_response({'error': str(exc)}, status=500, headers=CORS_HEADERS) + + async def seekstreaming_proxy_handler(self, request: Request) -> Response: + """SeekStreaming / embed4me proxy""" + referer = request.query.get('referer') + origin = request.query.get('origin') + + default_domain = 'lpayer.embed4me.com' + + headers = { + 'Accept': '*/*', + 'Referer': referer if referer else f'https://{default_domain}/', + 'Origin': origin if origin else f'https://{default_domain}', + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36' + } + + return await self._service_proxy(request, 'seekstreaming', headers) + + async def cinep_proxy_handler(self, request: Request) -> Response: + """CinePulse proxy""" + return await self._service_proxy(request, 'cinep', { + 'Accept': 'application/vnd.apple.mpegurl,*/*', + 'Origin': 'https://cinepulse.lol', + 'Referer': 'https://cinepulse.lol/', + 'User-Agent': 'Mozilla/5.0 Chrome/143.0.0.0' + }) + + # ===== DRM Proxy Handlers (WideFrog integration) ===== + + async def drm_extract_handler(self, request: Request) -> Response: + """Extract manifest info from a content URL (JSON API, GET or POST)""" + # VIP check — DRM extraction is a premium feature + if not await self._check_vip(request): + return self._vip_denied_response() + + # Support both GET ?url= and POST {"url": ...} like proxy_server.py + if request.method == 'POST': + try: + body = await request.json() + content_url = body.get('url', '').strip() + except Exception: + content_url = '' + else: + content_url = request.query.get('url', '').strip() + + if not content_url: + return web.json_response({'error': "Missing 'url' parameter"}, status=400, headers=CORS_HEADERS) + + try: + loop = asyncio.get_event_loop() + info = await loop.run_in_executor(_DRM_EXECUTOR, _extract_manifest_sync, content_url) + return web.json_response({ + 'manifest_url': info['manifest_url'], + 'all_manifests': info['all_manifests'], + 'proxied_manifest_url': _drm_proxy_url(info['manifest_url'], '/drm/manifest'), + 'manifest_type': info['manifest_type'], + 'keys': info['keys'], + 'key_errors': info.get('key_errors', []), + 'pssh': info.get('pssh', []), + 'is_hls_aes': info['is_hls_aes'], + 'title': info['title'], + }, headers=CORS_HEADERS) + except Exception as e: + traceback.print_exc() + return web.json_response({'error': str(e)}, status=500, headers=CORS_HEADERS) + + async def drm_manifest_handler(self, request: Request) -> Response: + """Fetch a manifest, rewrite its URLs, and return it through the DRM proxy""" + target_url = request.query.get('url', '') + if not target_url: + return web.Response(text='Missing url parameter', status=400) + + target_url = urllib.parse.unquote(target_url) + + # Build headers + headers = { + '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', + 'Accept': '*/*', + 'Accept-Language': 'en-US,en;q=0.9', + } + if _WIDEFROG_AVAILABLE and hasattr(builtins, 'CONFIG'): + headers['User-Agent'] = builtins.CONFIG.get('USER_AGENT', headers['User-Agent']) + + # Use proxy for France.tv CDN domains (need French IP) + if self._is_francetv_url(target_url): + session = self.sessions.get('proxy_0', self.sessions['normal']) + headers['Accept-Language'] = 'fr-FR,fr;q=0.9,en;q=0.6' + headers['Origin'] = 'https://www.france.tv' + headers['Referer'] = 'https://www.france.tv/' + logger.info(f'[drm/manifest] Using proxy for france.tv URL: {target_url[:120]}') + else: + session = self.sessions['normal'] + try: + async with session.get(target_url, headers=headers, + timeout=ClientTimeout(total=30)) as response: + body = await response.text() + resp_content_type = response.headers.get('Content-Type', '').lower() + if response.status == 403: + logger.warning(f'[drm/manifest] 403 on {target_url[:150]}') + return web.json_response({'msg': 'Access denied', 'code': 1400}, status=403, headers=CORS_HEADERS) + except Exception as e: + return web.Response(text=f'Failed to fetch manifest: {e}', status=502) + + content_type = 'application/octet-stream' + base_url = target_url.rsplit('/', 1)[0] + '/' + + # Detect type from content, URL, and Content-Type header (like proxy_server.py) + if '#EXTM3U' in body or 'm3u8' in target_url.lower() or 'mpegurl' in resp_content_type: + body = _drm_rewrite_m3u8(body, base_url) + content_type = 'application/vnd.apple.mpegurl' + elif ' Response: + """Generic proxy for DRM segments, keys, init data, sub-playlists""" + target_url = request.query.get('url', '') + if not target_url: + return web.Response(text='Missing url parameter', status=400) + + target_url = urllib.parse.unquote(target_url) + + headers = { + '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', + 'Accept': '*/*', + 'Accept-Language': 'en-US,en;q=0.9', + } + if _WIDEFROG_AVAILABLE and hasattr(builtins, 'CONFIG'): + headers['User-Agent'] = builtins.CONFIG.get('USER_AGENT', headers['User-Agent']) + + # Forward range headers + range_header = request.headers.get('Range') or request.headers.get('range') + if range_header: + headers['Range'] = range_header + + # Determine content type for streaming optimization + content = detect_content_type(target_url, request.headers.get('accept', '')) + + if content.is_ts or content.is_m4s: + timeout = ClientTimeout(total=None, connect=10, sock_read=60) + elif content.is_mp4: + timeout = ClientTimeout(total=None, connect=10, sock_read=30) + else: + timeout = ClientTimeout(total=60, connect=10) + + # Use proxy for France.tv CDN domains + if self._is_francetv_url(target_url): + session = self.sessions.get('proxy_0', self.sessions['normal']) + headers['Accept-Language'] = 'fr-FR,fr;q=0.9,en;q=0.6' + headers['Origin'] = 'https://www.france.tv' + headers['Referer'] = 'https://www.france.tv/' + else: + session = self.sessions['normal'] + try: + async with session.get(target_url, headers=headers, timeout=timeout) as response: + resp_headers = self._prepare_stream_headers(response.headers) + body_bytes = await response.read() + content_type_header = response.headers.get('Content-Type', 'application/octet-stream') + + # If sub-playlist (m3u8), rewrite URLs + is_m3u8 = 'mpegurl' in content_type_header.lower() or target_url.lower().split('?')[0].endswith('.m3u8') + try: + if is_m3u8 or body_bytes[:7] == b'#EXTM3U': + text = body_bytes.decode('utf-8', errors='replace') + base_url = target_url.rsplit('/', 1)[0] + '/' + text = _drm_rewrite_m3u8(text, base_url) + body_bytes = text.encode('utf-8') + content_type_header = 'application/vnd.apple.mpegurl' + except Exception: + pass + + # If DASH sub-manifest + is_mpd = 'dash' in content_type_header.lower() or target_url.lower().split('?')[0].endswith('.mpd') + try: + if is_mpd and b' Response: + """Path-based proxy for DASH: resolves subpath relative to decoded base URL. + Used when is set to /drm/b// in rewritten MPD manifests.""" + base_b64 = request.match_info['base_b64'] + subpath = request.match_info['subpath'] + + # Decode base URL + padding = 4 - len(base_b64) % 4 + if padding != 4: + base_b64 += '=' * padding + try: + decoded_base = base64.urlsafe_b64decode(base_b64).decode() + except Exception: + return web.Response(text='Invalid base encoding', status=400) + + target_url = decoded_base + subpath + + # Preserve query string + if request.query_string: + target_url += '?' + request.query_string + + headers = { + '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', + 'Accept': '*/*', + 'Accept-Language': 'en-US,en;q=0.9', + } + if _WIDEFROG_AVAILABLE and hasattr(builtins, 'CONFIG'): + headers['User-Agent'] = builtins.CONFIG.get('USER_AGENT', headers['User-Agent']) + + range_header = request.headers.get('Range') or request.headers.get('range') + if range_header: + headers['Range'] = range_header + + content = detect_content_type(target_url, request.headers.get('accept', '')) + + if content.is_ts or content.is_m4s: + timeout = ClientTimeout(total=None, connect=10, sock_read=60) + elif content.is_mp4: + timeout = ClientTimeout(total=None, connect=10, sock_read=30) + else: + timeout = ClientTimeout(total=60, connect=10) + + # Use proxy for France.tv CDN domains + if self._is_francetv_url(target_url): + session = self.sessions.get('proxy_0', self.sessions['normal']) + headers['Accept-Language'] = 'fr-FR,fr;q=0.9,en;q=0.6' + headers['Origin'] = 'https://www.france.tv' + headers['Referer'] = 'https://www.france.tv/' + else: + session = self.sessions['normal'] + try: + async with session.get(target_url, headers=headers, timeout=timeout) as response: + resp_headers = self._prepare_stream_headers(response.headers) + body_bytes = await response.read() + content_type_header = response.headers.get('Content-Type', 'application/octet-stream') + + # Rewrite sub-manifests + try: + if b'#EXTM3U' in body_bytes[:20]: + text = body_bytes.decode('utf-8', errors='replace') + text_base = target_url.rsplit('/', 1)[0] + '/' + text = _drm_rewrite_m3u8(text, text_base) + body_bytes = text.encode('utf-8') + content_type_header = 'application/vnd.apple.mpegurl' + elif b' { + if (!value) return fallback; + if (value === 'true') return true; + if (value === '*') return '*'; + if (value.includes(',')) return value.split(',').map((v) => v.trim()).filter(Boolean); + return value; +}; + +const WATCHPARTY_CORS_CREDENTIALS = (process.env.WATCHPARTY_CORS_CREDENTIALS || 'true') === 'true'; +const WATCHPARTY_REST_CORS_ORIGIN = parseCorsOrigin(process.env.WATCHPARTY_REST_CORS_ORIGIN, true); +const WATCHPARTY_SOCKET_CORS_ORIGIN = parseCorsOrigin(process.env.WATCHPARTY_SOCKET_CORS_ORIGIN, '*'); +const WATCHPARTY_SOCKET_CORS_METHODS = (process.env.WATCHPARTY_SOCKET_CORS_METHODS || 'GET,POST') + .split(',') + .map((method) => method.trim()) + .filter(Boolean); +const app = express(); + +// Autoriser toutes les origines (API REST) +app.use(cors({ origin: WATCHPARTY_REST_CORS_ORIGIN, credentials: WATCHPARTY_CORS_CREDENTIALS })); +app.use(express.json({ limit: '100mb' })); + +// HTTP server + Socket.IO (CORS ouvert) +const server = createServer(app); +const io = new SocketIOServer(server, { + cors: { + origin: WATCHPARTY_SOCKET_CORS_ORIGIN, + methods: WATCHPARTY_SOCKET_CORS_METHODS, + credentials: WATCHPARTY_CORS_CREDENTIALS + } +}); + +// --- Persistance basique des rooms --- +const CACHE_DIR = path.join(__dirname, 'cache'); +const WATCHPARTY_ROOMS_FILE = path.join(CACHE_DIR, 'watchparty-rooms.json'); +const watchpartyRooms = new Map(); + +async function ensureCacheDir() { + try { await fsp.access(CACHE_DIR); } catch { await fsp.mkdir(CACHE_DIR, { recursive: true }); } +} + +async function loadRoomsFromDisk() { + try { + await ensureCacheDir(); + const data = await fsp.readFile(WATCHPARTY_ROOMS_FILE, 'utf-8'); + const roomsArray = JSON.parse(data); + roomsArray.forEach((room) => watchpartyRooms.set(room.id, room)); + // Optionnel: supprimer le fichier après restauration, comme dans le serveur principal + try { await fsp.unlink(WATCHPARTY_ROOMS_FILE); } catch { } + console.log(`[Watchparty] ${roomsArray.length} rooms restaurées depuis le disque.`); + } catch { } +} + +async function saveRoomsToDisk() { + try { + await ensureCacheDir(); + const roomsArray = Array.from(watchpartyRooms.values()); + await fsp.writeFile(WATCHPARTY_ROOMS_FILE, JSON.stringify(roomsArray, null, 2), 'utf-8'); + console.log(`[Watchparty] ${roomsArray.length} rooms sauvegardées sur le disque.`); + } catch (e) { + console.error('[Watchparty] Erreur lors de la sauvegarde des rooms:', e); + } +} + +let isShuttingDown = false; +async function gracefulShutdown(signal) { + if (isShuttingDown) return; + isShuttingDown = true; + console.log(`[Watchparty] Signal ${signal} reçu. Sauvegarde des rooms avant arrêt...`); + await saveRoomsToDisk(); + try { io.close(); } catch { } + try { server.close(() => process.exit(0)); } catch { process.exit(0); } +} +process.on('SIGTERM', () => gracefulShutdown('SIGTERM')); +process.on('SIGINT', () => gracefulShutdown('SIGINT')); + +// --- Helpers --- +function generateRoomCode() { + const charset = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; + let result = ''; + for (let i = 0; i < 6; i++) result += charset[Math.floor(Math.random() * charset.length)]; + return result; +} + +// --- Socket.IO namespace dédié watchparty --- +const watchpartyIO = io.of('/watchparty'); +const SYNC_PRO_SCHEDULE_DELAY_MS = 250; + +function buildRoomInfo(roomId, room) { + return { + id: roomId, + code: room.code, + hostId: room.hostId, + maxParticipants: room.maxParticipants, + isPublic: !!room.isPublic, + syncMode: room.syncMode || 'classic', + chatEnabled: room.chatEnabled !== false, + controlMode: room.controlMode, + coHosts: room.coHosts, + media: room.media, + createdAt: room.createdAt, + participants: room.participants + }; +} + +function emitRoomInfo(roomId, room) { + watchpartyIO.to(roomId).emit('room:info', buildRoomInfo(roomId, room)); +} + +function emitControlState(roomId, room) { + watchpartyIO.to(roomId).emit('control:state', { + controlMode: room.controlMode, + coHosts: room.coHosts, + pendingRequests: room.pendingControlRequests + }); +} + +function buildScheduledPlaybackEvent(playbackUpdate, action) { + const serverNow = Date.now(); + return { + action, + position: playbackUpdate.position, + scheduledAt: serverNow + SYNC_PRO_SCHEDULE_DELAY_MS, + serverNow, + updatedBy: playbackUpdate.updatedBy + }; +} + +watchpartyIO.on('connection', (socket) => { + console.log('New watch party connection:', socket.id); + + const roomId = socket.handshake.query.roomId; + const nickname = socket.handshake.query.nickname || 'Guest'; + + if (!roomId || !watchpartyRooms.has(roomId)) { + console.log(`Invalid room ID: ${roomId}`); + socket.emit('error', { message: 'Invalid room ID' }); + socket.disconnect(); + return; + } + + // Join room + socket.join(roomId); + const room = watchpartyRooms.get(roomId); + + // Add participant + const participant = { + id: socket.id, + nickname, + isHost: room.participants.length === 0, + isActive: true, + joinedAt: Date.now() + }; + if (room.participants.length === 0) room.hostId = socket.id; + room.participants.push(participant); + + // Emit room info + participants + emitRoomInfo(roomId, room); + watchpartyIO.to(roomId).emit('room:participants', room.participants); + // Send control state and ready state to the new participant + socket.emit('control:state', { + controlMode: room.controlMode, + coHosts: room.coHosts, + pendingRequests: room.pendingControlRequests + }); + socket.emit('ready:state', room.readyState); + + // System join message + const joinMessage = { + id: uuidv4(), + senderId: 'system', + senderNickname: 'System', + text: `${participant.nickname} a rejoint la Watch Party.`, + timestamp: Date.now(), + type: 'system' + }; + room.messages.push(joinMessage); + watchpartyIO.to(roomId).emit('room:chat', joinMessage); + + // Send current playback state + chat history + pause timer + socket.emit('room:playback', room.playbackState); + if (room.pauseTimer && room.pauseTimer.endTime > Date.now()) { + socket.emit('pause:timerStarted', room.pauseTimer); + } + room.messages.filter(m => !m.deleted).forEach(m => socket.emit('room:chat', m)); + + // Chat + socket.on('chat:message', (data) => { + if (!watchpartyRooms.has(roomId)) return; + const r = watchpartyRooms.get(roomId); + if (r.chatEnabled === false && socket.id !== r.hostId) return; + const me = r.participants.find(p => p.id === socket.id); + if (!me) return; + const msg = { + id: uuidv4(), + senderId: socket.id, + senderNickname: me.nickname, + text: data.text, + timestamp: Date.now(), + type: 'chat' + }; + r.messages.push(msg); + if (r.messages.length > 100) r.messages.shift(); + watchpartyIO.to(roomId).emit('room:chat', msg); + }); + + socket.on('playback:update', (data) => { + if (!watchpartyRooms.has(roomId)) return; + const r = watchpartyRooms.get(roomId); + // Check if user can control: host, co-host, or democratic mode + const canControl = socket.id === r.hostId || + r.coHosts.includes(socket.id) || + r.controlMode === 'democratic'; + + console.log(`[Playback] User ${socket.id} trying to update. Host: ${r.hostId}, CoHosts: [${r.coHosts.join(', ')}], Mode: ${r.controlMode}, CanControl: ${canControl}`); + + if (canControl) { + const playbackUpdate = { + isPlaying: data.isPlaying, + position: data.position, + updatedAt: Date.now(), + updatedBy: socket.id + }; + const reason = ['play', 'pause', 'seek', 'heartbeat', 'ended'].includes(data.reason) + ? data.reason + : 'heartbeat'; + r.playbackState = playbackUpdate; + // Broadcast aux autres clients (exclure le sender pour éviter la boucle de feedback) + socket.to(roomId).emit('playback:state', playbackUpdate); + if (r.syncMode === 'pro' && reason !== 'heartbeat') { + socket.to(roomId).emit( + 'playback:schedule', + buildScheduledPlaybackEvent(playbackUpdate, reason === 'ended' ? 'pause' : reason) + ); + } + } else { + console.log(`[Playback] REJECTED update from ${socket.id} - not authorized`); + } + }); + + // Control request from participant + socket.on('control:request', () => { + if (!watchpartyRooms.has(roomId)) return; + const r = watchpartyRooms.get(roomId); + if (socket.id === r.hostId || r.coHosts.includes(socket.id)) return; // Already has control + const me = r.participants.find(p => p.id === socket.id); + if (!me) return; + // Check if already pending + if (r.pendingControlRequests.some(req => req.participantId === socket.id)) return; + r.pendingControlRequests.push({ + participantId: socket.id, + nickname: me.nickname, + requestedAt: Date.now() + }); + // Notify host of request + const hostSocket = watchpartyIO.sockets.get(r.hostId); + if (hostSocket) { + hostSocket.emit('control:requestReceived', { participantId: socket.id, nickname: me.nickname }); + } + // Broadcast updated control state + watchpartyIO.to(roomId).emit('control:state', { + controlMode: r.controlMode, + coHosts: r.coHosts, + pendingRequests: r.pendingControlRequests + }); + }); + + // Host approves control request + socket.on('control:approve', ({ participantId }) => { + if (!watchpartyRooms.has(roomId)) return; + const r = watchpartyRooms.get(roomId); + if (socket.id !== r.hostId) return; // Only host can approve + // Remove from pending + r.pendingControlRequests = r.pendingControlRequests.filter(req => req.participantId !== participantId); + // Add to co-hosts if not already + if (!r.coHosts.includes(participantId)) { + r.coHosts.push(participantId); + } + // Notify the participant + const targetSocket = watchpartyIO.sockets.get(participantId); + if (targetSocket) { + targetSocket.emit('control:approved'); + } + // System message + const participant = r.participants.find(p => p.id === participantId); + const systemMsg = { + id: uuidv4(), senderId: 'system', senderNickname: 'System', + text: `${participant?.nickname || 'Un participant'} peut maintenant contrôler la lecture.`, + timestamp: Date.now(), type: 'system' + }; + r.messages.push(systemMsg); + watchpartyIO.to(roomId).emit('room:chat', systemMsg); + // Broadcast updated control state + watchpartyIO.to(roomId).emit('control:state', { + controlMode: r.controlMode, + coHosts: r.coHosts, + pendingRequests: r.pendingControlRequests + }); + }); + + // Host denies control request + socket.on('control:deny', ({ participantId }) => { + if (!watchpartyRooms.has(roomId)) return; + const r = watchpartyRooms.get(roomId); + if (socket.id !== r.hostId) return; + r.pendingControlRequests = r.pendingControlRequests.filter(req => req.participantId !== participantId); + const targetSocket = watchpartyIO.sockets.get(participantId); + if (targetSocket) { + targetSocket.emit('control:denied'); + } + watchpartyIO.to(roomId).emit('control:state', { + controlMode: r.controlMode, + coHosts: r.coHosts, + pendingRequests: r.pendingControlRequests + }); + }); + + // Host revokes control from co-host + socket.on('control:revoke', ({ participantId }) => { + if (!watchpartyRooms.has(roomId)) return; + const r = watchpartyRooms.get(roomId); + if (socket.id !== r.hostId) return; + r.coHosts = r.coHosts.filter(id => id !== participantId); + const targetSocket = watchpartyIO.sockets.get(participantId); + if (targetSocket) { + targetSocket.emit('control:revoked'); + } + watchpartyIO.to(roomId).emit('control:state', { + controlMode: r.controlMode, + coHosts: r.coHosts, + pendingRequests: r.pendingControlRequests + }); + }); + + // Host toggles control mode + socket.on('control:setMode', ({ mode }) => { + if (!watchpartyRooms.has(roomId)) return; + const r = watchpartyRooms.get(roomId); + if (socket.id !== r.hostId) return; + if (mode === 'host-only' || mode === 'democratic') { + r.controlMode = mode; + const systemMsg = { + id: uuidv4(), senderId: 'system', senderNickname: 'System', + text: mode === 'democratic' + ? '🎮 Mode démocratique activé - Tout le monde peut contrôler la lecture !' + : '🔒 Mode hôte activé - Seul l\'hôte contrôle la lecture.', + timestamp: Date.now(), type: 'system' + }; + r.messages.push(systemMsg); + watchpartyIO.to(roomId).emit('room:chat', systemMsg); + watchpartyIO.to(roomId).emit('control:state', { + controlMode: r.controlMode, + coHosts: r.coHosts, + pendingRequests: r.pendingControlRequests + }); + } + }); + + socket.on('sync:setMode', ({ mode }) => { + if (!watchpartyRooms.has(roomId)) return; + const r = watchpartyRooms.get(roomId); + if (socket.id !== r.hostId) return; + if (mode !== 'classic' && mode !== 'pro') return; + if (r.syncMode === mode) return; + + r.syncMode = mode; + const systemMsg = { + id: uuidv4(), + senderId: 'system', + senderNickname: 'System', + text: mode === 'pro' + ? 'Sync Pro activé par l’hôte. La synchronisation avancée est maintenant active.' + : 'Le mode de synchronisation classique a été réactivé par l’hôte.', + timestamp: Date.now(), + type: 'system' + }; + r.messages.push(systemMsg); + watchpartyIO.to(roomId).emit('room:chat', systemMsg); + watchpartyIO.to(roomId).emit('sync:modeChanged', { + mode, + changedBy: socket.id + }); + emitRoomInfo(roomId, r); + }); + + socket.on('sync:probe', ({ probeId, clientSentAt }) => { + if (!watchpartyRooms.has(roomId)) return; + const serverReceivedAt = Date.now(); + socket.emit('sync:probeResult', { + probeId, + clientSentAt, + serverReceivedAt, + serverSentAt: Date.now() + }); + }); + + socket.on('playback:buffering', ({ isBuffering, position }) => { + if (!watchpartyRooms.has(roomId)) return; + socket.to(roomId).emit('playback:buffering', { + participantId: socket.id, + isBuffering: !!isBuffering, + position: Number.isFinite(position) ? position : 0 + }); + }); + + socket.on('room:setVisibility', ({ isPublic }) => { + if (!watchpartyRooms.has(roomId)) return; + const r = watchpartyRooms.get(roomId); + if (socket.id !== r.hostId) return; + r.isPublic = isPublic === true; + emitRoomInfo(roomId, r); + }); + + socket.on('room:toggleChat', ({ enabled }) => { + if (!watchpartyRooms.has(roomId)) return; + const r = watchpartyRooms.get(roomId); + if (socket.id !== r.hostId) return; + r.chatEnabled = enabled !== false; + watchpartyIO.to(roomId).emit('room:chatToggled', { enabled: r.chatEnabled }); + emitRoomInfo(roomId, r); + }); + + socket.on('room:setMaxParticipants', ({ max }) => { + if (!watchpartyRooms.has(roomId)) return; + const r = watchpartyRooms.get(roomId); + if (socket.id !== r.hostId) return; + const parsedMax = Math.max(r.participants.length, Math.min(50, Number(max) || 10)); + r.maxParticipants = parsedMax; + emitRoomInfo(roomId, r); + }); + + socket.on('media:change', (media) => { + if (!watchpartyRooms.has(roomId)) return; + const r = watchpartyRooms.get(roomId); + if (socket.id !== r.hostId) return; + + r.media = { + src: media.src || '', + title: media.title || 'Media', + poster: media.poster || null, + mediaType: media.mediaType || 'movie', + mediaId: media.mediaId || null, + seasonNumber: media.seasonNumber || null, + episodeNumber: media.episodeNumber || null, + nightflixSources: media.nightflixSources || [], + nexusSources: media.nexusSources || [], + bravoSources: media.bravoSources || [], + mp4Sources: media.mp4Sources || [], + rivestreamSources: media.rivestreamSources || [], + captions: media.captions || [], + currentNexusSource: media.currentNexusSource || null, + currentBravoSource: media.currentBravoSource || null + }; + r.playbackState = { + isPlaying: false, + position: 0, + updatedAt: Date.now(), + updatedBy: socket.id + }; + + watchpartyIO.to(roomId).emit('media:updated', r.media); + watchpartyIO.to(roomId).emit('playback:state', r.playbackState); + emitRoomInfo(roomId, r); + }); + + // Ready toggle + socket.on('ready:toggle', () => { + if (!watchpartyRooms.has(roomId)) return; + const r = watchpartyRooms.get(roomId); + r.readyState[socket.id] = !r.readyState[socket.id]; + watchpartyIO.to(roomId).emit('ready:state', r.readyState); + }); + + // Emoji reaction + socket.on('reaction:send', ({ emoji }) => { + if (!watchpartyRooms.has(roomId)) return; + const r = watchpartyRooms.get(roomId); + const me = r.participants.find(p => p.id === socket.id); + if (!me) return; + watchpartyIO.to(roomId).emit('reaction:received', { + id: uuidv4(), + emoji, + senderId: socket.id, + senderNickname: me.nickname, + timestamp: Date.now() + }); + }); + + // Pause timer start (host or co-host) + socket.on('pause:start', ({ duration }) => { + if (!watchpartyRooms.has(roomId)) return; + const r = watchpartyRooms.get(roomId); + const canControl = socket.id === r.hostId || r.coHosts.includes(socket.id); + if (!canControl) return; + const durationMs = (duration || 60) * 1000; // Default 60 seconds + r.pauseTimer = { + endTime: Date.now() + durationMs, + startedBy: socket.id, + duration: duration || 60 + }; + // Pause playback + r.playbackState.isPlaying = false; + r.playbackState.updatedAt = Date.now(); + r.playbackState.updatedBy = socket.id; + watchpartyIO.to(roomId).emit('playback:state', r.playbackState); + if (r.syncMode === 'pro') { + watchpartyIO.to(roomId).emit('playback:schedule', buildScheduledPlaybackEvent(r.playbackState, 'pause')); + } + watchpartyIO.to(roomId).emit('pause:timerStarted', r.pauseTimer); + // System message + const me = r.participants.find(p => p.id === socket.id); + const systemMsg = { + id: uuidv4(), senderId: 'system', senderNickname: 'System', + text: `⏸️ ${me?.nickname || 'L\'hôte'} a lancé une pause de ${duration || 60} secondes.`, + timestamp: Date.now(), type: 'system' + }; + r.messages.push(systemMsg); + watchpartyIO.to(roomId).emit('room:chat', systemMsg); + }); + + // Pause timer cancel + socket.on('pause:cancel', () => { + if (!watchpartyRooms.has(roomId)) return; + const r = watchpartyRooms.get(roomId); + const canControl = socket.id === r.hostId || r.coHosts.includes(socket.id); + if (!canControl) return; + r.pauseTimer = null; + watchpartyIO.to(roomId).emit('pause:timerCancelled'); + }); + + // Vote request for pause (guests only) + socket.on('vote:request', ({ duration }) => { + if (!watchpartyRooms.has(roomId)) return; + const r = watchpartyRooms.get(roomId); + // Only non-hosts can request a vote + if (socket.id === r.hostId || r.coHosts.includes(socket.id)) return; + // Don't allow vote if one is already in progress + if (r.pauseVote) return; + + const me = r.participants.find(p => p.id === socket.id); + if (!me) return; + + const voteDuration = 20000; // 20 seconds to vote + r.pauseVote = { + requestedBy: socket.id, + requestedByNickname: me.nickname, + requestedDuration: duration || 60, + votes: {}, // participantId -> true (yes) or false (no) + endTime: Date.now() + voteDuration, + totalParticipants: r.participants.length + }; + + // Auto-resolve after 20 seconds + r.pauseVote.timeoutId = setTimeout(() => { + if (watchpartyRooms.has(roomId)) { + const room = watchpartyRooms.get(roomId); + if (room.pauseVote) { + resolveVote(roomId); + } + } + }, voteDuration); + + // Notify everyone about the vote + watchpartyIO.to(roomId).emit('vote:started', { + requestedBy: socket.id, + requestedByNickname: me.nickname, + requestedDuration: duration || 60, + endTime: r.pauseVote.endTime, + totalParticipants: r.participants.length + }); + + // System message + const voteMsg = { + id: uuidv4(), + senderId: 'system', + senderNickname: 'System', + text: `${me.nickname} a demandé une pause de ${duration || 60}s. Vote en cours...`, + timestamp: Date.now(), + type: 'system' + }; + r.messages.push(voteMsg); + watchpartyIO.to(roomId).emit('room:chat', voteMsg); + }); + + // Cast vote + socket.on('vote:cast', ({ vote }) => { + if (!watchpartyRooms.has(roomId)) return; + const r = watchpartyRooms.get(roomId); + if (!r.pauseVote) return; + + // Record vote (true = yes, false = no) + r.pauseVote.votes[socket.id] = vote === true; + + // Broadcast vote update + const yesVotes = Object.values(r.pauseVote.votes).filter(v => v === true).length; + const noVotes = Object.values(r.pauseVote.votes).filter(v => v === false).length; + const totalVotes = Object.keys(r.pauseVote.votes).length; + + watchpartyIO.to(roomId).emit('vote:update', { + yesVotes, + noVotes, + totalVotes, + totalParticipants: r.pauseVote.totalParticipants + }); + + // Check if everyone has voted + if (totalVotes >= r.pauseVote.totalParticipants) { + // Clear the timeout since everyone voted + if (r.pauseVote.timeoutId) { + clearTimeout(r.pauseVote.timeoutId); + } + resolveVote(roomId); + } + }); + + // Helper function to resolve vote + function resolveVote(roomId) { + if (!watchpartyRooms.has(roomId)) return; + const r = watchpartyRooms.get(roomId); + if (!r.pauseVote) return; + + const yesVotes = Object.values(r.pauseVote.votes).filter(v => v === true).length; + const totalVotes = Object.keys(r.pauseVote.votes).length; + const majority = Math.ceil(r.pauseVote.totalParticipants / 2); + + const passed = yesVotes >= majority; + + if (passed) { + // Start the pause timer + const durationMs = r.pauseVote.requestedDuration * 1000; + r.pauseTimer = { + endTime: Date.now() + durationMs, + startedBy: r.pauseVote.requestedBy, + duration: r.pauseVote.requestedDuration + }; + // Pause playback + r.playbackState.isPlaying = false; + r.playbackState.updatedAt = Date.now(); + r.playbackState.updatedBy = 'vote'; + watchpartyIO.to(roomId).emit('playback:state', r.playbackState); + if (r.syncMode === 'pro') { + watchpartyIO.to(roomId).emit('playback:schedule', buildScheduledPlaybackEvent(r.playbackState, 'pause')); + } + watchpartyIO.to(roomId).emit('pause:timerStarted', r.pauseTimer); + + // System message + const passMsg = { + id: uuidv4(), + senderId: 'system', + senderNickname: 'System', + text: `✅ Vote accepté (${yesVotes}/${r.pauseVote.totalParticipants}). Pause de ${r.pauseVote.requestedDuration}s lancée.`, + timestamp: Date.now(), + type: 'system' + }; + r.messages.push(passMsg); + watchpartyIO.to(roomId).emit('room:chat', passMsg); + } else { + // System message + const failMsg = { + id: uuidv4(), + senderId: 'system', + senderNickname: 'System', + text: `❌ Vote refusé (${yesVotes}/${r.pauseVote.totalParticipants}). La majorité n'a pas été atteinte.`, + timestamp: Date.now(), + type: 'system' + }; + r.messages.push(failMsg); + watchpartyIO.to(roomId).emit('room:chat', failMsg); + } + + // Notify result and clear vote + watchpartyIO.to(roomId).emit('vote:ended', { + passed, + yesVotes, + noVotes: totalVotes - yesVotes, + totalParticipants: r.pauseVote.totalParticipants + }); + + // Clear timeout if it exists + if (r.pauseVote.timeoutId) { + clearTimeout(r.pauseVote.timeoutId); + } + r.pauseVote = null; + } + + // Delete message (host only) + socket.on('message:delete', ({ messageId }) => { + if (!watchpartyRooms.has(roomId)) return; + const r = watchpartyRooms.get(roomId); + if (socket.id !== r.hostId || !messageId) return; + const idx = r.messages.findIndex(m => m.id === messageId); + if (idx !== -1) { + r.messages[idx].deleted = true; + watchpartyIO.to(roomId).emit('message:deleted', { messageId }); + } + }); + + // Kick participant (host only) + socket.on('participant:kick', ({ participantId }) => { + if (!watchpartyRooms.has(roomId)) return; + const r = watchpartyRooms.get(roomId); + if (socket.id !== r.hostId || !participantId || participantId === r.hostId) return; + const target = r.participants.find(p => p.id === participantId); + if (!target) return; + const s = watchpartyIO.sockets.get(participantId); + if (s) { + s.emit('room:kicked', { reason: 'You have been removed from the watch party by the host.' }); + s.disconnect(true); + } + const kickMessage = { + id: uuidv4(), senderId: 'system', senderNickname: 'System', + text: `${target.nickname} a été retiré de la Watch Party.`, timestamp: Date.now(), type: 'system' + }; + r.messages.push(kickMessage); + watchpartyIO.to(roomId).emit('room:chat', kickMessage); + }); + + // Playback get state + socket.on('playback:getState', () => { + console.log(`Socket ${socket.id} requested playback state for room ${roomId}`); + if (!roomId || typeof roomId !== 'string') { + console.error(`[playback:getState] Invalid or missing roomId: ${roomId} for socket ${socket.id}`); + return; + } + if (!watchpartyRooms.has(roomId)) { + console.error(`[playback:getState] Room ${roomId} not found in watchpartyRooms for socket ${socket.id}. Available rooms: ${Array.from(watchpartyRooms.keys())}`); + const currentSocketRooms = Array.from(socket.rooms); + console.log(`[playback:getState] Socket ${socket.id} is currently in rooms: ${currentSocketRooms.join(', ')}`); + return; + } + + const r = watchpartyRooms.get(roomId); + if (!r) { + console.error(`[playback:getState] Room object for ${roomId} is unexpectedly undefined, though key exists.`); + return; + } + + if (!r.playbackState) { + console.warn(`[playback:getState] Room ${roomId} was missing playbackState. Initializing to default.`); + r.playbackState = { + isPlaying: false, + position: 0, + updatedAt: Date.now(), + updatedBy: null, + }; + } + + const stateToSend = r.playbackState; + socket.emit('playback:state', stateToSend); + console.log(`[playback:getState] Sent playback state to ${socket.id} for room ${roomId}:`, stateToSend); + }); + + // Disconnect + socket.on('disconnect', () => { + if (!watchpartyRooms.has(roomId)) return; + const r = watchpartyRooms.get(roomId); + const idx = r.participants.findIndex(p => p.id === socket.id); + if (idx === -1) return; + const leaving = r.participants[idx]; + r.participants.splice(idx, 1); + + const leaveMessage = { + id: uuidv4(), senderId: 'system', senderNickname: 'System', + text: `${leaving.nickname} a quitté la Watch Party.`, timestamp: Date.now(), type: 'system' + }; + r.messages.push(leaveMessage); + + // Reassign host if needed + if (socket.id === r.hostId && r.participants.length > 0) { + const newHost = r.participants.sort((a, b) => a.joinedAt - b.joinedAt)[0]; + r.hostId = newHost.id; newHost.isHost = true; + const newHostMsg = { + id: uuidv4(), senderId: 'system', senderNickname: 'System', + text: `${newHost.nickname} est maintenant l'hôte de la Watch Party.`, timestamp: Date.now(), type: 'system' + }; + r.messages.push(newHostMsg); + watchpartyIO.to(roomId).emit('room:chat', newHostMsg); + } + + // If empty, auto-clean after 5 min + if (r.participants.length === 0) { + setTimeout(() => { + const still = watchpartyRooms.get(roomId); + if (still && still.participants.length === 0) { + watchpartyRooms.delete(roomId); + console.log(`Room ${roomId} closed due to inactivity`); + } + }, 5 * 60 * 1000); + } else { + watchpartyIO.to(roomId).emit('room:participants', r.participants); + watchpartyIO.to(roomId).emit('room:chat', leaveMessage); + emitRoomInfo(roomId, r); + } + }); +}); + +// --- Routes API (mêmes que le serveur principal) --- +app.post('/api/watchparty/create', (req, res) => { + try { + const { nickname, maxParticipants, media, roomCode, isPublic, syncMode } = req.body || {}; + if (!nickname || !media?.src) { + return res.status(400).json({ success: false, message: 'Missing required fields: nickname, media.src' }); + } + + const roomId = uuidv4(); + const code = roomCode || generateRoomCode(); + + for (const [, room] of watchpartyRooms.entries()) { + if (room.code === code) return res.status(400).json({ success: false, message: 'Room code already in use. Please try again.' }); + } + + const newRoom = { + id: roomId, + code, + hostId: null, + maxParticipants: maxParticipants || 10, + isPublic: isPublic === true, + syncMode: syncMode === 'pro' ? 'pro' : 'classic', + chatEnabled: true, + controlMode: 'host-only', // 'host-only' | 'democratic' + coHosts: [], // Array of participant IDs with control + pendingControlRequests: [], // Array of {participantId, nickname, requestedAt} + readyState: {}, // Map: participantId -> boolean + pauseTimer: null, // {endTime, startedBy, duration} or null + pauseVote: null, // {requestedBy, requestedDuration, votes: {participantId: boolean}, endTime, timeoutId} + media: { + src: media.src, + title: media.title || 'Media', + poster: media.poster || null, + mediaType: media.mediaType || 'movie', + mediaId: media.mediaId || null, + seasonNumber: media.seasonNumber || null, + episodeNumber: media.episodeNumber || null, + nightflixSources: media.nightflixSources || [], + nexusSources: media.nexusSources || [], + bravoSources: media.bravoSources || [], + mp4Sources: media.mp4Sources || [], + rivestreamSources: media.rivestreamSources || [], // VO/VOSTFR HLS sources + captions: media.captions || [], // Subtitles/captions for the sources + currentNexusSource: media.currentNexusSource || null, + currentBravoSource: media.currentBravoSource || null + }, + participants: [], + messages: [], + playbackState: { + isPlaying: false, + position: media.position || 0, + updatedAt: Date.now(), + updatedBy: 'system' + }, + createdAt: Date.now() + }; + + watchpartyRooms.set(roomId, newRoom); + res.status(200).json({ success: true, roomId, roomCode: code }); + } catch (e) { + console.error('Error creating watch party:', e); + res.status(500).json({ success: false, message: 'Server error' }); + } +}); + +app.post('/api/watchparty/join', (req, res) => { + try { + const { roomCode, nickname } = req.body || {}; + if (!roomCode || !nickname) return res.status(400).json({ success: false, message: 'Missing required fields: roomCode, nickname' }); + + let foundRoomId = null; let foundRoom = null; + for (const [id, room] of watchpartyRooms.entries()) { + if (room.code === roomCode) { foundRoomId = id; foundRoom = room; break; } + } + if (!foundRoomId) return res.status(404).json({ success: false, message: 'Watch party not found. Please check the room code and try again.' }); + if (foundRoom.participants.length >= foundRoom.maxParticipants) return res.status(400).json({ success: false, message: 'This watch party is full.' }); + + res.status(200).json({ success: true, roomId: foundRoomId, roomCode }); + } catch (e) { + console.error('Error joining watch party:', e); + res.status(500).json({ success: false, message: 'Server error' }); + } +}); + +app.get('/api/watchparty/room/:roomId', (req, res) => { + const { roomId } = req.params; + if (!watchpartyRooms.has(roomId)) return res.status(404).json({ message: 'Room not found' }); + const room = watchpartyRooms.get(roomId); + res.json({ + room: { + id: roomId, + code: room.code, + hostId: room.hostId, + maxParticipants: room.maxParticipants, + isPublic: !!room.isPublic, + syncMode: room.syncMode || 'classic', + chatEnabled: room.chatEnabled !== false, + controlMode: room.controlMode, + coHosts: room.coHosts, + media: room.media, + createdAt: room.createdAt, + participants: room.participants.map(p => ({ id: p.id, nickname: p.nickname, isHost: p.id === room.hostId, isActive: p.isActive })), + playbackState: room.playbackState + } + }); +}); + +app.get('/api/watchparty/info/:code', (req, res) => { + try { + const { code } = req.params; + let foundRoom = null; + for (const room of watchpartyRooms.values()) { if (room.code === code) { foundRoom = room; break; } } + if (!foundRoom) return res.status(404).json({ success: false, message: 'Watch party not found' }); + res.status(200).json({ + success: true, room: { + title: foundRoom.media.title, + mediaType: foundRoom.media.mediaType, + participantCount: foundRoom.participants.length, + maxParticipants: foundRoom.maxParticipants, + isPublic: !!foundRoom.isPublic, + syncMode: foundRoom.syncMode || 'classic' + } + }); + } catch (e) { + console.error('Error getting watch party info by code:', e); + res.status(500).json({ success: false, message: 'Server error' }); + } +}); + +app.get('/api/watchparty/public', (_req, res) => { + try { + const publicRooms = []; + for (const [id, room] of watchpartyRooms.entries()) { + if (room.isPublic) publicRooms.push({ + id, + code: room.code, + title: room.media.title, + poster: room.media.poster, + mediaType: room.media.mediaType, + participantCount: room.participants.length, + maxParticipants: room.maxParticipants, + syncMode: room.syncMode || 'classic', + seasonNumber: room.media.seasonNumber, + episodeNumber: room.media.episodeNumber, + createdAt: room.createdAt + }); + } + res.status(200).json({ success: true, rooms: publicRooms }); + } catch (e) { + console.error('Error listing public watch parties:', e); + res.status(500).json({ success: false, message: 'Server error' }); + } +}); + +app.get('/api/watchparty/all', (_req, res) => { + try { + const allRooms = Array.from(watchpartyRooms.entries()).map(([id, room]) => ({ + id, + code: room.code, + hostId: room.hostId, + maxParticipants: room.maxParticipants, + isPublic: room.isPublic, + syncMode: room.syncMode || 'classic', + media: room.media, + participants: room.participants, + createdAt: room.createdAt, + playbackState: room.playbackState + })); + res.status(200).json({ success: true, rooms: allRooms }); + } catch (e) { + console.error('Error listing all watch parties:', e); + res.status(500).json({ success: false, message: 'Server error' }); + } +}); + +// Setup watchparty cleanup job (hourly) +setInterval(() => { + const nowTime = Date.now(); + const expiredRooms = []; + + // Find expired rooms (older than 12 hours or inactive for 3 hours) + for (const [roomId, room] of watchpartyRooms.entries()) { + const roomAge = nowTime - room.createdAt; + const isExpired = roomAge > 12 * 60 * 60 * 1000; // 12 hours + const isEmpty = room.participants.length === 0; + const inactiveFor = isEmpty ? nowTime - Math.max(...room.participants.map(p => p.joinedAt), room.createdAt) : 0; + const isInactive = isEmpty && inactiveFor > 3 * 60 * 60 * 1000; // 3 hours + + if (isExpired || isInactive) { + expiredRooms.push(roomId); + // Notify any remaining participants + watchpartyIO.to(roomId).emit('room:closed', 'The watch party has ended due to inactivity or expiration.'); + } + } + + // Remove expired rooms + expiredRooms.forEach(roomId => { + watchpartyRooms.delete(roomId); + console.log(`Room ${roomId} closed due to expiration or inactivity`); + }); +}, 60 * 60 * 1000); + +// Startup +(async () => { + await loadRoomsFromDisk(); + server.listen(PORT, () => console.log(`Watchparty server listening on http://localhost:${PORT}`)); +})(); diff --git a/PreMid/metadata.json b/PreMid/metadata.json new file mode 100644 index 0000000..5dc9f22 --- /dev/null +++ b/PreMid/metadata.json @@ -0,0 +1,37 @@ +{ + "apiVersion": 1, + "author": { + "name": "Movix", + "id": "1259926474174238741" + }, + "service": "Movix", + "description": { + "fr": "Affiche une présence Discord détaillée et un peu absurde pendant la navigation sur Movix.", + "en": "Shows a detailed and slightly absurd Discord presence while browsing Movix." + }, + "url": ["movix.rodeo", "movix.website", "movix.blog"], + "version": "1.0.0", + "logo": "https://movix.rodeo/movix512.png", + "thumbnail": "https://movix.rodeo/movix512.png", + "color": "#dc2626", + "category": "videos", + "tags": ["movies", "series", "anime", "watchparty", "streaming"], + "regExp": "([a-z0-9-]+[.])*(movix[.](?:rodeo|website|blog))[/]?", + "allowURLOverrides": true, + "settings": [ + { + "id": "showTimestamp", + "title": "Afficher le temps", + "icon": "fas fa-clock", + "value": true, + "description": "Affiche le temps passé sur une page ou la durée média quand elle est disponible." + }, + { + "id": "showButtons", + "title": "Afficher le bouton", + "icon": "fas fa-link", + "value": false, + "description": "Ajoute un bouton vers certaines pages profondes quand l'URL est en HTTPS." + } + ] +} diff --git a/PreMid/presence.ts b/PreMid/presence.ts new file mode 100644 index 0000000..b7d43e2 --- /dev/null +++ b/PreMid/presence.ts @@ -0,0 +1,2628 @@ +type ActivityTypeValue = 0 | 2 | 3 | 5; + +interface PresenceButton { + label: string; + url: string; +} + +type VariantText = string | readonly string[]; +type TmdbMediaType = "movie" | "tv"; + +interface PresenceDataLike { + name?: string; + type?: ActivityTypeValue; + details?: string; + state?: string; + startTimestamp?: number; + endTimestamp?: number; + largeImageKey?: string; + largeImageText?: string; + buttons?: PresenceButton[]; +} + +interface PresenceInstance { + on(event: "UpdateData", callback: () => void | Promise): void; + setActivity(data: PresenceDataLike): void; + clearActivity(): void; + getSetting( + settingId: string, + ): Promise; +} + +declare const Presence: new (options: { clientId: string }) => PresenceInstance; + +interface TmdbMediaSummary { + title: string; + image?: string; +} + +interface WatchContext { + title: string; + mediaType: string; + season: string; + episode: string; + episodeTitle: string; + sourceLabel: string; + sourceDetail: string; +} + +const presence = new Presence({ + clientId: "1259926474174238741", +}); + +const ActivityType = { + Playing: 0, + Listening: 2, + Watching: 3, + Competing: 5, +} as const; + +const SITE_NAME = "Movix"; +const FALLBACK_SITE_URL = "https://movix.rodeo"; +const FALLBACK_LOGO = `${FALLBACK_SITE_URL}/movix512.png`; +const TMDB_API_BASE = "https://api.themoviedb.org/3"; +const TMDB_IMAGE_BASE = "https://image.tmdb.org/t/p"; +const TMDB_API_KEY = "f3d757824f08ea2cff45eb8f47ca3a1e"; + +const tmdbMediaCache = new Map>(); + +const PROVIDER_NAMES: Record = { + "8": "Netflix", + "119": "Prime Video", + "337": "Disney+", + "338": "Marvel Studios", + "350": "Apple TV+", + "355": "Warner Bros", + "356": "DC Comics", + "384": "HBO MAX", + "531": "Paramount+", +}; + +const SAFE_BUTTON_PATTERNS = [ + /^\/collection\/[^/]+$/i, + /^\/movie\/[^/]+$/i, + /^\/tv\/[^/]+$/i, + /^\/download\/[^/]+\/[^/]+$/i, + /^\/genre\/[^/]+\/[^/]+$/i, + /^\/provider\/[^/]+\/[^/]+(?:\/[^/]+)?$/i, + /^\/person\/[^/]+$/i, + /^\/watchparty\/room\/[^/]+$/i, + /^\/list\/[^/]+$/i, + /^\/vip\/invoice\/[^/]+$/i, + /^\/vip\/cadeau\/[^/]+$/i, + /^\/ftv\/info\/[^/]+$/i, + /^\/wrapped(?:\/[^/]+)?$/i, +]; + +const PAGE_DETAIL_VARIANTS: Array<{ + pattern: RegExp; + variants: readonly string[]; +}> = [ + { + pattern: /^\/$/, + variants: [ + "Patrouille sur l'accueil comme un critique payé en popcorn 🍿", + "Scrolle l'accueil avec l'assurance d'un jury imaginaire 🎬", + "Fouille l'accueil comme un détective du canapé 🛋️", + ], + }, + { + pattern: /^\/search$/i, + variants: [ + "Traque une pépite avec un calme purement décoratif 🔎", + "Interroge la recherche comme un enquêteur du streaming 🕵️", + "Lance des mots-clés avec l'énergie d'un génie fatigué 🔍", + ], + }, + { + pattern: /^\/movies$/i, + variants: [ + "Passe le catalogue films au rayon X sans diplôme officiel 🎬", + "Inspecte les films comme un sommelier du popcorn 🍿", + "Fouille les films avec un sérieux beaucoup trop cinématographique 🎞️", + ], + }, + { + pattern: /^\/tv-shows$/i, + variants: [ + "Collectionne les séries comme si dormir était facultatif 📺", + "Parcourt les séries avec des ambitions de binge incontrôlables 🍿", + "Évalue les séries comme un comité secret du canapé 📡", + ], + }, + { + pattern: /^\/collections$/i, + variants: [ + "Fouille les collections comme un archiviste sous café ☕", + "Visite les collections avec le respect d'un conservateur dramatique 🗂️", + "Classe des sagas dans sa tête comme si c'était son métier 📚", + ], + }, + { + pattern: /^\/collection\/[^/]+$/i, + variants: [ + "Inspecte une collection avec un sérieux presque gouvernemental 🗂️", + "Retourne une collection comme un brocanteur du streaming 📦", + "Examine une saga avec une passion très peu discrète 🎞️", + ], + }, + { + pattern: /^\/movie\/[^/]+$/i, + variants: [ + "Épluche une fiche film comme un jury de festival en retard 🎬", + "Analyse un film avant le clic fatal avec beaucoup trop d'émotion 🍿", + "Observe une fiche film comme si le réalisateur regardait 👀", + ], + }, + { + pattern: /^\/tv\/[^/]+$/i, + variants: [ + "Dissèque une fiche série comme si le binge était un sport olympique 📺", + "Examine une série avec l'énergie d'un fan qui ne dort pas 😵", + "Observe une fiche série comme un comité de cliffhangers 🍿", + ], + }, + { + pattern: /^\/download\/(movie|tv)\/[^/]+$/i, + variants: [ + "Prépare un plan B avec l'élégance d'un pirate en costume ⬇️", + "Monte un plan secours comme si Internet était en grève 📦", + "Sécurise une sortie de secours ciné avec un calme douteux 🧳", + ], + }, + { + pattern: /^\/debrid$/i, + variants: [ + "Dompte des liens capricieux avec la grâce d'un sorcier réseau 🪄", + "Répare des liens comme un mécano du streaming 🧰", + "Négocie avec des hosters récalcitrants à mains nues 🔧", + ], + }, + { + pattern: /^\/genre\/[^/]+\/[^/]+$/i, + variants: [ + "Trie le chaos par genre avec une autorité totalement inventée 🗂️", + "Range les goûts du monde dans de petites cases très pratiques 🎭", + "Organise le catalogue comme un bibliothécaire du binge 📚", + ], + }, + { + pattern: /^\/roulette$/i, + variants: [ + "Laisse le destin choisir à sa place, aveu courageux 🎲", + "Confie sa soirée à une roulette manifestement instable 🎰", + "Demande au hasard de prendre les commandes avec panache 🎯", + ], + }, + { + pattern: /^\/provider\/[^/]+\/[^/]+(?:\/[^/]+)?$/i, + variants: [ + "Retourne un catalogue provider comme un inspecteur trop motivé 📦", + "Épluche un provider avec l'enthousiasme d'un auditeur secret 🕵️", + "Passe un provider au scanner ciné sans autorisation officielle 📺", + ], + }, + { + pattern: /^\/provider\/[^/]+$/i, + variants: [ + "Espionne un provider avec une curiosité très assumée 👀", + "Observe un provider comme si un abonnement était en jeu 💳", + "Fait l'inventaire d'un provider avec une dignité variable 📋", + ], + }, + { + pattern: /^\/auth(?:\/google)?$/i, + variants: [ + "Négocie avec la connexion comme un diplomate en sueur 🔐", + "Affronte l'authentification avec un courage administratif 🪪", + "Tente de se connecter sans vexer les serveurs 🤝", + ], + }, + { + pattern: /^\/(?:create-account|link-bip39\/create)$/i, + variants: [ + "Forge un compte comme un druide numérique très appliqué ✨", + "Crée un compte avec le sérieux d'un mage du mot de passe 🔮", + "Ouvre un nouveau chapitre administratif en grand style 📝", + ], + }, + { + pattern: /^\/(?:login-bip39|link-bip39)$/i, + variants: [ + "Récite sa formule secrète sans éternuer 🔑", + "Murmure une phrase magique avec un calme discutable 🧠", + "Déverrouille son accès comme un sorcier sous pression ✨", + ], + }, + { + pattern: /^\/person\/[^/]+$/i, + variants: [ + "Épluche une filmo comme un détective du générique 🕵️", + "Remonte une carrière plan par plan avec passion 🎭", + "Inspecte une star comme si Cannes avait appelé 📸", + ], + }, + { + pattern: /^\/profile$/i, + variants: [ + "Range son profil puis le rerange pour le principe 👤", + "Contemple son profil comme un PDG du canapé 🪞", + "Ajuste son profil avec une minutie ridiculement noble ✍️", + ], + }, + { + pattern: /^\/alerts$/i, + variants: [ + "Surveille ses alertes comme une tour de contrôle du binge 🔔", + "Attend ses alertes avec le sang-froid d'une casserole 🌡️", + "Écoute les signaux du catalogue comme un radar humain 📡", + ], + }, + { + pattern: /^\/live-tv$/i, + variants: [ + "Zappe plus vite que la télécommande ne peut protester 📡", + "Navigue en direct avec les réflexes d'un ninja du canapé 📺", + "Fait du slalom entre les chaînes sans prévenir personne 🎛️", + ], + }, + { + pattern: /^\/watchparty\/create$/i, + variants: [ + "Prépare une WatchParty comme un wedding planner du popcorn 🍿", + "Monte une WatchParty avec la sérénité d'un chef de gare 👥", + "Assemble une soirée visionnage comme un maître de cérémonie chaotique 🎉", + ], + }, + { + pattern: /^\/watchparty\/room\/[^/]+$/i, + variants: [ + "Coordonne une WatchParty pendant que le chat part en freestyle 💬", + "Gère une WatchParty avec l'autorité d'un roi du canapé 👑", + "Tient une salle WatchParty comme un DJ des cliffhangers 🎚️", + ], + }, + { + pattern: /^\/watchparty\/join(?:\/[^/]+)?$/i, + variants: [ + "Essaie d'entrer dans une WatchParty sans rater le code 🚪", + "Tente une infiltration sociale très popcorn 🍿", + "Rejoint une WatchParty avec la discrétion d'une fanfare 🥁", + ], + }, + { + pattern: /^\/watchparty\/list$/i, + variants: [ + "Fouille les salons WatchParty comme un videur curieux 👀", + "Parcourt les salons comme un agent immobilier du binge 🏠", + "Cherche une WatchParty où poser son popcorn 🍿", + ], + }, + { + pattern: /^\/suggestion$/i, + variants: [ + "Demande au site de penser à sa place, aveu très honnête 🧠", + "Réclame une idée brillante avec le panache d'un indécis 🎯", + "Confie sa soirée à l'algorithme avec un courage rare 🤖", + ], + }, + { + pattern: /^\/extension$/i, + variants: [ + "Arme son navigateur comme un chevalier anti-hoster 🧩", + "Équipe le navigateur pour boxer les pubs et les caprices 🥊", + "Installe des renforts techniques avec une joie suspecte 🛠️", + ], + }, + { + pattern: /^\/list\/[^/]+$/i, + variants: [ + "Explore une liste partagée avec un jugement délicatement silencieux 📋", + "Déguste une liste publique comme un critique bénévole 🍽️", + "Parcourt une sélection avec la ferveur d'un collectionneur 🗃️", + ], + }, + { + pattern: /^\/list-catalog$/i, + variants: [ + "Parcourt les listes publiques comme un brocanteur du streaming 📚", + "Inspecte des listes comme un curateur de canapé 🛋️", + "Feuillette le catalogue des listes avec des ambitions très nobles 📖", + ], + }, + { + pattern: /^\/dmca$/i, + variants: [ + "Lit la DMCA, oui ça arrive vraiment ⚖️", + "Affronte la paperasse juridique comme un héros discret 📜", + "Traverse la zone légale avec un courage franchement admirable 🧾", + ], + }, + { + pattern: /^\/admin$/i, + variants: [ + "Traîne dans l'admin avec beaucoup trop de boutons 🛠️", + "Pilote l'admin comme un capitaine légèrement dangereux 🚨", + "Regarde l'admin droit dans les permissions 👮", + ], + }, + { + pattern: /^\/profile-selection$/i, + variants: [ + "Choisit un profil comme si toute la famille observait 👥", + "Sélectionne un profil avec le sérieux d'un casting 🎭", + "Hésite entre les profils comme devant un buffet 👀", + ], + }, + { + pattern: /^\/profile-management$/i, + variants: [ + "Bidouille les profils avec une autorité discutable 🧰", + "Réorganise les profils comme un DRH du canapé 📁", + "Jongle avec les profils en mode administrateur de salon 🛋️", + ], + }, + { + pattern: /^\/wishboard$/i, + variants: [ + "Vote sur le Wishboard comme un ministre du catalogue 🗳️", + "Fait campagne pour ses envies avec aplomb 📣", + "Milite pour de nouveaux contenus avec une ferveur électorale 🎤", + ], + }, + { + pattern: /^\/wishboard\/new$/i, + variants: [ + "Dépose une requête avec l'espoir d'être exaucé 🙏", + "Rédige une demande comme un citoyen du binge modèle ✍️", + "Soumet un souhait avec la gravité d'un traité international 📬", + ], + }, + { + pattern: /^\/wishboard\/my-requests$/i, + variants: [ + "Surveille ses requêtes comme des actions en bourse 📈", + "Observe ses demandes avec un stress très rentable 👀", + "Suit ses requêtes comme un trader du catalogue 💹", + ], + }, + { + pattern: /^\/wishboard\/submit-link$/i, + variants: [ + "Soumet un lien pour sauver le catalogue à mains nues 🔗", + "Apporte du renfort au catalogue avec panache 🧷", + "Lance un lien de secours comme un héros logistique 📡", + ], + }, + { + pattern: /^\/vip$/i, + variants: [ + "Examine le VIP avec un regard de mécène stratégique 💎", + "Observe l'espace VIP comme un investisseur du popcorn 💸", + "Évalue le club VIP avec un sérieux de milliardaire du canapé 🪙", + ], + }, + { + pattern: /^\/vip\/don$/i, + variants: [ + "Sort la carte bleue avec un panache douteux 💳", + "S'avance vers le don VIP comme un noble du streaming 👑", + "Finance le chaos audiovisuel avec élégance 💸", + ], + }, + { + pattern: /^\/vip\/invoice\/[^/]+$/i, + variants: [ + "Contemple une facture VIP, romance moderne 🧾", + "Observe une facture comme si c'était un poème fiscal 💼", + "Vérifie une facture VIP avec le calme d'un comptable du luxe 💎", + ], + }, + { + pattern: /^\/vip\/cadeau\/[^/]+$/i, + variants: [ + "Déballe un cadeau VIP sans papier brillant 🎁", + "Examine un cadeau VIP avec les yeux d'un enfant premium ✨", + "Ouvre une surprise VIP avec une noblesse discutable 🎀", + ], + }, + { + pattern: /^\/about$/i, + variants: [ + "Raconte l'histoire de Movix comme une légende locale 📖", + "Explore les origines de Movix comme un archéologue du streaming 🏺", + "Lit le lore de Movix avec des étoiles dans les yeux ✨", + ], + }, + { + pattern: /^\/privacy$/i, + variants: [ + "Lit la politique de confidentialité avec un courage rare 🕶️", + "Affronte la confidentialité ligne par ligne sans trembler 🔐", + "Traverse les règles de vie privée comme un juriste du dimanche 📜", + ], + }, + { + pattern: /^\/(?:terms-of-service|terms)$/i, + variants: [ + "Traverse les CGU armé d'un café très serré ☕", + "Lit les conditions avec le courage d'un gladiateur du clic ⚖️", + "Affronte la prose légale sans quitter le canapé 📜", + ], + }, + { + pattern: /^\/cinegraph$/i, + variants: [ + "Cartographie ses obsessions ciné comme un savant fou 🧠", + "Trace des connexions ciné avec une énergie très conspirationniste 🕸️", + "Dessine son cerveau cinéma en mode laboratoire secret 🧪", + ], + }, + { + pattern: /^\/settings$/i, + variants: [ + "Tripatouille les réglages jusqu'à friser la perfection ⚙️", + "Ajuste les paramètres comme un horloger du binge 🛠️", + "Cherche le réglage parfait avec une obstination admirable 🎛️", + ], + }, + { + pattern: /^\/top10$/i, + variants: [ + "Scrute le top 10 comme un analyste de canapé 🏆", + "Observe le classement avec l'autorité d'un jury auto-proclamé 🎖️", + "Compare les tendances comme un stratège du popcorn 📈", + ], + }, + { + pattern: /^\/ftv$/i, + variants: [ + "Fouille France.tv sans télécommande et sans honte 🇫🇷", + "Navigue dans France.tv comme un explorateur du direct 📺", + "Inspecte France.tv avec une curiosité très nationale 🗼", + ], + }, + { + pattern: /^\/ftv\/info\/[^/]+$/i, + variants: [ + "Inspecte une fiche France.tv avant le clic fatal 🇫🇷", + "Analyse un programme France.tv comme un critique du service public 🎬", + "Examine un programme France.tv avec un sérieux très républicain 📺", + ], + }, + { + pattern: /^\/wrapped(?:\/[^/]+)?$/i, + variants: [ + "Relit son année ciné comme un audit émotionnel 📊", + "Observe son Wrapped comme un bilan existentiel premium 🪞", + "Revit son année Movix avec des statistiques et des frissons 📈", + ], + }, + { + pattern: /^(?:\*|\/404)$/i, + variants: [ + "S'est perdu avec une assurance spectaculaire 🧭", + "Erre dans le 404 comme un aventurier sans carte 🗺️", + "A réussi l'exploit de se perdre sur Movix, bravo 🫡", + ], + }, +]; + +const WATCH_WAITING_VARIANTS: Array<{ + pattern: RegExp; + variants: readonly string[]; +}> = [ + { + pattern: /^\/watch\/movie\/[^/]+$/i, + variants: [ + "cherche la bonne source sans paniquer 🍿", + "choisit un lecteur comme un sommelier du streaming 🎬", + "prépare le décollage du film avec gravité 🚀", + ], + }, + { + pattern: /^\/watch\/tv\/[^/]+\/s\/[^/]+\/e\/[^/]+$/i, + variants: [ + "sélectionne une source avec panique élégante 📺", + "prépare le binge comme un ingénieur du canapé 🍿", + "cherche le bon épisode avec une foi inébranlable 🔎", + ], + }, + { + pattern: /^\/watch\/anime\/[^/]+\/season\/[^/]+\/episode\/[^/]+$/i, + variants: [ + "cherche son épisode comme un héros secondaire 🌸", + "prépare l'anime avec une hype difficile à cacher ✨", + "sélectionne une source en mode arc d'introduction ⚔️", + ], + }, + { + pattern: /^\/ftv\/watch\/[^/]+$/i, + variants: [ + "cherche le bon flux avec dignité 🇫🇷", + "accorde France.tv avec un sang-froid télévisuel 📡", + "prépare le direct comme un régisseur du salon 🎛️", + ], + }, +]; + +const WATCH_PLAYING_VARIANTS: Array<{ + pattern: RegExp; + variants: readonly string[]; +}> = [ + { + pattern: /^\/watch\/movie\/[^/]+$/i, + variants: [ + "lecture en cours, canapé en surchauffe 🍿", + "film lancé, le popcorn travaille en heures sup' 🎬", + "visionnage actif, dignité momentanément absente 🛋️", + ], + }, + { + pattern: /^\/watch\/tv\/[^/]+\/s\/[^/]+\/e\/[^/]+$/i, + variants: [ + "binge hors de contrôle 📺", + "épisode en cours, plus personne ne dort 🍿", + "visionnage de série avec implication totale 🧠", + ], + }, + { + pattern: /^\/watch\/anime\/[^/]+\/season\/[^/]+\/episode\/[^/]+$/i, + variants: [ + "anime en cours, théorie du fanclub activée 🌸", + "épisode lancé, niveau de hype dangereusement élevé ⚡", + "visionnage anime en mode ouverture dramatique 🎌", + ], + }, + { + pattern: /^\/ftv\/watch\/[^/]+$/i, + variants: [ + "programme en cours, télécommande au chômage 📺", + "direct lancé, salon officiellement mobilisé 🇫🇷", + "lecture France.tv active, canapé en mission 🛋️", + ], + }, +]; + +const WATCH_PAUSED_VARIANTS: Array<{ + pattern: RegExp; + variants: readonly string[]; +}> = [ + { + pattern: /^\/watch\/movie\/[^/]+$/i, + variants: [ + "pause stratégique, le drame attend ⏸️", + "film en pause, le popcorn reprend son souffle 🍿", + "interruption tactique, suspense sous cloche 🎬", + ], + }, + { + pattern: /^\/watch\/tv\/[^/]+\/s\/[^/]+\/e\/[^/]+$/i, + variants: [ + "pause très dramatique ⏸️", + "épisode en pause, cliffhanger sous surveillance 👀", + "arrêt technique du binge, émotion intacte 📺", + ], + }, + { + pattern: /^\/watch\/anime\/[^/]+\/season\/[^/]+\/episode\/[^/]+$/i, + variants: [ + "pause technique, hype toujours intacte ⏸️", + "anime en pause, énergie shonen conservée ⚡", + "interruption temporaire, pouvoir de l'amitié stable 🌸", + ], + }, + { + pattern: /^\/ftv\/watch\/[^/]+$/i, + variants: [ + "pause stratégique du direct ⏸️", + "programme en pause, personne ne touche à la télécommande 📡", + "intermède technique à la française 🇫🇷", + ], + }, +]; + +const WATCH_ENDED_VARIANTS: Array<{ + pattern: RegExp; + variants: readonly string[]; +}> = [ + { + pattern: /^\/watch\/movie\/[^/]+$/i, + variants: [ + "générique en vue, personne ne bouge 🎞️", + "film terminé, silence solennel dans le salon 🛋️", + "fin de séance, popcorn officiellement retraité 🍿", + ], + }, + { + pattern: /^\/watch\/tv\/[^/]+\/s\/[^/]+\/e\/[^/]+$/i, + variants: [ + "épisode terminé, prochain cliffhanger en approche 📺", + "fin d'épisode, volonté personnelle en miettes 🍿", + "générique lancé, binge toujours menaçant 🎞️", + ], + }, + { + pattern: /^\/watch\/anime\/[^/]+\/season\/[^/]+\/episode\/[^/]+$/i, + variants: [ + "épisode terminé, l'arc suivant appelle déjà 🌸", + "fin d'épisode, niveau de hype toujours irresponsable ⚡", + "générique lancé, fanclub intérieurement debout 🎌", + ], + }, + { + pattern: /^\/ftv\/watch\/[^/]+$/i, + variants: [ + "programme terminé, la télécommande réclame des congés 📺", + "fin de diffusion, mission salon accomplie 🇫🇷", + "générique France.tv détecté, calme retrouvé 🎞️", + ], + }, +]; + +let lastRouteKey = ""; +let lastRouteStartedAt = Date.now(); + +function normalizeText(value: unknown): string { + return String(value ?? "") + .replace(/\u00A0/g, " ") + .replace(/\s+/g, " ") + .trim(); +} + +function truncate(value: unknown, max = 128): string { + const text = normalizeText(value); + if (!text) return ""; + if (text.length <= max) return text; + return `${text.slice(0, max - 1).trim()}...`; +} + +function stripSiteName(value: unknown): string { + return normalizeText(value) + .replace(/\s*(?:[-|:]\s*)?Movix$/i, "") + .trim(); +} + +const RELEASE_TAG_PATTERN = /\s*\bSORTI(?:E|ES|S)?\b[.!]*$/i; + +function stripReleaseTag(value: string): string { + return value.replace(RELEASE_TAG_PATTERN, "").trim(); +} + +function firstNonEmpty(...values: T[]): T | "" { + for (const value of values) { + if (normalizeText(value)) { + return value; + } + } + + return ""; +} + +function safeDecode(value: string): string { + try { + return decodeURIComponent(value); + } catch { + return value; + } +} + +function shortenId(value: string, size = 6): string { + const text = normalizeText(value); + return text ? text.slice(0, size).toUpperCase() : ""; +} + +function toAbsoluteUrl(value: string): string { + const text = normalizeText(value); + if (!text) return ""; + + try { + return new URL(text, document.location.origin).toString(); + } catch { + return ""; + } +} + +function toTmdbImageUrl(path: unknown, size = "w500"): string { + const text = normalizeText(path); + return text ? `${TMDB_IMAGE_BASE}/${size}${text}` : ""; +} + +function isImageUrlAllowed(value: string): boolean { + return ( + /^https:\/\//i.test(value) || + value.startsWith("data:") || + value.startsWith("blob:") + ); +} + +function isButtonUrlAllowed(value: string): boolean { + return /^https:\/\//i.test(value); +} + +function findLatestValue( + elements: readonly T[], + resolveValue: (element: T) => string, +): string { + for (let index = elements.length - 1; index >= 0; index -= 1) { + const element = elements[index]; + if (!element) { + continue; + } + + const value = resolveValue(element); + if (value) { + return value; + } + } + + return ""; +} + +function isRelevantDomElement(element: Element | null): element is HTMLElement { + if (!(element instanceof HTMLElement)) { + return false; + } + + if ( + !element.isConnected || + element.hidden || + element.closest("[hidden], [inert], [aria-hidden='true']") + ) { + return false; + } + + const style = window.getComputedStyle(element); + if ( + style.display === "none" || + style.visibility === "hidden" || + style.visibility === "collapse" || + Number.parseFloat(style.opacity || "1") === 0 + ) { + return false; + } + + return ( + element.getClientRects().length > 0 || + element.offsetWidth > 0 || + element.offsetHeight > 0 + ); +} + +function getMetaContent(selector: string): string { + const elements = Array.from( + document.querySelectorAll(selector), + ) as HTMLMetaElement[]; + + const latestManagedMeta = findLatestValue(elements, (element) => + element.getAttribute("data-rh") === "true" + ? normalizeText(element.content) + : "", + ); + + if (latestManagedMeta) { + return latestManagedMeta; + } + + return findLatestValue(elements, (element) => normalizeText(element.content)); +} + +function getAttribute(selector: string, attribute: string): string { + const elements = Array.from(document.querySelectorAll(selector)); + + const visibleValue = findLatestValue(elements, (element) => + isRelevantDomElement(element) + ? normalizeText(element.getAttribute(attribute)) + : "", + ); + + if (visibleValue) { + return visibleValue; + } + + return findLatestValue(elements, (element) => + normalizeText(element.getAttribute(attribute)), + ); +} + +function getText(selector: string): string { + const elements = Array.from(document.querySelectorAll(selector)); + + const visibleText = findLatestValue(elements, (element) => + isRelevantDomElement(element) + ? normalizeText(element.innerText || element.textContent) + : "", + ); + + if (visibleText) { + return visibleText; + } + + return findLatestValue(elements, (element) => + element instanceof HTMLElement + ? normalizeText(element.innerText || element.textContent) + : "", + ); +} + +function findTitleAttribute(predicate: (title: string) => boolean): string { + const elements = Array.from(document.querySelectorAll("[title]")); + + const visibleTitle = findLatestValue(elements, (element) => { + if (!isRelevantDomElement(element)) { + return ""; + } + + const title = normalizeText(element.getAttribute("title")); + return title && predicate(title) ? title : ""; + }); + + if (visibleTitle) { + return visibleTitle; + } + + return findLatestValue(elements, (element) => { + const title = normalizeText(element.getAttribute("title")); + return title && predicate(title) ? title : ""; + }); +} + +function getCurrentVideoElement(): HTMLVideoElement | null { + const videos = Array.from( + document.querySelectorAll("video"), + ) as HTMLVideoElement[]; + let bestVideo: HTMLVideoElement | null = null; + let bestScore = Number.NEGATIVE_INFINITY; + + for (const video of videos) { + if (!video.isConnected) { + continue; + } + + const isVisible = isRelevantDomElement(video); + const rect = isVisible ? video.getBoundingClientRect() : null; + const area = rect ? rect.width * rect.height : 0; + + let score = 0; + if (isVisible) { + score += 100; + } + + score += Math.min(40, Math.floor(area / 20000)); + + if (video.currentSrc || video.src) { + score += 20; + } + + if (video.readyState >= 2) { + score += 15; + } + + if (Number.isFinite(video.duration) && video.duration > 0) { + score += 20; + } + + if (!video.paused) { + score += 25; + } + + if (!video.ended) { + score += 5; + } + + if (score >= bestScore) { + bestScore = score; + bestVideo = video; + } + } + + return bestVideo; +} + +function getSearchParam(name: string): string { + return normalizeText(new URLSearchParams(document.location.search).get(name)); +} + +function getMatchPart(match: RegExpMatchArray | null, index: number): string { + return normalizeText(match?.[index]); +} + +function getRouteStartedAt(): number { + const key = `${document.location.pathname}${document.location.search}`; + + if (key !== lastRouteKey) { + lastRouteKey = key; + lastRouteStartedAt = Date.now(); + } + + return lastRouteStartedAt; +} + +function hashString(value: string): number { + let hash = 0; + + for (let index = 0; index < value.length; index += 1) { + hash = (hash << 5) - hash + value.charCodeAt(index); + hash |= 0; + } + + return Math.abs(hash); +} + +function pickVariant(seed: string, variants: readonly string[]): string { + const cleanVariants = variants + .map((variant) => normalizeText(variant)) + .filter(Boolean); + + if (cleanVariants.length === 0) { + return ""; + } + + return cleanVariants[hashString(seed) % cleanVariants.length] || ""; +} + +function findVariantsForPath( + pathname: string, + collection: Array<{ pattern: RegExp; variants: readonly string[] }>, +): readonly string[] | undefined { + return collection.find((entry) => entry.pattern.test(pathname))?.variants; +} + +function resolveVariantText(value: VariantText, seed: string): string { + return Array.isArray(value) ? pickVariant(seed, value) : normalizeText(value); +} + +function getPageTitle(): string { + const title = firstNonEmpty( + getText("main h1"), + getText("h1"), + document.title, + getText("main h2"), + getText("h2"), + getMetaContent('meta[property="og:title"]'), + ); + + return stripSiteName(stripReleaseTag(title)); +} + +function getPageImage(mode: "logo" | "content" = "logo"): string { + if (mode === "logo") { + return FALLBACK_LOGO; + } + + const candidates = + mode === "content" + ? [ + getAttribute("video[poster]", "poster"), + getAttribute(".cinegraph-detail-backdrop img", "src"), + getAttribute(".cinegraph-tooltip-poster", "src"), + getMetaContent('meta[property="og:image"]'), + getAttribute('img[alt="Poster"]', "src"), + getAttribute('img[alt*="poster" i]', "src"), + getAttribute('img[src*="tmdb.org"][src*="/w500"]', "src"), + getAttribute('img[src*="tmdb.org"][src*="/original"]', "src"), + FALLBACK_LOGO, + ] + : [FALLBACK_LOGO]; + + for (const candidate of candidates) { + const absolute = toAbsoluteUrl(candidate); + if (absolute && isImageUrlAllowed(absolute)) { + return absolute; + } + } + + return FALLBACK_LOGO; +} + +function getSafeButtons( + pathname: string, + enabled: boolean, +): Array<{ label: string; url: string }> | undefined { + if ( + !enabled || + !SAFE_BUTTON_PATTERNS.some((pattern) => pattern.test(pathname)) + ) { + return undefined; + } + + const url = document.location.href; + if (!isButtonUrlAllowed(url)) { + return undefined; + } + + return [ + { + label: "Voir la page", + url, + }, + ]; +} + +function buildBasePresence(image?: string): PresenceDataLike { + return { + name: SITE_NAME, + largeImageKey: image || getPageImage() || FALLBACK_LOGO, + }; +} + +function finalizePresence( + presenceData: PresenceDataLike | null, + options: { + showTimestamp: boolean; + showButtons: boolean; + pathname: string; + allowPageTimestamp?: boolean; + }, +) { + if (!presenceData) { + return null; + } + + presenceData.details = truncate(presenceData.details); + presenceData.state = truncate(presenceData.state); + + if (!presenceData.details || !presenceData.state) { + return null; + } + + if (!presenceData.buttons) { + const buttons = getSafeButtons(options.pathname, options.showButtons); + if (buttons?.length) { + presenceData.buttons = buttons; + } + } + + if ( + options.showTimestamp && + options.allowPageTimestamp !== false && + !presenceData.startTimestamp && + !presenceData.endTimestamp + ) { + presenceData.startTimestamp = getRouteStartedAt(); + } + + if (!presenceData.largeImageKey) { + presenceData.largeImageKey = FALLBACK_LOGO; + } + + return presenceData; +} + +function createPagePresence( + details: VariantText, + state: VariantText, + image?: string, +) { + const presenceData = buildBasePresence(image); + const seed = `${document.location.pathname}${document.location.search}`; + const routeDetails = Array.isArray(details) + ? details + : findVariantsForPath(document.location.pathname, PAGE_DETAIL_VARIANTS) || + details; + + presenceData.details = resolveVariantText(routeDetails, `${seed}:details`); + presenceData.state = resolveVariantText(state, `${seed}:state`); + return presenceData; +} + +function createWatchingPresence(options: { + title: string; + displayTitle?: string; + playingText: VariantText; + pausedText: VariantText; + waitingText: VariantText; + embedText?: VariantText; + endedText?: VariantText; + season?: string; + episode?: string; + image?: string; + statePrefix?: string; +}) { + const presenceData = buildBasePresence(options.image); + const video = getCurrentVideoElement(); + const season = normalizeText(options.season); + const episode = normalizeText(options.episode); + const routeWatchMediaType = getWatchMediaTypeForPath(document.location.pathname); + const useSimpleWatchRoute = Boolean(routeWatchMediaType); + const details = normalizeText( + options.displayTitle || + (routeWatchMediaType + ? getFormattedWatchTitle( + options.title, + routeWatchMediaType, + season, + episode, + ) + : options.title), + ); + const prefix = + options.statePrefix !== undefined + ? options.statePrefix + : useSimpleWatchRoute + ? "" + : season && episode + ? `S${season}E${episode} - ` + : ""; + const seed = `${document.location.pathname}:${details}:${season}:${episode}`; + const waitingVariant = useSimpleWatchRoute + ? "Selection de la source" + : Array.isArray(options.waitingText) + ? options.waitingText + : findVariantsForPath(document.location.pathname, WATCH_WAITING_VARIANTS) || + options.waitingText; + const playingVariant = useSimpleWatchRoute + ? "Lecture en cours" + : Array.isArray(options.playingText) + ? options.playingText + : findVariantsForPath(document.location.pathname, WATCH_PLAYING_VARIANTS) || + options.playingText; + const pausedVariant = useSimpleWatchRoute + ? "En pause" + : Array.isArray(options.pausedText) + ? options.pausedText + : findVariantsForPath(document.location.pathname, WATCH_PAUSED_VARIANTS) || + options.pausedText; + const endedVariant = useSimpleWatchRoute + ? "Lecture terminee" + : Array.isArray(options.endedText) + ? options.endedText + : findVariantsForPath(document.location.pathname, WATCH_ENDED_VARIANTS) || + options.endedText || + "Le generique approche, personne ne bouge"; + const waitingText = resolveVariantText( + waitingVariant, + `${seed}:waiting`, + ); + const playingText = resolveVariantText( + playingVariant, + `${seed}:playing`, + ); + const pausedText = resolveVariantText( + pausedVariant, + `${seed}:paused`, + ); + const embedText = resolveVariantText( + options.embedText || "Lecteur embed actif", + `${seed}:embed`, + ); + const endedText = resolveVariantText( + Array.isArray(options.endedText) + ? options.endedText + : findVariantsForPath(document.location.pathname, WATCH_ENDED_VARIANTS) || + options.endedText || + "Le générique approche, personne ne bouge", + `${seed}:ended`, + ); + + const watchEndedText = useSimpleWatchRoute + ? resolveVariantText(endedVariant, `${seed}:ended:simple`) + : endedText; + const watchContext = getWatchContext(); + const activeEmbedFrame = getActiveEmbedFrame(); + const embedSourceLabel = getActiveEmbedSourceLabel(activeEmbedFrame); + const selectedSourceLabel = formatWatchSourceLabel(watchContext.sourceLabel); + const embedSourceDisplay = formatWatchSourceDisplay( + embedSourceLabel, + watchContext.sourceDetail, + ); + const selectedSourceDisplay = formatWatchSourceDisplay( + watchContext.sourceLabel, + watchContext.sourceDetail, + ); + const embedSourceState = formatWatchSourceState( + embedSourceLabel, + watchContext.sourceDetail, + ); + const selectedSourceState = formatWatchSourceState( + watchContext.sourceLabel, + watchContext.sourceDetail, + ); + const hoverEpisodeLabel = getWatchEpisodeHoverLabel(season, episode); + + presenceData.type = ActivityType.Watching; + presenceData.details = details || options.title; + presenceData.state = `${prefix}${waitingText}`; + + if (hoverEpisodeLabel) { + presenceData.largeImageText = hoverEpisodeLabel; + } else { + presenceData.largeImageText = "Lecture en cours"; + } + + if (video && Number.isFinite(video.duration) && video.duration > 0) { + if (video.ended) { + presenceData.state = `${prefix}${watchEndedText}`; + } else if (video.paused) { + presenceData.state = selectedSourceDisplay + ? `En pause - ${selectedSourceDisplay}` + : `${prefix}${pausedText}`; + } else { + presenceData.state = selectedSourceDisplay || `${prefix}${playingText}`; + presenceData.startTimestamp = + Date.now() - Math.floor(video.currentTime * 1000); + presenceData.endTimestamp = + Date.now() + + Math.max(0, Math.floor((video.duration - video.currentTime) * 1000)); + } + } else if (activeEmbedFrame || embedSourceLabel) { + presenceData.state = embedSourceLabel + ? embedSourceState + : embedSourceDisplay || embedText; + } else if (useSimpleWatchRoute && selectedSourceLabel) { + presenceData.state = selectedSourceState; + } + + return presenceData; +} + +const WATCH_EMBED_SOURCE_LABELS = new Set([ + "coflix", + "custom", + "dood", + "doodstream", + "dropload", + "emmmmbed", + "frembed", + "fstream", + "lecteur6", + "mixdrop", + "omega", + "oneupload", + "sibnet", + "supervideo", + "uqload", + "videasy", + "vidmoly", + "viper", + "voe", + "vostfr", + "vox", + "wiflix", +]); + +const WATCH_SOURCE_LABEL_MAP: Record = { + coflix: "Coflix", + custom: "Custom", + darkino: "Nightflix", + dood: "Doodstream", + doodstream: "Doodstream", + dropload: "Dropload", + emmmmbed: "Emmmmbed", + frembed: "Frembed", + fstream: "FStream", + lecteur6: "Lecteur6", + mixdrop: "Mixdrop", + mp4: "MP4", + nexus_file: "Nexus File", + nexus_hls: "Nexus HLS", + omega: "Omega", + oneupload: "OneUpload", + rivestream: "Rivestream", + rivestream_hls: "Rivestream", + sibnet: "Sibnet", + supervideo: "Supervideo", + uqload: "Uqload", + videasy: "Videasy", + vidmoly: "Vidmoly", + viper: "Viper", + voe: "VOE", + vostfr: "VOSTFR", + vox: "Vox", + wiflix: "Wiflix", +}; + +const WATCH_EMBED_PROVIDER_PATTERNS: Array<{ pattern: RegExp; label: string }> = + [ + { pattern: /frembed/i, label: "Frembed" }, + { pattern: /videasy/i, label: "Videasy" }, + { pattern: /vidmoly/i, label: "Vidmoly" }, + { pattern: /sibnet/i, label: "Sibnet" }, + { pattern: /oneupload/i, label: "OneUpload" }, + { pattern: /mixdrop/i, label: "Mixdrop" }, + { pattern: /dood/i, label: "Doodstream" }, + { pattern: /dropload/i, label: "Dropload" }, + { pattern: /supervideo/i, label: "Supervideo" }, + { pattern: /uqload/i, label: "Uqload" }, + { pattern: /voe/i, label: "VOE" }, + { pattern: /emmmmbed/i, label: "Emmmmbed" }, + { pattern: /lecteur6/i, label: "Lecteur6" }, + { pattern: /coflix/i, label: "Coflix" }, + { pattern: /omega/i, label: "Omega" }, + { pattern: /wiflix/i, label: "Wiflix" }, + { pattern: /viper/i, label: "Viper" }, + { pattern: /vox/i, label: "Vox" }, + ]; + +const WATCH_TITLE_BLOCKLIST = [ + /^d[ée]velopp[ée] avec$/i, + /^changer de source$/i, + /^episodes?$/i, + /^lecture en cours$/i, + /^copier$/i, + /^param(?:è|e)tres?$/i, + /^param/i, + /^settings?$/i, + /^saison \d+\s*[,-]\s*[ée]pisode \d+$/i, +]; + +function getWatchContext(): WatchContext { + const element = document.querySelector("[data-premid-watch-context]"); + + if (!(element instanceof HTMLElement)) { + return { + title: "", + mediaType: "", + season: "", + episode: "", + episodeTitle: "", + sourceLabel: "", + sourceDetail: "", + }; + } + + return { + title: normalizeText(element.getAttribute("data-premid-title")), + mediaType: normalizeText(element.getAttribute("data-premid-media-type")), + season: normalizeText(element.getAttribute("data-premid-season")), + episode: normalizeText(element.getAttribute("data-premid-episode")), + episodeTitle: normalizeText( + element.getAttribute("data-premid-episode-title"), + ), + sourceLabel: normalizeText( + element.getAttribute("data-premid-source-label"), + ), + sourceDetail: normalizeText( + element.getAttribute("data-premid-source-detail"), + ), + }; +} + +function formatWatchSourceLabel(value: unknown): string { + const normalized = normalizeText(value); + if (!normalized) { + return ""; + } + + const lowered = normalized.toLowerCase().replace(/\s+/g, "_"); + if (WATCH_SOURCE_LABEL_MAP[lowered]) { + return WATCH_SOURCE_LABEL_MAP[lowered]; + } + + return lowered + .replace(/[_-]+/g, " ") + .replace(/\b\w/g, (character) => character.toUpperCase()); +} + +function formatWatchSourceDisplay(label: unknown, detail: unknown): string { + const sourceLabel = formatWatchSourceLabel(label); + if (!sourceLabel) { + return ""; + } + + const sourceDetail = normalizeText(detail); + if (!sourceDetail) { + return `Via ${sourceLabel}`; + } + + const normalizedLabel = sourceLabel + .toLowerCase() + .replace(/[_-]+/g, " ") + .trim(); + const cleanedDetail = sourceDetail + .replace( + new RegExp( + `^${sourceLabel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:\\s*[:-]\\s*|\\s+)`, + "i", + ), + "", + ) + .trim(); + const normalizedDetail = cleanedDetail + .toLowerCase() + .replace(/[_-]+/g, " ") + .trim(); + + if (!cleanedDetail || normalizedDetail === normalizedLabel) { + return sourceLabel; + } + + return `${sourceLabel} - ${cleanedDetail}`; +} + +function formatWatchSourceState(label: unknown, detail: unknown): string { + const sourceDisplay = formatWatchSourceDisplay(label, detail); + return sourceDisplay ? `Via ${sourceDisplay}` : ""; +} + +function isLikelyEmbedSource(value: unknown): boolean { + const normalized = normalizeText(value).toLowerCase().replace(/\s+/g, "_"); + return WATCH_EMBED_SOURCE_LABELS.has(normalized); +} + +function getActiveEmbedFrame(): HTMLIFrameElement | null { + const frames = Array.from( + document.querySelectorAll("iframe"), + ) as HTMLIFrameElement[]; + + for (let index = frames.length - 1; index >= 0; index -= 1) { + const frame = frames[index]; + const src = normalizeText(frame?.src || frame?.getAttribute("src")); + + if (frame && src && isRelevantDomElement(frame)) { + return frame; + } + } + + return null; +} + +function getEmbedSourceLabelFromUrl(value: unknown): string { + const normalized = normalizeText(value); + if (!normalized) { + return ""; + } + + for (const entry of WATCH_EMBED_PROVIDER_PATTERNS) { + if (entry.pattern.test(normalized)) { + return entry.label; + } + } + + try { + const hostname = new URL(normalized).hostname.replace(/^www\./i, ""); + const root = hostname.split(".")[0] || ""; + return formatWatchSourceLabel(root); + } catch { + return ""; + } +} + +function getActiveEmbedSourceLabel(frame?: HTMLIFrameElement | null): string { + const activeFrame = frame || getActiveEmbedFrame(); + const frameLabel = getEmbedSourceLabelFromUrl( + activeFrame?.src || activeFrame?.getAttribute("src"), + ); + + if (frameLabel) { + return frameLabel; + } + + const contextSourceLabel = formatWatchSourceLabel(getWatchContext().sourceLabel); + if (contextSourceLabel && isLikelyEmbedSource(contextSourceLabel)) { + return contextSourceLabel; + } + + return ""; +} + +function sanitizeWatchTitle(value: unknown): string { + const normalized = normalizeText(value); + if (!normalized) { + return ""; + } + + const stripped = stripSiteName(stripReleaseTag(normalized)); + if (!stripped) { + return ""; + } + + if (WATCH_TITLE_BLOCKLIST.some((pattern) => pattern.test(stripped))) { + return ""; + } + + return stripped; +} + +function sanitizeWatchEpisodeTitle(value: unknown): string { + const normalized = normalizeText(value) + .replace(/^\d+\.\s*/, "") + .replace(/^episode\s+\d+\s*[:-]?\s*/i, "") + .trim(); + + if (!normalized || /^episode\s+\d+$/i.test(normalized)) { + return ""; + } + + return normalized; +} + +function getWatchTitle(fallback: string): string { + const routeWatchMediaType = getWatchMediaTypeForPath(document.location.pathname); + const titleFromAttributes = findTitleAttribute((title) => { + if (title.length < 4) return false; + if (/ouvrir dans une nouvelle page/i.test(title)) return false; + if (/trailer background/i.test(title)) return false; + if (/^[-+]\d+s$/i.test(title)) return false; + if (/^zoom [+-]$/i.test(title)) return false; + return Boolean(sanitizeWatchTitle(title)); + }); + + const contextTitle = sanitizeWatchTitle(getWatchContext().title); + if (contextTitle) { + return contextTitle; + } + + if (routeWatchMediaType) { + return fallback; + } + + const candidates = [ + titleFromAttributes, + getText("main h2.text-white.text-3xl"), + getText("h2.text-white.text-3xl"), + getText("main h3.text-sm.font-bold"), + getText("main h3.text-lg.font-semibold"), + getText("main h1"), + getText("h3.text-lg"), + getText("h3"), + getText("h1"), + document.title, + getMetaContent('meta[property="og:title"]'), + ]; + + for (const candidate of candidates) { + const sanitized = sanitizeWatchTitle(candidate); + if (sanitized) { + return sanitized; + } + } + + return fallback; +} + +function getFormattedWatchTitle( + fallbackTitle: string, + mediaTypeFallback: "movie" | "tv" | "anime", + seasonFallback = "", + episodeFallback = "", +): string { + const context = getWatchContext(); + const mediaType = + normalizeText(context.mediaType).toLowerCase() || mediaTypeFallback; + const title = sanitizeWatchTitle(context.title) || fallbackTitle; + + if (mediaType === "tv" || mediaType === "anime") { + const season = normalizeText(context.season) || seasonFallback; + const episode = normalizeText(context.episode) || episodeFallback; + const episodeCode = season && episode ? `S${season}E${episode}` : ""; + const episodeTitle = sanitizeWatchEpisodeTitle(context.episodeTitle); + + return [title, episodeCode, episodeTitle].filter(Boolean).join(" - "); + } + + return title; +} + +function getWatchEpisodeHoverLabel(season: string, episode: string): string { + const episodeCode = season && episode ? `S${season}E${episode}` : ""; + const episodeTitle = sanitizeWatchEpisodeTitle(getWatchContext().episodeTitle); + + return [episodeCode, episodeTitle].filter(Boolean).join(" - "); +} + +function getWatchMediaTypeForPath( + pathname: string, +): "movie" | "tv" | "anime" | "" { + if (/^\/watch\/movie\/[^/]+$/i.test(pathname)) { + return "movie"; + } + + if (/^\/watch\/tv\/[^/]+\/s\/[^/]+\/e\/[^/]+$/i.test(pathname)) { + return "tv"; + } + + if (/^\/watch\/anime\/[^/]+\/season\/[^/]+\/episode\/[^/]+$/i.test(pathname)) { + return "anime"; + } + + return ""; +} + +function getProviderName(providerId: string): string { + return PROVIDER_NAMES[providerId] || `Provider ${providerId}`; +} + +function extractQuotedText(value: unknown): string { + const text = normalizeText(value); + if (!text) return ""; + + const patterns = [ + /«\s*([^«»]+?)\s*»/, + /“\s*([^“”]+?)\s*”/, + /"\s*([^"]+?)\s*"/, + /'\s*([^']+?)\s*'/, + ]; + + for (const pattern of patterns) { + const match = text.match(pattern); + const extracted = normalizeText(match?.[1]); + if (extracted) { + return extracted; + } + } + + return ""; +} + +function createSpecificPagePresence( + details: string, + state: VariantText, + image?: string, + seedSuffix?: string, +) { + const subject = normalizeText(details); + if (!subject) { + return null; + } + + const presenceData = buildBasePresence(image); + const seed = `${document.location.pathname}${document.location.search}:${normalizeText(seedSuffix) || subject}`; + + presenceData.details = subject; + presenceData.state = resolveVariantText(state, `${seed}:state`); + return presenceData; +} + +async function fetchTmdbMediaSummary( + type: TmdbMediaType, + id: string, +): Promise { + const mediaId = normalizeText(id); + if (!TMDB_API_KEY || !mediaId) { + return null; + } + + const cacheKey = `${type}:${mediaId}`; + const cachedPromise = tmdbMediaCache.get(cacheKey); + if (cachedPromise) { + return cachedPromise; + } + + const request = (async () => { + try { + const url = new URL(`${TMDB_API_BASE}/${type}/${mediaId}`); + url.searchParams.set("api_key", TMDB_API_KEY); + url.searchParams.set("language", "fr-FR"); + + const response = await fetch(url.toString()); + if (!response.ok) { + return null; + } + + const data = (await response.json()) as { + title?: string; + name?: string; + poster_path?: string; + backdrop_path?: string; + }; + + const title = stripSiteName(firstNonEmpty(data.title, data.name)); + if (!title) { + return null; + } + + return { + title, + image: firstNonEmpty( + toTmdbImageUrl(data.poster_path), + toTmdbImageUrl(data.backdrop_path, "w780"), + ), + }; + } catch { + return null; + } + })(); + + tmdbMediaCache.set(cacheKey, request); + return request; +} + +function getCinegraphVariants(type: string): readonly string[] { + if (type === "movie") { + return [ + "Connexions d'un film passées au scanner 🕸️", + "Univers d'un film disséqué dans CinéGraph 🎬", + "Réseau d'un film analysé comme un dossier secret 🧠", + ]; + } + + if (type === "tv") { + return [ + "Connexions d'une série passées au scanner 🕸️", + "Univers d'une série disséqué dans CinéGraph 📺", + "Réseau d'une série analysé comme un complot premium 🧠", + ]; + } + + if (type === "person") { + return [ + "Connexions d'une personne passées au scanner 👤", + "Carrière disséquée dans CinéGraph 🎭", + "Réseau créatif observé comme un tableau d'enquête 🕵️", + ]; + } + + return [ + "Cartographie ciné en cours dans CinéGraph 🧠", + "Connexions ciné passées au scanner 🕸️", + "Univers Movix disséqué comme un dossier top secret 🧪", + ]; +} + +async function getCinegraphContext(pageTitle: string, pageImage: string) { + const selectedTitle = firstNonEmpty( + getText("h2.cinegraph-detail-title"), + getText(".cinegraph-tooltip-title"), + ); + const selectedImage = firstNonEmpty( + getAttribute(".cinegraph-detail-backdrop img", "src"), + getAttribute(".cinegraph-tooltip-poster", "src"), + ); + const selectedBadge = normalizeText( + firstNonEmpty( + getText(".cinegraph-detail-meta .cinegraph-type-badge"), + getText(".cinegraph-tooltip-meta .cinegraph-type-badge"), + ), + ).toLowerCase(); + + const queryType = normalizeText(getSearchParam("type")).toLowerCase(); + const queryId = getSearchParam("id"); + + let graphType = queryType; + if (/film|movie/i.test(selectedBadge)) { + graphType = "movie"; + } else if (/série|serie|tv/i.test(selectedBadge)) { + graphType = "tv"; + } else if (/personne|artist|artiste|person/i.test(selectedBadge)) { + graphType = "person"; + } + + let title = normalizeText(selectedTitle); + let image = toAbsoluteUrl(selectedImage); + + if (!title && (queryType === "movie" || queryType === "tv") && queryId) { + const summary = await fetchTmdbMediaSummary( + queryType as TmdbMediaType, + queryId, + ); + title = normalizeText(summary?.title); + image = firstNonEmpty(image, toAbsoluteUrl(summary?.image || "")); + } + + if (!title) { + title = firstNonEmpty( + extractQuotedText(getText(".cinegraph-subtitle")), + pageTitle, + "CinéGraph", + ); + } + + return { + title: String(title), + image: firstNonEmpty(image, pageImage), + variants: getCinegraphVariants(graphType), + }; +} + +async function buildRoutePresence( + showTimestamp: boolean, + showButtons: boolean, +) { + const { pathname } = document.location; + const pageTitle = getPageTitle(); + const pageImage = getPageImage("logo"); + const contentImage = getPageImage("content"); + + let match: RegExpMatchArray | null = null; + + if (pathname === "/") { + return finalizePresence( + createPagePresence( + "Farfouille l'accueil comme un critique sous caféine", + "Accueil Movix", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/search") { + const query = getSearchParam("q"); + + return finalizePresence( + createPagePresence( + "Traque la perle rare avec un calme très relatif", + query ? `Recherche : ${query}` : "Recherche globale", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/movies") { + return finalizePresence( + createPagePresence( + "Passe le catalogue films au rayon X", + "Catalogue films", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/tv-shows") { + return finalizePresence( + createPagePresence( + "Collectionne les séries sans finir les précédentes", + "Catalogue séries", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/collections") { + return finalizePresence( + createPagePresence( + "Fouille les collections comme un conservateur insomniaque", + pageTitle || "Collections Movix", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if ((match = pathname.match(/^\/collection\/([^/]+)$/i))) { + const collectionId = getMatchPart(match, 1); + const collectionTitle = + pageTitle || `Collection ${shortenId(collectionId)}`; + + return finalizePresence( + createSpecificPagePresence( + collectionTitle, + [ + "Collection passée au scanner 🗂️", + "Saga observée avec un sérieux disproportionné 🎞️", + "Collection inspectée comme un trésor du canapé 📚", + ], + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if ((match = pathname.match(/^\/movie\/([^/]+)$/i))) { + const movieId = getMatchPart(match, 1); + const movieTitle = pageTitle || `Film ${shortenId(movieId)}`; + + return finalizePresence( + createSpecificPagePresence( + movieTitle, + [ + "Fiche film sous la loupe 🎬", + "Film inspecté comme un dossier brûlant 🍿", + "Autopsie ciné en cours sur Movix 🎞️", + ], + contentImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if ((match = pathname.match(/^\/tv\/([^/]+)$/i))) { + const showId = getMatchPart(match, 1); + const showTitle = pageTitle || `Série ${shortenId(showId)}`; + + return finalizePresence( + createSpecificPagePresence( + showTitle, + [ + "Fiche série sous surveillance 📺", + "Série inspectée comme un complot à cliffhangers 🍿", + "Binge en préparation devant la fiche série 🎞️", + ], + contentImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if ((match = pathname.match(/^\/download\/(movie|tv)\/([^/]+)$/i))) { + const contentType = getMatchPart(match, 1); + const typeLabel = contentType === "movie" ? "Film" : "Série"; + const title = firstNonEmpty( + getText("h2"), + pageTitle, + `${typeLabel} à télécharger`, + ); + + return finalizePresence( + createSpecificPagePresence( + String(title), + contentType === "movie" + ? [ + "Téléchargement film en préparation ⬇️", + "Plan B cinéma armé jusqu'aux dents 📦", + "Mode furtif: aucun spoiler autorisé 🕶️", + ] + : [ + "Téléchargement série en préparation ⬇️", + "Plan B binge prêt à décoller 📺", + "Rechargement stratégique des buffers 🔄", + ], + contentImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/debrid") { + const provider = getSearchParam("provider"); + const state = provider + ? `Debrid via ${provider}` + : "Atelier anti-liens capricieux"; + + return finalizePresence( + createPagePresence( + "Dompte des liens récalcitrants à mains nues", + state, + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + if ((match = pathname.match(/^\/genre\/([^/]+)\/([^/]+)$/i))) { + const mediaType = getMatchPart(match, 1); + const mediaLabel = mediaType === "movie" ? "Films" : "Séries"; + + return finalizePresence( + createPagePresence( + "Trie le chaos par genre parce qu'il le peut", + pageTitle || `${mediaLabel} par genre`, + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/roulette") { + return finalizePresence( + createPagePresence( + "Laisse le destin choisir quelle idée brillante", + pageTitle || "Roulette Movix", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if ( + (match = pathname.match(/^\/provider\/([^/]+)\/([^/]+)(?:\/([^/]+))?$/i)) + ) { + const providerId = getMatchPart(match, 1); + const mediaType = getMatchPart(match, 2); + const providerName = getProviderName(providerId); + const mediaLabel = mediaType === "movies" ? "Films" : "Séries"; + + return finalizePresence( + createPagePresence( + "Retourne un catalogue provider dans tous les sens", + pageTitle || `${providerName} - ${mediaLabel}`, + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if ((match = pathname.match(/^\/provider\/([^/]+)$/i))) { + const providerId = getMatchPart(match, 1); + + return finalizePresence( + createPagePresence( + "Espionne un provider avec une curiosité très assumée", + getProviderName(providerId), + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/auth" || pathname === "/auth/google") { + return finalizePresence( + createPagePresence( + "Négocie avec l'authentification sans perdre la face", + "Connexion en cours", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/create-account" || pathname === "/link-bip39/create") { + return finalizePresence( + createPagePresence( + "Forge un compte comme un druide numérique", + "Création de compte", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/login-bip39" || pathname === "/link-bip39") { + return finalizePresence( + createPagePresence( + "Récite sa phrase magique sans cligner des yeux", + "Connexion BIP39", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if ((match = pathname.match(/^\/person\/([^/]+)$/i))) { + const personId = getMatchPart(match, 1); + const personTitle = pageTitle || `Personne ${shortenId(personId)}`; + + return finalizePresence( + createSpecificPagePresence( + personTitle, + [ + "Filmo disséquée comme un détective du générique 🎭", + "Carrière passée au scanner plan par plan 🎬", + "Profil ciné observé comme une archive sacrée 📚", + ], + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/profile") { + return finalizePresence( + createPagePresence( + "Range son profil puis dérange tout à nouveau", + "Profil utilisateur", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/alerts") { + return finalizePresence( + createPagePresence( + "Surveille ses alertes comme une tour de contrôle du binge", + pageTitle || "Mes alertes", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/live-tv") { + const liveTitle = firstNonEmpty( + getText("h1"), + getText("h2"), + pageTitle, + "Live TV", + ); + + return finalizePresence( + createPagePresence( + "Zappe plus vite que la télécommande ne l'accepte", + String(liveTitle), + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if ((match = pathname.match(/^\/watch\/movie\/([^/]+)$/i))) { + const title = getWatchTitle("Film mystère"); + + return finalizePresence( + createWatchingPresence({ + title, + playingText: "lecture en cours, canapé en surchauffe", + pausedText: "pause stratégique, le drame attend", + waitingText: "cherche la bonne source sans paniquer", + image: contentImage, + }), + { showTimestamp, showButtons, pathname, allowPageTimestamp: false }, + ); + } + + if ( + (match = pathname.match(/^\/watch\/tv\/([^/]+)\/s\/([^/]+)\/e\/([^/]+)$/i)) + ) { + const season = getMatchPart(match, 2); + const episode = getMatchPart(match, 3); + const rawTitle = getWatchTitle("Série mystère"); + const title = + rawTitle.replace(/\s*-\s*S\d+E\d+$/i, "").trim() || "Série mystère"; + + return finalizePresence( + createWatchingPresence({ + title, + season, + episode, + playingText: "binge hors de contrôle", + pausedText: "pause très dramatique", + waitingText: "sélectionne une source avec panique élégante", + image: contentImage, + }), + { showTimestamp, showButtons, pathname, allowPageTimestamp: false }, + ); + } + + if ( + (match = pathname.match( + /^\/watch\/anime\/([^/]+)\/season\/([^/]+)\/episode\/([^/]+)$/i, + )) + ) { + const season = getMatchPart(match, 2); + const episode = getMatchPart(match, 3); + const rawTitle = getWatchTitle("Anime mystère"); + const title = + rawTitle.replace(/\s*-\s*S\d+E\d+$/i, "").trim() || "Anime mystère"; + + return finalizePresence( + createWatchingPresence({ + title, + season, + episode, + playingText: "anime en cours, théorie du fanclub activée", + pausedText: "pause technique, hype toujours intacte", + waitingText: "cherche son épisode comme un héros secondaire", + image: contentImage, + }), + { showTimestamp, showButtons, pathname, allowPageTimestamp: false }, + ); + } + + if (pathname === "/watchparty/create") { + const title = firstNonEmpty( + getText("h2"), + getText("h1"), + "Création de WatchParty", + ); + + return finalizePresence( + createPagePresence( + "Prépare une WatchParty comme un maître de cérémonie chaotique", + String(title), + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if ((match = pathname.match(/^\/watchparty\/room\/([^/]+)$/i))) { + const roomId = getMatchPart(match, 1); + const roomTitle = firstNonEmpty( + getAttribute("h1[title]", "title"), + getText("h1"), + getText("h2"), + `Salon ${shortenId(roomId)}`, + ); + + return finalizePresence( + createSpecificPagePresence( + String(roomTitle), + [ + "Salon WatchParty en ébullition 💬", + "WatchParty pilotée comme un chaos organisé 🎉", + "Salle commune tenue d'une main très popcorn 🍿", + ], + contentImage === FALLBACK_LOGO ? pageImage : contentImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if ((match = pathname.match(/^\/watchparty\/join(?:\/([^/]+))?$/i))) { + const joinCode = getMatchPart(match, 1); + const state = joinCode + ? `Code ${safeDecode(joinCode).toUpperCase()}` + : String( + firstNonEmpty( + getText("h2"), + getText("h1"), + "Rejoindre une WatchParty", + ), + ); + + return finalizePresence( + createPagePresence( + "Essaie d'entrer dans une WatchParty sans rater le code", + state, + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/watchparty/list") { + return finalizePresence( + createPagePresence( + "Fouille les salons WatchParty comme un videur curieux", + String(firstNonEmpty(getText("h1"), "Liste des salons WatchParty")), + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/suggestion") { + return finalizePresence( + createPagePresence( + "Demande au site de choisir à sa place, aveu touchant", + pageTitle || "Suggestions personnalisées", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/extension") { + return finalizePresence( + createPagePresence( + "Équipe son navigateur pour boxer les hosters relous", + pageTitle || "Extension Movix", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if ((match = pathname.match(/^\/list\/([^/]+)$/i))) { + const listId = getMatchPart(match, 1); + const listTitle = pageTitle || `Liste ${shortenId(listId)}`; + + return finalizePresence( + createSpecificPagePresence( + listTitle, + [ + "Liste publique inspectée avec gravité 📋", + "Sélection passée au peigne fin 🍽️", + "Compilation ciné dégustée comme un menu secret 🗃️", + ], + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/list-catalog") { + return finalizePresence( + createPagePresence( + "Parcourt les listes publiques comme un brocanteur du streaming", + pageTitle || "Catalogue des listes publiques", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/dmca") { + return finalizePresence( + createPagePresence( + "Lit la DMCA, oui ça arrive vraiment", + "Section juridique", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/admin") { + return finalizePresence( + createPagePresence( + "Traîne dans l'admin avec beaucoup trop de boutons", + "Console admin", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/profile-selection") { + return finalizePresence( + createPagePresence( + "Choisit un profil comme si Netflix observait", + "Sélection de profil", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/profile-management") { + return finalizePresence( + createPagePresence( + "Bidouille les profils avec une autorité discutable", + "Gestion des profils", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/wishboard") { + return finalizePresence( + createPagePresence( + "Vote sur le Wishboard comme un ministre du catalogue", + pageTitle || "Wishboard", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/wishboard/new") { + return finalizePresence( + createPagePresence( + "Dépose une requête avec l'espoir d'être exaucé", + String(firstNonEmpty(getText("h1"), "Nouvelle demande Wishboard")), + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/wishboard/my-requests") { + return finalizePresence( + createPagePresence( + "Surveille ses requêtes comme des actions en bourse", + String(firstNonEmpty(getText("h1"), "Mes demandes Wishboard")), + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/wishboard/submit-link") { + return finalizePresence( + createPagePresence( + "Soumet un lien pour sauver le catalogue à mains nues", + String( + firstNonEmpty(getText("h2"), getText("h1"), "Soumission de lien"), + ), + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/vip") { + return finalizePresence( + createPagePresence( + "Examine le VIP avec un regard de mécène stratégique", + "Espace VIP", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/vip/don") { + return finalizePresence( + createPagePresence( + "Sort la carte bleue avec un panache douteux", + "Don VIP", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if ((match = pathname.match(/^\/vip\/invoice\/([^/]+)$/i))) { + const invoiceId = getMatchPart(match, 1); + + return finalizePresence( + createPagePresence( + "Contemple une facture VIP, romance moderne", + `Facture ${shortenId(invoiceId)}`, + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if ((match = pathname.match(/^\/vip\/cadeau\/([^/]+)$/i))) { + const giftId = getMatchPart(match, 1); + + return finalizePresence( + createPagePresence( + "Déballe un cadeau VIP sans papier brillant", + `Cadeau ${shortenId(giftId)}`, + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/about") { + return finalizePresence( + createPagePresence( + "Raconte l'histoire de Movix comme une légende locale", + pageTitle || "À propos de Movix", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/privacy") { + return finalizePresence( + createPagePresence( + "Lit la politique de confidentialité avec un courage rare", + "Politique de confidentialité", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/terms-of-service" || pathname === "/terms") { + return finalizePresence( + createPagePresence( + "Traverse les CGU armé d'un café très serré", + "Conditions d'utilisation", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/cinegraph") { + const graphContext = await getCinegraphContext(pageTitle, pageImage); + + return finalizePresence( + createSpecificPagePresence( + graphContext.title, + graphContext.variants, + graphContext.image, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/settings") { + return finalizePresence( + createPagePresence( + "Tripatouille les réglages jusqu'à friser la perfection", + "Réglages Movix", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/top10") { + return finalizePresence( + createPagePresence( + "Scrute le top 10 comme un analyste de canapé", + pageTitle || "Top 10 Movix", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "/ftv") { + return finalizePresence( + createPagePresence( + "Fouille France.tv sans télécommande et sans honte", + String(firstNonEmpty(getText("h2"), pageTitle, "France.tv")), + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if ((match = pathname.match(/^\/ftv\/info\/([^/]+)$/i))) { + const programId = getMatchPart(match, 1); + const programTitle = String( + firstNonEmpty( + getText("h1"), + pageTitle, + `Programme ${shortenId(programId)}`, + ), + ); + + return finalizePresence( + createSpecificPagePresence( + programTitle, + [ + "Fiche France.tv sous inspection 🇫🇷", + "Programme France.tv étudié avec un sérieux républicain 📺", + "France.tv passé au microscope télévisuel 🎬", + ], + contentImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if ((match = pathname.match(/^\/ftv\/watch\/([^/]+)$/i))) { + const title = getWatchTitle("Programme France.tv"); + + return finalizePresence( + createWatchingPresence({ + title, + playingText: + "programme en cours, télécommande officiellement au chômage", + pausedText: "pause stratégique du direct", + waitingText: "cherche le bon flux avec dignité", + image: contentImage, + }), + { showTimestamp, showButtons, pathname, allowPageTimestamp: false }, + ); + } + + if ((match = pathname.match(/^\/wrapped(?:\/([^/]+))?$/i))) { + const wrappedYear = getMatchPart(match, 1); + const state = wrappedYear + ? `Wrapped ${wrappedYear}` + : String(firstNonEmpty(getText("h1"), "Wrapped Movix")); + + return finalizePresence( + createPagePresence( + "Relit son année ciné comme un bilan existentiel", + state, + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + if (pathname === "*" || pathname === "/404") { + return finalizePresence( + createPagePresence( + "S'est perdu dans Movix, ce qui était statistiquement évitable", + "404 - page introuvable", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); + } + + return finalizePresence( + createPagePresence( + "Explore Movix sans carte ni boussole", + pageTitle || "Exploration en cours", + pageImage, + ), + { showTimestamp, showButtons, pathname }, + ); +} + +async function getBooleanSetting( + settingId: string, + fallback: boolean, +): Promise { + try { + const value = await presence.getSetting(settingId); + return typeof value === "boolean" ? value : fallback; + } catch { + return fallback; + } +} + +presence.on("UpdateData", async () => { + const [showTimestamp, showButtons] = await Promise.all([ + getBooleanSetting("showTimestamp", true), + getBooleanSetting("showButtons", false), + ]); + + const presenceData = await buildRoutePresence(showTimestamp, showButtons); + + if (presenceData) { + presence.setActivity(presenceData); + } else { + presence.clearActivity(); + } +}); diff --git a/README.md b/README.md index 6695ebd..5ee782e 100644 --- a/README.md +++ b/README.md @@ -1,69 +1,215 @@ -
+

+ Movix +

-Movix OS +

Movix

-# Movix OS +

+ Le 1er site de streaming open source made in France et 100% vibecodé. +

-**Le dépôt dédié aux outils navigateur Movix.** +

+ React | + Vite | + TypeScript | + Node.js | + MySQL | + Redis | + Socket.IO | + Python | + Rust +

-[![Repository](https://img.shields.io/badge/GitHub-MysticSaba--max%2Fmovix--open--source-181717?style=flat&logo=github)](https://github.com/MysticSaba-max/movix-open-source) -[![Extension](https://img.shields.io/badge/Movix-Extension-orange?style=flat)](extension/README.md) -[![Userscript](https://img.shields.io/badge/Movix-Userscript-blue?style=flat)](userscript/README.md) +

+ + React + + + Vite + + + TypeScript + + + Node.js + + + MySQL + + + Redis + + + Socket.IO + + + Python + + + Rust + +

-
+Movix est un monorepo produit pour une plateforme de streaming communautaire. Le frontend, l'API principale, la WatchParty, les proxies, les outils navigateur et plusieurs briques d'infra vivent dans le même dépôt parce qu'ils évoluent ensemble. ---- +Ce n'est pas un simple duo "frontend + backend". Une feature peut très vite traverser plusieurs couches à la fois : interface React, persistance locale, sync backend, extraction vidéo, proxy Python et parfois extension navigateur. -Movix OS regroupe les deux solutions navigateur de Movix pour débloquer les sources qui demandent une extraction locale ou des headers spécifiques : +## Ce que contient le repo -- l'extension Movix -- le userscript Movix via Tampermonkey +| Zone | Rôle | Documentation | +| --- | --- | --- | +| `src/` | Frontend Vite + React + TypeScript | [Frontend](src/README.md) | +| `API/Mainapi/` | Backend principal clusterisé | [Main API](API/Mainapi/README.md) | +| `API/watchpartyAPI/` | Service temps réel WatchParty | [WatchParty API](API/watchpartyAPI/README.md) | +| `API/proxiesembed/` | Proxy aiohttp pour embeds, flux et DRM | [Proxies Embed](API/proxiesembed/README.md) | +| `API/miscs/` | Micro-service Flask pour certains 403 | [bypass403](API/miscs/README.md) | +| `extension/` + `userscript/` | Outils navigateur Movix | [Movix OS](README_MOVIX_OS.md) | +| `wasm/watchparty-sync/` | Moteur Rust/WASM de la Sync Pro | [WatchParty Sync WASM](wasm/watchparty-sync/README.md) | +| `cloudflareproxy/` | Worker Cloudflare CORS/proxy | [Cloudflare Proxy](cloudflareproxy/README.md) | -## Documentation - -- [README Extension Movix](extension/README.md) -- [README Userscript Movix](userscript/README.md) - -## Choisir la bonne option - -- **Firefox** : utilise de préférence l'[extension Movix](extension/README.md). -- **Chrome / Edge / Brave** : utilise de préférence le [userscript Movix](userscript/README.md). -- **Développement local** : les dossiers de l'extension et le script source sont inclus dans le dépôt. - -## Contenu du dépôt +## Architecture du monorepo ```text -movix-open-source/ -├── extension/ # Extension Firefox / Chrome -└── userscript/ # Version Tampermonkey +movix-main/ +|-- src/ # Frontend principal +|-- public/ # Assets statiques et artefacts WASM publiés +|-- API/ +| |-- Mainapi/ # Backend actif +| |-- watchpartyAPI/ # Temps réel WatchParty +| |-- proxiesembed/ # Proxy Python haute charge +| `-- miscs/ # Micro-services annexes +|-- extension/ # Extension Chrome / Firefox +|-- userscript/ # Variante Tampermonkey +|-- wasm/watchparty-sync/ # Sync Pro en Rust/WASM +|-- cloudflareproxy/ # Worker Cloudflare +|-- functions/ # Handlers serverless annexes +|-- PreMid/ # Présence PreMiD +`-- RivestreamCloudflareProxy/ # Variante de worker pour Rivestream ``` -## Liens utiles +## Démarrage rapide -- [README Extension Movix](extension/README.md) -- [README Userscript Movix](userscript/README.md) -- [Installation directe de movix.user.js](https://github.com/MysticSaba-max/movix-open-source/raw/refs/heads/main/userscript/movix.user.js) -- [Extension Firefox sur Add-ons](https://addons.mozilla.org/en-US/firefox/addon/movix-proxy-extension/) +### Prérequis -## Installation rapide +- Node.js 18+ et npm +- Python 3.10+ pour les services Python +- MySQL et Redis pour `API/Mainapi` +- Rust + `wasm-bindgen` seulement si tu touches la Sync Pro WASM -### Extension +### Installer les dépendances utiles -Consulte le guide dédié : +```bash +npm install +cd API/Mainapi +npm install +``` -- [extension/README.md](extension/README.md) +`API/watchpartyAPI/` n'a pas son propre `package.json` : il consomme les dépendances du `node_modules` racine. -### Userscript +### Configurer les `.env` avant de lancer quoi que ce soit -Consulte le guide dédié : +Ne saute pas cette étape. Une bonne partie du monorepo dépend des variables d'environnement pour les URLs, la base de données, Redis, les proxys, TMDB, Turnstile et plusieurs intégrations de lecture. -- [userscript/README.md](userscript/README.md) +```bash +# Frontend +cp .env.example .env -## Contribution +# API principale +cp API/Mainapi/.env.example API/Mainapi/.env -Les contributions sont bienvenues pour : +# WatchParty +cp API/watchpartyAPI/.env.example API/watchpartyAPI/.env -- améliorer l'extension -- améliorer le userscript -- corriger la documentation -- simplifier l'installation +# Proxy embed +cp API/proxiesembed/.env.example API/proxiesembed/.env + +# bypass403 +cp API/miscs/.env.example API/miscs/.env +``` + +### Lancer le minimum utile en local + +```bash +# Frontend - http://localhost:3000 +npm run dev +``` + +```bash +# Backend principal - http://localhost:25565 +cd API/Mainapi +npm run dev +``` + +```bash +# WatchParty - http://localhost:25566 +node API/watchpartyAPI/watchparty.js +``` + +Services optionnels selon la zone que tu touches : + +```bash +# Proxy embed +cd API/proxiesembed +pip install -r requirements.txt +python server.py +``` + +```bash +# bypass403 +cd API/miscs +pip install flask requests python-dotenv +python bypass403.py +``` + +## Configuration + +Les fichiers d'exemple ou de config existants sont déjà dans le repo : + +- Frontend : `.env.example` +- API principale : `API/Mainapi/.env.example` +- WatchParty : `API/watchpartyAPI/.env.example` +- Proxy embed : `API/proxiesembed/.env.example` +- bypass403 : `API/miscs/.env.example` + +Les variables frontend les plus importantes sont `VITE_MAIN_API`, `VITE_WATCHPARTY_API`, `VITE_PROXY_BASE_URL`, `VITE_API_PROXY_BASE_URL`, `VITE_PROXIES_EMBED_API` et `VITE_SITE_URL`. + +Pour un premier lancement local, configure au minimum : + +- `/.env` +- `API/Mainapi/.env` +- `API/watchpartyAPI/.env` + +## Comment s'orienter vite + +- Feature frontend : commence par `src/App.tsx`, puis la page cible dans `src/pages/`. +- Auth, profils, persistance : regarde `src/context/`, `src/App.tsx`, `API/Mainapi/routes/authRoutes.js` et `API/Mainapi/routes/sync.js`. +- Lecture vidéo et proxies : recoupe `src/pages/Watch/`, les composants player, `API/Mainapi/liveTvRoutes.js`, `API/proxiesembed/` et parfois `extension/`. +- WatchParty : vérifie à la fois `API/watchpartyAPI/watchparty.js`, `src/pages/WatchParty*.tsx`, `src/hooks/useWatchParty.ts`, `src/utils/watchparty*.ts` et `src/workers/watchpartySync.worker.ts`. +- Browser tooling : si tu modifies l'extension, compare toujours `extension/Chrome/` et `extension/Firefox/`, puis vérifie si le userscript doit suivre. +- Sync Rust/WASM : modifie `wasm/watchparty-sync/`, puis rebuild `public/wasm/watchparty-sync/`. + +## Points importants avant de contribuer + +- Le backend actif est `API/Mainapi/`. Le vieux contenu directement sous `API/` n'est plus la référence. +- Ce monorepo n'utilise pas de workspace tooling : chaque sous-projet garde ses scripts. +- Une partie importante de l'état produit vit dans `localStorage` et dans la sync backend. Ne raisonne pas "base de données only". +- Le lint frontend se lance à la racine avec `npm run lint`. +- Il n'y a pas de suite de tests globale fiable pour tout le repo. Vérifie au minimum les scripts touchés et le comportement manuel. + +## Documentation par module + +- [Frontend](src/README.md) +- [Services backend](API/README.md) +- [Main API](API/Mainapi/README.md) +- [WatchParty API](API/watchpartyAPI/README.md) +- [Proxies Embed](API/proxiesembed/README.md) +- [bypass403](API/miscs/README.md) +- [Movix OS](README_MOVIX_OS.md) +- [Extension navigateur](extension/README.md) +- [Userscript Tampermonkey](userscript/README.md) +- [WatchParty Sync WASM](wasm/watchparty-sync/README.md) +- [Cloudflare Proxy](cloudflareproxy/README.md) + +## Star History + +[![Star History Chart](https://api.star-history.com/svg?repos=MysticSaba-max/movix-open-source&type=Timeline)](https://star-history.com/#MysticSaba-max/movix-open-source&Timeline) diff --git a/RivestreamCloudflareProxy/worker.js b/RivestreamCloudflareProxy/worker.js new file mode 100644 index 0000000..cb51310 --- /dev/null +++ b/RivestreamCloudflareProxy/worker.js @@ -0,0 +1,257 @@ +/** + * Cloudflare Workers Proxy Server + * Supporte la route /proxy pour le streaming de MP4 avec Range requests + */ + +// Headers CORS pour toutes les réponses +const CORS_HEADERS = { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, DELETE, PATCH', + 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Range, Authorization, Cache-Control, Pragma', + 'Access-Control-Allow-Credentials': 'true', + 'Access-Control-Expose-Headers': 'Content-Length, Content-Range, Accept-Ranges', +}; + +/** + * Prépare les headers pour la requête vers l'URL cible + */ +function prepareHeaders(targetUrl, request, customHeaders = {}) { + const url = new URL(targetUrl); + const refererOrigin = `${url.protocol}//${url.host}`; + const targetHost = url.host; + + // Headers par défaut pour les requêtes vidéo + let headers = { + 'Accept': '*/*', + 'Accept-Encoding': 'identity;q=1, *;q=0', + 'Accept-Language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7', + 'Connection': 'keep-alive', + 'Host': targetHost, + 'Referer': request.headers.get('referer') || refererOrigin, + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36', + }; + + // Ajouter le header Range si présent + const rangeHeader = request.headers.get('range'); + if (rangeHeader) { + headers['Range'] = rangeHeader; + } + + // Ajouter les cookies si présents + const cookieHeader = request.headers.get('cookie'); + if (cookieHeader) { + headers['Cookie'] = cookieHeader; + } + + // Fusionner les headers personnalisés (ils ont la priorité) + if (customHeaders && typeof customHeaders === 'object') { + headers = { ...headers, ...customHeaders }; + } + + return headers; +} + +/** + * Gère les requêtes OPTIONS (preflight CORS) + */ +function handleOptions() { + return new Response(null, { + status: 204, + headers: { + ...CORS_HEADERS, + 'Access-Control-Max-Age': '86400', + }, + }); +} + +/** + * Gère les requêtes proxy + */ +async function handleProxy(request) { + try { + // Extraire l'URL cible depuis les query parameters + const url = new URL(request.url); + const targetUrlParam = url.searchParams.get('url'); + + if (!targetUrlParam) { + return new Response( + JSON.stringify({ error: 'No URL provided' }), + { + status: 400, + headers: { + 'Content-Type': 'application/json', + ...CORS_HEADERS, + }, + } + ); + } + + // Décoder l'URL + const targetUrl = decodeURIComponent(targetUrlParam); + + // Extraire les headers personnalisés depuis le paramètre headers + let customHeaders = {}; + const headersParam = url.searchParams.get('headers'); + if (headersParam) { + try { + customHeaders = JSON.parse(decodeURIComponent(headersParam)); + } catch (e) { + // Si le parsing échoue, continuer sans les headers personnalisés + console.warn('Failed to parse custom headers:', e); + } + } + + // Détecter si c'est un fichier MP4 + const isMp4 = targetUrl.toLowerCase().includes('.mp4') || + request.headers.get('accept')?.includes('video/mp4'); + + // Préparer les headers pour la requête + const forwardHeaders = prepareHeaders(targetUrl, request, customHeaders); + + // Faire la requête vers l'URL cible + const proxyRequest = new Request(targetUrl, { + method: request.method, + headers: forwardHeaders, + // Cloudflare Workers supporte automatiquement les Range requests + }); + + // Exécuter la requête avec fetch + const response = await fetch(proxyRequest); + + // Si ce n'est pas une réponse réussie, retourner l'erreur + if (!response.ok && response.status !== 206) { + return new Response( + JSON.stringify({ + error: 'Request failed', + status: response.status, + statusText: response.statusText, + }), + { + status: response.status, + headers: { + 'Content-Type': 'application/json', + ...CORS_HEADERS, + }, + } + ); + } + + // Préparer les headers de réponse + const responseHeaders = new Headers(); + + // Copier les headers de la réponse source (sauf ceux qu'on ne veut pas) + const headersToSkip = ['transfer-encoding', 'connection', 'content-encoding', 'access-control-allow-origin']; + for (const [key, value] of response.headers.entries()) { + if (!headersToSkip.includes(key.toLowerCase())) { + responseHeaders.set(key, value); + } + } + + // Ajouter les headers CORS + for (const [key, value] of Object.entries(CORS_HEADERS)) { + responseHeaders.set(key, value); + } + + // Headers spécifiques pour MP4 + if (isMp4) { + responseHeaders.set('Accept-Ranges', 'bytes'); + responseHeaders.set('Cache-Control', 'public, max-age=3600'); + + // S'assurer que Content-Type est défini + if (!responseHeaders.has('Content-Type')) { + responseHeaders.set('Content-Type', 'video/mp4'); + } + + // Pour les réponses 206 (Partial Content), s'assurer que Content-Range est présent + if (response.status === 206) { + const contentRange = response.headers.get('content-range'); + const contentLength = response.headers.get('content-length'); + + if (contentRange) { + responseHeaders.set('Content-Range', contentRange); + } + if (contentLength) { + responseHeaders.set('Content-Length', contentLength); + } + + // S'assurer que Accept-Ranges est présent + if (!responseHeaders.has('Accept-Ranges')) { + responseHeaders.set('Accept-Ranges', 'bytes'); + } + } + } + + // Retourner la réponse en streaming (Cloudflare Workers stream automatiquement) + return new Response(response.body, { + status: response.status, + statusText: response.statusText, + headers: responseHeaders, + }); + + } catch (error) { + console.error('Proxy error:', error); + return new Response( + JSON.stringify({ + error: 'Internal Server Error', + message: error.message, + }), + { + status: 500, + headers: { + 'Content-Type': 'application/json', + ...CORS_HEADERS, + }, + } + ); + } +} + +/** + * Handler principal du worker + */ +export default { + async fetch(request, env, ctx) { + const url = new URL(request.url); + const path = url.pathname; + + // Gérer les requêtes OPTIONS (preflight CORS) + if (request.method === 'OPTIONS') { + return handleOptions(); + } + + // Route proxy + if (path === '/proxy' || path.startsWith('/proxy/')) { + return handleProxy(request); + } + + // Route de santé + if (path === '/health') { + return new Response( + JSON.stringify({ + status: 'ok', + message: 'Cloudflare Workers Proxy Server is running', + }), + { + status: 200, + headers: { + 'Content-Type': 'application/json', + ...CORS_HEADERS, + }, + } + ); + } + + // Route non trouvée + return new Response( + JSON.stringify({ error: 'Not Found' }), + { + status: 404, + headers: { + 'Content-Type': 'application/json', + ...CORS_HEADERS, + }, + } + ); + }, +}; + diff --git a/RivestreamCloudflareProxy/wrangler.toml b/RivestreamCloudflareProxy/wrangler.toml new file mode 100644 index 0000000..36266fa --- /dev/null +++ b/RivestreamCloudflareProxy/wrangler.toml @@ -0,0 +1,9 @@ +name = "rivestream-proxy" +main = "worker.js" +compatibility_date = "2024-01-01" + +[env.production] +name = "rivestream-proxy" + +[env.production.vars] +# Variables d'environnement si nécessaire diff --git a/cloudflareproxy/worker.js b/cloudflareproxy/worker.js new file mode 100644 index 0000000..92c995c --- /dev/null +++ b/cloudflareproxy/worker.js @@ -0,0 +1,116 @@ +(() => { + var __defProp = Object.defineProperty; + var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); + + // index.js + var blacklistUrls = []; + var whitelistOrigins = [".*"]; + function isListedInWhitelist(uri, listing) { + let isListed = false; + if (typeof uri === "string") { + listing.forEach((pattern) => { + if (uri.match(pattern) !== null) { + isListed = true; + } + }); + } else { + isListed = true; + } + return isListed; + } + __name(isListedInWhitelist, "isListedInWhitelist"); + addEventListener("fetch", async (event) => { + event.respondWith(async function() { + const isPreflightRequest = event.request.method === "OPTIONS"; + const originUrl = new URL(event.request.url); + function setupCORSHeaders(headers) { + headers.set("Access-Control-Allow-Origin", event.request.headers.get("Origin")); + if (isPreflightRequest) { + headers.set("Access-Control-Allow-Methods", event.request.headers.get("access-control-request-method")); + const requestedHeaders = event.request.headers.get("access-control-request-headers"); + if (requestedHeaders) { + headers.set("Access-Control-Allow-Headers", requestedHeaders); + } + headers.delete("X-Content-Type-Options"); + } + return headers; + } + __name(setupCORSHeaders, "setupCORSHeaders"); + const targetUrl = decodeURIComponent(decodeURIComponent(originUrl.search.substr(1))); + const originHeader = event.request.headers.get("Origin"); + const connectingIp = event.request.headers.get("CF-Connecting-IP"); + if (!isListedInWhitelist(targetUrl, blacklistUrls) && isListedInWhitelist(originHeader, whitelistOrigins)) { + let customHeaders = event.request.headers.get("x-cors-headers"); + if (customHeaders !== null) { + try { + customHeaders = JSON.parse(customHeaders); + } catch (e) { + } + } + if (originUrl.search.startsWith("?")) { + const filteredHeaders = {}; + for (const [key, value] of event.request.headers.entries()) { + if (key.match("^origin") === null && key.match("eferer") === null && key.match("^cf-") === null && key.match("^x-forw") === null && key.match("^x-cors-headers") === null) { + filteredHeaders[key] = value; + } + } + if (customHeaders !== null) { + Object.entries(customHeaders).forEach((entry) => filteredHeaders[entry[0]] = entry[1]); + } + const newRequest = new Request(event.request, { + redirect: "follow", + headers: filteredHeaders + }); + const response = await fetch(targetUrl, newRequest); + let responseHeaders = new Headers(response.headers); + const exposedHeaders = []; + const allResponseHeaders = {}; + for (const [key, value] of response.headers.entries()) { + exposedHeaders.push(key); + allResponseHeaders[key] = value; + } + exposedHeaders.push("cors-received-headers"); + responseHeaders = setupCORSHeaders(responseHeaders); + responseHeaders.set("Access-Control-Expose-Headers", exposedHeaders.join(",")); + responseHeaders.set("cors-received-headers", JSON.stringify(allResponseHeaders)); + const responseBody = isPreflightRequest ? null : await response.arrayBuffer(); + const responseInit = { + headers: responseHeaders, + status: isPreflightRequest ? 200 : response.status, + statusText: isPreflightRequest ? "OK" : response.statusText + }; + return new Response(responseBody, responseInit); + } else { + let responseHeaders = new Headers(); + responseHeaders = setupCORSHeaders(responseHeaders); + let country = false; + let colo = false; + if (typeof event.request.cf !== "undefined") { + country = event.request.cf.country || false; + colo = event.request.cf.colo || false; + } + return new Response( + "CLOUDFLARE-CORS-ANYWHERE\n\nSource:\nhttps://github.com/Zibri/cloudflare-cors-anywhere\n\nUsage:\n" + originUrl.origin + "/?uri\n\nLimits: 100,000 requests/day\n 1,000 requests/10 minutes\n\n" + (originHeader !== null ? "Origin: " + originHeader + "\n" : "") + "IP: " + connectingIp + "\n" + (country ? "Country: " + country + "\n" : "") + (colo ? "Datacenter: " + colo + "\n" : "") + "\n" + (customHeaders !== null ? "\nx-cors-headers: " + JSON.stringify(customHeaders) : ""), + { + status: 200, + headers: responseHeaders + } + ); + } + } else { + return new Response( + "Create your own CORS proxy
\nhttps://github.com/Zibri/cloudflare-cors-anywhere\n", + { + status: 403, + statusText: "Forbidden", + headers: { + "Content-Type": "text/html" + } + } + ); + } + }()); + }); + })(); + //# sourceMappingURL=index.js.map + \ No newline at end of file diff --git a/cloudflareproxy/wrangler.toml b/cloudflareproxy/wrangler.toml new file mode 100644 index 0000000..706c9b8 --- /dev/null +++ b/cloudflareproxy/wrangler.toml @@ -0,0 +1,9 @@ +name = "cloudflareproxy403" +main = "worker.js" +compatibility_date = "2024-01-01" + +[env.production] +name = "cloudflareproxy403" + +[env.production.vars] +# Variables d'environnement si nécessaire diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 0000000..6f4715b --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,41 @@ +import js from '@eslint/js' +import globals from 'globals' +import reactHooks from 'eslint-plugin-react-hooks' +import reactRefresh from 'eslint-plugin-react-refresh' +import tseslint from 'typescript-eslint' +import unusedImports from 'eslint-plugin-unused-imports' + +export default tseslint.config( + { ignores: ['dist'] }, + { + extends: [js.configs.recommended, ...tseslint.configs.recommended], + files: ['**/*.{ts,tsx}'], + languageOptions: { + ecmaVersion: 2020, + globals: globals.browser, + }, + plugins: { + 'react-hooks': reactHooks, + 'react-refresh': reactRefresh, + 'unused-imports': unusedImports, + }, + rules: { + ...reactHooks.configs.recommended.rules, + 'react-refresh/only-export-components': [ + 'warn', + { allowConstantExport: true }, + ], + '@typescript-eslint/no-unused-vars': 'off', + 'unused-imports/no-unused-imports': 'error', + 'unused-imports/no-unused-vars': [ + 'warn', + { + vars: 'all', + varsIgnorePattern: '^_', + args: 'after-used', + argsIgnorePattern: '^_', + }, + ], + }, + }, +) diff --git a/extension/Chrome/Chrome.zip b/extension/Chrome/Chrome.zip new file mode 100644 index 0000000..62e946a Binary files /dev/null and b/extension/Chrome/Chrome.zip differ diff --git a/extension/Chrome/background.js b/extension/Chrome/background.js index 5f3f471..9fc435a 100644 --- a/extension/Chrome/background.js +++ b/extension/Chrome/background.js @@ -82,7 +82,6 @@ async function setupRules() { initiatorDomains: [ "localhost", "127.0.0.1", - "movix.blog", "movix.rodeo", "movix.club", ], @@ -348,8 +347,8 @@ function handleDetectEmbeds(payload) { function buildBackendApiHeaders(accessKey, extraHeaders = {}) { const headers = { Accept: "application/json", - Origin: "https://movix.blog", - Referer: "https://movix.blog/", + Origin: "https://movix.rodeo", + Referer: "https://movix.rodeo/", ...extraHeaders, }; diff --git a/extension/Chrome/extractors.js b/extension/Chrome/extractors.js index 9734544..b8b797a 100644 --- a/extension/Chrome/extractors.js +++ b/extension/Chrome/extractors.js @@ -5,7 +5,7 @@ */ // ===== Configuration ===== -const PROXY_BASE = 'https://proxiesembed.movix.blog'; +const PROXY_BASE = 'https://proxiesembed.movix.rodeo'; // AES constants for SeekStreaming (embed4me) const SEEKSTREAMING_AES_KEY_HEX = '6b69656d7469656e6d7561393131636131323334353637383930'; diff --git a/extension/Chrome/manifest.json b/extension/Chrome/manifest.json index 0c185af..787625a 100644 --- a/extension/Chrome/manifest.json +++ b/extension/Chrome/manifest.json @@ -36,8 +36,6 @@ "externally_connectable": { "matches": [ "*://localhost/*", - "*://movix.blog/*", - "*://*.movix.blog/*", "*://movix.rodeo/*", "*://*.movix.rodeo/*", "*://movix.club/*", diff --git a/extension/Chrome/popup.html b/extension/Chrome/popup.html index 61ff23d..2bdc655 100644 --- a/extension/Chrome/popup.html +++ b/extension/Chrome/popup.html @@ -431,7 +431,7 @@