v1.5.9 (Actuel)
This commit is contained in:
+86
-34
@@ -1,18 +1,18 @@
|
||||
import { CONFIG } from '../../src/utils/config.js';
|
||||
|
||||
export const CONFIG_HYDRACKER = {
|
||||
BASE_URL: (CONFIG.HYDRACKER_URL || '').replace(/\/$/, ''), // Supprime le slash final
|
||||
API_KEY: CONFIG.HYDRACKER_API_KEY,
|
||||
TIMEOUT: CONFIG.HYDRACKER_TIMEOUT || 15000,
|
||||
get BASE_URL() { return (CONFIG.HYDRACKER_URL || '').replace(/\/$/, ''); },
|
||||
get API_KEY() { return CONFIG.HYDRACKER_API_KEY; },
|
||||
get TIMEOUT() { return CONFIG.HYDRACKER_TIMEOUT || 15000; },
|
||||
};
|
||||
|
||||
const HYDRACKER_HEADERS = {
|
||||
'Accept': 'application/json',
|
||||
'Authorization': `Bearer ${CONFIG_HYDRACKER.API_KEY}`,
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
|
||||
};
|
||||
|
||||
const TIMEOUT = CONFIG_HYDRACKER.TIMEOUT; // 30 secondes par défaut (configurable)
|
||||
export function getHydrackerHeaders() {
|
||||
return {
|
||||
'Accept': 'application/json',
|
||||
'Authorization': `Bearer ${CONFIG_HYDRACKER.API_KEY}`,
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
|
||||
};
|
||||
}
|
||||
|
||||
async function fetchWithRetry(
|
||||
url: string,
|
||||
@@ -26,7 +26,7 @@ async function fetchWithRetry(
|
||||
while (true) {
|
||||
attempt++;
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), TIMEOUT);
|
||||
const timeoutId = setTimeout(() => controller.abort(), CONFIG_HYDRACKER.TIMEOUT);
|
||||
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
@@ -60,11 +60,13 @@ async function fetchWithRetry(
|
||||
}
|
||||
|
||||
export async function apiGet(urlPath: string, params: Record<string, any> = {}) {
|
||||
const qs = Object.entries(params).map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join('&');
|
||||
let qs = Object.entries(params).map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join('&');
|
||||
// FIX: Hydracker API returns 401 if ':' is URL-encoded as '%3A'
|
||||
qs = qs.replace(/%3A/g, ':');
|
||||
const url = `${CONFIG_HYDRACKER.BASE_URL}/api/v1/${urlPath}` + (qs ? `?${qs}` : '');
|
||||
try {
|
||||
const res = await fetchWithRetry(url, {
|
||||
headers: HYDRACKER_HEADERS
|
||||
headers: getHydrackerHeaders()
|
||||
});
|
||||
if (!res.ok) {
|
||||
console.error(`[Hydracker-API] apiGet HTTP ${res.status} on ${urlPath}`);
|
||||
@@ -82,7 +84,7 @@ export async function apiPost(urlPath: string, body: any = {}) {
|
||||
try {
|
||||
const res = await fetchWithRetry(url, {
|
||||
method: 'POST',
|
||||
headers: { ...HYDRACKER_HEADERS, 'Content-Type': 'application/json' },
|
||||
headers: { ...getHydrackerHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
return { status: res.status, body: await res.text() };
|
||||
@@ -93,16 +95,21 @@ export async function apiPost(urlPath: string, body: any = {}) {
|
||||
}
|
||||
|
||||
export async function fetchSearch(query: string) {
|
||||
const url = `${CONFIG_HYDRACKER.BASE_URL}/api/v1/search/${encodeURIComponent(query)}?loader=searchAutocomplete`;
|
||||
const url = `${CONFIG_HYDRACKER.BASE_URL}/api/v1/titles?query=${encodeURIComponent(query)}`;
|
||||
try {
|
||||
const res = await fetchWithRetry(url, {
|
||||
headers: HYDRACKER_HEADERS
|
||||
headers: getHydrackerHeaders()
|
||||
});
|
||||
if (!res.ok) {
|
||||
console.error(`[Hydracker-API] Search HTTP ${res.status} for "${query}"`);
|
||||
return null;
|
||||
}
|
||||
return await res.json();
|
||||
const data = await res.json();
|
||||
// Transform the new API structure to match the old expected structure
|
||||
if (data && data.pagination && Array.isArray(data.pagination.data)) {
|
||||
return { results: data.pagination.data };
|
||||
}
|
||||
return data;
|
||||
} catch (e: any) {
|
||||
console.error('[Hydracker-API] Search failed:', e.message);
|
||||
return null;
|
||||
@@ -113,7 +120,7 @@ export async function fetchMovieLinks(titleId: string) {
|
||||
const url = `${CONFIG_HYDRACKER.BASE_URL}/api/v1/titles/${titleId}/download`;
|
||||
try {
|
||||
const res = await fetchWithRetry(url, {
|
||||
headers: HYDRACKER_HEADERS
|
||||
headers: getHydrackerHeaders()
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
return await res.json();
|
||||
@@ -122,22 +129,67 @@ export async function fetchMovieLinks(titleId: string) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchSeriesLiens(titleId: string, season: number = 1) {
|
||||
const allLiens: any[] = [];
|
||||
let page = 1;
|
||||
while (true) {
|
||||
const result = await apiGet('liens', {
|
||||
title_id: titleId, loader: 'linksdl', season,
|
||||
perPage: 500, page, filters: '', paginate: 'lengthAware'
|
||||
});
|
||||
if (!result || result.error) break;
|
||||
const pagination = result.pagination || {};
|
||||
const data = pagination.data || [];
|
||||
if (!data.length) break;
|
||||
allLiens.push(...data);
|
||||
const lastPage = pagination.last_page || pagination.lastPage || 1;
|
||||
if (page >= lastPage) break;
|
||||
page++;
|
||||
/**
|
||||
* Récupère la page de download d'un titre.
|
||||
* - Films : GET /titles/{id}/download
|
||||
* - Séries : GET /titles/{id}/season/{s}/episode/{e}/download
|
||||
*
|
||||
* Retourne l'objet complet contenant: video, alternative_videos, title.seasons, last_episode, etc.
|
||||
*/
|
||||
export async function fetchDownloadPage(titleId: string, season?: number, episode?: number) {
|
||||
let urlPath: string;
|
||||
if (season && season > 0 && episode && episode > 0) {
|
||||
urlPath = `titles/${titleId}/season/${season}/episode/${episode}/download`;
|
||||
} else if (season && season > 0) {
|
||||
// On demande le premier épisode de la saison pour obtenir les métadonnées
|
||||
urlPath = `titles/${titleId}/season/${season}/episode/1/download`;
|
||||
} else {
|
||||
urlPath = `titles/${titleId}/download`;
|
||||
}
|
||||
return await apiGet(urlPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupère TOUS les liens d'une saison en itérant sur chaque épisode via /download.
|
||||
* Utilise last_episode pour savoir combien d'épisodes ont des liens.
|
||||
*/
|
||||
export async function fetchSeriesLiens(titleId: string, season: number = 1) {
|
||||
// D'abord, obtenir les métadonnées pour savoir combien d'épisodes il y a
|
||||
const firstPage = await fetchDownloadPage(titleId, season, 1);
|
||||
if (!firstPage) return [];
|
||||
|
||||
const lastEpisodeMap = firstPage.last_episode || {};
|
||||
const lastEp = lastEpisodeMap[String(season)] || 0;
|
||||
|
||||
if (lastEp === 0) return [];
|
||||
|
||||
// Collecter les liens de tous les épisodes
|
||||
const allLiens: any[] = [];
|
||||
|
||||
// Extraire les liens du premier épisode qu'on a déjà chargé
|
||||
const extractLiens = (downloadData: any) => {
|
||||
const liens: any[] = [];
|
||||
if (downloadData.video) liens.push(downloadData.video);
|
||||
if (downloadData.alternative_videos) {
|
||||
for (const av of downloadData.alternative_videos) {
|
||||
// Éviter les doublons (video est souvent dans alternative_videos aussi)
|
||||
if (!liens.find(l => l.id === av.id)) {
|
||||
liens.push(av);
|
||||
}
|
||||
}
|
||||
}
|
||||
return liens;
|
||||
};
|
||||
|
||||
allLiens.push(...extractLiens(firstPage));
|
||||
|
||||
// Charger les épisodes suivants (2 à lastEp)
|
||||
for (let ep = 2; ep <= lastEp; ep++) {
|
||||
const epData = await fetchDownloadPage(titleId, season, ep);
|
||||
if (epData) {
|
||||
allLiens.push(...extractLiens(epData));
|
||||
}
|
||||
}
|
||||
|
||||
return allLiens;
|
||||
}
|
||||
|
||||
+135
-76
@@ -1,6 +1,6 @@
|
||||
import { ISource, SearchResult, MediaType, ContentLinks, VideoLink, SelectionData } from '../../src/types/source.js';
|
||||
import { sourceRegistry } from '../../src/core/registry.js';
|
||||
import { CONFIG_HYDRACKER, apiGet, apiPost, fetchSearch, fetchMovieLinks, fetchSeriesLiens } from './api.js';
|
||||
import { CONFIG_HYDRACKER, apiGet, apiPost, fetchSearch, fetchDownloadPage, fetchSeriesLiens } from './api.js';
|
||||
import {
|
||||
QUALITY_MAP, formatSize,
|
||||
parseSearchResults, parseTrendingResults,
|
||||
@@ -13,19 +13,8 @@ export class HydrackerAPI implements ISource {
|
||||
displayName = 'Hydracker (Token)';
|
||||
|
||||
async healthCheck(): Promise<boolean> {
|
||||
if (!CONFIG_HYDRACKER.BASE_URL || !CONFIG_HYDRACKER.API_KEY) {
|
||||
console.warn('[Hydracker] ⚠️ HYDRACKER_URL ou HYDRACKER_API_KEY manquante.');
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const res = await fetch(CONFIG_HYDRACKER.BASE_URL, {
|
||||
headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36' },
|
||||
signal: AbortSignal.timeout(CONFIG_HYDRACKER.TIMEOUT)
|
||||
});
|
||||
return res.ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
console.warn('[Hydracker] ⚠️ Plugin désactivé (Site fermé définitivement). Conservé pour archivage.');
|
||||
return false;
|
||||
}
|
||||
|
||||
async search(query: string, mediaType: MediaType = 'movie'): Promise<SearchResult[]> {
|
||||
@@ -41,12 +30,20 @@ export class HydrackerAPI implements ISource {
|
||||
}
|
||||
|
||||
async getTrending(mediaType: MediaType): Promise<SearchResult[]> {
|
||||
const type = mediaType === 'series' ? 'series' : 'movie';
|
||||
// Channel 12 = Films, Channel 10 = Séries
|
||||
const channelId = mediaType === 'series' ? 10 : 12;
|
||||
try {
|
||||
const data = await apiGet('titles', { order: 'trending:desc', type, page: 1, paginate: 'lengthAware' });
|
||||
const data = await apiGet(`channel/${channelId}`, {
|
||||
restriction: '',
|
||||
order: 'trending:desc',
|
||||
filters: '',
|
||||
page: 1,
|
||||
paginate: 'lengthAware',
|
||||
returnContentOnly: true
|
||||
});
|
||||
return parseTrendingResults(data);
|
||||
} catch (e: any) {
|
||||
console.error(`[Hydracker] getTrending Error for ${type}:`, e.message);
|
||||
console.error(`[Hydracker] getTrending Error for channel ${channelId}:`, e.message);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -62,16 +59,31 @@ export class HydrackerAPI implements ISource {
|
||||
}
|
||||
|
||||
async getSelection(identifier: string, type?: string, seasonValue?: string | number): Promise<SelectionData> {
|
||||
const seasonsList = await this.getSeasons(identifier);
|
||||
|
||||
// Récupérer les infos du titre via /download pour avoir les saisons
|
||||
const titleData = await fetchDownloadPage(identifier);
|
||||
|
||||
let isSeries = false;
|
||||
if (type) {
|
||||
isSeries = (type === 'series' || type === 'serie' || type === 'tv');
|
||||
} else {
|
||||
isSeries = seasonsList.length > 0;
|
||||
} else if (titleData && titleData.title) {
|
||||
isSeries = titleData.title.is_series === true;
|
||||
}
|
||||
|
||||
const currentSeason = seasonValue ? parseInt(String(seasonValue), 10) : 1;
|
||||
// Extraire les saisons depuis la réponse /download
|
||||
const seasonsList: number[] = [];
|
||||
if (titleData && titleData.title && titleData.title.seasons) {
|
||||
const seasons = titleData.title.seasons;
|
||||
for (const s of seasons) {
|
||||
if (typeof s.number === 'number' && s.number > 0) {
|
||||
seasonsList.push(s.number);
|
||||
}
|
||||
}
|
||||
seasonsList.sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
if (seasonsList.length > 0) isSeries = true;
|
||||
|
||||
const currentSeason = seasonValue ? parseInt(String(seasonValue), 10) : (isSeries ? 1 : 0);
|
||||
const content = await this.getContentLinks(identifier, currentSeason);
|
||||
const formattedSeasons = seasonsList.map(num => ({ label: `Saison ${num}`, value: num }));
|
||||
|
||||
@@ -83,36 +95,80 @@ export class HydrackerAPI implements ISource {
|
||||
}
|
||||
|
||||
async getContentLinks(titleId: string, season: number = 1): Promise<ContentLinks> {
|
||||
// Essai film en premier
|
||||
const movieData = await fetchMovieLinks(titleId);
|
||||
if (movieData) {
|
||||
const movieLinks = parseMovieLinks(movieData);
|
||||
if (movieLinks.length > 0) return { links: movieLinks };
|
||||
if (season === 0) {
|
||||
// Film : utiliser /download directement
|
||||
const downloadData = await fetchDownloadPage(titleId);
|
||||
if (!downloadData) return { links: [] };
|
||||
return { links: this.parseLiensFromDownload(downloadData, season) };
|
||||
}
|
||||
|
||||
// Fallback série
|
||||
// Série : itérer sur les épisodes
|
||||
const rawLiens = await fetchSeriesLiens(titleId, season);
|
||||
const links: VideoLink[] = rawLiens.map(l => ({
|
||||
id: l.id,
|
||||
host: (l.host && l.host.name) || '?',
|
||||
size: formatSize(l.taille),
|
||||
sizeBytes: l.taille || 0,
|
||||
quality: QUALITY_MAP[l.qualite] || `id:${l.qualite}`,
|
||||
langs: getLangs(l),
|
||||
subs: getSubs(l),
|
||||
releaseName: l.release || l.name || l.titre || l.titre_release || undefined,
|
||||
episode: (l.episode === 0 || l.episode === "0" || l.episode === "00")
|
||||
? 'Saison complète'
|
||||
: (l.episode ? String(l.episode) : null),
|
||||
url: null
|
||||
}));
|
||||
|
||||
const links: VideoLink[] = rawLiens.map(l => this.parseSingleLien(l, season));
|
||||
return { links };
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse les liens depuis une réponse /download (film ou épisode unique)
|
||||
*/
|
||||
private parseLiensFromDownload(downloadData: any, season: number): VideoLink[] {
|
||||
const allLiens: any[] = [];
|
||||
if (downloadData.video) allLiens.push(downloadData.video);
|
||||
if (downloadData.alternative_videos) {
|
||||
for (const av of downloadData.alternative_videos) {
|
||||
if (!allLiens.find(l => l.id === av.id)) {
|
||||
allLiens.push(av);
|
||||
}
|
||||
}
|
||||
}
|
||||
return allLiens.map(l => this.parseSingleLien(l, season));
|
||||
}
|
||||
|
||||
/**
|
||||
* Convertit un objet lien brut de l'API en VideoLink unifié
|
||||
*/
|
||||
private parseSingleLien(l: any, season: number): VideoLink {
|
||||
// Extraire le nom du host
|
||||
const hostName = l.host_compact?.name || l.host?.name || l.name || '?';
|
||||
|
||||
// Extraire la qualité
|
||||
const quality = l.qual?.qual || l.quality || QUALITY_MAP[l.qualite] || `id:${l.qualite}`;
|
||||
|
||||
// Extraire les langues
|
||||
const langs = l.langues
|
||||
? l.langues.map((la: any) => la.lang || la.name || '')
|
||||
: getLangs(l);
|
||||
|
||||
// Extraire les sous-titres
|
||||
const subs = l.subs_compact
|
||||
? l.subs_compact.map((s: any) => s.name || '')
|
||||
: getSubs(l);
|
||||
|
||||
return {
|
||||
id: l.id,
|
||||
host: hostName,
|
||||
size: formatSize(l.taille),
|
||||
sizeBytes: l.taille || 0,
|
||||
quality,
|
||||
langs,
|
||||
subs,
|
||||
releaseName: l.release || l.filename || l.name || l.titre || l.titre_release || undefined,
|
||||
episode: (l.episode === 0 || l.episode === "0" || l.episode === "00" || l.episode === null)
|
||||
? (season === 0 ? 'Film complet' : 'Saison complète')
|
||||
: (l.episode ? String(l.episode) : null),
|
||||
url: null
|
||||
};
|
||||
}
|
||||
|
||||
async getSeasons(titleId: string): Promise<number[]> {
|
||||
const result = await apiGet(`titles/${titleId}/seasons`);
|
||||
return parseSeasons(result);
|
||||
// Utiliser /download pour récupérer les saisons (au lieu de /titles/{id} qui est redondant)
|
||||
const downloadData = await fetchDownloadPage(titleId);
|
||||
if (!downloadData || !downloadData.title || !downloadData.title.seasons) return [];
|
||||
|
||||
return downloadData.title.seasons
|
||||
.map((s: any) => s.number)
|
||||
.filter((n: any) => typeof n === 'number' && n > 0)
|
||||
.sort((a: number, b: number) => a - b);
|
||||
}
|
||||
|
||||
private isPremiumCache: boolean | null = null;
|
||||
@@ -150,50 +206,54 @@ export class HydrackerAPI implements ISource {
|
||||
}
|
||||
}
|
||||
|
||||
const isPremium = await this.checkPremiumStatus();
|
||||
|
||||
if (!isPremium) {
|
||||
console.log(`[Hydracker] Compte non Premium détecté. Bypass de Hydracker, passage direct à Movix...`);
|
||||
return await this.resolveMovixLink(linkId);
|
||||
}
|
||||
|
||||
const maxRetries = 4;
|
||||
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
||||
try {
|
||||
if (attempt > 1) {
|
||||
console.log(`[Hydracker] Retry ${attempt}/${maxRetries} for lien ${linkId}`);
|
||||
await new Promise(r => setTimeout(r, 4000));
|
||||
}
|
||||
|
||||
const result = await apiGet(`content/liens/${linkId}`);
|
||||
if (!result) continue;
|
||||
|
||||
const finalUrl = result.directDL || result.url || result.link || '';
|
||||
if (!finalUrl) continue;
|
||||
|
||||
console.log(`[Hydracker] Got final URL: ${finalUrl.substring(0, 80)}...`);
|
||||
|
||||
// Tenter la résolution via l'API /content/liens/{id}
|
||||
try {
|
||||
const result = await apiGet(`content/liens/${linkId}`);
|
||||
if (result && (result.directDL || result.url || result.link)) {
|
||||
const finalUrl = result.directDL || result.url || result.link;
|
||||
console.log(`[Hydracker] Got final URL via API: ${finalUrl.substring(0, 80)}...`);
|
||||
return finalUrl;
|
||||
} catch (e: any) {
|
||||
console.error(`[Hydracker] Exception resolving lien ${linkId} (attempt ${attempt}):`, e.message);
|
||||
}
|
||||
// Vérifier aussi dans result.lien (format alternatif)
|
||||
if (result && result.lien && result.lien.lien) {
|
||||
console.log(`[Hydracker] Got final URL via result.lien.lien`);
|
||||
return result.lien.lien;
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.error(`[Hydracker] Exception resolving lien ${linkId}:`, e.message);
|
||||
}
|
||||
|
||||
console.log(`[Hydracker] Échec de la résolution classique (Erreur). Fallback automatique via Movix...`);
|
||||
console.log(`[Hydracker] Échec de la résolution API. Fallback automatique via Movix...`);
|
||||
return await this.resolveMovixLink(linkId);
|
||||
}
|
||||
|
||||
async resolveMovixLink(lienId: string, titleId?: string): Promise<string | null> {
|
||||
try {
|
||||
const { CONFIG } = await import('../../src/utils/config.js');
|
||||
const movixBase = CONFIG.MOVIX_URL || '';
|
||||
if (!movixBase) {
|
||||
console.warn('[Hydracker] MOVIX_URL non configurée, impossible de résoudre via Movix.');
|
||||
return null;
|
||||
}
|
||||
|
||||
const movixApiBase = (() => {
|
||||
try {
|
||||
const u = new URL(movixBase);
|
||||
return `${u.protocol}//api.${u.host}/api`;
|
||||
} catch { return ''; }
|
||||
})();
|
||||
if (!movixApiBase) return null;
|
||||
|
||||
console.log(`[Hydracker] Tentative de débridage Movix pour le lien ${lienId}...`);
|
||||
const url = `https://api.movix.cloud/api/darkiworld/decode/${lienId}${titleId ? `?title_id=${titleId}` : ''}`;
|
||||
const url = `${movixApiBase}/darkiworld/decode/${lienId}${titleId ? `?title_id=${titleId}` : ''}`;
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Referer': 'https://movix.cloud/',
|
||||
'Origin': 'https://movix.cloud',
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
|
||||
'Accept': 'application/json, text/plain, */*',
|
||||
'Referer': `${movixBase}/`,
|
||||
'Origin': movixBase,
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36 OPR/133.0.0.0'
|
||||
}
|
||||
});
|
||||
|
||||
@@ -204,7 +264,6 @@ export class HydrackerAPI implements ISource {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Récupération du lien direct selon le format de réponse Movix
|
||||
const directUrl = data.directDL || data.direct_url ||
|
||||
(data.embed_url && (data.embed_url.directDL || data.embed_url.src || data.embed_url.lien));
|
||||
|
||||
|
||||
Reference in New Issue
Block a user