From bff992aa4a30b3f9e9e2ee51b423d7105b9341ab Mon Sep 17 00:00:00 2001 From: Nolhan Date: Tue, 15 Sep 2026 21:56:10 +0200 Subject: [PATCH] v1.5.9 (Actuel) --- .dockerignore | 12 ++ .env.exemple | 29 ++- .gitignore | 1 + .gitlab-ci.yml | 43 ----- README.md | 56 ++++-- database/config.json | 29 +++ database/flixart_cookie.txt | 1 + database/fs24_cookie.txt | 1 + docker-compose.yml | 9 +- package-lock.json | 8 +- package.json | 6 +- plugins/ZT/index.ts | 12 +- plugins/ZT/parser.ts | 10 +- plugins/flixart/api.ts | 112 +++++++++++ plugins/flixart/auth.ts | 148 +++++++++++++++ plugins/flixart/dump.ts | 15 ++ plugins/flixart/index.ts | 56 ++++++ plugins/flixart/parser.ts | 167 ++++++++++++++++ plugins/freetelecharger/index.ts | 10 +- plugins/freetelecharger/parser.ts | 30 ++- plugins/fs24/api.ts | 129 +++++++++++++ plugins/fs24/auth.ts | 58 ++++++ plugins/fs24/index.ts | 91 +++++++++ plugins/fs24/parser.ts | 164 ++++++++++++++++ plugins/hydracker/api.ts | 120 ++++++++---- plugins/hydracker/index.ts | 211 ++++++++++++-------- plugins/loadix/index.ts | 165 ++++++++++++++++ plugins/movix/api.ts | 47 +++++ plugins/movix/index.ts | 207 ++++++++++++++++++++ plugins/ztnews/api.ts | 2 +- plugins/ztnews/index.ts | 12 +- plugins/ztnews/parser.ts | 8 +- public/app.js | 120 +++++++++++- public/images/logo_svg.svg | 306 ++++++++++++++++++++++++++++++ public/logo_svg.svg | 306 ++++++++++++++++++++++++++++++ public/manifest.json | 4 +- public/sortable.min.js | 2 + public/sw.js | 6 +- src/core/registry.ts | 11 +- src/index.ts | 21 +- src/routes/api.ts | 162 +++++++++++++++- src/routes/setup.ts | 39 ++-- src/routes/views.ts | 5 +- src/utils/config.ts | 213 ++++++++++++++++++--- src/utils/jdownloader.ts | 3 +- src/utils/logger.ts | 19 ++ src/utils/state.ts | 26 ++- src/utils/tmdbEnricher.ts | 129 +++++++++++++ test_flixart.ts | 12 ++ views/login.ejs | 9 +- views/manual.ejs | 2 +- views/partials/header.ejs | 5 +- views/partials/sidebar.ejs | 4 +- views/recent.ejs | 15 ++ views/settings.ejs | 294 +++++++++++++++++++++++++++- views/setup.ejs | 49 ++++- 56 files changed, 3404 insertions(+), 327 deletions(-) create mode 100644 .dockerignore delete mode 100644 .gitlab-ci.yml create mode 100644 database/config.json create mode 100644 database/flixart_cookie.txt create mode 100644 database/fs24_cookie.txt create mode 100644 plugins/flixart/api.ts create mode 100644 plugins/flixart/auth.ts create mode 100644 plugins/flixart/dump.ts create mode 100644 plugins/flixart/index.ts create mode 100644 plugins/flixart/parser.ts create mode 100644 plugins/fs24/api.ts create mode 100644 plugins/fs24/auth.ts create mode 100644 plugins/fs24/index.ts create mode 100644 plugins/fs24/parser.ts create mode 100644 plugins/loadix/index.ts create mode 100644 plugins/movix/api.ts create mode 100644 plugins/movix/index.ts create mode 100644 public/images/logo_svg.svg create mode 100644 public/logo_svg.svg create mode 100644 public/sortable.min.js create mode 100644 src/utils/logger.ts create mode 100644 src/utils/tmdbEnricher.ts create mode 100644 test_flixart.ts diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..4e6f02e --- /dev/null +++ b/.dockerignore @@ -0,0 +1,12 @@ +node_modules +dist +database +sessions +images +downloads +.git +.github +*.db +*.sqlite +.env +.dockerignore diff --git a/.env.exemple b/.env.exemple index ba2c5ae..e3ad67e 100644 --- a/.env.exemple +++ b/.env.exemple @@ -1,5 +1,5 @@ # ============================================ -# Hydr'Hacked — Configuration +# Agora — Configuration # ============================================ # --- Plugin : Zone-Téléchargement (Source par défaut) --- @@ -13,10 +13,26 @@ ZT_URL= #https://... # --- Plugin : Base de Données Locale SQLite (Optionnel) --- # DB_PATH=./database/darkiworld.db -# --- Plugin : Hydracker --- -# HYDRACKER_URL= #https:// -# HYDRACKER_API_KEY= # 15746... -# HYDRACKER_TIMEOUT=30000 # Timeout de healthcheck et d'appels API en millisecondes (30s par défaut) + +# --- Enrichissement TMDB (Optionnel) --- +TMDB_ENABLED=false +TMDB_API_KEY= + +# --- Plugin : FS24 (Optionnel, nécessite un compte) --- +# FS24_URL= +# FS24_USERNAME= +# FS24_PASSWORD= + +# --- Plugin : Movix (Optionnel) --- +# MOVIX_URL= + +# --- Plugin : FlixArt (Optionnel, nécessite un compte) --- +# FLIXART_URL= +# FLIXART_USERNAME= +# FLIXART_PASSWORD= + +# --- Plugin : Loadix (Optionnel) --- +# LOADIX_URL= # --- Configuration Application --- PORT=3067 @@ -26,7 +42,7 @@ SECRET=generer-une-cle-aleatoire-ici # Si définis, le compte admin est créé automatiquement au premier lancement. # Si absents, accédez à /setup pour créer le premier admin manuellement. # ADMIN_USERNAME=admin -# ADMIN_PASSWORD=hydracked +# ADMIN_PASSWORD=agora # --- Paramètres de scan --- MIN_MINUTES=15 @@ -43,3 +59,4 @@ MAX_MINUTES=30 # JD_CREATE_SUBFOLDER=true # JD_AUTOSTART=true +# JD_FORCED_START=false diff --git a/.gitignore b/.gitignore index 75b18cc..2663fff 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,4 @@ database/darkiworld.db database/settings.json database/users.json scripts/ +BACKUP HYDRACKED_AGORA/ diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml deleted file mode 100644 index 980f74f..0000000 --- a/.gitlab-ci.yml +++ /dev/null @@ -1,43 +0,0 @@ -variables: - # Enable Docker BuildKit for multi-arch builds - DOCKER_BUILDKIT: 1 - IMAGE_NAME: $CI_REGISTRY_IMAGE - -stages: - - build - -build-and-push: - stage: build - image: docker:24.0.5 - services: - - docker:24.0.5-dind - before_script: - # Log into the GitLab Container Registry using provided CI/CD variables - - echo "$CI_REGISTRY_PASSWORD" | docker login $CI_REGISTRY -u "$CI_REGISTRY_USER" --password-stdin - - # Set up QEMU for multi-architecture builds (equivalent to setup-qemu-action) - - docker run --privileged --rm tonistiigi/binfmt --install all - - # Create and boot a new builder instance (equivalent to setup-buildx-action) - - docker buildx create --use --name multi-arch-builder - - docker buildx inspect --bootstrap - script: - # Determine the tags based on the trigger event (Release tag vs Manual branch run) - - | - if [ -n "$CI_COMMIT_TAG" ]; then - # If triggered by a tag (release), build with the specific version and 'latest' - TAG_ARGS="-t $IMAGE_NAME:$CI_COMMIT_TAG -t $IMAGE_NAME:latest" - else - # If triggered manually on a branch, use the branch name as the tag - TAG_ARGS="-t $IMAGE_NAME:$CI_COMMIT_REF_SLUG" - fi - - # Build and push the Docker image for both amd64 and arm64 architectures - - docker buildx build --push --platform linux/amd64,linux/arm64 $TAG_ARGS . - rules: - # Trigger automatically when pushing to main branch - - if: $CI_COMMIT_BRANCH == "main" - # Trigger automatically when a new tag is pushed - - if: $CI_COMMIT_TAG - # Allow manual triggering from the GitLab Web UI - - if: $CI_PIPELINE_SOURCE == "web" \ No newline at end of file diff --git a/README.md b/README.md index fa09698..9a9fc63 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ -# 🐍 Hydr'Hacked +# 🐍 Agora > [!IMPORTANT] > Merci de bien lire tout ça avant de déployer le server > Si vous êtes débutant(e) cette vidéo devrait répondre à vos questions [Vidéo tutoriel + DB](https://gofile.io/d/3CA4rk) -![Hydr'Hacked Logo](public/images/icone-192.png) +![Agora Logo](public/images/logo_svg.svg) > "Un immense merci à l'équipe technique d'Hydracker pour sa générosité. On a trouvé votre API tellement 'ouverte d'esprit' qu'on s'est permis de l'aider à partager ses liens sans les contraintes futiles d'un navigateur ou d'un abonnement. C'est presque trop facile, mais comme on dit : c'est l'intention qui compte." 💅 @@ -12,16 +12,36 @@ ## 🚀 Présentation -**Hydr'Hacked** est une solution complète (Serveur API + Interface Web) pour crawler, rechercher et télécharger du contenu depuis plusieurs sources : -- 🆓 **ZT** : Source principale, 100% gratuite et sans token (films et séries). -- 📰 **ZTNews** : Source secondaire gratuite (ZT News) pour des exclusivités et nouveaux ajouts. +**Agora** est une solution complète (Serveur API + Interface Web) pour crawler, rechercher et télécharger du contenu depuis plusieurs sources : +- 🆓 **Zone-Telechargement (ZT)** : Source principale, 100% gratuite et sans token (films et séries). Les affiches et titres sont automatiquement enrichis par TMDB. +- 📰 **ZTNews** : Source secondaire gratuite (Zone-Téléchargement News) pour des exclusivités et nouveaux ajouts. - ⚡ **FreeTélécharger (FreeTel)** : Source alternative gratuite avec de multiples miroirs. +- 🍿 **FS24** : Source spécialisée pour des films, séries et animés via streaming/téléchargement direct communautaire (nécessite un compte). +- 🎬 **FlixArt** : Source communautaire avec liens DDL, qualités et langues détaillées (nécessite un compte). +- 📦 **Loadix** : Source communautaire avec une API JSON propre — tendances, récents, recherche et qualités (pas de compte requis). +- 🎥 **Movix** : Source alternative gratuite de films et séries. - 🗄️ **LocalDB** : Base de données locale intégrée pour des recherches hors-ligne instantanées (Films, Séries, Jeux, Logiciels, Musique, etc.). - 🛡️ **Hydracker** : Source premium secondaire (nécessite un token et une configuration). > [!IMPORTANT] -> **Nouveauté :** La recherche, les tendances, les films ET les séries sont désormais **100% gratuits et sans aucun token** par défaut grâce aux plugins ZT, ZTNews et FreeTel. +> **Nouveauté 1.5.2 :** Ajout du plugin FS24 avec support des tendances et ajouts récents, correction de l'enrichissement TMDB pour ZT, et sécurisation des paramètres utilisateurs (qui sont désormais stockés dans `database/config.json` et n'écrasent plus votre fichier `.env`). +> **Nouveauté 1.5.4 :** Petite correction d'urgence concernant un encodage d'URL qui faisait planter les appels à l'API Hydracker (Erreur 401 Unauthorized sur les channels et titles). +> **Nouveauté 1.5.5 :** +> - **Hydracker** : Correction de l'erreur 403 sur l'accès aux liens en utilisant l'endpoint `/download` pour les films et les séries. Les saisons sont désormais récupérées directement via la fiche du titre, et les liens de séries s'obtiennent en itérant sur les épisodes. +> - **FreeTélécharger** : Mise à jour de l'expression régulière du domaine pour supporter le nouveau TLD `.biz` (et tout autre changement de TLD futur pour `liens.free-telecharger.*`). +> +> **Nouveauté 1.5.6 :** +> - **Loadix** : Nouveau plugin communautaire avec recherche, tendances, ajouts récents et affichage détaillé des qualités/langues/tailles. Les liens sont protégés par Cloudflare Turnstile — l'utilisateur est redirigé vers le site pour résoudre le captcha manuellement. +> - **FlixArt** : Nettoyage complet du plugin — suppression de toute la logique Turnstile embarquée (impossible à résoudre en local). L'utilisateur est désormais redirigé vers le site source. +> - **Architecture** : Toutes les URLs sont désormais 100% dynamiques via `database/config.json` — plus aucun lien en dur dans le code source. +> > La db locale (LocalDB) est au même endroit que la vidéo tuto ;) au dessus. +> +> **Nouveauté 1.5.9 :** +> - **Movix & TMDB** : Implémentation directe de l'API TMDB pour des tendances et récents ultra qualitatifs. Recherche automatique en arrière-plan lors du clic. +> - **Filtres et Interface** : Ajout d'une icône TMDB sur chaque affiche pour faire des recherches rapidement, et filtres Films/Séries sur la page des ajouts récents. +> - **JDownloader** : Option de 'Démarrage forcé' indépendante de l'ajout automatique. +> - **Nettoyage** : Disparition d'Hydracker et nettoyage silencieux d'Uptobox. ## ✨ Fonctionnalités @@ -65,7 +85,7 @@ C'est la méthode la plus simple pour garder un environnement propre. Nous utili ```bash # 1. Cloner le projet (si ce n'est pas déjà fait) -git clone https://gitlab.com/nonobzh22-group/Hydr-Hacked +git clone https://github.com/NoNoBzH22/Agora # 2. Préparer la configuration cp .env.example .env @@ -76,7 +96,7 @@ docker compose up -d 📍 Accès : `http://localhost:3067` > [!TIP] -> L'application utilise l'image `registry.gitlab.com/nonobzh22-group/hydr-hacked:latest`. Elle est reconstruite automatiquement à chaque mise à jour, vous n'avez plus besoin de compiler localement. +> L'application utilise l'image `ghcr.io/nonobzh22/Agora:latest`. Elle est reconstruite automatiquement à chaque mise à jour, vous n'avez plus besoin de compiler localement. --- @@ -112,13 +132,20 @@ Créez un fichier `.env` à la racine du projet et configurez les variables suiv | Variable | Type | Description | |---|---|---| -| `ZT_URL` | **Requis** | URL complète du site ZT. | +| `ZT_URL` | **Requis** | URL complète du site Zone-Telechargement. | | `ZTNEWS_URL` | Optionnel | URL complète de la source ZTNews. | | `FT_URL` | Optionnel | URL complète de la source FreeTélécharger. | | `HYDRACKER_URL` | Optionnel | URL complète de votre instance Hydracker (nécessaire si plugin actif). | -| `API_PASSWORD` | **Requis** | Mot de passe pour l'écran de connexion initial. | -| `SECRET` | **Requis** | Clé secrète pour les sessions. | | `HYDRACKER_API_KEY` | Optionnel | Votre token Hydracker. | +| `FS24_URL` | Optionnel | URL complète de FS24. | +| `FS24_USERNAME` | Optionnel | Identifiant FS24. | +| `FS24_PASSWORD` | Optionnel | Mot de passe FS24. | +| `MOVIX_URL` | Optionnel | URL complète de Movix. | +| `FLIXART_URL` | Optionnel | URL complète de FlixArt. | +| `FLIXART_USERNAME` | Optionnel | Identifiant FlixArt. | +| `FLIXART_PASSWORD` | Optionnel | Mot de passe FlixArt. | +| `LOADIX_URL` | Optionnel | URL complète de Loadix. | +| `SECRET` | **Requis** | Clé secrète pour les sessions. | | `PORT` | Optionnel | Port de l'application (Défaut : `3067`). | | `DB_PATH` | Optionnel | Chemin vers la base locale (Défaut : `./database/darkiworld.db`). | | `JD_HOST` | Optionnel | IP/Hôte de JDownloader. | @@ -135,7 +162,7 @@ Créez un fichier `.env` à la racine du projet et configurez les variables suiv ## 🧩 Créer un nouveau Plugin -L'architecture d'Hydr'Hacked est modulaire. Vous pouvez facilement ajouter une nouvelle source en créant un plugin qui implémente l'interface `ISource`. +L'architecture d'Agora est modulaire. Vous pouvez facilement ajouter une nouvelle source en créant un plugin qui implémente l'interface `ISource`. ### 1. Structure Créez un dossier dans `plugins/[NomDeVotreSource]/`. Vous aurez généralement besoin de : @@ -165,11 +192,8 @@ sourceRegistry.register(new VotrePluginAPI(CONFIG.VOTRE_URL)); Le serveur découvrira et chargera automatiquement votre plugin au démarrage. -## Note Liminaire -Cet outil est une preuve de concept destinée à la recherche et à l'apprentissage. Son auteur ne cautionne aucun usage abusif ni aucune violation de droits tiers. Il appartient à chaque utilisateur de s'assurer que ses activités restent conformes à la législation ; la responsabilité de l'usage incombe exclusivement à l'utilisateur final. - ## 🤝 Un Projet Communautaire -**Hydr'Hacked** est un projet fait par la communauté, pour la communauté. Parce que le savoir (et les liens de téléchargement) ne devrait jamais être prisonnier derrière des murs de paye ou des scripts de sécurité mal conçus. +**Agora** est un projet fait par la communauté, pour la communauté. Parce que le savoir (et les liens de téléchargement) ne devrait jamais être prisonnier derrière des murs de paye ou des scripts de sécurité mal conçus. Chaque Pull Request est la bienvenue, tant qu'elle contribue à rendre l'accès encore plus fluide et... disons, "généreux". ## Note Liminaire diff --git a/database/config.json b/database/config.json new file mode 100644 index 0000000..28c3662 --- /dev/null +++ b/database/config.json @@ -0,0 +1,29 @@ +{ + "PREFERRED_HOSTERS": [ + "1fichier", + "nitroflare", + "ddownload", + "rapidgator", + "gofile", + "mega", + "pixeldrain", + "turbobit" + ], + "HYDRACKER_URL": "https://hydracker.com", + "HYDRACKER_API_KEY": "107571|UcmgBErjph7kwI3B9aF5oAG9ga9WgUMV0IpYTXvuc1e04687", + "ZT_URL": "https://zone-telechargement.org", + "ZTTEAM_URL": "https://www.zone-telechargement.land", + "FT_URL": "https://www.free-telecharger.skin", + "TMDB_ENABLED": "true", + "TMDB_API_KEY": "67900f5a59c80873a70d9a3523152584", + "FS24_URL": "https://fs24.lol", + "FS24_USERNAME": "NoNoBzH", + "FS24_PASSWORD": "WHpE57PjpEk9WgT", + "MAX_RESULTS_PER_SOURCE": "20", + "MOVIX_URL": "https://movix.show", + "FLIXART_URL": "https://flixart.net", + "FLIXART_USERNAME": "pipiano663", + "FLIXART_PASSWORD": "j3WXnu3eHT8JdLy", + "LOADIX_URL": "https://loadix.fun", + "JD_FORCED_START": "false" +} \ No newline at end of file diff --git a/database/flixart_cookie.txt b/database/flixart_cookie.txt new file mode 100644 index 0000000..6548449 --- /dev/null +++ b/database/flixart_cookie.txt @@ -0,0 +1 @@ +flixart_device_id=6q_WcxRA-2VfIATy0NvR3QFATnfQCpkod13Vci6-veM; _lscache_vary=c993f0a67d154231b65a323e8e99d4e8; wordpress_sec_7991dcc7dbc2d1c8d081bc45babbe5dd=pipiano663%7C1789577571%7CwDGBay3HyJdEODgexMhcCJHv7lsiKr7QNKetDNTuc6p%7C5eb4fc042ef8cb12d6e7413ce6acb13a88f675bd0cefe5d98d6fc099cc8327bc; wordpress_sec_7991dcc7dbc2d1c8d081bc45babbe5dd=pipiano663%7C1789577571%7CwDGBay3HyJdEODgexMhcCJHv7lsiKr7QNKetDNTuc6p%7C5eb4fc042ef8cb12d6e7413ce6acb13a88f675bd0cefe5d98d6fc099cc8327bc; wordpress_logged_in_7991dcc7dbc2d1c8d081bc45babbe5dd=pipiano663%7C1789577571%7CwDGBay3HyJdEODgexMhcCJHv7lsiKr7QNKetDNTuc6p%7Cccca6252080e8f8fccc171cdef684b6edcf0e834e9c63849b0885e8ac090fc27 \ No newline at end of file diff --git a/database/fs24_cookie.txt b/database/fs24_cookie.txt new file mode 100644 index 0000000..a4baedf --- /dev/null +++ b/database/fs24_cookie.txt @@ -0,0 +1 @@ +PHPSESSID=d07cfe828766fcaf0b84d923ad7e14e7; dle_user_id=1954710; 05-Aug-2027 11:23:46 GMT; dle_password=a1fd7d561bf7816da6208f387527e3c8; 05-Aug-2027 11:23:46 GMT; fss_dvt=2976548; 05-Aug-2026 11:33:46 GMT; dle_newpm=0; 05-Aug-2027 11:23:46 GMT \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index b7cfad3..0f7fd1c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,8 +1,7 @@ services: - hydrhacked: - image: registry.gitlab.com/nonobzh22-group/hydr-hacked:main - build: . - container_name: hydrhacked_app + agora: + image: nonobzh22/agora:latest + container_name: agora_app restart: unless-stopped ports: - "${PORT:-3067}:${PORT:-3067}" @@ -18,4 +17,4 @@ services: deploy: resources: limits: - memory: 1024M \ No newline at end of file + memory: 1024M diff --git a/package-lock.json b/package-lock.json index 56a9e22..91abd29 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { - "name": "hydrhacked", - "version": "1.4.0", + "name": "Agora", + "version": "1.5.3", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "hydrhacked", - "version": "1.4.0", + "name": "Agora", + "version": "1.5.1", "dependencies": { "cookie-parser": "^1.4.6", "dotenv": "^16.4.5", diff --git a/package.json b/package.json index 5e220c5..f9a726a 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,8 @@ { - "name": "hydrhacked", - "version": "1.4.0", + "name": "Agora", + "version": "1.5.9", "type": "module", - "description": "Hydr'Hacked - API Proxy and Frontend", + "description": "Agora - API Proxy and Frontend", "main": "server.js", "scripts": { "start": "node --experimental-sqlite dist/src/index.js", diff --git a/plugins/ZT/index.ts b/plugins/ZT/index.ts index f399fbc..14d2571 100644 --- a/plugins/ZT/index.ts +++ b/plugins/ZT/index.ts @@ -30,13 +30,11 @@ function deduplicateByTitle(results: SearchResult[]): SearchResult[] { }); } -export class ZTAPI implements ISource { +export class ZoneTelechargementAPI implements ISource { name = 'zt'; - displayName = 'ZT'; - private baseUrl: string | undefined; - - constructor(baseUrl?: string) { - this.baseUrl = baseUrl; + displayName = 'Zone-Téléchargement'; + get baseUrl() { + return CONFIG.ZT_URL?.replace(/\/$/, ''); } async healthCheck(): Promise { @@ -161,4 +159,4 @@ export class ZTAPI implements ISource { } // ── Auto-registration ── -sourceRegistry.register(new ZTAPI(CONFIG.ZT_URL)); +sourceRegistry.register(new ZoneTelechargementAPI()); diff --git a/plugins/ZT/parser.ts b/plugins/ZT/parser.ts index aeaea2f..03d3e53 100644 --- a/plugins/ZT/parser.ts +++ b/plugins/ZT/parser.ts @@ -32,7 +32,13 @@ export function parseSearchHTML(html: string, baseUrl: string | undefined): Sear type = 'anime'; } - results.push({ title, image, hrefPath: href, year: null, type, source: 'zt' }); + let year: string | null = null; + const yearMatch = title.match(/\(\s*(\d{4})\s*\)/) || href.match(/-(\d{4})-/); + if (yearMatch) { + year = yearMatch[1]; + } + + results.push({ title, image, hrefPath: href, year, type, source: 'zt' }); } return results; @@ -80,7 +86,7 @@ export function parseContentHTML(html: string): ContentLinks { const cleanedLabel = label.replace(sizeRegex, "").trim(); // On n'utilise le label comme "épisode" que si c'est un vrai nom de fichier/épisode (pas juste "Télécharger") - const isGenericLabel = /^(t\u00e9l\u00e9charger|download|cliquez ici|lien|turbobit|1fichier|uptobox|rapidgator|nitroflare|send.now)/i.test(cleanedLabel); + const isGenericLabel = /^(t\u00e9l\u00e9charger|download|cliquez ici|lien|turbobit|1fichier|rapidgator|nitroflare|send.now)/i.test(cleanedLabel); let episode = (!isGenericLabel && cleanedLabel.length > 3) ? cleanedLabel : undefined; // SI le label est générique, on cherche un texte juste avant (ex: "Episode 1") diff --git a/plugins/flixart/api.ts b/plugins/flixart/api.ts new file mode 100644 index 0000000..98413c8 --- /dev/null +++ b/plugins/flixart/api.ts @@ -0,0 +1,112 @@ +import { SearchResult, VideoLink, SeasonOption, SelectionData, ContentLinks } from '../../src/types/source.js'; +import { FlixArtAuth } from './auth.js'; +import { FlixArtParser } from './parser.js'; +import { CONFIG } from '../../src/utils/config.js'; + +export class FlixArtAPI { + private static get baseUrl() { return CONFIG.FLIXART_URL || ''; } + private static get ajaxUrl() { return `${this.baseUrl}/wp-admin/admin-ajax.php`; } + private static userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'; + + // Cache the film page data temporarily for resolveLink + private static contextCache: { [url: string]: { postId: string, nonce: string, type: string } } = {}; + + private static async fetchWithAuth(url: string, options: RequestInit = {}, retries = 1): Promise { + try { + const cookie = await FlixArtAuth.getCookie(); + + const headers = new Headers(options.headers || {}); + headers.set('User-Agent', this.userAgent); + headers.set('Cookie', cookie); + headers.set('Origin', this.baseUrl); + headers.set('Referer', this.baseUrl); + + const response = await fetch(url, { ...options, headers }); + + // If FlixArt returns 403 or redirects to login, refresh cookie and retry + if (response.status === 403 && retries > 0) { + console.log('[FlixArt] Session expirée, renouvellement du cookie...'); + await FlixArtAuth.getCookie(true); + return this.fetchWithAuth(url, options, retries - 1); + } + + return response; + } catch (error) { + if (retries > 0) { + await FlixArtAuth.getCookie(true); + return this.fetchWithAuth(url, options, retries - 1); + } + throw error; + } + } + + public static async search(query: string, mediaType?: string): Promise { + const body = new URLSearchParams({ + action: 'flixart_header_search', + s: query, + search: query, + type_query: 'all', + post_type: mediaType === 'series' ? 'tv_shows' : 'movies' + }); + + // Search works without auth, but we use fetchWithAuth just in case + const res = await this.fetchWithAuth(this.ajaxUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-Requested-With': 'XMLHttpRequest' + }, + body: body.toString() + }); + + const data = await res.json(); + if (data.success && data.data && data.data.results) { + return FlixArtParser.parseSearchAjax(data.data.results); + } + return []; + } + + public static async getTrending(mediaType: 'movie' | 'series'): Promise { + const res = await this.fetchWithAuth(this.baseUrl, { method: 'GET' }); + const html = await res.text(); + return FlixArtParser.parseTrending(html, mediaType === 'series'); + } + + public static async getSelection(url: string): Promise { + const res = await this.fetchWithAuth(url, { method: 'GET' }); + const html = await res.text(); + + const parsed = FlixArtParser.parseSelection(html); + + // Cache post data for resolveLink + if (parsed.postId && parsed.nonce) { + this.contextCache[url] = { + postId: parsed.postId, + nonce: parsed.nonce, + type: parsed.isSeries ? 'tv_shows' : 'movies' // Note: actually parser returns isSeries. Captcha needs 'movies' or 'tv_shows' + }; + } + + // Prefix ID with url to pass state to resolveLink + parsed.links.forEach((link: any) => { + link.id = `${url}|${link.id}`; + }); + + return { + links: parsed.links, + seasons: parsed.seasons, + isSeries: parsed.isSeries + }; + } + + public static async getContentLinks(url: string, season?: number): Promise { + // Not used heavily if getSelection is prioritized, but we need to fetch the season HTML via ajax + // For simplicity, if season is passed, we fetch season content via AJAX. + // Actually, FlixArt loads all episodes HTML when you click a season tab. + // For now, getSelection is sufficient. + const selection = await this.getSelection(url); + return { links: selection.links }; + } + + +} diff --git a/plugins/flixart/auth.ts b/plugins/flixart/auth.ts new file mode 100644 index 0000000..05bb238 --- /dev/null +++ b/plugins/flixart/auth.ts @@ -0,0 +1,148 @@ +import { CONFIG } from '../../src/utils/config.js'; +import fs from 'fs'; +import path from 'path'; + +export class FlixArtAuth { + private static sessionCookie: string | null = null; + private static lastLoginTime: number = 0; + private static readonly COOKIE_FILE = path.resolve(process.cwd(), 'database', 'flixart_cookie.txt'); + + public static async getCookie(forceRefresh = false): Promise { + if (!this.sessionCookie && fs.existsSync(this.COOKIE_FILE)) { + try { + const stats = fs.statSync(this.COOKIE_FILE); + // Si le cookie a moins de 7 jours, on le réutilise (le renouvellement se fera si on obtient une 403) + if (Date.now() - stats.mtimeMs < 7 * 24 * 60 * 60 * 1000) { + this.sessionCookie = fs.readFileSync(this.COOKIE_FILE, 'utf-8'); + this.lastLoginTime = stats.mtimeMs; + } + } catch (e) { + console.warn('[FlixArt Auth] Impossible de lire le cookie sauvegardé:', e); + } + } + + if (!forceRefresh && this.sessionCookie && Date.now() - this.lastLoginTime < 12 * 60 * 60 * 1000) { + return this.sessionCookie; + } + + const username = CONFIG.FLIXART_USERNAME; + const password = CONFIG.FLIXART_PASSWORD; + const baseUrl = CONFIG.FLIXART_URL || ''; + const ajaxUrl = `${baseUrl}/wp-admin/admin-ajax.php`; + + if (!username || !password) { + throw new Error('[FlixArt Auth] Identifiants manquants.'); + } + + console.log(`[FlixArt] Tentative de connexion avec l'utilisateur: ${username}...`); + + try { + // 1. Obtenir un nouveau nonce de login + const refreshParams = new URLSearchParams({ + action: 'flixart_auth_refresh_nonces' + }); + const refreshRes = await fetch(ajaxUrl, { + method: 'POST', + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-Requested-With': 'XMLHttpRequest', + 'Referer': baseUrl + }, + body: refreshParams.toString() + }); + + const refreshData = await refreshRes.json(); + if (!refreshData.success || !refreshData.data || !refreshData.data.loginNonce) { + throw new Error("Impossible d'obtenir le nonce de connexion."); + } + const loginNonce = refreshData.data.loginNonce; + const refreshCookies = (refreshRes.headers.getSetCookie ? refreshRes.headers.getSetCookie() : [refreshRes.headers.get('set-cookie') || '']).map(c => c.split(';')[0]).filter(Boolean); + const refreshCookieStr = refreshCookies.join('; '); + + // 2. Se connecter + const dataParams = new URLSearchParams(); + dataParams.append('log', username); + dataParams.append('pwd', password); + dataParams.append('redirect', baseUrl + '/membership-account/'); + + const loginParams = new URLSearchParams(); + loginParams.append('action', 'flixart_auth_login'); + loginParams.append('nonce', loginNonce); + loginParams.append('data', dataParams.toString()); + + const loginRes = await fetch(ajaxUrl, { + method: 'POST', + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36', + 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', + 'Accept': 'application/json, text/javascript, */*; q=0.01', + 'X-Requested-With': 'XMLHttpRequest', + 'Origin': baseUrl, + 'Referer': baseUrl + '/', + 'Cookie': refreshCookieStr + }, + body: loginParams.toString(), + redirect: 'manual' + }); + + const loginBody = await loginRes.clone().json().catch(() => ({})); + + if (loginBody.success === false) { + const code = loginBody.data?.code || loginBody.data?.[0]?.code; + if (code === 'too_many_devices') { + console.log(`[FlixArt] ⚠️ Limite d'appareils atteinte. Tentative de libération...`); + const recoveryParams = new URLSearchParams({ + action: 'flixart_device_recovery', + nonce: refreshData.data.deviceRecoveryNonce, + username: username, + password: password + }); + await fetch(ajaxUrl, { + method: 'POST', + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', + 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', + 'X-Requested-With': 'XMLHttpRequest', + 'Referer': baseUrl, + 'Cookie': refreshCookieStr + }, + body: recoveryParams.toString() + }); + console.log(`[FlixArt] ✅ Appareils libérés, nouvelle tentative de connexion...`); + return this.getCookie(true); + } + throw new Error(loginBody.data?.[0]?.message || loginBody.data?.message || 'Échec de la connexion.'); + } + + // FlixArt returns 200 OK with success: true and sets cookies + const setCookieHeader = loginRes.headers.get('set-cookie') || loginRes.headers.get('Set-Cookie'); + + let cookies: string[] = []; + if (setCookieHeader) { + const setCookieHeaders = loginRes.headers.getSetCookie ? loginRes.headers.getSetCookie() : [setCookieHeader]; + cookies = setCookieHeaders.map(c => c.split(';')[0]); + } + + if (!cookies.some(c => c.includes('wordpress_logged_in_'))) { + console.warn(`[FlixArt] ⚠️ Pas de cookie wordpress_logged_in trouvé.`); + throw new Error('Échec de la connexion (Pas de cookie de session complet).'); + } + + this.sessionCookie = cookies.join('; '); + this.lastLoginTime = Date.now(); + + try { + fs.writeFileSync(this.COOKIE_FILE, this.sessionCookie, 'utf-8'); + } catch (e) { + console.warn('[FlixArt Auth] Impossible de sauvegarder le cookie:', e); + } + + console.log(`[FlixArt] ✅ Connexion réussie ! (Cookie généré)`); + return this.sessionCookie; + } catch (error: any) { + console.error('[FlixArt] ❌ Erreur lors de la connexion:', error.message); + throw error; + } + } +} diff --git a/plugins/flixart/dump.ts b/plugins/flixart/dump.ts new file mode 100644 index 0000000..37f96ad --- /dev/null +++ b/plugins/flixart/dump.ts @@ -0,0 +1,15 @@ +import { FlixArtAuth } from './auth.js'; +import fs from 'fs'; +import { CONFIG } from '../../src/utils/config.js'; + +async function dump() { + const cookie = await FlixArtAuth.getCookie(); + const baseUrl = CONFIG.FLIXART_URL || ''; + const res = await fetch(`${baseUrl}/film/avatar/`, { + headers: { 'Cookie': cookie, 'User-Agent': 'Mozilla/5.0' } + }); + const html = await res.text(); + fs.writeFileSync('scratch/avatar.html', html); + console.log('Saved to scratch/avatar.html, length:', html.length); +} +dump(); diff --git a/plugins/flixart/index.ts b/plugins/flixart/index.ts new file mode 100644 index 0000000..c475ce9 --- /dev/null +++ b/plugins/flixart/index.ts @@ -0,0 +1,56 @@ +import { ISource, SearchResult, SelectionData, ContentLinks, MediaType } from '../../src/types/source.js'; +import { FlixArtAPI } from './api.js'; + +export class FlixartSource implements ISource { + name = 'flixart'; + displayName = 'FlixArt'; + + async search(query: string, mediaType?: MediaType): Promise { + return FlixArtAPI.search(query, mediaType); + } + + async getTrending(mediaType: MediaType): Promise { + const type = mediaType === 'series' ? 'series' : 'movie'; + return FlixArtAPI.getTrending(type); + } + + async getRecent(): Promise { + return this.getTrending('movie'); + } + + async getSelection(identifier: string, type?: string, seasonValue?: string | number): Promise { + return FlixArtAPI.getSelection(identifier); + } + + async getContentLinks(identifier: string, season?: number): Promise { + return FlixArtAPI.getContentLinks(identifier, season); + } + + async healthCheck(): Promise { + try { + const results = await this.getTrending('movie'); + return results.length > 0; + } catch (e: any) { + console.error(`[FlixArt] Healthcheck failed: ${e.message}`); + return false; + } + } + + // Custom resolveLink that returns a Turnstile challenge instead of just the URL + // Actually, Agora's activeSource.resolveLink only accepts string. + // We will change ISource resolveLink to allow returning an object. + async resolveLink(linkId: string, extraData?: any): Promise { + const [url] = linkId.split('|'); + // FlixArt requires a Cloudflare Turnstile challenge which cannot be resolved on localhost. + // We directly return the manual redirection challenge. + return { + captcha: 'turnstile', + url: url, + sourceName: 'FlixArt' + }; + } +} + +// Auto-registration +import { sourceRegistry } from '../../src/core/registry.js'; +sourceRegistry.register(new FlixartSource()); diff --git a/plugins/flixart/parser.ts b/plugins/flixart/parser.ts new file mode 100644 index 0000000..2f8d04b --- /dev/null +++ b/plugins/flixart/parser.ts @@ -0,0 +1,167 @@ +import { SearchResult, VideoLink, SeasonOption } from '../../src/types/source.js'; + +function getMediaTypeFromUrl(url: string): 'movie' | 'series' { + return url.includes('/serie/') ? 'series' : 'movie'; +} + +function unescapeHtml(html: string): string { + return html + .replace(/&/g, '&') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/&/g, '&'); +} + +export class FlixArtParser { + static parseSearchAjax(htmlStr: string): SearchResult[] { + const results: SearchResult[] = []; + const cardRegex = /]*>([\s\S]*?)<\/a>/g; + let match; + + while ((match = cardRegex.exec(htmlStr)) !== null) { + const href = unescapeHtml(match[1]); + const inner = match[2]; + + let title = ''; + const titleMatch = inner.match(/([^<]+)<\/span>/); + if (titleMatch) title = unescapeHtml(titleMatch[1].trim()); + + let year = null; + const yearMatch = inner.match(/([^<]+)<\/span>/); + if (yearMatch) year = yearMatch[1].trim(); + + let image = null; + const imgMatch = inner.match(/]+src="([^"]+)"/); + if (imgMatch) { + image = unescapeHtml(imgMatch[1]); + if (image.includes('&quality=')) image = image.split('&quality=')[0]; + } + + if (title && href) { + results.push({ + title, + year, + image, + hrefPath: href, + type: getMediaTypeFromUrl(href), + source: 'flixart' + }); + } + } + + return results; + } + + static parseTrending(htmlStr: string, isSeries: boolean): SearchResult[] { + const results: SearchResult[] = []; + const sectionTitle = isSeries ? 'Top 10 séries du jour' : 'Top 10 films du jour'; + const fallbackTitle = isSeries ? 'Nouveautés séries' : 'Nouveautés films'; + + // Find section containing the title + let sectionRegexStr = `
\\s*
\\s*

(${sectionTitle}|${fallbackTitle})<\\/h2>[\\s\\S]*?<\\/section>`; + let sectionMatch = htmlStr.match(new RegExp(sectionRegexStr, 'i')); + + if (!sectionMatch) return results; + const sectionHtml = sectionMatch[0]; + + const cardRegex = /
([\s\S]*?)<\/article>/g; + let match; + while ((match = cardRegex.exec(sectionHtml)) !== null) { + const inner = match[1]; + + let href = null; + let title = ''; + const titleMatch = inner.match(/

]*>([^<]+)<\/a><\/h3>/); + if (titleMatch) { + href = unescapeHtml(titleMatch[1]); + title = unescapeHtml(titleMatch[2].trim()); + } + + let image = null; + const imgMatch = inner.match(/]+class="[^"]*flixart-season-tab[^"]*"[^>]+data-season="([^"]+)"[^>]*>([\s\S]*?)<\/button>/g; + let match; + while ((match = seasonTabRegex.exec(htmlStr)) !== null) { + isSeries = true; + const val = match[1]; + const inner = match[2]; + const numMatch = inner.match(/([^<]+)<\/span>/); + if (numMatch) { + seasons.push({ label: `Saison ${numMatch[1].trim()}`, value: val }); + } + } + + const rowRegex = /
]*data-qualite="([^"]*)"[^>]*data-langue="([^"]*)"[^>]*>([\s\S]*?)<\/div>/g; + while ((match = rowRegex.exec(htmlStr)) !== null) { + const inner = match[3]; + let episode = null; + const episodeMatch = htmlStr.substring(match.index - 100, match.index).match(/data-episode="([^"]+)"/); + if (episodeMatch) episode = episodeMatch[1]; + + const checkboxMatch = inner.match(/]+data-flixart-download-select[^>]+data-row-index="(\d+)"[^>]*data-download-title="([^"]*)"[^>]*data-download-meta="([^"]*)"/); + if (checkboxMatch) { + const rowIndex = checkboxMatch[1]; + const title = unescapeHtml(checkboxMatch[2]); + const meta = unescapeHtml(checkboxMatch[3]); + + let host = 'Inconnu'; + const lowerMeta = meta.toLowerCase(); + if (lowerMeta.includes('1fichier')) host = '1fichier'; + else if (lowerMeta.includes('nitroflare')) host = 'nitroflare'; + else if (lowerMeta.includes('ddownload')) host = 'ddownload'; + + links.push({ + id: rowIndex, + host, + label: title, + quality: meta, + url: null, + episode + }); + } + } + + return { links, seasons, isSeries, postId, nonce }; + } +} diff --git a/plugins/freetelecharger/index.ts b/plugins/freetelecharger/index.ts index 4dbd2f1..2e58860 100644 --- a/plugins/freetelecharger/index.ts +++ b/plugins/freetelecharger/index.ts @@ -11,10 +11,8 @@ function isSeriesIdentifier(identifier: string): boolean { export class FreeTeleAPI implements ISource { name = 'freetel'; displayName = 'Free-Télécharger'; - private baseUrl: string | undefined; - - constructor(baseUrl?: string) { - this.baseUrl = baseUrl?.replace(/\/$/, ''); + get baseUrl() { + return CONFIG.FT_URL?.replace(/\/$/, ''); } async healthCheck(): Promise { @@ -114,7 +112,7 @@ export class FreeTeleAPI implements ISource { let hostUrl: string | null = null; // Cas série : page intermédiaire liens.free-telecharger.cam/SLUG-episode_N - if (linkId.includes('liens.free-telecharger.cam')) { + if (linkId.includes('liens.free-telecharger.')) { try { const html = await fetchPage(linkId); const hosts = parseEpisodeLinks(html); @@ -139,4 +137,4 @@ export class FreeTeleAPI implements ISource { } } -sourceRegistry.register(new FreeTeleAPI(CONFIG.FT_URL)); +sourceRegistry.register(new FreeTeleAPI()); diff --git a/plugins/freetelecharger/parser.ts b/plugins/freetelecharger/parser.ts index be17ea4..2bfa35e 100644 --- a/plugins/freetelecharger/parser.ts +++ b/plugins/freetelecharger/parser.ts @@ -64,9 +64,17 @@ function detectType(href: string): 'movie' | 'series' | 'anime' { } function absUrl(url: string, baseUrl: string): string { - if (url.startsWith('http')) return url; + let path = url; + if (url.startsWith('http')) { + try { + const u = new URL(url); + path = u.pathname + u.search + u.hash; + } catch { + return url; + } + } const cleanedBase = baseUrl.replace(/\/$/, ''); - return cleanedBase + '/' + url.replace(/^\//, ''); + return cleanedBase + '/' + path.replace(/^\//, ''); } /** @@ -83,9 +91,15 @@ export function parseSearchResults(html: string, baseUrl: string): SearchResult[ const href = absUrl(hrefRaw, baseUrl); const title = m[3]!.replace(/<[^>]+>/g, '').replace(/\s+/g, ' ').trim(); if (!title) continue; + let year: string | null = null; + const yearMatch = title.match(/\(\s*(\d{4})\s*\)/) || hrefRaw.match(/-(\d{4})-/); + if (yearMatch) { + year = yearMatch[1]; + } + results.push({ title, - year: null, + year, image, hrefPath: href, type: detectType(hrefRaw), @@ -106,9 +120,15 @@ export function parseTrendingResults(html: string, baseUrl: string): SearchResul const hrefRaw = m[1]!; const title = m[2]!.trim(); const image = absUrl(m[3]!, baseUrl); + let year: string | null = null; + const yearMatch = title.match(/\(\s*(\d{4})\s*\)/) || hrefRaw.match(/-(\d{4})-/); + if (yearMatch) { + year = yearMatch[1]; + } + results.push({ title, - year: null, + year, image, hrefPath: absUrl(hrefRaw, baseUrl), type: detectType(hrefRaw), @@ -127,7 +147,7 @@ export function parseContentHTML(html: string, isSeries: boolean): ContentLinks const links: VideoLink[] = []; if (isSeries) { - const episodeRegex = /]+name="lien"\s+value="(https?:\/\/liens\.free-telecharger\.cam\/[^"]+)"/gi; + const episodeRegex = /]+name="lien"\s+value="(https?:\/\/liens\.free-telecharger\.[a-z]+\/[^"]+)"/gi; let m: RegExpExecArray | null; let idx = 0; while ((m = episodeRegex.exec(html)) !== null) { diff --git a/plugins/fs24/api.ts b/plugins/fs24/api.ts new file mode 100644 index 0000000..ca631de --- /dev/null +++ b/plugins/fs24/api.ts @@ -0,0 +1,129 @@ +import { FS24Auth } from './auth.js'; +import { CONFIG } from '../../src/utils/config.js'; + +export class FS24API { + private static get baseUrl(): string { + return CONFIG.FS24_URL; + } + + /** + * Recherche AJAX via /engine/ajax/search.php + */ + public static async fetchSearch(query: string, page: number = 1): Promise { + const cookie = await FS24Auth.getCookie(); + const searchUrl = `${this.baseUrl}/engine/ajax/search.php`; + + const params = new URLSearchParams(); + params.append('query', query); + params.append('page', page.toString()); + + console.log(`[FS24] Recherche: "${query}" (page ${page})`); + + const response = await fetch(searchUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', + 'Cookie': cookie, + 'X-Requested-With': 'XMLHttpRequest' + }, + body: params.toString() + }); + + if (!response.ok) { + throw new Error(`HTTP Error ${response.status}`); + } + + return await response.text(); + } + + /** + * Récupère la page HTML d'un contenu pour extraire le news_id + */ + public static async fetchPage(pathOrUrl: string): Promise { + const cookie = await FS24Auth.getCookie(); + const url = pathOrUrl.startsWith('http') ? pathOrUrl : `${this.baseUrl}${pathOrUrl.startsWith('/') ? '' : '/'}${pathOrUrl}`; + + const response = await fetch(url, { + method: 'GET', + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', + 'Cookie': cookie + } + }); + + if (!response.ok) { + throw new Error(`HTTP Error ${response.status}`); + } + + return await response.text(); + } + + /** + * Récupère la page des tendances (films ou séries) + */ + public static async fetchTrending(mediaType: 'movie' | 'series'): Promise { + const cookie = await FS24Auth.getCookie(); + const url = mediaType === 'series' ? `${this.baseUrl}/s-tv/` : `${this.baseUrl}/films/`; + + console.log(`[FS24] Chargement des tendances ${mediaType}`); + + const response = await fetch(url, { + method: 'GET', + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', + 'Cookie': cookie + } + }); + + if (!response.ok) throw new Error(`HTTP Error ${response.status}`); + return await response.text(); + } + + /** + * Récupère la page des ajouts récents + */ + public static async fetchRecent(): Promise { + const cookie = await FS24Auth.getCookie(); + const url = `${this.baseUrl}/film-commu/`; + + console.log(`[FS24] Chargement des ajouts récents`); + + const response = await fetch(url, { + method: 'GET', + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', + 'Cookie': cookie + } + }); + + if (!response.ok) throw new Error(`HTTP Error ${response.status}`); + return await response.text(); + } + + /** + * Appelle l'API JSON /engine/ajax/release-api.php pour récupérer les releases communautaires. + * C'est ici que se trouvent les vrais liens de téléchargement (fsprotect encodés en base64). + */ + public static async fetchReleases(newsId: string): Promise { + const cookie = await FS24Auth.getCookie(); + const url = `${this.baseUrl}/engine/ajax/release-api.php?action=release_list&post_id=${newsId}`; + + console.log(`[FS24] Chargement des releases pour post_id=${newsId}`); + + const response = await fetch(url, { + method: 'GET', + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', + 'Cookie': cookie, + 'X-Requested-With': 'XMLHttpRequest' + } + }); + + if (!response.ok) { + throw new Error(`HTTP Error ${response.status}`); + } + + return await response.json(); + } +} diff --git a/plugins/fs24/auth.ts b/plugins/fs24/auth.ts new file mode 100644 index 0000000..2c99ff9 --- /dev/null +++ b/plugins/fs24/auth.ts @@ -0,0 +1,58 @@ +import { CONFIG } from '../../src/utils/config.js'; + +export class FS24Auth { + private static sessionCookie: string | null = null; + private static lastLoginTime: number = 0; + + public static async getCookie(forceRefresh = false): Promise { + // If we already have a cookie and it's less than 12 hours old, return it + if (!forceRefresh && this.sessionCookie && Date.now() - this.lastLoginTime < 12 * 60 * 60 * 1000) { + return this.sessionCookie; + } + + const username = CONFIG.FS24_USERNAME; + const password = CONFIG.FS24_PASSWORD; + const baseUrl = CONFIG.FS24_URL; + + if (!username || !password) { + throw new Error('[FS24 Auth] Identifiants manquants.'); + } + + console.log(`[FS24] Tentative de connexion avec l'utilisateur: ${username}...`); + + try { + const params = new URLSearchParams(); + params.append('login_name', username); + params.append('login_password', password); + params.append('login', 'submit'); + + const response = await fetch(baseUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', + 'Referer': baseUrl + }, + body: params.toString(), + redirect: 'manual' // Capture the set-cookie from the redirect + }); + + // Collect cookies from the response headers + const setCookieHeader = response.headers.get('set-cookie'); + if (setCookieHeader) { + // Parse DLE / PHP session cookies + const cookies = setCookieHeader.split(',').map(c => c.split(';')[0].trim()); + this.sessionCookie = cookies.join('; '); + this.lastLoginTime = Date.now(); + console.log(`[FS24] ✅ Connexion réussie ! (Cookie généré)`); + return this.sessionCookie; + } else { + console.warn(`[FS24] ⚠️ Pas de header set-cookie retourné. Les identifiants sont-ils valides ?`); + throw new Error('Échec de la connexion (Pas de cookie de session).'); + } + } catch (error: any) { + console.error('[FS24] ❌ Erreur lors de la connexion:', error.message); + throw error; + } + } +} diff --git a/plugins/fs24/index.ts b/plugins/fs24/index.ts new file mode 100644 index 0000000..6211660 --- /dev/null +++ b/plugins/fs24/index.ts @@ -0,0 +1,91 @@ +import { ISource, SearchResult, ContentLinks, MediaType, SelectionData } from '../../src/types/source.js'; +import { sourceRegistry } from '../../src/core/registry.js'; +import { FS24API } from './api.js'; +import { FS24Auth } from './auth.js'; +import { parseListingHTML, extractNewsId, parseReleasesJSON } from './parser.js'; + +export class FS24Source implements ISource { + public readonly name = 'fs24'; + public readonly displayName = 'FS24'; + + public async healthCheck(): Promise { + try { + await FS24Auth.getCookie(true); + return true; + } catch (e: any) { + console.error(`[FS24] HealthCheck échoué: ${e.message}`); + return false; + } + } + + public async search(query: string, mediaType?: MediaType): Promise { + if (!query || query.length < 3) return []; + + try { + const html = await FS24API.fetchSearch(query); + const results = parseListingHTML(html, mediaType || 'movie'); + return results; + } catch (e: any) { + console.error(`[FS24] Erreur search: ${e.message}`); + return []; + } + } + + public async getTrending(mediaType: MediaType): Promise { + try { + const html = await FS24API.fetchTrending(mediaType === 'series' ? 'series' : 'movie'); + const results = parseListingHTML(html, mediaType); + return results.slice(0, 20); // Keep top 20 + } catch (e: any) { + console.error(`[FS24] Erreur trending: ${e.message}`); + return []; + } + } + + public async getRecent(): Promise { + try { + const html = await FS24API.fetchRecent(); + const results = parseListingHTML(html, 'movie'); // Default to movie for recents, TMDB will fix it if needed + return results.slice(0, 20); + } catch (e: any) { + console.error(`[FS24] Erreur recent: ${e.message}`); + return []; + } + } + + public async getContentLinks(identifier: string, season?: number): Promise { + try { + // Step 1: Fetch the page HTML to extract the news_id + const html = await FS24API.fetchPage(identifier); + const newsId = extractNewsId(html); + + if (!newsId) { + console.warn(`[FS24] Impossible d'extraire le news_id depuis: ${identifier}`); + return { links: [] }; + } + + // Step 2: Call the release JSON API to get the actual download links + const releaseData = await FS24API.fetchReleases(newsId); + const links = parseReleasesJSON(releaseData); + + console.log(`[FS24] ${links.length} lien(s) trouvé(s) pour post_id=${newsId}`); + return { links }; + } catch (e: any) { + console.error(`[FS24] Erreur getContentLinks: ${e.message}`); + return { links: [] }; + } + } + + public async getSelection(identifier: string, type?: string, seasonValue?: string | number): Promise { + const content = await this.getContentLinks(identifier); + + return { + links: content.links, + seasons: [], + isSeries: type === 'series' + }; + } +} + +// ── Auto-registration ── +sourceRegistry.register(new FS24Source()); diff --git a/plugins/fs24/parser.ts b/plugins/fs24/parser.ts new file mode 100644 index 0000000..3bc5373 --- /dev/null +++ b/plugins/fs24/parser.ts @@ -0,0 +1,164 @@ +import { SearchResult, VideoLink, MediaType } from '../../src/types/source.js'; + +/** + * Parse le HTML AJAX de résultats de recherche ou pages catégories FS24. + * Supporte les blocs `.search-item` et `.short` + */ +export function parseListingHTML(html: string, mediaType: MediaType): SearchResult[] { + const results: SearchResult[] = []; + + // 1. Matches pour les blocs de recherche AJAX (.search-item) + const searchRegex = /
]*onclick="location\.href='([^']+)'"[^>]*>([\s\S]*?)(?=
]*src=['"]([^'"]+)['"]/); + const image = imgMatch ? imgMatch[1]! : null; + + const titleMatch = block.match(/
([^<]+)<\/div>/); + if (!titleMatch) continue; + + let titleRaw = titleMatch[1]!.trim(); + let year: string | null = null; + const yearMatch = titleRaw.match(/\((\d{4})\)/); + if (yearMatch) { + year = yearMatch[1]!; + titleRaw = titleRaw.replace(/\s*\(\d{4}\)\s*/, '').trim(); + } + + if (titleRaw && hrefPath) { + results.push({ title: titleRaw, year, image, hrefPath, type: mediaType, source: 'fs24' }); + } + } + + // 2. Matches pour les pages régulières DLE (.short) + const shortRegex = /
([\s\S]*?)<\/div>\s*|
([\s\S]*?)(?=
]*src=['"]([^'"]+)['"]/); + const image = imgMatch ? imgMatch[1]! : null; + + // Extract title + const titleMatch = block.match(/
([^<]+)<\/div>/); + if (!titleMatch) continue; + let titleRaw = titleMatch[1]!.trim(); + + // Extract link + const linkMatch = block.match(/]*href=['"]([^'"]+)['"]/); + let hrefPath = linkMatch ? linkMatch[1]! : null; + if (!hrefPath) continue; + + // Remove domain if the link is absolute to keep paths source-agnostic + if (hrefPath.startsWith('http')) { + try { + const u = new URL(hrefPath); + hrefPath = u.pathname + u.search; + } catch { /* ignore */ } + } + + let year: string | null = null; + const yearMatch = titleRaw.match(/\((\d{4})\)/); + if (yearMatch) { + year = yearMatch[1]!; + titleRaw = titleRaw.replace(/\s*\(\d{4}\)\s*/, '').trim(); + } + + if (titleRaw && hrefPath) { + results.push({ title: titleRaw, year, image, hrefPath, type: mediaType, source: 'fs24' }); + } + } + + return results; +} + +/** + * Extrait le news_id depuis la page HTML (attribut data-news-id du bloc commu-releases-block). + */ +export function extractNewsId(html: string): string | null { + const match = html.match(/data-news-id="(\d+)"/); + return match ? match[1]! : null; +} + +/** + * Décode un lien fsprotect double-Base64 en URL finale. + * Format: base64 → "url:|metadata|timestamp|hash" + * second_b64 → URL finale (ex: https://1fichier.com/...) + */ +export function decodeFsProtectLink(rawHref: string): string | null { + try { + // Extract the ?t= parameter + const tParamMatch = rawHref.match(/[?&]t=([^&]+)/); + if (!tParamMatch) return null; + + const base64t = tParamMatch[1]!; + // First Base64 decode + const decodedT = Buffer.from(base64t, 'base64').toString('utf-8'); + // Format: url:||| + if (!decodedT.startsWith('url:')) return null; + + const firstPart = decodedT.substring(4).split('|')[0]!; + if (!firstPart) return null; + + // Second Base64 decode → final URL + return Buffer.from(firstPart, 'base64').toString('utf-8'); + } catch (e: any) { + console.error('[FS24] Erreur décodage lien Base64:', e.message); + return null; + } +} + +function formatBytes(bytes: number): string { + if (!bytes || bytes <= 0) return ''; + if (bytes > 1073741824) return (bytes / 1073741824).toFixed(2) + ' GB'; + if (bytes > 1048576) return (bytes / 1048576).toFixed(0) + ' MB'; + return (bytes / 1024).toFixed(0) + ' KB'; +} + +/** + * Parse la réponse JSON de l'API release-api.php en VideoLink[]. + */ +export function parseReleasesJSON(data: any): VideoLink[] { + const links: VideoLink[] = []; + if (!data || !data.ok || !Array.isArray(data.items)) return links; + + for (const item of data.items) { + const rawLink = item.original_link || ''; + const finalUrl = decodeFsProtectLink(rawLink); + if (!finalUrl) continue; + + const releaseName = item.release_name || 'Inconnu'; + const lowerName = releaseName.toLowerCase(); + + // Detect language from release name + const langs: string[] = []; + if (lowerName.includes('multi')) langs.push('vf', 'vostfr'); + else if (lowerName.includes('vostfr')) langs.push('vostfr'); + else if (lowerName.includes('truefrench') || lowerName.includes('french')) langs.push('vf'); + else langs.push('vf'); + + // Detect host from URL + let host = 'Inconnu'; + try { + const urlObj = new URL(finalUrl); + host = urlObj.hostname.replace('www.', ''); + } catch { /* ignore */ } + + links.push({ + id: String(item.id), + host, + url: finalUrl, + quality: item.quality || '', + size: formatBytes(item.size_bytes), + releaseName: item.is_team ? `[TEAM] ${releaseName}` : releaseName, + langs + }); + } + + return links; +} diff --git a/plugins/hydracker/api.ts b/plugins/hydracker/api.ts index dd9e8ae..ed8b2eb 100644 --- a/plugins/hydracker/api.ts +++ b/plugins/hydracker/api.ts @@ -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 = {}) { - 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; } diff --git a/plugins/hydracker/index.ts b/plugins/hydracker/index.ts index ad918bf..834596a 100644 --- a/plugins/hydracker/index.ts +++ b/plugins/hydracker/index.ts @@ -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 { - 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 { @@ -41,12 +30,20 @@ export class HydrackerAPI implements ISource { } async getTrending(mediaType: MediaType): Promise { - 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 { - 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 { - // 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 { - 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 { 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)); diff --git a/plugins/loadix/index.ts b/plugins/loadix/index.ts new file mode 100644 index 0000000..62afc7a --- /dev/null +++ b/plugins/loadix/index.ts @@ -0,0 +1,165 @@ +import { ISource, SearchResult, SelectionData, ContentLinks, MediaType } from '../../src/types/source.js'; +import { CONFIG } from '../../src/utils/config.js'; + +export class LoadixSource implements ISource { + name = 'loadix'; + displayName = 'Loadix'; + + private get frontUrl() { return (CONFIG.LOADIX_URL || '').replace(/\/+$/, ''); } + private get baseUrl() { + const urlObj = new URL(this.frontUrl); + return `https://api.${urlObj.host}/api`; + } + private tmdbImageBase = 'https://image.tmdb.org/t/p/w500'; + + private mapType(type: string): MediaType { + if (type === 'series') return 'series'; + if (type === 'anime') return 'anime'; + return 'movie'; + } + + private formatSearchResult(hit: any): SearchResult { + return { + title: hit.title, + year: hit.year ? hit.year.toString() : null, + image: hit.posterPath ? `${this.tmdbImageBase}${hit.posterPath}` : null, + hrefPath: `${this.frontUrl}/media/${hit.id}`, + type: this.mapType(hit.type), + source: this.name + }; + } + + async search(query: string, mediaType?: MediaType): Promise { + const url = `${this.baseUrl}/media/search?q=${encodeURIComponent(query)}&page=1&pageSize=30`; + const res = await fetch(url); + const data = await res.json(); + + let hits = data.hits || []; + if (mediaType && mediaType !== 'other') { + hits = hits.filter((h: any) => this.mapType(h.type) === mediaType); + } + + return hits.map((h: any) => this.formatSearchResult(h)); + } + + async getTrending(mediaType: MediaType): Promise { + const url = `${this.baseUrl}/media/search?q=&page=1&pageSize=30&sort=click_count_desc`; + const res = await fetch(url); + const data = await res.json(); + + let hits = data.hits || []; + if (mediaType && mediaType !== 'other') { + hits = hits.filter((h: any) => this.mapType(h.type) === mediaType); + } + + return hits.map((h: any) => this.formatSearchResult(h)); + } + + async getRecent(): Promise { + const url = `${this.baseUrl}/media/recent?limit=24`; + const res = await fetch(url); + const data = await res.json(); + + const items = data.items || []; + return items.map((h: any) => this.formatSearchResult(h)); + } + + async getSelection(identifier: string, type?: string, seasonValue?: string | number): Promise { + const idMatch = identifier.match(/media\/([a-f0-9\-]+)/); + if (!idMatch) throw new Error("URL Loadix invalide."); + const mediaId = idMatch[1]; + + // Fetch links + const url = `${this.baseUrl}/media/${mediaId}/links?page=1&perPage=100&sort=scope_asc`; + const res = await fetch(url); + const data = await res.json(); + const items = data.items || []; + + const links = items.map((item: any) => { + let episode = null; + if (item.scope === 'season' && item.seasonNumber) { + episode = `S${String(item.seasonNumber).padStart(2, '0')}`; + } else if (item.scope === 'episode' && item.seasonNumber && item.episodeNumber) { + episode = `S${String(item.seasonNumber).padStart(2, '0')}E${String(item.episodeNumber).padStart(2, '0')}`; + } + + return { + id: `${identifier}|${item.id}`, + host: item.provider || 'unknown', + quality: item.quality, + langs: item.language ? [item.language] : [], + sizeBytes: item.sizeBytes ? parseInt(item.sizeBytes) : undefined, + size: item.sizeHuman, + releaseName: item.releaseGroup, + episode: episode, + url: null // Protected by Turnstile, resolved later by direct redirect + }; + }); + + // Check if there are any episodes/seasons to determine if it's a series + const isSeries = links.some((l: any) => l.episode); + + // Extract seasons (just based on found links) + const seasonsMap = new Map(); + if (isSeries) { + items.forEach((item: any) => { + if (item.seasonNumber) { + const seasonStr = `Saison ${item.seasonNumber}`; + seasonsMap.set(String(item.seasonNumber), seasonStr); + } + }); + } + + const seasons = Array.from(seasonsMap.entries()).map(([val, label]) => ({ + value: val, + label: label + })); + + return { + links, + seasons, + isSeries + }; + } + + async getContentLinks(identifier: string, season?: number): Promise { + const selection = await this.getSelection(identifier); + let links = selection.links; + + if (season) { + const seasonPrefix = `S${String(season).padStart(2, '0')}`; + links = links.filter(l => l.episode && l.episode.startsWith(seasonPrefix)); + } + + return { links }; + } + + async healthCheck(): Promise { + if (!this.frontUrl) { + console.warn('[Loadix] ⚠️ LOADIX_URL non définie.'); + return false; + } + try { + const results = await this.getRecent(); + return results.length > 0; + } catch (e: any) { + console.error(`[Loadix] Healthcheck failed: ${e.message}`); + return false; + } + } + + async resolveLink(linkId: string, extraData?: any): Promise { + const [url] = linkId.split('|'); + // Like Flixart, Turnstile cannot be solved on localhost. + // We directly return the manual redirection challenge to open Loadix. + return { + captcha: 'turnstile', + url: url, + sourceName: 'Loadix' + }; + } +} + +// Auto-registration +import { sourceRegistry } from '../../src/core/registry.js'; +sourceRegistry.register(new LoadixSource()); diff --git a/plugins/movix/api.ts b/plugins/movix/api.ts new file mode 100644 index 0000000..8332b46 --- /dev/null +++ b/plugins/movix/api.ts @@ -0,0 +1,47 @@ +import { CONFIG } from '../../src/utils/config.js'; + +export class MovixAPI { + private static get baseUrl(): string { + return CONFIG.MOVIX_URL || ''; + } + + private static get apiUrl(): string { + if (!this.baseUrl) return ''; + try { + const url = new URL(this.baseUrl); + return `${url.protocol}//api.${url.host}/api`; + } catch { + return ''; + } + } + + private static getHeaders() { + return { + 'Accept': 'application/json, text/plain, */*', + 'Origin': this.baseUrl, + 'Referer': `${this.baseUrl}/`, + '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' + }; + } + + public static async search(query: string): Promise { + const url = `${this.apiUrl}/search?title=${encodeURIComponent(query)}`; + const res = await fetch(url, { headers: this.getHeaders() }); + if (!res.ok) throw new Error(`Movix Search HTTP ${res.status}`); + return res.json(); + } + + public static async getDownloadLinks(type: string, id: number | string, tmdbId: number | string): Promise { + const url = `${this.apiUrl}/darkiworld/download/${type}/${id}?tmdbId=${tmdbId}`; + const res = await fetch(url, { headers: this.getHeaders() }); + if (!res.ok) throw new Error(`Movix Download HTTP ${res.status}`); + return res.json(); + } + + public static async decodeLink(linkId: string | number, titleId: string | number): Promise { + const url = `${this.apiUrl}/darkiworld/decode/${linkId}?title_id=${titleId}`; + const res = await fetch(url, { headers: this.getHeaders() }); + if (!res.ok) throw new Error(`Movix Decode HTTP ${res.status}`); + return res.json(); + } +} diff --git a/plugins/movix/index.ts b/plugins/movix/index.ts new file mode 100644 index 0000000..f5c455c --- /dev/null +++ b/plugins/movix/index.ts @@ -0,0 +1,207 @@ +import { ISource, SearchResult, SelectionData, ContentLinks, MediaType, VideoLink } from '../../src/types/source.js'; +import { sourceRegistry } from '../../src/core/registry.js'; +import { MovixAPI } from './api.js'; +import { CONFIG } from '../../src/utils/config.js'; + +class MovixSource implements ISource { + public readonly name = 'movix'; + public readonly displayName = 'Movix'; + + public async healthCheck(): Promise { + if (!CONFIG.MOVIX_URL) return false; + try { + // A quick check to see if the search endpoint is reachable + await MovixAPI.search('test'); + return true; + } catch (e) { + console.error(`[MOVIX] Health check failed:`, e); + return false; + } + } + + public async search(query: string, mediaType?: MediaType): Promise { + try { + const response = await MovixAPI.search(query); + if (!response || !response.results) return []; + + const results: SearchResult[] = []; + const searchLower = query.toLowerCase().trim(); + + for (const item of response.results) { + if (!item.name) continue; + + // Filtre optionnel pour aligner les résultats avec la recherche + const nameLower = item.name.toLowerCase(); + const originalLower = item.original_title ? item.original_title.toLowerCase() : ''; + + // On vérifie si la requête est incluse dans le titre ou le titre original + if (!nameLower.includes(searchLower) && !originalLower.includes(searchLower)) { + // Pour être un peu plus permissif, on vérifie si tous les mots clés y sont + const words = searchLower.split(' '); + const allWordsMatch = words.every(w => nameLower.includes(w) || originalLower.includes(w)); + if (!allWordsMatch) continue; + } + + // Filtrage basique par mediaType si fourni + if (mediaType) { + if (mediaType === 'movie' && item.type !== 'movie') continue; + if (mediaType === 'series' && item.type !== 'serie') continue; // Verify if it's 'serie' or 'series' + } + + const hrefPath = `movix:${item.id}:${item.tmdb_id || 0}:${item.type}`; + + let image = null; + if (item.poster) { + image = item.poster.startsWith('http') ? item.poster : `https://image.tmdb.org/t/p/w300/${item.poster}`; + } + + results.push({ + title: item.name, + year: item.year ? item.year.toString() : null, + image, + hrefPath, + type: item.type === 'movie' ? 'movie' : (item.type === 'serie' || item.type === 'series' ? 'series' : 'other'), + source: this.name + }); + } + + return results; + } catch (e) { + console.error(`[MOVIX] Search error:`, e); + return []; + } + } + + public async getTrending(mediaType: MediaType): Promise { + const typeStr = mediaType === 'series' ? 'tv' : 'movie'; + const url = `https://api.themoviedb.org/3/trending/${typeStr}/day?api_key=f3d757824f08ea2cff45eb8f47ca3a1e&language=fr-FR`; + + try { + const res = await fetch(url); + const data = await res.json(); + + if (!data || !data.results) return []; + + return data.results.map((item: any) => { + const title = item.title || item.name; + const year = item.release_date ? item.release_date.split('-')[0] : (item.first_air_date ? item.first_air_date.split('-')[0] : null); + const image = item.poster_path ? `https://image.tmdb.org/t/p/w300${item.poster_path}` : null; + const tmdbId = item.id; + const type = mediaType === 'series' ? 'series' : 'movie'; + + // Identifiant spécial pour faire la recherche au moment du clic + const hrefPath = `movix:tmdb:${tmdbId}:${type}:${encodeURIComponent(title)}`; + + return { + title, + year, + image, + hrefPath, + type, + source: this.name + }; + }); + } catch(e) { + console.error(`[MOVIX] TMDB Trending error:`, e); + return []; + } + } + + public async getRecent(): Promise { + // Fallback on movies trending as recent if no specific endpoint + return this.getTrending('movie'); + } + + public async getContentLinks(identifier: string, season?: number): Promise { + try { + const parts = identifier.split(':'); + if (parts.length < 4) return { links: [] }; + + let id: string, tmdbId: string, type: string; + + if (parts[1] === 'tmdb') { + tmdbId = parts[2]; + type = parts[3]; + const title = decodeURIComponent(parts.slice(4).join(':')); + + // Recherche sur Movix pour récupérer l'ID interne + const searchRes = await MovixAPI.search(title); + const item = searchRes.results?.find((r: any) => String(r.tmdb_id) === String(tmdbId) || r.name === title); + if (!item) { + console.log(`[MOVIX] TMDB item not found on Movix: ${title}`); + return { links: [] }; + } + id = item.id; + // Update type depending on what Movix returned + type = item.type === 'serie' || item.type === 'series' ? 'series' : 'movie'; + } else { + id = parts[1]; + tmdbId = parts[2]; + type = parts[3]; + } + + const data = await MovixAPI.getDownloadLinks(type, id, tmdbId); + + const links: VideoLink[] = []; + + if (data && data.data) { + // Pour chaque host (1fichier, etc) + for (const item of data.data) { + if (!item.links || !Array.isArray(item.links)) continue; + + const host = item.host || 'unknown'; + const quality = item.qualite || 'Unknown'; + const lang = item.langue || 'Unknown'; + const size = item.size || ''; + + for (const linkObj of item.links) { + const linkId = linkObj.id; + if (!linkId) continue; + + links.push({ + id: `${linkId}|${id}`, // Store both linkId and titleId + host: host, + label: `${quality} - ${lang}`, + url: null, // Resolves later + size: size, + quality: quality, + langs: [lang] + }); + } + } + } + + return { links }; + } catch (e) { + console.error(`[MOVIX] Error in getContentLinks:`, e); + return { links: [] }; + } + } + + public async getSelection(identifier: string, type?: string, seasonValue?: string | number): Promise { + const content = await this.getContentLinks(identifier); + return { + links: content.links, + seasons: [], + isSeries: type === 'series' + }; + } + + public async resolveLink(combinedId: string): Promise { + try { + const [linkId, titleId] = combinedId.split('|'); + if (!linkId || !titleId) return null; + + const res = await MovixAPI.decodeLink(linkId, titleId); + if (res && res.url) { + return res.url; + } + return null; + } catch (e) { + console.error(`[MOVIX] ResolveLink error for ${combinedId}:`, e); + return null; + } + } +} + +sourceRegistry.register(new MovixSource()); diff --git a/plugins/ztnews/api.ts b/plugins/ztnews/api.ts index d3d3991..76f2cef 100644 --- a/plugins/ztnews/api.ts +++ b/plugins/ztnews/api.ts @@ -1,5 +1,5 @@ /** - * Appels réseau pour zt.news. + * Appels réseau pour zone-telechargement.news. * Pas de challenge CF actif, fetch direct simple. */ diff --git a/plugins/ztnews/index.ts b/plugins/ztnews/index.ts index 302a915..98c6735 100644 --- a/plugins/ztnews/index.ts +++ b/plugins/ztnews/index.ts @@ -29,12 +29,10 @@ function deduplicateByTitle(results: SearchResult[]): SearchResult[] { } export class ZtTeamAPI implements ISource { - name = 'ztteam'; - displayName = 'ZT (Team)'; - private baseUrl: string | undefined; - - constructor(baseUrl?: string) { - this.baseUrl = baseUrl?.replace(/\/$/, ''); + name = 'ztnews'; + displayName = 'Zone-Téléchargement (Team)'; + get baseUrl() { + return CONFIG.ZTTEAM_URL?.replace(/\/$/, ''); } async healthCheck(): Promise { @@ -132,4 +130,4 @@ export class ZtTeamAPI implements ISource { } } -sourceRegistry.register(new ZtTeamAPI(CONFIG.ZTTEAM_URL)); +sourceRegistry.register(new ZtTeamAPI()); diff --git a/plugins/ztnews/parser.ts b/plugins/ztnews/parser.ts index 11aa787..e6b0d60 100644 --- a/plugins/ztnews/parser.ts +++ b/plugins/ztnews/parser.ts @@ -69,9 +69,15 @@ export function parseListingHTML(html: string, baseUrl: string): SearchResult[] const title = titleMatch[2]!.trim(); const imgMatch = block.match(/]*src="([^"]+)"/); const image = imgMatch ? absUrl(imgMatch[1]!, baseUrl) : null; + let year: string | null = null; + const yearMatch = title.match(/\(\s*(\d{4})\s*\)/) || href.match(/-(\d{4})-/); + if (yearMatch) { + year = yearMatch[1]; + } + results.push({ title, - year: null, + year, image, hrefPath: href, type: detectType(titleMatch[1]!), diff --git a/public/app.js b/public/app.js index eaa8ad9..6689cac 100644 --- a/public/app.js +++ b/public/app.js @@ -366,6 +366,9 @@ document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('input[name="trending-type"]').forEach(radio => { radio.addEventListener('change', renderTrending); }); + document.querySelectorAll('input[name="recent-type"]').forEach(radio => { + radio.addEventListener('change', renderRecent); + }); // --- HEARTBEAT : Détection source down + Refresh Tendances --- let wasOffline = false; @@ -840,6 +843,7 @@ document.addEventListener('DOMContentLoaded', () => { if (!movie.quality) movie.quality = qualityFromTitle; } + if (movie.year) parts.push(movie.year); if (movie.quality) parts.push(movie.quality); if (movie.lang) parts.push(movie.lang); subtitle = parts.join(' — ') || ''; @@ -856,10 +860,22 @@ document.addEventListener('DOMContentLoaded', () => {
`; div.addEventListener('click', () => handleSelection(movie)); + + // Add hover effect for the TMDB link + const tmdbLink = div.querySelector('.tmdb-link'); + if (tmdbLink) { + tmdbLink.addEventListener('mouseenter', () => tmdbLink.style.opacity = '1'); + tmdbLink.addEventListener('mouseleave', () => tmdbLink.style.opacity = '0.7'); + } return div; }; @@ -900,12 +916,22 @@ document.addEventListener('DOMContentLoaded', () => { const grid = dom('recent-grid'); if (!grid) return; - const itemsToDisplay = state.trendingData.recent || []; + // Get filter type from radio buttons + const typeFilter = document.querySelector('input[name="recent-type"]:checked')?.value || 'all'; + + let itemsToDisplay = state.trendingData.recent || []; + + // Apply filter + if (typeFilter === 'film') { + itemsToDisplay = itemsToDisplay.filter(m => m.type === 'movie'); + } else if (typeFilter === 'serie') { + itemsToDisplay = itemsToDisplay.filter(m => m.type === 'series' || m.type === 'serie'); + } grid.innerHTML = ''; if (!itemsToDisplay || !itemsToDisplay.length) { - grid.innerHTML = '

Aucun ajout récent trouvé.

'; + grid.innerHTML = '

Aucun ajout récent trouvé pour ce filtre.

'; return; } @@ -961,6 +987,10 @@ document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('input[name="trending-type"]').forEach(radio => { radio.addEventListener('change', renderTrending); }); + + document.querySelectorAll('input[name="recent-type"]').forEach(radio => { + radio.addEventListener('change', renderRecent); + }); // --- SEARCH --- const searchInput = dom('search-input'); @@ -1160,7 +1190,7 @@ document.addEventListener('DOMContentLoaded', () => { return; } - const MAX_FILM_SIZE_MB = 45360; + const MAX_FILM_SIZE_MB = 150000; const enriched = data.clientOptions.map(q => { const lowEp = q.episode ? q.episode.toLowerCase() : ''; @@ -1466,7 +1496,15 @@ document.addEventListener('DOMContentLoaded', () => { } toggleBlockingLoader(true, "Récupération du lien..."); try { - const result = await apiCall('/get-link', 'POST', { chosenId: q.id, useJD }); + let result = await apiCall('/get-link', 'POST', { chosenId: q.id, useJD }); + + if (result.status === 'challenge' && result.challenge) { + toggleBlockingLoader(false); + const captchaData = await window.handleCaptchaChallenge(result.challenge); + toggleBlockingLoader(true, "Vérification du captcha..."); + result = await apiCall('/get-link', 'POST', { chosenId: q.id, useJD, captchaData }); + } + toggleBlockingLoader(false); if (useJD) { @@ -1555,11 +1593,23 @@ document.addEventListener('DOMContentLoaded', () => { if (forcedDirect) { useJD = false; } - toggleBlockingLoader(true, "Récupération des liens..."); try { - const result = await apiCall('/get-links-batch', 'POST', { chosenIds: Array.from(selectedIds), useJD }); + toggleBlockingLoader(true, "Récupération des liens..."); + let result = await apiCall('/get-links-batch', 'POST', { chosenIds: Array.from(selectedIds), useJD }); + + if (result.status === 'challenge' && result.challenge) { + toggleBlockingLoader(false); + const captchaData = await window.handleCaptchaChallenge(result.challenge); + toggleBlockingLoader(true, "Vérification du captcha et récupération..."); + result = await apiCall('/get-links-batch', 'POST', { chosenIds: Array.from(selectedIds), useJD, captchaData }); + } + toggleBlockingLoader(false); + if (result.errors) { + showToast('Erreurs: ' + result.errors.join(', ')); + } + if (useJD) { showToast(result.message || 'Liens envoyés à JDownloader !'); } else { @@ -1601,6 +1651,7 @@ document.addEventListener('DOMContentLoaded', () => { dom('modal-body').innerHTML = content; show(dom('modal-overlay')); }; + window.showModal = showModal; const showDirectLinkModal = (title, content) => { const existing = document.getElementById('direct-link-modal-overlay'); @@ -1649,6 +1700,61 @@ document.addEventListener('DOMContentLoaded', () => { } }; + window.handleCaptchaChallenge = function(challenge) { + return new Promise((resolve, reject) => { + const existing = document.getElementById('captcha-modal-overlay'); + if (existing) existing.remove(); + + const overlay = document.createElement('div'); + overlay.id = 'captcha-modal-overlay'; + overlay.className = 'modal-overlay'; + overlay.style.zIndex = '10005'; + + if (challenge.captcha === 'turnstile') { + overlay.innerHTML = ` +
+ `; + } else { + overlay.innerHTML = ` + + `; + } + + document.body.appendChild(overlay); + lucide.createIcons({ root: overlay }); + show(overlay); + + const closeBtn = overlay.querySelector('#captcha-modal-close'); + if (closeBtn) { + closeBtn.addEventListener('click', () => { + reject(new Error(challenge.captcha === 'turnstile' ? 'Redirection manuelle requise par Cloudflare.' : 'Captcha annulé.')); + hide(overlay); + setTimeout(() => overlay.remove(), 300); + }); + } + }); + }; + const modalClose = dom('modal-close'); if (modalClose) { modalClose.onclick = () => { diff --git a/public/images/logo_svg.svg b/public/images/logo_svg.svg new file mode 100644 index 0000000..a024296 --- /dev/null +++ b/public/images/logo_svg.svg @@ -0,0 +1,306 @@ + + + + diff --git a/public/logo_svg.svg b/public/logo_svg.svg new file mode 100644 index 0000000..a024296 --- /dev/null +++ b/public/logo_svg.svg @@ -0,0 +1,306 @@ + + + + diff --git a/public/manifest.json b/public/manifest.json index 65cc69b..29477d1 100644 --- a/public/manifest.json +++ b/public/manifest.json @@ -1,6 +1,6 @@ { - "name": "Hydr'Hacked", - "short_name": "Hydr'Hacked", + "name": "Agora", + "short_name": "Agora", "start_url": "/", "display": "standalone", "orientation": "portrait", diff --git a/public/sortable.min.js b/public/sortable.min.js new file mode 100644 index 0000000..8148b9d --- /dev/null +++ b/public/sortable.min.js @@ -0,0 +1,2 @@ +/*! Sortable 1.15.7 - MIT | git://github.com/SortableJS/Sortable.git */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).Sortable=e()}(this,function(){"use strict";function o(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,o=Array(e);n"===e[0]&&(e=e.substring(1)),t))try{if(t.matches)return t.matches(e);if(t.msMatchesSelector)return t.msMatchesSelector(e);if(t.webkitMatchesSelector)return t.webkitMatchesSelector(e)}catch(t){return}}function m(t){return t.host&&t!==document&&t.host.nodeType&&t.host!==t?t.host:t.parentNode}function P(t,e,n,o){if(t){n=n||document;do{if(null!=e&&(">"!==e[0]||t.parentNode===n)&&g(t,e)||o&&t===n)return t}while(t!==n&&(t=m(t)))}return null}var v,b=/\s+/g;function k(t,e,n){var o;t&&e&&(t.classList?t.classList[n?"add":"remove"](e):(o=(" "+t.className+" ").replace(b," ").replace(" "+e+" "," "),t.className=(o+(n?" "+e:"")).replace(b," ")))}function R(t,e,n){var o=t&&t.style;if(o){if(void 0===n)return document.defaultView&&document.defaultView.getComputedStyle?n=document.defaultView.getComputedStyle(t,""):t.currentStyle&&(n=t.currentStyle),void 0===e?n:n[e];o[e=!(e in o||-1!==e.indexOf("webkit"))?"-webkit-"+e:e]=n+("string"==typeof n?"":"px")}}function D(t,e){var n="";if("string"==typeof t)n=t;else do{var o=R(t,"transform")}while(o&&"none"!==o&&(n=o+" "+n),!e&&(t=t.parentNode));var i=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return i&&new i(n)}function E(t,e,n){if(t){var o=t.getElementsByTagName(e),i=0,r=o.length;if(n)for(;i=n.left-e&&i<=n.right+e,e=r>=n.top-e&&r<=n.bottom+e;return o&&e?a=t:void 0}}),a);if(e){var n,o={};for(n in t)t.hasOwnProperty(n)&&(o[n]=t[n]);o.target=o.rootEl=e,o.preventDefault=void 0,o.stopPropagation=void 0,e[K]._onDragOver(o)}}var i,r,a}function jt(t){$&&$.parentNode[K]._isOutsideThisEl(t.target)}function Ht(t,e){if(!t||!t.nodeType||1!==t.nodeType)throw"Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(t));this.el=t,this.options=e=a({},e),t[K]=this;var n,o,i={group:null,sort:!0,disabled:!1,store:null,handle:null,draggable:/^[uo]l$/i.test(t.nodeName)?">li":">*",swapThreshold:1,invertSwap:!1,invertedSwapThreshold:null,removeCloneOnHide:!0,direction:function(){return Rt(t,this.options)},ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",ignore:"a, img",filter:null,preventOnFilter:!0,animation:0,easing:null,setData:function(t,e){t.setData("Text",e.textContent)},dropBubble:!1,dragoverBubble:!1,dataIdAttr:"data-id",delay:0,delayOnTouchOnly:!1,touchStartThreshold:(Number.parseInt?Number:window).parseInt(window.devicePixelRatio,10)||1,forceFallback:!1,fallbackClass:"sortable-fallback",fallbackOnBody:!1,fallbackTolerance:0,fallbackOffset:{x:0,y:0},supportPointer:!1!==Ht.supportPointer&&"PointerEvent"in window&&(!u||d),emptyInsertThreshold:5};for(n in G.initializePlugins(this,t,i),i)n in e||(e[n]=i[n]);for(o in Xt(e),this)"_"===o.charAt(0)&&"function"==typeof this[o]&&(this[o]=this[o].bind(this));this.nativeDraggable=!e.forceFallback&&Pt,this.nativeDraggable&&(this.options.touchStartThreshold=1),e.supportPointer?f(t,"pointerdown",this._onTapStart):(f(t,"mousedown",this._onTapStart),f(t,"touchstart",this._onTapStart)),this.nativeDraggable&&(f(t,"dragover",this),f(t,"dragenter",this)),_t.push(this.el),e.store&&e.store.get&&this.sort(e.store.get(this)||[]),a(this,N())}function Lt(t,e,n,o,i,r,a,l){var s,c,u=t[K],d=u.options.onMove;return!window.CustomEvent||y||w?(s=document.createEvent("Event")).initEvent("move",!0,!0):s=new CustomEvent("move",{bubbles:!0,cancelable:!0}),s.to=e,s.from=t,s.dragged=n,s.draggedRect=o,s.related=i||e,s.relatedRect=r||X(e),s.willInsertAfter=l,s.originalEvent=a,t.dispatchEvent(s),c=d?d.call(u,s,a):c}function Kt(t){t.draggable=!1}function Wt(){Ot=!1}function zt(t){return setTimeout(t,0)}function Gt(t){return clearTimeout(t)}Ht.prototype={constructor:Ht,_isOutsideThisEl:function(t){this.el.contains(t)||t===this.el||(bt=null)},_getDirection:function(t,e){return"function"==typeof this.options.direction?this.options.direction.call(this,t,e,$):this.options.direction},_onTapStart:function(e){if(e.cancelable){var n=this,o=this.el,t=this.options,i=t.preventOnFilter,r=e.type,a=e.touches&&e.touches[0]||e.pointerType&&"touch"===e.pointerType&&e,l=(a||e).target,s=e.target.shadowRoot&&(e.path&&e.path[0]||e.composedPath&&e.composedPath()[0])||l,c=t.filter;if(!function(t){Mt.length=0;var e=t.getElementsByTagName("input"),n=e.length;for(;n--;){var o=e[n];o.checked&&Mt.push(o)}}(o),!$&&!(/mousedown|pointerdown/.test(r)&&0!==e.button||t.disabled)&&!s.isContentEditable&&(this.nativeDraggable||!u||!l||"SELECT"!==l.tagName.toUpperCase())&&!((l=P(l,t.draggable,o,!1))&&l.animated||nt===l)){if(rt=j(l),lt=j(l,t.draggable),"function"==typeof c){if(c.call(this,e,l,this))return Z({sortable:n,rootEl:s,name:"filter",targetEl:l,toEl:o,fromEl:o}),q("filter",n,{evt:e}),void(i&&e.preventDefault())}else if(c=c&&c.split(",").some(function(t){if(t=P(s,t.trim(),o,!1))return Z({sortable:n,rootEl:t,name:"filter",targetEl:l,fromEl:o,toEl:o}),q("filter",n,{evt:e}),!0}))return void(i&&e.preventDefault());t.handle&&!P(s,t.handle,o,!1)||this._prepareDragStart(e,a,l)}}},_prepareDragStart:function(t,e,n){var o,i=this,r=i.el,a=i.options,l=r.ownerDocument;n&&!$&&n.parentNode===r&&(o=X(n),tt=r,Q=($=n).parentNode,et=$.nextSibling,nt=n,ct=a.group,dt={target:Ht.dragged=$,clientX:(e||t).clientX,clientY:(e||t).clientY},gt=dt.clientX-o.left,mt=dt.clientY-o.top,this._lastX=(e||t).clientX,this._lastY=(e||t).clientY,$.style["will-change"]="all",o=function(){q("delayEnded",i,{evt:t}),Ht.eventCanceled?i._onDrop():(i._disableDelayedDragEvents(),!c&&i.nativeDraggable&&($.draggable=!0),i._triggerDragStart(t,e),Z({sortable:i,name:"choose",originalEvent:t}),k($,a.chosenClass,!0))},a.ignore.split(",").forEach(function(t){E($,t.trim(),Kt)}),f(l,"dragover",Ft),f(l,"mousemove",Ft),f(l,"touchmove",Ft),a.supportPointer?(f(l,"pointerup",i._onDrop),this.nativeDraggable||f(l,"pointercancel",i._onDrop)):(f(l,"mouseup",i._onDrop),f(l,"touchend",i._onDrop),f(l,"touchcancel",i._onDrop)),c&&this.nativeDraggable&&(this.options.touchStartThreshold=4,$.draggable=!0),q("delayStart",this,{evt:t}),!a.delay||a.delayOnTouchOnly&&!e||this.nativeDraggable&&(w||y)?o():Ht.eventCanceled?this._onDrop():(a.supportPointer?(f(l,"pointerup",i._disableDelayedDrag),f(l,"pointercancel",i._disableDelayedDrag)):(f(l,"mouseup",i._disableDelayedDrag),f(l,"touchend",i._disableDelayedDrag),f(l,"touchcancel",i._disableDelayedDrag)),f(l,"mousemove",i._delayedDragTouchMoveHandler),f(l,"touchmove",i._delayedDragTouchMoveHandler),a.supportPointer&&f(l,"pointermove",i._delayedDragTouchMoveHandler),i._dragStartTimer=setTimeout(o,a.delay)))},_delayedDragTouchMoveHandler:function(t){t=t.touches?t.touches[0]:t;Math.max(Math.abs(t.clientX-this._lastX),Math.abs(t.clientY-this._lastY))>=Math.floor(this.options.touchStartThreshold/(this.nativeDraggable&&window.devicePixelRatio||1))&&this._disableDelayedDrag()},_disableDelayedDrag:function(){$&&Kt($),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},_disableDelayedDragEvents:function(){var t=this.el.ownerDocument;p(t,"mouseup",this._disableDelayedDrag),p(t,"touchend",this._disableDelayedDrag),p(t,"touchcancel",this._disableDelayedDrag),p(t,"pointerup",this._disableDelayedDrag),p(t,"pointercancel",this._disableDelayedDrag),p(t,"mousemove",this._delayedDragTouchMoveHandler),p(t,"touchmove",this._delayedDragTouchMoveHandler),p(t,"pointermove",this._delayedDragTouchMoveHandler)},_triggerDragStart:function(t,e){e=e||"touch"==t.pointerType&&t,!this.nativeDraggable||e?this.options.supportPointer?f(document,"pointermove",this._onTouchMove):f(document,e?"touchmove":"mousemove",this._onTouchMove):(f($,"dragend",this),f(tt,"dragstart",this._onDragStart));try{document.selection?zt(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch(t){}},_dragStarted:function(t,e){var n;Et=!1,tt&&$?(q("dragStarted",this,{evt:e}),this.nativeDraggable&&f(document,"dragover",jt),n=this.options,t||k($,n.dragClass,!1),k($,n.ghostClass,!0),Ht.active=this,t&&this._appendGhost(),Z({sortable:this,name:"start",originalEvent:e})):this._nulling()},_emulateDragOver:function(){if(ht){this._lastX=ht.clientX,this._lastY=ht.clientY,Yt();for(var t=document.elementFromPoint(ht.clientX,ht.clientY),e=t;t&&t.shadowRoot&&(t=t.shadowRoot.elementFromPoint(ht.clientX,ht.clientY))!==e;)e=t;if($.parentNode[K]._isOutsideThisEl(t),e)do{if(e[K])if(e[K]._onDragOver({clientX:ht.clientX,clientY:ht.clientY,target:t,rootEl:e})&&!this.options.dragoverBubble)break}while(e=m(t=e));Bt()}},_onTouchMove:function(t){if(dt){var e=this.options,n=e.fallbackTolerance,o=e.fallbackOffset,i=t.touches?t.touches[0]:t,r=J&&D(J,!0),a=J&&r&&r.a,l=J&&r&&r.d,e=Nt&&Dt&&S(Dt),a=(i.clientX-dt.clientX+o.x)/(a||1)+(e?e[0]-xt[0]:0)/(a||1),l=(i.clientY-dt.clientY+o.y)/(l||1)+(e?e[1]-xt[1]:0)/(l||1);if(!Ht.active&&!Et){if(n&&Math.max(Math.abs(i.clientX-this._lastX),Math.abs(i.clientY-this._lastY))E.right+10||S.clientY>x.bottom&&S.clientX>x.left:S.clientY>E.bottom+10||S.clientX>x.right&&S.clientY>x.top)||m.animated)){if(m&&(t=n,e=r,C=X(B((_=this).el,0,_.options,!0)),_=L(_.el,_.options,J),e?t.clientX<_.left-10||t.clientY { url.pathname.endsWith('.png') || url.pathname.endsWith('.json'); - if (!isStaticAsset || event.request.method !== 'GET') { + if (!isStaticAsset || event.request.method !== 'GET' || !url.protocol.startsWith('http')) { return; } @@ -65,4 +65,4 @@ self.addEventListener('fetch', event => { return caches.match(event.request); }) ); -}); +}); \ No newline at end of file diff --git a/src/core/registry.ts b/src/core/registry.ts index a0f483b..01968bc 100644 --- a/src/core/registry.ts +++ b/src/core/registry.ts @@ -27,14 +27,18 @@ class SourceRegistry { } /** - * Lance les health checks sur toutes les sources en attente (en parallèle) + * Lance les health checks sur toutes les sources enregistrées (en parallèle) * Seules les sources qui passent le check sont dites"active" */ async initialize(): Promise { - console.log(`[Registry] ${this.pending.length} source(s) détectée(s), lancement des health checks...`); + const sourcesToTest = Array.from(this.allRegistered.values()); + console.log(`[Registry] Lancement des health checks sur ${sourcesToTest.length} source(s)...`); + + this.active.clear(); + this.pending = []; const results = await Promise.allSettled( - this.pending.map(async (source) => { + sourcesToTest.map(async (source) => { const healthy = await source.healthCheck(); return { source, healthy }; }) @@ -55,7 +59,6 @@ class SourceRegistry { } } - this.pending = []; const names = this.getAvailableNames(); console.log(`[Registry] ${this.active.size} source(s) active(s): ${names.length ? names.map(n => n.toUpperCase()).join(', ') : 'Aucune'}`); } diff --git a/src/index.ts b/src/index.ts index be7823a..1d64ec7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,4 @@ +import './utils/logger.js'; import express from 'express'; import session from 'express-session'; import connectSessionFileStore from 'session-file-store'; @@ -31,6 +32,11 @@ const PORT = CONFIG.PORT; app.set('view engine', 'ejs'); app.set('views', path.join(process.cwd(), 'views')); +// Inject appVersion in all views +import fs from 'fs'; +const packageJson = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf-8')); +app.locals.appVersion = packageJson.version; + // ========================= MIDDLEWARES SÉCURITÉ ========================= // CORS : désactivé (app self-hosted, pas besoin de cross-origin) @@ -39,12 +45,13 @@ app.set('views', path.join(process.cwd(), 'views')); app.use(helmet({ contentSecurityPolicy: { directives: { - defaultSrc: ["'self'"], - scriptSrc: ["'self'", "'unsafe-inline'"], - styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"], - fontSrc: ["'self'", "https://fonts.gstatic.com"], - imgSrc: ["'self'", "data:", "blob:"], - connectSrc: ["'self'"], + "default-src": ["'self'"], + "script-src": ["'self'", "'unsafe-inline'", "https://cdn.jsdelivr.net"], + "script-src-attr": ["'unsafe-inline'"], + "style-src": ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"], + "font-src": ["'self'", "https://fonts.gstatic.com"], + "img-src": ["'self'", "data:", "blob:", "https://www.google.com", "https://*.gstatic.com"], + "connect-src": ["'self'"], "upgrade-insecure-requests": null, } }, @@ -98,7 +105,7 @@ app.use(express.static(path.join(process.cwd(), 'public'))); app.listen(PORT, async () => { console.log(`\n${'='.repeat(60)}`); - console.log(` Hydr'Hacked — API Server`); + console.log(` Agora — API Server`); console.log(`${'='.repeat(60)}`); console.log(`Serveur API démarré sur http://localhost:${PORT}\n`); diff --git a/src/routes/api.ts b/src/routes/api.ts index 68d4248..19f2221 100644 --- a/src/routes/api.ts +++ b/src/routes/api.ts @@ -6,6 +6,7 @@ import apiLimiter from '../utils/rateLimiter.js'; import authMiddleware, { requireAdmin } from '../utils/authMiddleware.js'; import { sendToJDownloader } from '../utils/jdownloader.js'; import { MediaType, SearchResult } from '../types/source.js'; +import { enrichSearchResults } from '../utils/tmdbEnricher.js'; import { CONFIG } from '../utils/config.js'; import { getAllUsers, createUserWithGeneratedPassword, deleteUser, resetPassword, updateUserPreferences } from '../utils/userStore.js'; @@ -64,7 +65,7 @@ router.post('/api/set-sources', apiLimiter, authMiddleware, async (req, res) => await checkSiteStatus(); } else { // Si seul l'ordre a changé, reconstruire les tendances depuis le cache en mémoire - rebuildTrendingFromCache(); + await rebuildTrendingFromCache(); } res.json({ success: true, activeSources: globalState.activeSources }); @@ -137,13 +138,20 @@ router.post('/api/search', apiLimiter, authMiddleware, async (req, res) => { } return res.status(404).json({ error: "Aucun résultat trouvé." }); } + + allResults = await enrichSearchResults(allResults); + res.json(allResults); } else { // Return grouped results const grouped: Record = {}; - allResultsRaw.forEach(item => { - grouped[item.sourceName] = item.results || { error: item.error! }; - }); + for (const item of allResultsRaw) { + if (item.results) { + grouped[item.sourceName] = await enrichSearchResults(item.results); + } else { + grouped[item.sourceName] = { error: item.error! }; + } + } res.json(grouped); } } catch (error: any) { @@ -174,6 +182,20 @@ const handleSelectContent: express.RequestHandler = async (req, res) => { globalState.isSeries = selection.isSeries; globalState.currentLiens = selection.links; + // Tri des liens selon l'ordre préféré + const { CONFIG } = await import('../utils/config.js'); + const preferredHosters: string[] = CONFIG.PREFERRED_HOSTERS || []; + + selection.links.sort((a: any, b: any) => { + const getIndex = (host: string) => { + if (!host) return 999; + const h = host.toLowerCase(); + const idx = preferredHosters.findIndex(pref => h.includes(pref.toLowerCase()) || pref.toLowerCase().includes(h)); + return idx === -1 ? 999 : idx; + }; + return getIndex(a.host) - getIndex(b.host); + }); + selection.links.forEach((link: any, i: number) => { const key = link.id != null ? String(link.id) : String(i); if (link.url) globalState.directUrlMap[key] = link.url; @@ -207,7 +229,7 @@ router.post('/api/get-link', apiLimiter, authMiddleware, async (req, res) => { console.log(`\n--- Get Link [${activeSource?.name.toUpperCase()}]: ID ${chosenId} pour "${currentTitleName}" (JD: ${useJD}) ---`); try { - let finalLink: string | null = null; + let finalLink: any = null; if (directUrlMap[chosenId]) { finalLink = directUrlMap[chosenId]; @@ -217,6 +239,10 @@ router.post('/api/get-link', apiLimiter, authMiddleware, async (req, res) => { if (!finalLink) throw new Error("Impossible de résoudre le lien."); + if (typeof finalLink === 'object' && finalLink.captcha) { + return res.json({ status: 'challenge', challenge: finalLink }); + } + console.log(`🎉 Lien final: ${finalLink}`); if (useJD) { @@ -248,13 +274,17 @@ router.post('/api/get-links-batch', apiLimiter, authMiddleware, async (req, res) for (const chosenId of chosenIds) { try { - let finalLink: string | null = null; + let finalLink: any = null; if (directUrlMap[String(chosenId)]) { finalLink = directUrlMap[String(chosenId)]; } else if (activeSource?.resolveLink) { finalLink = await activeSource.resolveLink(String(chosenId)); } + if (finalLink && typeof finalLink === 'object' && finalLink.captcha) { + return res.json({ status: 'challenge', challenge: finalLink }); + } + if (finalLink) { results.push(finalLink); if (useJD !== false && useJD !== 'false') { @@ -459,6 +489,95 @@ router.post('/api/admin/users/:id/reset-password', apiLimiter, authMiddleware, r } }); +/** POST /admin/plugins/save — Enregistre la config dynamique des plugins */ +router.post('/api/admin/plugins/save', apiLimiter, authMiddleware, requireAdmin, async (req, res) => { + try { + const { config } = req.body; + if (!config || typeof config !== 'object') { + return res.status(400).json({ error: 'Configuration invalide.' }); + } + + const { configManager } = await import('../utils/config.js'); + for (const [key, value] of Object.entries(config)) { + if (typeof value === 'string') { + const trimmed = value.trim(); + if (trimmed !== '') { + configManager.set(key, trimmed); + } else { + configManager.delete(key); + } + } + } + configManager.save(); + + const { sourceRegistry } = await import('../core/registry.js'); + await sourceRegistry.initialize(); + + const { globalState } = await import('../utils/state.js'); + const availableSources = sourceRegistry.getAvailableNames(); + + // Add any newly available sources to globalState.activeSources + for (const s of availableSources) { + if (!globalState.activeSources.includes(s)) { + globalState.activeSources.push(s); + } + } + // Remove any sources that are no longer available + globalState.activeSources = globalState.activeSources.filter(s => availableSources.includes(s)); + + const { clearTmdbCache } = await import('../utils/tmdbEnricher.js'); + clearTmdbCache(); + + const { checkSiteStatus } = await import('../utils/state.js'); + await checkSiteStatus(); // Re-scrape all sites and update trending + + res.json({ success: true, message: 'Configuration enregistrée et plugins rechargés.', activeSources: availableSources }); + } catch (e: any) { + console.error('[API] Erreur save plugins:', e.message); + res.status(500).json({ error: "Erreur interne lors de l'enregistrement de la configuration." }); + } +}); + +/** POST /admin/plugins/test — Teste et recharge les plugins */ +router.post('/api/admin/plugins/test', apiLimiter, authMiddleware, requireAdmin, async (req, res) => { + try { + const { sourceRegistry } = await import('../core/registry.js'); + await sourceRegistry.initialize(); + + const { globalState } = await import('../utils/state.js'); + const active = sourceRegistry.getAvailableNames(); + + for (const s of active) { + if (!globalState.activeSources.includes(s)) globalState.activeSources.push(s); + } + globalState.activeSources = globalState.activeSources.filter(s => active.includes(s)); + + res.json({ success: true, activeSources: active }); + } catch (e: any) { + console.error('[API] Erreur test plugins:', e.message); + res.status(500).json({ error: "Erreur interne lors du test des plugins." }); + } +}); + +/** POST /admin/hosters/save — Enregistre l'ordre des hébergeurs préférés */ +router.post('/api/admin/hosters/save', apiLimiter, authMiddleware, requireAdmin, async (req, res) => { + try { + const { preferredHosters } = req.body; + if (!Array.isArray(preferredHosters)) { + return res.status(400).json({ error: 'Format invalide.' }); + } + + const { configManager } = await import('../utils/config.js'); + configManager.set('PREFERRED_HOSTERS', preferredHosters); + configManager.save(); + + res.json({ success: true, message: 'Ordre enregistré.' }); + } catch (e: any) { + console.error('[API] Erreur save hosters:', e.message); + res.status(500).json({ error: "Erreur interne lors de l'enregistrement de l'ordre." }); + } +}); + // ============================================================ // PREFERENCES // ============================================================ @@ -484,4 +603,35 @@ router.post('/api/preferences', apiLimiter, authMiddleware, (req, res) => { } }); + +/** GET /admin/check-update — Vérifie les mises à jour depuis l'API publique */ +router.get('/api/admin/check-update', apiLimiter, authMiddleware, requireAdmin, async (req, res) => { + try { + const { CONFIG } = await import('../utils/config.js'); + const updateUrl = 'https://agora.nolhantirer.space/api/public/version'; + + // Pour éviter de crasher si l'URL n'existe pas, on met un timeout court. + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), 5000); + + try { + const response = await fetch(updateUrl, { signal: controller.signal }); + clearTimeout(timeoutId); + + if (response.ok) { + const data = await response.json(); + res.json({ success: true, currentVersion: req.app.locals.appVersion, latestVersion: data.version, notes: data.notes, updateInfo: data }); + } else { + res.status(502).json({ error: 'Serveur de mise à jour injoignable (Erreur HTTP ' + response.status + ').' }); + } + } catch (fetchErr) { + clearTimeout(timeoutId); + res.status(502).json({ error: 'Serveur de mise à jour injoignable ou hors ligne.' }); + } + } catch (e: any) { + console.error('[API] Erreur check update:', e.message); + res.status(500).json({ error: "Erreur inattendue lors de la vérification de la mise à jour." }); + } +}); + export default router; \ No newline at end of file diff --git a/src/routes/setup.ts b/src/routes/setup.ts index 8705d71..f073a4a 100644 --- a/src/routes/setup.ts +++ b/src/routes/setup.ts @@ -1,50 +1,51 @@ import express from 'express'; +import fs from 'fs'; +import path from 'path'; +import { fileURLToPath } from 'url'; import { hasAnyUser, createUser } from '../utils/userStore.js'; +import { configManager, CONFIG, getPluginsToConfigure } from '../utils/config.js'; const router = express.Router(); -// ============================================================ -// GET /setup — Page de création du premier administrateur -// ============================================================ - router.get('/', (req, res) => { - // Sécurité : si des users existent déjà, pas d'accès au setup if (hasAnyUser()) { return res.redirect('/login'); } - - res.render('setup', { error: null }); + const pluginsToConfigure = getPluginsToConfigure(); + res.render('setup', { error: null, pluginsToConfigure }); }); -// ============================================================ -// POST /setup — Création du premier admin -// ============================================================ - router.post('/', (req, res) => { - // Sécurité : si des users existent déjà, bloquer if (hasAnyUser()) { return res.redirect('/login'); } - const { username, password, confirmPassword } = req.body; + const { username, password, confirmPassword, config } = req.body; - // Validation if (!username || !password) { - return res.render('setup', { error: "Tous les champs sont requis." }); + return res.render('setup', { error: "Tous les champs sont requis.", pluginsToConfigure: getPluginsToConfigure() }); } if (password !== confirmPassword) { - return res.render('setup', { error: "Les mots de passe ne correspondent pas." }); + return res.render('setup', { error: "Les mots de passe ne correspondent pas.", pluginsToConfigure: getPluginsToConfigure() }); } try { + if (config) { + for (const [key, value] of Object.entries(config)) { + if (value && typeof value === 'string' && value.trim() !== '') { + configManager.set(key, value.trim()); + } + } + configManager.save(); + } + const { user } = createUser(username, password, 'admin'); - // Connecter automatiquement après setup req.session.regenerate((err) => { if (err) { console.error('[Setup] Erreur session.regenerate:', err); - return res.render('setup', { error: "Erreur interne. Réessayez." }); + return res.render('setup', { error: "Erreur interne. Réessayez.", pluginsToConfigure: getPluginsToConfigure() }); } (req.session as any).user = { @@ -59,7 +60,7 @@ router.post('/', (req, res) => { }); } catch (error: any) { console.error('[Setup] Erreur création admin:', error.message); - res.render('setup', { error: error.message }); + res.render('setup', { error: error.message, pluginsToConfigure: getPluginsToConfigure() }); } }); diff --git a/src/routes/views.ts b/src/routes/views.ts index cf5ed83..d4bd0bf 100644 --- a/src/routes/views.ts +++ b/src/routes/views.ts @@ -65,11 +65,14 @@ router.get('/recent', ...protectedRoute('recent', 'recent')); router.get('/search', ...protectedRoute('search', 'search')); router.get('/downloads', ...protectedRoute('downloads', 'downloads')); router.get('/manual', ...protectedRoute('manual', 'manual')); -router.get('/settings', viewAuthMiddleware, viewRequireAdmin, (req, res) => { +router.get('/settings', viewAuthMiddleware, viewRequireAdmin, async (req, res) => { const session = req.session as any; + const { getPluginsToConfigure, CONFIG } = await import('../utils/config.js'); res.render('settings', { page: 'settings', currentUser: session.user || null, + pluginsToConfigure: getPluginsToConfigure(), + preferredHosters: CONFIG.PREFERRED_HOSTERS }); }); diff --git a/src/utils/config.ts b/src/utils/config.ts index f0849be..e3a3334 100644 --- a/src/utils/config.ts +++ b/src/utils/config.ts @@ -1,41 +1,198 @@ import dotenv from 'dotenv'; +import fs from 'fs'; +import path from 'path'; +import { fileURLToPath } from 'url'; dotenv.config(); -const DEV_SECRET = 'hydracked-secret-key-12345'; +const DEV_SECRET = 'agora-secret-key-12345'; const isProd = process.env.NODE_ENV === 'production'; if (isProd && (!process.env.SECRET || process.env.SECRET === DEV_SECRET)) { throw new Error('[CONFIG] SECRET requis et différent du fallback dev en production.'); } -export const CONFIG = { - // Plugin ZT (par défaut) - ZT_URL: process.env.ZT_URL, - ZTTEAM_URL: process.env.ZTTEAM_URL, - FT_URL: process.env.FT_URL, +const CONFIG_PATH = path.resolve(process.cwd(), 'database', 'config.json'); +const OLD_CONFIG_PATH = path.resolve(process.cwd(), 'config.json'); - // Plugin Hydracker (optionnel) - HYDRACKER_URL: process.env.HYDRACKER_URL || process.env.BASE_URL, - HYDRACKER_API_KEY: process.env.HYDRACKER_API_KEY || process.env.API_KEY, - HYDRACKER_TIMEOUT: parseInt(process.env.HYDRACKER_TIMEOUT || '30000', 10), +export class ConfigurationManager { + private dynamicConfig: Record = {}; - // Local Database (optionnel) - DB_PATH: process.env.DB_PATH || './database/darkiworld.db', + constructor() { + this.load(); + } - // App — Auth bootstrap (optionnel, pour création auto du premier admin) - ADMIN_USERNAME: process.env.ADMIN_USERNAME, - ADMIN_PASSWORD: process.env.ADMIN_PASSWORD, + public load() { + // Migration: si un fichier de config existe à la racine, on le déplace dans database/ pour plus de sécurité + if (fs.existsSync(OLD_CONFIG_PATH) && !fs.existsSync(CONFIG_PATH)) { + try { + const dbDir = path.resolve(process.cwd(), 'database'); + if (!fs.existsSync(dbDir)) fs.mkdirSync(dbDir, { recursive: true }); + fs.copyFileSync(OLD_CONFIG_PATH, CONFIG_PATH); + fs.unlinkSync(OLD_CONFIG_PATH); + console.log('[CONFIG] Migration de config.json vers database/ réussie.'); + } catch (e) { + console.error('[CONFIG] Erreur de migration de config.json', e); + } + } - // App - JD_HOST: process.env.JD_HOST?.trim(), - JD_API_PORT: process.env.JD_API_PORT?.trim(), - PATHS_JD_SERIES: process.env.PATHS_JD_SERIES, - PATHS_JD_FILMS: process.env.PATHS_JD_FILMS, - PATHS_JD_WATCH: process.env.PATHS_JD_WATCH, - JD_CREATE_SUBFOLDER: process.env.JD_CREATE_SUBFOLDER === 'true', - JD_AUTOSTART: process.env.JD_AUTOSTART === 'true', - SECRET: process.env.SECRET || DEV_SECRET, - MIN_MINUTES: parseInt(process.env.MIN_MINUTES || '15', 10), - MAX_MINUTES: parseInt(process.env.MAX_MINUTES || '30', 10), - PORT: parseInt(process.env.PORT || '3067', 10), -}; + if (fs.existsSync(CONFIG_PATH)) { + try { + const data = fs.readFileSync(CONFIG_PATH, 'utf-8'); + this.dynamicConfig = JSON.parse(data); + } catch (e) { + console.error('[CONFIG] Erreur de lecture de database/config.json', e); + } + } + } + + public save() { + try { + const dbDir = path.dirname(CONFIG_PATH); + if (!fs.existsSync(dbDir)) fs.mkdirSync(dbDir, { recursive: true }); + fs.writeFileSync(CONFIG_PATH, JSON.stringify(this.dynamicConfig, null, 2), 'utf-8'); + } catch (e) { + console.error('[CONFIG] Erreur d\'écriture de database/config.json', e); + } + } + + public get(key: string, fallback?: any): any { + if (this.dynamicConfig[key] !== undefined && this.dynamicConfig[key] !== '') { + return this.dynamicConfig[key]; + } + if (process.env[key] !== undefined && process.env[key] !== '') { + return process.env[key]; + } + return fallback; + } + + public set(key: string, value: any) { + this.dynamicConfig[key] = value; + } + + public delete(key: string) { + delete this.dynamicConfig[key]; + } + + public getAllPluginsConfig(): Record { + // Renvoie tout sauf les variables systèmes pour l'UI + const exclude = ['PORT', 'SECRET', 'ADMIN_USERNAME', 'ADMIN_PASSWORD']; + const result: Record = {}; + for (const [k, v] of Object.entries(this.dynamicConfig)) { + if (!exclude.includes(k)) { + result[k] = v; + } + } + return result; + } +} + +export const configManager = new ConfigurationManager(); + +export const CONFIG = new Proxy({}, { + get: (target, prop) => { + if (typeof prop !== 'string') return undefined; + + switch(prop) { + case 'HYDRACKER_URL': return configManager.get('HYDRACKER_URL', process.env.BASE_URL || ''); + case 'HYDRACKER_API_KEY': return configManager.get('HYDRACKER_API_KEY', process.env.API_KEY || ''); + case 'HYDRACKER_TIMEOUT': return parseInt(configManager.get('HYDRACKER_TIMEOUT', '30000'), 10); + case 'TMDB_ENABLED': return String(configManager.get('TMDB_ENABLED', 'false')) === 'true'; + case 'TMDB_API_KEY': return configManager.get('TMDB_API_KEY', ''); + + case 'ZT_URL': return configManager.get('ZT_URL', ''); + case 'ZTTEAM_URL': return configManager.get('ZTTEAM_URL', ''); + case 'FT_URL': return configManager.get('FT_URL', ''); + + case 'FS24_URL': return configManager.get('FS24_URL', ''); + case 'FS24_USERNAME': return configManager.get('FS24_USERNAME', ''); + case 'FS24_PASSWORD': return configManager.get('FS24_PASSWORD', ''); + + case 'MOVIX_URL': return configManager.get('MOVIX_URL', ''); + + case 'FLIXART_URL': return configManager.get('FLIXART_URL', ''); + case 'FLIXART_USERNAME': return configManager.get('FLIXART_USERNAME', ''); + case 'FLIXART_PASSWORD': return configManager.get('FLIXART_PASSWORD', ''); + + case 'LOADIX_URL': return configManager.get('LOADIX_URL', ''); + + case 'DB_PATH': return configManager.get('DB_PATH', './database/darkiworld.db'); + + case 'JD_HOST': return configManager.get('JD_HOST')?.trim(); + case 'JD_API_PORT': return String(configManager.get('JD_API_PORT') || '').trim() || undefined; + case 'JD_CREATE_SUBFOLDER': return String(configManager.get('JD_CREATE_SUBFOLDER')) === 'true'; + case 'JD_AUTOSTART': return String(configManager.get('JD_AUTOSTART')) === 'true'; + case 'JD_FORCED_START': return String(configManager.get('JD_FORCED_START')) === 'true'; + + case 'SECRET': return configManager.get('SECRET', DEV_SECRET); + case 'MIN_MINUTES': return parseInt(configManager.get('MIN_MINUTES', '15'), 10); + case 'MAX_MINUTES': return parseInt(configManager.get('MAX_MINUTES', '30'), 10); + case 'PORT': return parseInt(configManager.get('PORT', '3067'), 10); + + case 'PREFERRED_HOSTERS': { + const val = configManager.get('PREFERRED_HOSTERS'); + if (Array.isArray(val)) return val.filter(h => h.toLowerCase() !== 'uptobox'); + if (typeof val === 'string') return val.split(',').map(s => s.trim()).filter(h => h.toLowerCase() !== 'uptobox'); + return ['1fichier', 'turbobit', 'rapidgator', 'nitroflare', 'ddownload', 'mega', 'gofile', 'pixeldrain']; + } + case 'MAX_RESULTS_PER_SOURCE': return parseInt(configManager.get('MAX_RESULTS_PER_SOURCE', '20'), 10); + default: return configManager.get(prop); + } + } +}) as any; + +export function getPluginsToConfigure() { + const __filename = fileURLToPath(import.meta.url); + const __dirname = path.dirname(__filename); + const pluginsDir = path.join(__dirname, '../../plugins'); + let detected: string[] = []; + if (fs.existsSync(pluginsDir)) { + detected = fs.readdirSync(pluginsDir, { withFileTypes: true }) + .filter(d => d.isDirectory()) + .map(d => d.name); + } + + const pluginConfigMap: Record = { + 'ZT': [{ key: 'ZT_URL', label: 'Zone-Téléchargement URL', placeholder: 'https://...', default: CONFIG.ZT_URL }], + 'ztnews': [{ key: 'ZTTEAM_URL', label: 'ZT (Team) URL', placeholder: 'https://...', default: CONFIG.ZTTEAM_URL }], + 'freetelecharger': [{ key: 'FT_URL', label: 'Free-Télécharger URL', placeholder: 'https://...', default: CONFIG.FT_URL }], + 'fs24': [ + { key: 'FS24_URL', label: 'FS24 URL', placeholder: 'https://...', default: CONFIG.FS24_URL }, + { key: 'FS24_USERNAME', label: 'FS24 Identifiant', placeholder: 'Nom d\'utilisateur...', default: CONFIG.FS24_USERNAME }, + { key: 'FS24_PASSWORD', label: 'FS24 Mot de passe', placeholder: 'Mot de passe...', default: CONFIG.FS24_PASSWORD } + ], + 'movix': [ + { key: 'MOVIX_URL', label: 'Movix URL', placeholder: 'https://...', default: CONFIG.MOVIX_URL } + ], + 'flixart': [ + { key: 'FLIXART_URL', label: 'FlixArt URL', placeholder: 'https://...', default: CONFIG.FLIXART_URL }, + { key: 'FLIXART_USERNAME', label: 'FlixArt Identifiant', placeholder: 'Nom d\'utilisateur...', default: CONFIG.FLIXART_USERNAME }, + { key: 'FLIXART_PASSWORD', label: 'FlixArt Mot de passe', placeholder: 'Mot de passe...', default: CONFIG.FLIXART_PASSWORD } + ], + 'loadix': [ + { key: 'LOADIX_URL', label: 'Loadix API URL', placeholder: 'https://...', default: CONFIG.LOADIX_URL } + ] + }; + + const configs = detected.filter(p => pluginConfigMap[p]).map(p => ({ + name: p, + fields: pluginConfigMap[p] + })); + + configs.push({ + name: 'Paramètres Généraux', + fields: [ + { key: 'MAX_RESULTS_PER_SOURCE', label: 'Limite de résultats par source (Tendances/Récents)', placeholder: 'ex: 20', default: String(CONFIG.MAX_RESULTS_PER_SOURCE) }, + { key: 'JD_FORCED_START', label: 'JDownloader : Démarrage Forcé (ignore la file d\'attente)', placeholder: 'true ou false', default: String(CONFIG.JD_FORCED_START === true) } + ] + }); + + configs.push({ + name: 'TMDB (Enrichissement Auto)', + fields: [ + { key: 'TMDB_ENABLED', label: 'Activer TMDB', placeholder: 'true ou false', default: String(CONFIG.TMDB_ENABLED === true) }, + { key: 'TMDB_API_KEY', label: 'Clé API TMDB (v3 auth)', placeholder: 'Clé API...', default: CONFIG.TMDB_API_KEY } + ] + }); + + return configs; +} diff --git a/src/utils/jdownloader.ts b/src/utils/jdownloader.ts index 1d0eb82..56b78fa 100644 --- a/src/utils/jdownloader.ts +++ b/src/utils/jdownloader.ts @@ -24,10 +24,11 @@ export async function sendToJDownloader(link: string, titleName: string, isSerie const safeLink = link.trim() + "#movie.mkv"; const autoStartStr = CONFIG.JD_AUTOSTART ? 'TRUE' : 'FALSE'; + const forcedStartStr = CONFIG.JD_FORCED_START ? 'TRUE' : 'FALSE'; let fileContent = `text=${safeLink}${lineEnding}`; fileContent += `enabled=TRUE${lineEnding}`; fileContent += `autoStart=${autoStartStr}${lineEnding}`; - fileContent += `forcedStart=${autoStartStr}${lineEnding}`; + fileContent += `forcedStart=${forcedStartStr}${lineEnding}`; fileContent += `deepAnalyse=TRUE${lineEnding}`; fileContent += `autoConfirm=TRUE${lineEnding}`; fileContent += `overwritePackagizerEnabled=TRUE${lineEnding}`; diff --git a/src/utils/logger.ts b/src/utils/logger.ts new file mode 100644 index 0000000..7dab09f --- /dev/null +++ b/src/utils/logger.ts @@ -0,0 +1,19 @@ +const originalLog = console.log; +const originalError = console.error; +const originalWarn = console.warn; + +function getTimestamp() { + return new Date().toISOString().replace('T', ' ').substring(0, 19); +} + +console.log = (...args) => { + originalLog(`[${getTimestamp()}]`, ...args); +}; + +console.error = (...args) => { + originalError(`[${getTimestamp()}]`, ...args); +}; + +console.warn = (...args) => { + originalWarn(`[${getTimestamp()}]`, ...args); +}; diff --git a/src/utils/state.ts b/src/utils/state.ts index e113201..71bba3a 100644 --- a/src/utils/state.ts +++ b/src/utils/state.ts @@ -1,5 +1,8 @@ import { sourceRegistry } from '../core/registry.js'; import { ISource, SearchResult } from '../types/source.js'; +import { loadSettings } from './settingsManager.js'; +import { enrichSearchResults } from './tmdbEnricher.js'; +import { CONFIG } from './config.js'; export interface GlobalState { currentTitleId: string | null; @@ -71,9 +74,10 @@ export async function checkSiteStatus() { try { const results = await Promise.allSettled(sources.map(async (source) => { - const films = await source.getTrending('movie'); - const series = await source.getTrending('series'); - const recent = source.getRecent ? await source.getRecent() : []; + const limit = CONFIG.MAX_RESULTS_PER_SOURCE; + const films = (await source.getTrending('movie')).slice(0, limit); + const series = (await source.getTrending('series')).slice(0, limit); + const recent = (source.getRecent ? await source.getRecent() : []).slice(0, limit); return { source, films, series, recent }; })); @@ -100,6 +104,7 @@ export async function checkSiteStatus() { const seen = new Set(); const unique: SearchResult[] = []; for (const item of items) { + if (!item.title) continue; const key = item.title.toLowerCase().replace(/[^a-z0-9]/g, ''); if (!seen.has(key)) { seen.add(key); @@ -109,9 +114,9 @@ export async function checkSiteStatus() { return unique; }; - globalState.trendingFilms = deduplicate(allFilms); - globalState.trendingSeries = deduplicate(allSeries); - globalState.recentItems = deduplicate(allRecent); + globalState.trendingFilms = await enrichSearchResults(deduplicate(allFilms)); + globalState.trendingSeries = await enrichSearchResults(deduplicate(allSeries)); + globalState.recentItems = await enrichSearchResults(deduplicate(allRecent)); if (onlineSourcesCount > 0) { globalState.isSiteOffline = false; @@ -139,7 +144,7 @@ const sourceTrendsCache = new Map(); const unique: SearchResult[] = []; for (const item of items) { + if (!item.title) continue; const key = item.title.toLowerCase().replace(/[^a-z0-9]/g, ''); if (!seen.has(key)) { seen.add(key); @@ -167,8 +173,8 @@ export function rebuildTrendingFromCache() { return unique; }; - globalState.trendingFilms = deduplicate(allFilms); - globalState.trendingSeries = deduplicate(allSeries); - globalState.recentItems = deduplicate(allRecent); + globalState.trendingFilms = await enrichSearchResults(deduplicate(allFilms)); + globalState.trendingSeries = await enrichSearchResults(deduplicate(allSeries)); + globalState.recentItems = await enrichSearchResults(deduplicate(allRecent)); console.log(`[Cache] Tendances reconstruites en mémoire pour ${sources.length} sources actives.`); } diff --git a/src/utils/tmdbEnricher.ts b/src/utils/tmdbEnricher.ts new file mode 100644 index 0000000..364a5e9 --- /dev/null +++ b/src/utils/tmdbEnricher.ts @@ -0,0 +1,129 @@ +import { SearchResult } from '../types/source.js'; +import { CONFIG } from './config.js'; + +// Cache (CleanTitle+Type => TmdbData) +interface TmdbData { + year: string | null; + title: string; + image: string | null; +} + +const tmdbCache = new Map(); +const MAX_CACHE_SIZE = 500; + +function enforceCacheLimit() { + if (tmdbCache.size > MAX_CACHE_SIZE) { + let i = 0; + for (const key of tmdbCache.keys()) { + tmdbCache.delete(key); + if (++i > 50) break; // Remove oldest 50 + } + } +} + +export function clearTmdbCache() { + tmdbCache.clear(); + console.log("[TMDB] Cache réinitialisé."); +} + +export function cleanTitle(title: string): string { + // Décode les entités HTML fréquentes + let clean = title.replace(/'|'/g, "'") + .replace(/"/g, '"') + .replace(/&/g, '&') + .replace(/</g, '<') + .replace(/>/g, '>'); + + clean = clean.replace(/\b(saison|season)\s*\d+.*$/i, ''); + clean = clean.replace(/\b(complete|french|truefrench|vostfr|multi|web-dl|1080p|720p|4k|x265|x264|bluray|bdrip)\b/gi, ''); + clean = clean.replace(/,\s*le film\b/i, ''); + clean = clean.replace(/[-_\[\]\(\):]/g, ' '); + clean = clean.replace(/\s{2,}/g, ' '); + return clean.trim(); +} + +async function fetchTmdbData(title: string, type: string): Promise { + if (!CONFIG.TMDB_ENABLED || !CONFIG.TMDB_API_KEY) return null; + + const clean = cleanTitle(title); + if (!clean) return null; + + const searchType = (type === 'series' || type === 'serie' || type === 'anime') ? 'tv' : 'movie'; + const cacheKey = `${searchType}:${clean.toLowerCase()}`; + + if (tmdbCache.has(cacheKey)) { + return tmdbCache.get(cacheKey)!; + } + + try { + console.log(`[TMDB] Recherche API: Type "${searchType}", Requête "${clean}" (Original: "${title}")`); + const url = `https://api.themoviedb.org/3/search/${searchType}?api_key=${CONFIG.TMDB_API_KEY}&query=${encodeURIComponent(clean)}&language=fr-FR&page=1`; + const res = await fetch(url, { signal: AbortSignal.timeout(3000) }); + if (!res.ok) { + console.error(`[TMDB] Erreur HTTP ${res.status} pour "${clean}"`); + return null; + } + const data = await res.json(); + let resultData: TmdbData | null = null; + + if (data.results && data.results.length > 0) { + const first = data.results[0]; + const dateStr = searchType === 'tv' ? first.first_air_date : first.release_date; + const year = (dateStr && typeof dateStr === 'string') ? dateStr.substring(0, 4) : null; + const tmdbTitle = searchType === 'tv' ? first.name : first.title; + const image = first.poster_path ? `https://image.tmdb.org/t/p/w300${first.poster_path}` : null; + + resultData = { year, title: tmdbTitle, image }; + console.log(`[TMDB] ✅ Trouvé "${clean}" -> ${tmdbTitle} (${year || 'N/A'})`); + } else { + console.log(`[TMDB] ❌ Aucun résultat pour "${clean}" en tant que ${searchType}.`); + // Fallback: search as the opposite type + const fallbackType = searchType === 'movie' ? 'tv' : 'movie'; + console.log(`[TMDB] 🔄 Fallback: recherche "${clean}" en tant que ${fallbackType}...`); + const fallbackUrl = `https://api.themoviedb.org/3/search/${fallbackType}?api_key=${CONFIG.TMDB_API_KEY}&query=${encodeURIComponent(clean)}&language=fr-FR&page=1`; + const fbRes = await fetch(fallbackUrl, { signal: AbortSignal.timeout(3000) }); + if (fbRes.ok) { + const fbData = await fbRes.json(); + if (fbData.results && fbData.results.length > 0) { + const first = fbData.results[0]; + const dateStr = fallbackType === 'tv' ? first.first_air_date : first.release_date; + const year = (dateStr && typeof dateStr === 'string') ? dateStr.substring(0, 4) : null; + const tmdbTitle = fallbackType === 'tv' ? first.name : first.title; + const image = first.poster_path ? `https://image.tmdb.org/t/p/w300${first.poster_path}` : null; + + resultData = { year, title: tmdbTitle, image }; + console.log(`[TMDB] ✅ Trouvé (Fallback) "${clean}" -> ${tmdbTitle} (${year || 'N/A'})`); + } + } + } + + enforceCacheLimit(); + tmdbCache.set(cacheKey, resultData); + return resultData; + } catch (e) { + console.error(`[TMDB] ❌ Erreur recherche pour "${clean}":`, (e as Error).message); + return null; + } +} + +export async function enrichSearchResults(results: SearchResult[]): Promise { + if (!CONFIG.TMDB_ENABLED || !CONFIG.TMDB_API_KEY) return results; + + const enrichmentPromises = results.map(async (r) => { + // We now enrich ALWAYS, not just when !r.year, so ZT benefits from it. + const tmdbData = await fetchTmdbData(r.title, r.type || 'movie'); + if (tmdbData) { + if (tmdbData.year) r.year = tmdbData.year; + if (tmdbData.image) r.image = tmdbData.image; + // Clean up original title by removing the HTML entities if TMDB didn't return a title + r.title = tmdbData.title || cleanTitle(r.title); + } else { + // Still decode HTML entities if TMDB fails + r.title = cleanTitle(r.title); + } + return r; + }); + + await Promise.allSettled(enrichmentPromises); + return results; +} diff --git a/test_flixart.ts b/test_flixart.ts new file mode 100644 index 0000000..14764d0 --- /dev/null +++ b/test_flixart.ts @@ -0,0 +1,12 @@ +import { FlixArtAuth } from './plugins/flixart/auth.js'; +import { CONFIG } from './src/utils/config.js'; + +(async () => { + try { + console.log('Testing FlixArt Auth...'); + const cookie = await FlixArtAuth.getCookie(true); + console.log('Cookie:', cookie); + } catch (e) { + console.error(e); + } +})(); diff --git a/views/login.ejs b/views/login.ejs index 056bcec..dd8b00d 100644 --- a/views/login.ejs +++ b/views/login.ejs @@ -3,14 +3,14 @@ - Hydr'Hacked — Connexion + Agora — Connexion - + @@ -25,14 +25,15 @@ font-weight: 600; } +
+
+ + + +
+
diff --git a/views/settings.ejs b/views/settings.ejs index 1dd3baa..07c8898 100644 --- a/views/settings.ejs +++ b/views/settings.ejs @@ -1,4 +1,5 @@ <%- include('partials/header') %> + <%- include('partials/sidebar') %>
@@ -7,6 +8,25 @@

Paramètres

+ <% if (typeof currentUser !== 'undefined' && currentUser && currentUser.role === 'admin') { %> +
+

+ Système & Mises à jour + v<%= appVersion %> +

+

+ Vérifiez si une nouvelle version d'Agora est disponible et consultez les instructions de mise à jour. +

+ + + +
+ <% } %> +

Sources de Recherche @@ -26,14 +46,113 @@
- -

+ <% if (typeof currentUser !== 'undefined' && currentUser && currentUser.role === 'admin') { %> +
+

+ Hébergeurs Préférés +

+

+ Glissez et déposez les hébergeurs pour définir leur ordre de préférence. Les liens de téléchargement seront triés selon cet ordre. +

+
+ <% if (typeof preferredHosters !== 'undefined' && preferredHosters.length > 0) { %> + <% preferredHosters.forEach(function(hoster) { + const h = hoster.toLowerCase(); + let domain = h + '.com'; + if (h === 'turbobit') domain = 'turbobit.net'; + if (h === 'rapidgator') domain = 'rapidgator.net'; + if (h === 'mega') domain = 'mega.nz'; + if (h === 'gofile') domain = 'gofile.io'; + if (h === 'nitroflare') domain = 'nitroflare.com'; + %> +
+
+ + logo + + <%= hoster %> +
+
+ <% }); %> + <% } %> +
+
+ +
+
+ +
+

+ Configuration des Plugins +

+

+ Modifiez les adresses et clés d'accès des plugins. Les modifications seront appliquées immédiatement sans redémarrage. +

+ + + <% if (typeof pluginsToConfigure !== 'undefined' && pluginsToConfigure.length > 0) { %> + <% pluginsToConfigure.forEach(function(plugin) { %> +
+ + + <%= plugin.name %> + + <% + const urlField = plugin.fields.find(f => f.key.endsWith('_URL')); + const urlEmpty = urlField && !urlField.default; + %> + + <% if (plugin.name.includes('TMDB')) { %> +

+ + Pour obtenir une clé d'API, créez un compte gratuit sur themoviedb.org, générez une clé (API v3 Auth) et collez-la ci-dessous. +

+ <% plugin.fields.forEach(function(field) { %> +
+ + <% if (field.key.endsWith('_ENABLED') || field.key === 'JD_FORCED_START') { %> + + <% } else { %> + + <% } %> +
+ <% }); %> + <% } else { %> + <% plugin.fields.forEach(function(field) { %> +
+ + +
+ <% }); %> + <% } %> +
+ <% }); %> +
+ +
+ <% } else { %> +

Aucun plugin détecté.

+ <% } %> + +
+ <% } %> +

Page d'accueil par défaut

@@ -118,10 +237,173 @@

- Hydr'Hacked v1.4.8 + Agora v<%= appVersion %>

+ +

diff --git a/views/setup.ejs b/views/setup.ejs index 5bc77da..35499c7 100644 --- a/views/setup.ejs +++ b/views/setup.ejs @@ -3,14 +3,14 @@ - Hydr'Hacked — Installation + Agora — Installation - + @@ -22,10 +22,11 @@ min-height: 100vh; width: 100%; display: flex; - align-items: center; + align-items: flex-start; justify-content: center; - padding: 2rem; + padding: 2rem 1rem; background: var(--bg-main); + overflow-y: auto; } .setup-box { background: var(--bg-card); @@ -33,8 +34,9 @@ border-radius: 16px; padding: 2.5rem; width: 100%; - max-width: 420px; + max-width: 480px; box-shadow: 0 8px 32px rgba(0,0,0,0.4); + margin: auto; } .setup-logo { text-align: center; @@ -127,13 +129,14 @@ font-weight: 500; } +
@@ -190,11 +193,41 @@
+ + <% if (typeof pluginsToConfigure !== 'undefined' && pluginsToConfigure.length > 0) { %> +
+

+ + Configuration des Plugins (Optionnel) +

+

+ Des sources ont été détectées. Vous pouvez les configurer maintenant ou plus tard dans les paramètres. +

+ + <% pluginsToConfigure.forEach(function(plugin) { %> +
+ + + <%= plugin.name %> + + <% plugin.fields.forEach(function(field) { %> +
+ + +
+ <% }); %> +
+ <% }); %> +
+ <% } %> +

- Hydr'Hacked v1.4.8 + Agora v<%= appVersion %>