mirror of
https://github.com/movixcorp/MovixOpenSource.git
synced 2026-07-26 20:42:08 +00:00
feat: live TV FCTV, fournisseur OAuth, sources J1F/Cinestream, modération IA & durcissement Gros lot de travail synchronisé depuis le repo de dev. Les grands axes : migration de domaine (movix.date + miroirs), deux nouvelles sources films/séries (1jour1film, Cinestream) et une n ouvelle source livetv, un fournisseur OAuth « Se connecter avec Movix », une modération de contenu par IA revue, plus un lot de durcissement mémoire/réseau, sécurité et perf côté API et front. ## 🌐 Domaines & miroirs - Domaine canonique `movix.chat`/`movix.golf`/`movix.tax` → **movix.date** partout (front, allow-lists CORS/domaine, Discord RPC). Miroir `movix.health` → **movix.online** (Footer, Header, pages d'aide CaMarchePlus/Dns/Miroirs). Lien Telegram du footer → `mysticsaba.com`. ~10 clés i18n mises à jour. ## 🎬 Sources de streaming (VOD) - **J1F (1jour1film)** — nouvelle source de bout en bout (`routes/j1f.js`, monté sur `/api/j1f`). Résout le domaine tournant via une page `/go/`, décode les blobs base64 `J1F_SRV`/`j1fEpsData` (Dooplay/WP), ne garde que les players uniques, ignore les agrégateurs (frembed/vidsrc/videasy). Cache stale-while-revalidate dédié. Players 1J1F lus via l'extension/userscript. - **Cinestream** — nouvelle source films (`routes/cinestream.js`, scrape Next.js `cinestream.info`, match par id TMDB autoritaire). Wiflix bascule ses **films** sur Cinestream (bot-shield flemmix pénible sur les films) ; la **TV** reste sur flemmix. - **Wiflix** — `flemmix.farm` → **`flemmix.golf`** ; handshake cookie (`makeWiflixSearchRequest`, `h_check=25`) ; sélecteurs de template corrigés. - **Cpasmal** — axios+proxy → `makeCpasmalRequest` (CycleTLS JA3) car Cloudflare 403 ; recherche GET → POST form (le WAF bloque le GET). - **Fstream** — cookie anti-bot `fsschal` ; source épisodes JS statique (`/static/series/<id>.js`) avant l'AJAX `episodes_p.php` ; fallback `get_seasons.php`. - **FranceTV** — `fetchSeasonEpisodesViaDeepPage` (pagination JSON « Afficher plus »). - **Coflix** — `coflix.date` → `coflix.trade` ; logs 429 silencés en double. - **proxyManager** — cinq helpers de contournement Cloudflare exportés (`makeCinestreamRequest`, `make1j1fRequest`, `makeCpasmalRequest`, handshake Wiflix `makeWiflixSearchRequest`/`wiflixHandshake`, `classifyCloudflare429` worker-vs-site) ; CycleTLS + rotation ProxyScrape, ne throw jamais sur statut HTTP. Coflix/LecteurVideo quittent les Cloudflare Workers pour ProxyScrape. ## 📺 Live TV — remplacement de Sosplay/Vavoo par FCTV33 - Source sport **Sosplay → FCTV33** (API RBTV, protobuf brut) réécrite de bout en bout dans `liveTvRoutes.js`, **Vavoo retiré** (manifest/catalogue/stream) — tout passe par `/api/livetv/*`. - Pipeline neuf : décodeur protobuf maison, signature `sfver` (bs keys + MD5), auto-découverte des domaines API/player tournants (`hubu.ru/fctvlink` + Nuxt SSR / `params` rot47, cache 30 min), scraper de matchs (`scrapeFctvMatches` : équipes/logos, ligue, pays, statut live, tri live-first), résolution de flux (HLS natif d'abord, embed en secours), token CDN (XOR keystream + base64, gate `rb-session`). - Route `GET /api/livetv/fctv/playlist` : proxy m3u8 intelligent (résout le token, réécrit les segments, retry sur token périmé, modes `raw` extension / `proxy` VIP). - **Matchs plus réservés aux VIP** (seul `iptv_` le reste) : flux natif proxifié pour les VIP, stub `_fctvLocal` résolu côté client par l'extension/userscript (`RESOLVE_FCTV`), fallback embed sinon. - Front `LiveTV.tsx` : `matches` → `fctv`, UI accordéon par match (logos, badges ligue/pays, score/timer live, favori), disclaimer, fix icône `music`. Rotations d'hôtes : `witv.team`→`witv.football`, `livetv876.me`→`livetv901.me`. ## 🧩 Extensions · Userscript · Discord RPC - **FCTV en lecture native** : handlers `SETUP_FCTV_HEADERS`/`RESOLVE_FCTV` (règle DNR Referer/Origin/UA sur `/cfall/s*` + résolveur local IP-bindé : protobuf-lite + rot47 + token XOR). - **Vavoo retiré** , `cinepulse.lol` → `purstream.mx`. - Fix extracteur **Sibnet** (`Range: bytes=0-0`) ; fix bug userscript `matchToRegex` (patterns ancrés `^…$` cassant `/cfall/s` → dé-ancrés) ; override dev `localhost:25565`. - Bumps de version (Chrome 1.3.3→1.3.8, Firefox 1.5.1→1.5.5, userscript 1.4.0→1.4.7) ; PreMid nouveau `clientId` Discord + `regExp` élargi (1.0.3→1.0.4). ## 🔑 OAuth (fournisseur « Se connecter avec Movix ») & codes d'accès - Refonte du flux d'autorisation OAuth (`OAuthAuthorizePage.tsx`) + routes (`routes/authRoutes.js`, `routes/oauth.js`) et stockage des clients OAuth étoffé (`utils/oauthClientsDb.js`, `routes/adminOauthApps.js` pour la gestion admin des apps). - `AccessCodeForm.tsx` retouché en cohérence avec le nouveau flux ; `checkVip.js` ajusté. - Session centralisée : `accountAuth.ts` expose `clearStoredAuthSession()` / `broadcastAuthChange()` (liste `AUTH_KEYS` unifiée), désormais utilisés partout à la déconnexion. ## 💬 Modération de contenu (IA) - Modèle OpenRouter `google/gemini-2.5-flash-lite` → `deepseek/deepseek-v4-flash` (`commentsRoutes.js`, `sharedListsRoutes.js`) ; fonctions/logs renommés `moderateContentWithGemini` → `moderateContentWithAI` (découplés du nom du modèle). - Prompt durci (critères INSULTES / DEMANDE_AJOUT resserrés) pour éviter les faux positifs sur questions, signalements de bug et plaintes de contenu manquant. - `AdminComments.tsx` : libellé « par Gemini » → clé i18n générique. ## 🧊 Hydracker / Darkiworld - **Sortie du debrid** : AllDebrid/RealDebrid supprimés (`utils/hydrackerLive.js` : branche provider retirée ; vars `ALLDEBRID_*`/`REALDEBRID_*` sorties du `.env`) — hydracker renvoie directement `rawUrl`/`directDL`. Liens servis depuis les snapshots SQLite locaux (`utils/darkiworldSqlite.js`, `darkino-backups/`). - **Anti-scraping** sur `/decode/:id` (`routes/darkiworld.js`) : watchlist + alerte webhook Discord (`DISCORD_SCRAPER_WEBHOOK`) et empoisonnement/blocage de réponse pour les IP listées (`SCRAPER_BLOCKED_IPS`). - **Mémoire** : cache d'agents proxy borné (`utils/lruMap.js`) qui détruit les sockets des agents évincés. ## 🛠️ Admin — propriété des liens & équipe - **Propriété des liens** : les liens streaming gagnent l'attribution `added_by` et l'ownership est appliquée des deux côtés (uploader = ses liens, admin = tous). GET public masqué (`stripLinkOwner`), `GET /admin/streaming-links/:type/:id` authentifié conserve le tag ; `DELETE /admin/links` par URL unique ; `PUT /admin/links` masse admin-only. - **Équipe** : `GET/POST/DELETE /admin/admins` + `GET /admin/team/history` (audit), identité via `adminIdentity.js` (option `preferProfile` → premier profil Movix). UI `AdminTeam.tsx`. - **Privilèges** (`middleware/auth.js`) : `isAdmin` rejette `role !== 'admin'` (403) — les uploaders ne passent plus les routes admin-only. Migration `add_role_to_admins.sql`. ## 🎁 Wrapped v2 - Cartes de partage : logique canvas extraite (`utils/wrappedCanvas.ts`, `utils/wrappedShareCards.ts`), formats de partage supplémentaires + preview. - Nouvelles slides : jour record, répartition par jour de semaine, champion de rewatch, âge ciné (année de sortie médiane pondérée par le temps de visionnage). - Perf : données depuis le payload backend (zéro re-fetch TMDB), trailer lazy, percentile non bloquant (réchauffe en arrière-plan, lock Redis `NX`), shuffle seedé. ## 🔐 Auth · Profils · VIP - **Pseudo forcé** : `validateProfileName` (1–32 chars, strip control/zero-width, + `maxLength={32}` côté UI Profile/WatchParty) ; les pseudos OAuth trop longs → `requiresUsernameChange` + modale bloquante `RequireUsernameChange.tsx`. - **Sync durci** (`ProfileContext.tsx`, `syncPolicy.js`) : anti-replay cross-user, filtrage des ops à clés non-syncables (`access_code`/`access_code_expires` exclues), « wipe guard » qui préserve le local sur profil vide inattendu, dédupe des `loadProfiles()` concurrents. Logout centralisé (voir OAuth). - **VIP** : `is_vip` préservé au chargement de profil (corrige un downgrade VIP inter-onglets qui relançait la popup pub) ; `vipDonations.js` poll de secours `payment-status.php` (via `ipn_token`, colonne `paygate_ipn_token`) → plus d'invoices bloquées. ## ▶️ Lecteur (HLS) - Basse latence opt-in : `isLowLatencyEnabled('movies')` (scope movies/livetv, `lowLatencyPref.ts`) au lieu du mode forcé ; `FloatingPlayer` aligné. - Sous-titres cinep : wrapper m3u8 synthétique pour les URI `.vtt`/`.srt` directes, `isSubtitleLoadError` (une piste cassée ne tue plus la vidéo), rendu `<i>/<b>/<u>`. - Menu sources regroupé par langue (VF/VFQ/VFF/VOSTFR). ## 📡 Cast (AirPlay / Chromecast) - Retrait du contournement proxy darkibox (`buildApiProxyUrl`) → cast direct de l'URL ; `runtime.ts` supprime `API_PROXY_BASE_URL`/`buildApiProxyUrl` devenus morts. - Paramètre `streamType` (`BUFFERED` par défaut) propagé jusqu'à `loadMediaOnCastWithFallback`. ## 📢 Pubs - Modes de popup (`adPopupMode.ts`) : `normal`, `auto`, `click-anywhere` ; toggle « +18 » séparé (`adAdultMode.ts`). `SCRIPT_AD_MODE_ENABLED` → `false`, URL du script changée. ## 🔎 Recherche & priorité des sources - `searchUtils.ts` : le terme original contourne le filtre « trop générique » (fix zéro-résultat sur titres courts : Baki, Gantz). - `animeSignals.ts` : détection donghua (CN/TW/HK ou `zh` + Animation, hors C-drama). - `sourceAutoSelect.ts` : `VFF`/`VFQ` normalisés en `vf` (sinon reléguées derrière VOSTFR). `sourcePriorityPrefs.ts` : schéma v2 → v3 (nouvel ordre par défaut + `j1f`, migration non destructive des ordres personnalisés). `extractionPrefs.ts` : +daddylive. ## 🔒 Sécurité - Sanitisation d'URL avant rendu en `href` : `CommentsSection.tsx` (liens markdown `http(s)://`) et `Greenlight/AdminLinkSubmissions.tsx` — bloque les `javascript:`. ## ⚙️ Infra & perf - **server.js** : recyclage périodique des workers (12h) + `[memstats]` + hook `SIGUSR2` → heap-snapshot. - **app.js** : monte `/api/j1f`, retire la route statique `/oauth-icons`, passe `makeCpasmalRequest` au router Cpasmal, `coflix.date` → `coflix.trade`. - **lazyWithRetry.ts / main.tsx / ErrorBoundary.tsx** : récupération chunk-load réécrite (retry + reload budgété), garde `removeChild/insertBefore`, écran soft « Mise à jour » au lieu du crash-report. - **UI** : `TopProgressBar` écrit `transform` directement sur un ref (compositor-only, plus de re-render) ; `blur-text` relâche `will-change` après l'animation. - **proxiesembed/server.py** : `curl_cffi` (JA3) pour `cinep-proxy` + retry SOCKS5 sur 403 ; lookup clé VIP réaligné sur `checkVip.js` ; log WARNING par défaut ; SOCKS5 forcé IPv4 ; wrapper VTT/SRT pour hls.js ; re-label `application/zip` → `video/mp2t` ; `cinepulse.lol` → `purstream.mx`. ## 🧹 Nettoyage & suppressions - **Front** : carte promo « Loadix » sur Download (remplace l'encart beta), « 1jour1film » ajouté à « C'est quoi Movix », fallback Darkino/Nightflix gutté en no-op (`api.movix.chat` décommissionné), classes CSS mortes retirées, fix `fetchPriority` → `fetchpriority`. - **Backend** : scrapers/utilitaires morts retirés — `routes/dragiv.js`, `routes/topstream.js`, `routes/proxy.js`, `utils/cloudflareSession.js`, `utils/hydrackerBatch.js`, `utils/hydrackerQueue.js'. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
446 lines
17 KiB
JavaScript
446 lines
17 KiB
JavaScript
/**
|
|
* 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.cloud/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;
|