MovixOpenSource/API/Mainapi/utils/hydrackerLive.js
Movix 8657a856f8 feat: live TV FCTV, fournisseur OAuth, sources J1F/Cinestream, modération IA & durcissement
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>
2026-07-05 18:22:13 +02:00

428 lines
14 KiB
JavaScript

// API/Mainapi/utils/hydrackerLive.js
//
// Live raw-URL resolution path used by darkiworldSqlite.decodeLink when both
// the disk cache and the two sqlite snapshots miss. See:
// docs/superpowers/plans/2026-05-16-hydracker-live-raw-resolution.md
'use strict';
const { randomUUID } = require('node:crypto');
const LOCK_RELEASE_SCRIPT =
"if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end";
function createLimit(max) {
let active = 0;
const queue = [];
const pump = () => {
if (active >= max || queue.length === 0) return;
const job = queue.shift();
active++;
Promise.resolve()
.then(job.fn)
.then(
(v) => { active--; job.resolve(v); pump(); },
(e) => { active--; job.reject(e); pump(); },
);
};
return (fn) => new Promise((resolve, reject) => {
queue.push({ fn, resolve, reject });
pump();
});
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function withRedisLock(redis, key, ttlSec, work, opts = {}) {
const waitMs = opts.waitMs ?? 65000;
const pollMs = opts.pollMs ?? 500;
const onWaitCheck = opts.onWaitCheck || (async () => null);
const token = randomUUID();
let acquired = null;
try {
acquired = await redis.set(key, token, 'NX', 'EX', ttlSec);
} catch (_) {
// Redis unreachable — fail closed so we don't bypass single-flight and
// overload upstream during a Redis outage.
return { owned: false, value: null, redisDown: true };
}
if (acquired === 'OK') {
try {
const value = await work();
return { owned: true, value };
} finally {
try {
await redis.eval(LOCK_RELEASE_SCRIPT, 1, key, token);
} catch (_) { /* swallow */ }
}
}
const deadline = Date.now() + waitMs;
while (Date.now() < deadline) {
await sleep(pollMs);
let cached = null;
try { cached = await onWaitCheck(); } catch (_) { cached = null; }
if (cached) return { owned: false, value: cached };
}
return { owned: false, value: null, timedOut: true };
}
async function fetchHydrackerLien(lienId, deps) {
const { axios, limit, cookies, xsrf, timeoutMs } = deps;
return limit(async () => {
try {
const resp = await axios.get(
`https://hydracker.com/api/v1/content/liens/${lienId}`,
{
timeout: timeoutMs,
headers: {
accept: 'application/json',
cookie: cookies || '',
'x-xsrf-token': xsrf || '',
'user-agent': 'Mozilla/5.0 (Movix HydrackerLive)',
},
validateStatus: (s) => s >= 200 && s < 300,
},
);
const body = resp.data || {};
const directDL = body.directDL;
if (!directDL || typeof directDL !== 'string') {
return { ok: false, code: 'live_no_directdl' };
}
return {
ok: true,
directDL,
rawUrl: typeof body.raw_url === 'string' && body.raw_url ? body.raw_url : null,
taille: body.lien?.taille ?? null,
created_at: body.lien?.created_at ?? null,
};
} catch (e) {
return {
ok: false,
code: 'live_hydracker_error',
status: e?.response?.status || 0,
};
}
});
}
async function fetchHydrackerTitleLiens(titleId, deps) {
const { axios, limit, cookies, xsrf, timeoutMs } = deps;
return limit(async () => {
try {
const resp = await axios.get(
`https://hydracker.com/api/v1/titles/${titleId}/content/liens`,
{
params: {
perPage: 100,
loader: 'linksdl',
filters: '',
paginate: 'preferLengthAware',
},
timeout: timeoutMs,
headers: {
accept: 'application/json',
cookie: cookies || '',
'x-xsrf-token': xsrf || '',
'user-agent': 'Mozilla/5.0 (Movix HydrackerLive)',
},
validateStatus: (s) => s >= 200 && s < 300,
},
);
const rows = Array.isArray(resp.data?.pagination?.data) ? resp.data.pagination.data : [];
return { ok: true, rows };
} catch (e) {
return {
ok: false,
code: 'live_hydracker_list_error',
status: e?.response?.status || 0,
};
}
});
}
function normalizeHydrackerLien(row) {
if (!row || typeof row.id !== 'number') return null;
const langs = Array.isArray(row.langues_compact)
? row.langues_compact.map((l) => l.name).filter(Boolean).join('/')
: '';
const subs = Array.isArray(row.subs_compact)
? row.subs_compact.map((s) => s.name).filter(Boolean).join('/')
: '';
const hostName = row.host?.name || undefined;
return {
id: row.id,
language: langs || undefined,
quality: row.qual?.qual || undefined,
sub: subs || undefined,
// Frontend uses `provider` as the visible host label, so surface the
// real host name (1Fichier, Send, ...) instead of a generic tag.
provider: hostName || 'darkiworld',
host_id: row.id_host != null ? row.id_host : undefined,
host_name: hostName,
host_icon: row.host?.icon || undefined,
size: row.taille || undefined,
upload_date: row.created_at || undefined,
saison: row.saison != null ? row.saison : undefined,
episode: row.episode != null ? row.episode : undefined,
full_saison: row.full_saison ? 1 : undefined,
source: 'hydracker-live',
};
}
const FAILED_MARKER_TTL_MS = 2 * 60 * 60 * 1000; // 2h — match darkiworldSqlite
function buildFailedMarker(lienId, code, status) {
return {
failed: true,
failedAt: Date.now(),
id: String(lienId),
error: 'Lien indisponible',
debug: code,
status: status ?? null,
};
}
function buildSuccessPayload(lienId, raw, hydracker) {
return {
success: true,
id: String(lienId),
provider: 'hydracker-live',
embed_url: {
lien: raw.link,
taille: raw.size ?? hydracker.taille ?? 0,
created_at: hydracker.created_at ?? null,
},
metadata: {
language: undefined,
quality: undefined,
sub: undefined,
size: raw.size ?? hydracker.taille ?? undefined,
upload_date: hydracker.created_at ?? undefined,
host: raw.host ?? undefined,
filename: raw.filename ?? undefined,
},
source: 'live',
};
}
function createHydrackerLive(deps) {
const {
redis, axios, cookies, xsrf,
concurrency = 6, timeoutMs = 20000,
cacheGet, cacheSet, cacheKeyFor, cacheDir,
hydrackerLienCacheTtl = 60,
titleListCacheTtl = 300,
lockTtlSec = 60, lockWaitMs = 65000, lockPollMs = 500,
upstreamCooldownMs = 5 * 60 * 1000,
} = deps;
const limit = createLimit(concurrency);
// Cluster-wide hydracker upstream cooldown — stored in Redis so a 5xx
// observed by any worker stops ALL workers from hammering a sick server.
// Key carries a TTL = upstreamCooldownMs, so it self-expires.
// Fail-open on Redis errors: a Redis outage must not block live fetches.
const HYDRACKER_COOLDOWN_KEY = 'hydracker:cooldown:5xx';
const cooldownTtlSec = Math.max(1, Math.ceil(upstreamCooldownMs / 1000));
async function isHydrackerInCooldown() {
try {
const exists = await redis.exists(HYDRACKER_COOLDOWN_KEY);
return exists === 1;
} catch (_) {
return false;
}
}
async function armHydrackerCooldownIfServerError(status) {
if (typeof status !== 'number' || status < 500 || status >= 600) {
return false;
}
try {
// NX so concurrent 5xx responses don't keep resetting the TTL window —
// first writer wins, the rest are no-ops.
const armed = await redis.set(
HYDRACKER_COOLDOWN_KEY,
String(Date.now()),
'EX',
cooldownTtlSec,
'NX',
);
if (armed === 'OK') {
console.warn(
`[hydrackerLive] upstream ${status} — cooldown ${Math.round(upstreamCooldownMs / 60000)}min (cluster-wide)`,
);
}
} catch (_) {
// Redis down — cooldown not armed, but per-worker retry pressure stays
// low because hydracker itself is still returning 5xx quickly.
}
return true;
}
async function getCachedHydracker(lienId) {
try {
const raw = await redis.get(`hydracker:lien:${lienId}`);
if (raw) return JSON.parse(raw);
} catch (_) { /* swallow */ }
return null;
}
async function cacheHydracker(lienId, hyd) {
try {
await redis.set(
`hydracker:lien:${lienId}`,
JSON.stringify(hyd),
'EX',
hydrackerLienCacheTtl,
);
} catch (_) { /* swallow */ }
}
async function resolveLien(lienId) {
const key = cacheKeyFor(lienId);
const lockKey = `lock:hydracker:lien:${lienId}`;
const enterTime = Date.now();
const lockResult = await withRedisLock(redis, lockKey, lockTtlSec, async () => {
// Winner path. Re-check cache in case a previous holder finished
// between our miss check and lock acquisition.
// IMPORTANT: only short-circuit on success payloads. Failed markers
// (especially the legacy `sqlite_miss` one) are precisely why the
// caller's decodeLink self-heal decided to invoke us; honouring them
// here would loop the retry back into the same marker and the live
// fetch would never run.
const pre = await cacheGet(cacheDir, key);
if (pre && pre.success === true) return pre;
// Reuse a recent hydracker response (Redis, hydrackerLienCacheTtl) so
// we don't re-hit upstream while waiting for AllDebrid history to
// pick up a freshly-debrided link. Saves rate-limit budget.
let hyd = await getCachedHydracker(lienId);
if (!hyd) {
if (await isHydrackerInCooldown()) {
// Don't persist marker — cooldown is transient; retry cheap after
// window ends instead of locking a 2h disk marker.
return buildFailedMarker(lienId, 'live_hydracker_cooldown', 0);
}
hyd = await fetchHydrackerLien(lienId, {
axios, limit, cookies, xsrf, timeoutMs,
});
if (hyd.ok) {
await cacheHydracker(lienId, hyd);
} else {
await armHydrackerCooldownIfServerError(hyd.status);
}
}
if (!hyd.ok) {
const marker = buildFailedMarker(lienId, hyd.code, hyd.status);
try { await cacheSet(cacheDir, key, marker); } catch (_) {}
return marker;
}
// hydracker returns the raw host link (1fichier, ...) directly in
// raw_url/directDL now — no debrid unlock step. directDL is the
// fallback when raw_url is absent.
const match = {
link: hyd.rawUrl || hyd.directDL,
size: hyd.taille ?? undefined,
host: undefined,
filename: undefined,
};
const payload = buildSuccessPayload(lienId, match, hyd);
try { await cacheSet(cacheDir, key, payload); } catch (_) {}
return payload;
}, {
waitMs: lockWaitMs,
pollMs: lockPollMs,
onWaitCheck: async () => {
const c = await cacheGet(cacheDir, key);
if (!c) return null;
if (c.success === true) return c;
// Only honour a failed marker if it was written AFTER we started
// waiting — otherwise it's a stale pre-existing marker that has
// nothing to do with the current holder's in-flight work.
if (c.failed === true && typeof c.failedAt === 'number' && c.failedAt >= enterTime) {
return c;
}
return null;
},
});
if (lockResult.redisDown) {
return { failed: buildFailedMarker(lienId, 'live_redis_down') };
}
if (lockResult.timedOut || !lockResult.value) {
return { failed: buildFailedMarker(lienId, 'live_lock_timeout') };
}
const result = lockResult.value;
return result.success === true ? { payload: result } : { failed: result };
}
async function listLiensForTitle(titleId, opts = {}) {
const { type, season, episode } = opts;
const titleNum = Number(titleId);
if (!Number.isFinite(titleNum) || !Number.isInteger(titleNum) || titleNum <= 0) {
return [];
}
const cacheKey = `hydracker:title:${titleNum}`;
let rows = null;
try {
const raw = await redis.get(cacheKey);
if (raw) {
try { rows = JSON.parse(raw); } catch (_) { rows = null; }
}
} catch (_) { /* redis down — refetch */ }
if (!rows) {
if (await isHydrackerInCooldown()) {
console.warn(`[hydrackerLive] title list skipped (cooldown active) title=${titleNum}`);
return [];
}
const res = await fetchHydrackerTitleLiens(titleNum, {
axios, limit, cookies, xsrf, timeoutMs,
});
if (!res.ok) {
await armHydrackerCooldownIfServerError(res.status);
console.warn(`[hydrackerLive] title list fetch failed title=${titleNum} code=${res.code} status=${res.status ?? '-'}`);
return [];
}
rows = res.rows;
try {
await redis.set(cacheKey, JSON.stringify(rows), 'EX', titleListCacheTtl);
} catch (_) { /* swallow */ }
}
let filtered = rows;
if (type === 'tv') {
const sNum = Number(season);
const eNum = Number(episode);
if (Number.isFinite(sNum) && Number.isFinite(eNum)) {
filtered = rows.filter((r) =>
Number(r.saison) === sNum && (Number(r.episode) === eNum || r.full_saison === 1 || r.full_saison === true),
);
}
}
// For 'movie' (or unspecified) return everything — hydracker stores movies
// as saison=0/episode=null and the caller already implies that by passing
// type='movie'.
return filtered.map(normalizeHydrackerLien).filter(Boolean);
}
return { resolveLien, listLiensForTitle };
}
module.exports = {
createHydrackerLive,
_createLimit: createLimit,
_withRedisLock: withRedisLock,
_fetchHydrackerLien: fetchHydrackerLien,
_fetchHydrackerTitleLiens: fetchHydrackerTitleLiens,
_normalizeHydrackerLien: normalizeHydrackerLien,
_buildSuccessPayload: buildSuccessPayload,
_buildFailedMarker: buildFailedMarker,
};