Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
27c31839e1 | ||
|
|
b7e401c941 | ||
|
|
8325af2b01 | ||
|
|
cbf72df09a | ||
|
|
adab24ca61 | ||
|
|
231a1f2599 | ||
|
|
e07a887c34 | ||
|
|
4c370cc728 | ||
|
|
aadf30bb07 | ||
|
|
b4cd2dc855 | ||
|
|
5fccc71326 | ||
|
|
f7379c67df | ||
|
|
ba90ba3675 | ||
|
|
c793411595 | ||
|
|
6191b32bf7 | ||
|
|
70ce0b95a8 | ||
|
|
078905e944 | ||
|
|
39319b7caa | ||
|
|
10830f3562 | ||
|
|
87fd6b39fd | ||
|
|
acc1609b4d | ||
|
|
8e76fb7112 | ||
|
|
c7344f8988 | ||
|
|
3a75527135 | ||
|
|
23132c6219 | ||
|
|
514f417c15 | ||
|
|
e8bbbc7d1e | ||
|
|
95e5ead67a | ||
|
|
76dbd7e425 | ||
|
|
f0b5f2b21e |
No files matched your search
@@ -9,3 +9,5 @@ config/
|
||||
web/node_modules/
|
||||
web/dist/
|
||||
*.tsbuildinfo
|
||||
web/.e2e-results/
|
||||
web/.e2e-report/
|
||||
@@ -84,6 +84,36 @@ web:test:
|
||||
paths:
|
||||
- .npm-cache
|
||||
|
||||
|
||||
# Tests fonctionnels Playwright: le vrai front (web/dist du job web:build)
|
||||
# contre l'API reelle en mode simulation (scripts/e2e_server.py), serveur
|
||||
# isole avec donnees semees.
|
||||
web:e2e:
|
||||
stage: test
|
||||
image: node:22-bookworm
|
||||
needs:
|
||||
- job: web:build
|
||||
artifacts: true
|
||||
script:
|
||||
- curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
- export PATH="$HOME/.local/bin:$PATH"
|
||||
- uv sync --frozen
|
||||
- npm --prefix web ci
|
||||
- npx --prefix web playwright install --with-deps chromium
|
||||
- npm --prefix web run test:e2e
|
||||
artifacts:
|
||||
when: always
|
||||
paths:
|
||||
- web/.e2e-report
|
||||
- web/.e2e-results
|
||||
expire_in: 3 days
|
||||
cache:
|
||||
- key:
|
||||
files:
|
||||
- web/package-lock.json
|
||||
paths:
|
||||
- .npm-cache
|
||||
|
||||
# --- Release (pipeline de tag, ex. v1.2.3) ---
|
||||
# Kaniko : build sans daemon Docker, compatible runner non privilegie.
|
||||
# - Si le Container Registry est actif (CI_REGISTRY_IMAGE defini) : push de
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
# DOCUMENTATION
|
||||
|
||||
Documentation fonctionnelle du projet : chaque méthode et chaque endpoint,
|
||||
avec ce qu'elle fait et quand elle intervient. Le HOW-TO général (déploiement,
|
||||
activation MakeMKV, migrations) est dans `README.md` et `IMAGE.md`.
|
||||
|
||||
- **Section APP** — logique Python (backend) : modules, méthodes, endpoints.
|
||||
- **Section WEB** — logique TypeScript (frontend) : fonctions, composants,
|
||||
tests fonctionnels.
|
||||
|
||||
---
|
||||
|
||||
## Section APP — logique Python
|
||||
|
||||
### `app/config.py` — configuration d'exécution
|
||||
|
||||
| Élément | Fonctionnalité |
|
||||
| --- | --- |
|
||||
| `AppSettings` | Charge la configuration depuis l'environnement (préfixe `MKVTOOL_`, fichier `.env`) : dossiers (config, films, téléchargements), `radarr_films_dir` (chemins tels que Radarr les rapporte, traduits vers `films_dir`), `simulate_conversion` (faux MKV au lieu d'appeler MakeMKV), `worker_interval` (période du worker). |
|
||||
| `AppSettings.resolved_database_url` | URL SQLAlchemy effective : variable `database_url` si fournie, sinon SQLite dans `config_dir/mkvtool.db`. |
|
||||
| `settings` | Instance unique lue par tous les modules. |
|
||||
|
||||
### `app/database.py` — accès à la base
|
||||
|
||||
| Élément | Fonctionnalité |
|
||||
| --- | --- |
|
||||
| `engine` | Moteur SQLAlchemy (SQLite avec `check_same_thread=False`). |
|
||||
| `SessionLocal` | Fabrique de sessions (expire_on_commit désactivé). |
|
||||
| `Base` | Base déclarative commune aux modèles. |
|
||||
| `get_db` | Dépendance FastAPI : ouvre une session par requête et la ferme. |
|
||||
|
||||
### `app/models.py` — modèles SQLAlchemy
|
||||
|
||||
| Élément | Fonctionnalité |
|
||||
| --- | --- |
|
||||
| `IsoMovie` | Un film ISO suivi par MKVTool : identifiants Radarr (`radarr_movie_id`, `radarr_movie_file_id`, uniques ensemble), titre, année, chemin du fichier (référentiel Radarr), taille, statut (`detected → ready/queued → converting → importing → validating → completed`, `failed`), drapeau `radarr_linked` (le fichier existe toujours côté Radarr), affiche, horodatages (`last_seen_at`, `created_at`, `processed_at`, `completed_at`), `failed_step` et `last_error` en cas d'échec. |
|
||||
| `User` | Compte local : nom unique, hash PBKDF2 du mot de passe, date de création. |
|
||||
| `ApplicationSetting` | Table générique clé/valeur (réservée). |
|
||||
|
||||
### `app/conf_store.py` — configuration des services (conf.json)
|
||||
|
||||
| Élément | Fonctionnalité |
|
||||
| --- | --- |
|
||||
| `TestState` | Résultat du dernier test de connexion : date, succès, version détectée, erreur. |
|
||||
| `ApiServiceConfig` | Connexion d'un service à clé API : URL, port optionnel, clé, état de test. Utilisé pour Radarr. |
|
||||
| `QbittorrentConfig` | Connexion qBittorrent : URL, port, identifiants optionnels, clé API (≥ 5.2), état de test. |
|
||||
| `AppConfig` | Racine de `conf.json` : `version` (structure du fichier, migrée au démarrage) + les deux services. |
|
||||
| `build_base_url` | Normalise une adresse (schéma déduit, port séparé appliqué si l'URL n'en porte pas). |
|
||||
| `config_path` | Chemin de `conf.json` (`config_dir/conf.json`). |
|
||||
| `read_raw_config` | Contenu brut du fichier (dict) pour les migrations ; `None` si absent ou non-dict. |
|
||||
| `read_config` | Valide le fichier en `AppConfig` ; valeurs par défaut si absent/invalide. |
|
||||
| `write_raw_config` | Écriture atomique (fichier temporaire + `os.replace`). |
|
||||
| `write_config` | Sérialise un `AppConfig` via l'écriture atomique. |
|
||||
| `service_configured` | Un service est configuré quand son URL (et sa clé pour les services à clé) est renseignée. |
|
||||
| `service_status` | Statut exposé à l'UI : `unconfigured` / `configured` / `tested` / `error`. |
|
||||
| `record_test` | Persiste le résultat d'un test de connexion (succès avec version, ou échec avec erreur). |
|
||||
| `reset_test` | Réinitialise l'état de test quand la configuration change (l'ancien test ne correspond plus). |
|
||||
|
||||
### `app/migrations.py` — migrations versionnées
|
||||
|
||||
| Élément | Fonctionnalité |
|
||||
| --- | --- |
|
||||
| `DbMigration` / `DB_MIGRATIONS` | Liste ordonnée de migrations de base, chacune dans sa transaction, tracée dans `schema_migrations`. v1 : colonnes de suivi des conversions ; v2 : `created_at`/`last_seen_at` sur les bases très anciennes. Une migration doit rester inoffensive sur un schéma à jour (vérification d'existence avant action). |
|
||||
| `run_db_migrations` | Applique les migrations non enregistrées et renvoie leurs descriptions (affichées au démarrage). |
|
||||
| `CONF_MIGRATIONS` | Transformations de `conf.json` par version. v1→v2 : retrait des services hors périmètre (Sonarr, Prowlarr, Jellyfin, Seerr). |
|
||||
| `current_conf_version` | Version courante de la structure (doit rester synchrone avec `AppConfig.version`, un test le vérifie). |
|
||||
| `migrate_conf_file` | Applique les transformations en chaîne au premier lancement, estampille la version dans le fichier. |
|
||||
|
||||
### `app/auth.py` — authentification locale
|
||||
|
||||
| Élément | Fonctionnalité |
|
||||
| --- | --- |
|
||||
| `hash_password` / `verify_password` | Hachage PBKDF2-SHA256 (600 000 itérations, sel aléatoire) et vérification à temps constant. |
|
||||
| `user_count` | Nombre de comptes (0 = premier lancement). |
|
||||
| `bootstrap_setup` | Au premier lancement, génère et affiche en console un lien à jeton à usage unique pour créer le compte ; le jeton est en mémoire (un redémarrage le régénère). |
|
||||
| `create_user` | Crée un compte (409 si le nom existe déjà). |
|
||||
| `check_credentials` | Vérifie les identifiants, renvoie l'id utilisateur ou `None`. |
|
||||
| `create_session` / `end_session` | Sessions en mémoire : jeton → id utilisateur, cookie `mkvtool_session`. |
|
||||
| `current_user` | Dépendance FastAPI : extrait l'utilisateur de la session ou refuse (401). |
|
||||
| `SESSION_COOKIE` | Nom du cookie de session. |
|
||||
|
||||
### `app/radarr.py` — client API Radarr
|
||||
|
||||
| Élément | Fonctionnalité |
|
||||
| --- | --- |
|
||||
| `RadarrClient.__init__` | URL de base + clé API (en-tête `X-Api-Key`). |
|
||||
| `system_status` | `GET /api/v3/system/status` — test de connexion (version). |
|
||||
| `movies` | `GET /api/v3/movie?includeMovieFile=true` — inventaire complet. |
|
||||
| `rescan_movie` | Enfile `RescanMovie` : Radarr rescanne le dossier du film (adopte le MKV lié après validation). |
|
||||
| `rename_movie` | Enfile `RenameMovie` : Radarr renomme le fichier selon sa config Media Management (les commandes s'exécutent dans l'ordre d'envoi ; un renommage préserve l'inode, le lien dur reste intact). |
|
||||
| `movie_file_path` | Extrait le chemin du fichier d'un film (chemin direct ou `relativePath` + dossier). |
|
||||
|
||||
### `app/qbittorrent.py` — client qBittorrent
|
||||
|
||||
| Élément | Fonctionnalité |
|
||||
| --- | --- |
|
||||
| `QbittorrentClient.__init__` | URL WebUI, identifiants optionnels, clé API optionnelle. |
|
||||
| `_request` | Exécute un appel API v2. Authentification par priorité : clé API (`Authorization: Bearer`, sans login), identifiants (login `POST /api/v2/auth/login`, accepte « 200 Ok. » des versions antérieures et « 204 » de ≥ 5.2), ou aucun (bypass IP côté qBittorrent). `Referer` posé pour le CSRF. |
|
||||
| `version` | Version qBittorrent (test de connexion). |
|
||||
| `torrents` | Liste des torrents. |
|
||||
| `delete` | Supprime des torrents (avec ou sans leurs données). |
|
||||
| `match_torrent` | Retrouve le torrent correspondant à un chemin ISO (nom exact, nom sans extension, ou nom du fichier contenu). |
|
||||
|
||||
### `app/converter.py` — conversion et gestion de fichiers
|
||||
|
||||
| Élément | Fonctionnalité |
|
||||
| --- | --- |
|
||||
| `guarded_folder` | Sécurité : refuse toute opération sur un dossier hors de la bibliothèque `films_dir`. |
|
||||
| `sanitize_component` | Nettoie un titre pour un nom de fichier/dossier (caractères interdits, espaces multiples ; « Sans titre » si vide). |
|
||||
| `radarr_to_container_path` | Traduit un chemin Radarr vers son équivalent conteneur (via `radarr_films_dir` → `films_dir`). |
|
||||
| `container_iso_path` | Chemin conteneur de l'ISO d'un film. |
|
||||
| `looks_like_iso` | Un `.iso` est une vraie image disque : écarte tout fichier dont l'en-tête est EBML (MKV renommé) ; fichier illisible → confiance à l'extension. |
|
||||
| `conversion_paths` | Calcule les trois chemins d'une conversion : dossier de travail (`downloads_dir/"Titre Année"`), MKV brut (`"Titre (Année).mkv"` dans le dossier de travail), dossier de destination (le dossier du film côté bibliothèque). |
|
||||
| `workspace_files` / `clear_workspace` | Inventorie / vide le dossier de travail (restes d'anciennes conversions), erreurs traduites. |
|
||||
| `_run_makemkv` | Exécute `makemkvcon` et diffuse sa sortie ligne par ligne (terminal de l'UI). |
|
||||
| `longest_title_id` | Analyse `--robot info` (TINFO durée) et renvoie le titre le plus long — le titre 0 n'est pas forcément le film. |
|
||||
| `extract_mkv` | Extraction MakeMKV : simulation si activée ; choisit le titre le plus long, diffuse la sortie ; traduit les échecs (clé manquante, signal de kill type OOM, code d'erreur). |
|
||||
| `file_error` | Traduit une `OSError` en message français (droits, introuvable, disque plein…) pour la notification. |
|
||||
| `unlink_if_exists` / `rmdir_if_empty` / `_remove_entry` | Suppressions tolérantes : l'absence n'est pas une erreur ; les erreurs de droits remontent traduites. |
|
||||
| `clear_folder` | Vide le dossier du film sauf les chemins conservés (l'ISO jusqu'à la validation). |
|
||||
| `import_mkv` | Prépare le dossier du film, nettoie, pose le lien dur — ou une **copie** si les volumes de travail et de films sont des montages distincts (EXDEV) : jamais de lien symbolique, dont le chemin absolu n'est valide que dans le conteneur MKVTool et casse Jellyfin/Radarr. |
|
||||
| `link_or_copy` | Helper du lien du MKV : lien dur si possible, copie indépendante entre volumes distincts ; retourne `lien` ou `copie` pour le message. |
|
||||
| `finalize_validation` | Supprime l'ISO et le reste du dossier du film, ne garde que le MKV lié. |
|
||||
| `cancel_conversion` | Annulation : supprime le MKV converti et son lien ; tolère les fichiers déjà disparus ; l'ISO reste en place. |
|
||||
|
||||
### `app/worker.py` — worker de conversion
|
||||
|
||||
| Élément | Fonctionnalité |
|
||||
| --- | --- |
|
||||
| `conversion_log` / `is_converting` | Journal de conversion d'un film (diffusé dans l'UI) et film en cours. |
|
||||
| `_log` | Ajoute une ligne au journal (plafonné à 500 lignes). |
|
||||
| `_process` | Traite un film « queued » : extraction MakeMKV (sauf reprise d'un échec à l'import), import du lien, passage en `validating` ; toute erreur passe le film en `failed` avec étape et message, sans tuer le worker. |
|
||||
| `_process_next` / `conversion_worker` | Boucle : traite la file une conversion à la fois, dort `worker_interval` quand vide. |
|
||||
|
||||
### `app/schemas.py` — modèles d'échange (pydantic)
|
||||
|
||||
| Élément | Fonctionnalité |
|
||||
| --- | --- |
|
||||
| `RadarrSettingsRead/Write` | Lecture/écriture de la connexion Radarr (la clé n'est jamais relue, seulement `api_key_configured`). |
|
||||
| `QbittorrentSettingsRead/Write` | Idem qBittorrent, incluant clé API et statut de test. |
|
||||
| `SettingsRead/Write` | Ensemble des connexions (`GET/PUT /api/settings`). |
|
||||
| `ConnectionResult` | Résultat d'un test de connexion (message, version). |
|
||||
| `IsoMovieRead` / `IsoMovieDetailRead` | Ligne d'inventaire ; la fiche détaillée ajoute les chemins calculés (MKV lié, MKV brut) et l'état du dossier de travail. |
|
||||
| `ConversionLogRead` | Journal de conversion (lignes, en cours ou non). |
|
||||
| `BulkRenameFailure/Result` | Résultat du renommage Radarr groupé (succès, échecs détaillés). |
|
||||
| `ScanResult` | Bilan d'un scan : films inspectés, ISO trouvées, créations, mises à jour, chemins de films traités rafraîchis. |
|
||||
| `HealthRead` | État du service : base, MakeMKV disponible et sa version. |
|
||||
| `AuthSetupWrite/CredentialsWrite/UserRead` | Création du premier compte (jeton), connexion, identité. |
|
||||
| `ValidationRead` | Résultat d'une validation : le film + `rescan_warning` (échec Radarr sans invalider la validation). |
|
||||
|
||||
### `app/main.py` — endpoints HTTP
|
||||
|
||||
| Endpoint | Fonctionnalité |
|
||||
| --- | --- |
|
||||
| `GET /api/health` | État du service : base, MakeMKV (binaire, version). |
|
||||
| `GET /api/settings` | Connexions Radarr + qBittorrent avec statut de test. |
|
||||
| `PUT /api/settings` | Enregistre les connexions (champs vides = conserver) ; tout changement invalide le statut de test. |
|
||||
| `GET/PUT /api/settings/radarr` | Connexion Radarr seule (endpoint dédié au panneau d'accueil). |
|
||||
| `POST /api/settings/radarr/test` | Test de connexion Radarr (version), résultat persisté. |
|
||||
| `GET/PUT /api/settings/qbittorrent` | Connexion qBittorrent seule ; utilisateur vide = bypass d'authentification. |
|
||||
| `POST /api/settings/qbittorrent/test` | Test de connexion qBittorrent, résultat persisté. |
|
||||
| `POST /api/scans` | Scan Radarr : inventorie les vraies ISO (contenu vérifié), met à jour/crée les lignes, repasse « Radarr lié », et rafraîtit chemin/taille des films convertis (fichier MKV côté Radarr — rattrapage des traitements antérieurs). |
|
||||
| `GET /api/movies` / `GET /api/files` | Liste des films (ordre alphabétique). |
|
||||
| `GET /api/files/{id}` | Fiche détaillée : film + chemins calculés + contenu du dossier de travail. |
|
||||
| `GET /api/movies/{id}/log` | Journal de conversion (terminal), conservé après échec. |
|
||||
| `POST /api/movies/{id}/convert` | Met en file (`?force=true` pour purger les restes du dossier de travail au préalable) ; refuse hors `detected/ready/failed` et si le dossier contient des restes (409 détaillé avec la liste des fichiers) ; une reprise d'échec à l'import n'est pas bloquée. |
|
||||
| `POST /api/movies/{id}/cancel` | Annule une conversion **à valider** : supprime MKV et lien, retour à `detected` ; tolère les fichiers disparus, traduit les erreurs de droits. |
|
||||
| `POST /api/movies/{id}/validate` | Validation : supprime l'ISO (tout le dossier sauf le MKV lié), retire le torrent **sans ses données** (l'ISO est déjà effacée ; qBittorrent ne peut pas toucher le dossier du film), conserve le MKV brut (même inode), passe en `completed`, puis demande à Radarr rescan + renommage Media Management (échec → `rescan_warning`, la validation reste acquise). |
|
||||
| `POST /api/movies/{id}/radarr-rename` | Rattrapage unitaire : rescan + renommage Radarr pour un film **déjà traité**. |
|
||||
| `POST /api/movies/{id}/delete-iso` | Suppression **manuelle** de l'ISO du dossier de téléchargements qBittorrent, réservée à l'état « Traité ». Garde-fous : fichier strictement sous la racine des téléchargements uniquement, dossier du film retiré seulement s'il devient vide, racine jamais supprimable, idempotent. |
|
||||
| `POST /api/movies/{id}/repair-link` | Répare le lien du MKV du dossier du film à partir du MKV brut conservé (même inode, données intactes) : recrée le lien dur (copie entre volumes distincts) avec le nom attendu par Radarr (movieFile courant), puis rescan Radarr. Remplace aussi un **vieux lien symbolique** hérité d'anciennes versions (chemin interne au conteneur, illisible depuis Jellyfin/Radarr). Réservé à l'état « Traité », détecté dans la fiche (`link_broken` ou `link_symbolic`). |
|
||||
| `POST /api/radarr/rename-processed` | Rattrapage groupé : rescan + renommage de tous les films traités, échecs collectés sans interrompre. |
|
||||
| `DELETE /api/movies/{id}` | Retire une ligne de l'inventaire (refusé si une conversion est en cours). |
|
||||
| `POST /api/auth/setup` | Création du premier compte via le jeton du premier lancement. |
|
||||
| `POST /api/auth/login` / `POST /api/auth/logout` | Connexion (cookie de session) / déconnexion. |
|
||||
| `GET /api/auth/me` | Identité de la session courante. |
|
||||
| `GET /{chemin}` (catch-all) | Sert le front compilé (`MKVTOOL_WEB_DIR`), SPA inclus ; les routes `/api` gardent la priorité. |
|
||||
|
||||
---
|
||||
|
||||
## Section WEB — logique TypeScript
|
||||
|
||||
### `web/src/main.tsx`
|
||||
|
||||
| Élément | Fonctionnalité |
|
||||
| --- | --- |
|
||||
| `createRoot(...).render(<App/>)` | Point d'entrée : monte l'application dans `#root`, importe le style global. |
|
||||
|
||||
### `web/src/App.tsx` — application complète
|
||||
|
||||
**Types** : `Movie` (ligne d'inventaire), `MovieDetail` (fiche : chemins MKV lié/brut, dossier de travail), `RadarrSettings`/`QbittorrentSettings` (connexions avec statut de test), `ServiceStatus` (statuts `unconfigured/configured/tested/error`), `Notification`, `Page`/`Tab` (navigation par état local — pas de routeur).
|
||||
|
||||
**Constantes** : `STATUS_LABELS` (libellés français), `PENDING/ACTIVE/DONE/BROKEN` (répartition dans les onglets), `BLOCKED` (états bloquant suppression/conversion), `CONVERTIBLE` (états convertibles), `STEP_LABELS` (étapes en échec).
|
||||
|
||||
**Helpers**
|
||||
|
||||
| Fonction | Fonctionnalité |
|
||||
| --- | --- |
|
||||
| `api<T>` | `fetch` typé ; traduit les erreurs HTTP : message simple, ou objet structuré (restes de conversion) portant `detail` pour l'UI. |
|
||||
| `readableSize` | Octets → Go affichables. |
|
||||
| `statusLabel` | Libellé français d'un statut. |
|
||||
| `statusClass` / `isSpinning` | Classe CSS par état (une couleur par état) et présence du spinner (états actifs). |
|
||||
| `StatusPill` | Pastille d'état : couleur + spinner + libellé. |
|
||||
| `ServiceBadge` | Badge de connexion dans la page Configuration : vert « Testé · version », bleu « Configuré · non testé », orange « non configuré », rouge « Test échoué » (détail au survol). |
|
||||
| `inGroup` | Répartit un statut dans un onglet. |
|
||||
| `formatDateTime` | Formatage français des dates. |
|
||||
|
||||
**Gestion d'état et effets**
|
||||
|
||||
| Fonction/effet | Fonctionnalité |
|
||||
| --- | --- |
|
||||
| `loadMovies` | Rafraîchit la liste depuis `/api/movies`. |
|
||||
| `notify` / `dismissNotification` | Pile de notifications (info/erreur/avertissement) en bas à droite, refermables. |
|
||||
| `hasActive` + effet de polling | Rafraîchit la liste toutes les 3 s pendant une conversion, 10 s sinon — les lignes changent d'onglet sans recharger. |
|
||||
| Effet « fiche ouverte » | Tant que la popup est ouverte : rafraîchit la fiche et le journal toutes les 2 s, **uniquement si le contenu change** (pas de re-rendu inutile, les boutons restent stables). Le chemin du lien suit le renommage Radarr. |
|
||||
| Effet terminal | Colle le terminal en bas de la sortie en direct. |
|
||||
| Effets menu/thème | Fermeture du menu utilisateur au clic extérieur ; persistance du thème clair/sombre dans `localStorage`. |
|
||||
| `toggleTheme` | Bascule le thème (attribut `data-theme` sur `<html>`). |
|
||||
|
||||
**Authentification**
|
||||
|
||||
| Fonction | Fonctionnalité |
|
||||
| --- | --- |
|
||||
| `handleLogin` | Connexion (erreurs affichées), pose la session. |
|
||||
| `handleSetup` | Création du premier compte depuis le lien à jeton (vérifie la confirmation du mot de passe). |
|
||||
| `handleLogout` | Déconnexion, retour à l'écran de connexion. |
|
||||
| Effets `authState` | Détection de session (`/api/auth/me`), page `/setup` dédiée au premier lancement. |
|
||||
|
||||
**Configuration**
|
||||
|
||||
| Fonction | Fonctionnalité |
|
||||
| --- | --- |
|
||||
| `saveSettings` | Enregistre Radarr, teste la connexion, rafraîchit le badge (persisté côté serveur) ; en cas d'échec le badge passe en rouge. |
|
||||
| `saveQbittorrent` | Idem qBittorrent (identifiants ou clé API ≥ 5.2, vide = bypass). |
|
||||
| `scan` | Lance le scan, affiche le bilan (ISO trouvées, chemins rafraîchis pour les films traités). |
|
||||
|
||||
**Inventaire et traitements**
|
||||
|
||||
| Fonction | Fonctionnalité |
|
||||
| --- | --- |
|
||||
| `groups` | Regroupement des films par onglet (à traiter, en cours, traités, erreurs). |
|
||||
| `convert` | Met en file ; en cas de restes dans le dossier de travail (409 structuré), la fiche les affiche avec le bouton « Tout supprimer et reprendre la conversion » (`?force=true`). |
|
||||
| `validate` | Valide (« à valider » → « terminé ») ; notifie l'avertissement Radarr éventuel. |
|
||||
| `deleteDownloadIso` | Suppression manuelle de l'ISO de téléchargements depuis la fiche d'un traité (tag « ISO à supprimer » + bouton) ; rafraîchit la fiche (le tag retombe). |
|
||||
| `repairMovieLink` | Réparation du lien du MKV depuis la fiche d'un traité quand le lien a disparu (bloc « Lien du MKV introuvable ») ou quand c'est un vieux lien symbolique illisible depuis Jellyfin (bloc « Lien symbolique fragile ») ; recrée le lien dur/copie au nom Radarr et rafraîchit la fiche. |
|
||||
| `cancel` | Annule une conversion « à valider » (retour à « détecté ») ; erreurs notifiées explicitement. |
|
||||
| `radarrRename` / `radarrRenameAll` | Rattrapage : renommage Radarr d'un film traité (fiche) ou de tous (onglet Traités). |
|
||||
| `deleteRow` / `deleteSelection` | Suppression d'une ligne (confirmation) / de la sélection multiple, bilan notifié. |
|
||||
| `openMovie` / `closeModal` | Ouvre la fiche (récupère chemins et journal), fermeture par bouton ou Échap. |
|
||||
| `copyPath` | Copie un chemin dans le presse-papiers (notification). |
|
||||
| `toggleSelect` / `toggleSelectAll` / `enterSelectMode` / `exitSelectMode` | Mode sélection multiple. |
|
||||
|
||||
**Rendu** : page de premier lancement (`/setup`), page de connexion, en-tête (scan, menu utilisateur), navigation (Tableau de bord / Traitements / Configuration), tableau de bord (statistiques + activité), traitements (onglets, filtre « Radarr lié », sélection multiple, lignes avec pastilles colorées, bouton de renommage groupé), configuration (panneaux Radarr/qBittorrent avec badges), fiche film (état, chemins copiables du MKV lié et brut, avertissement de restes avec bouton de purge, terminal de conversion en direct ou journal d'erreur), confirmations de suppression, pile de notifications.
|
||||
|
||||
### `web/src/style.css`
|
||||
|
||||
Styles globaux (thème sombre/clair via `data-theme`), pastilles d'état colorées, spinner, terminal, avertissement de restes, badges de connexion, et media queries responsives (≤ 760 px : une colonne, onglets défilants, popup plein écran).
|
||||
|
||||
### Tests fonctionnels (`web/e2e/`, Playwright)
|
||||
|
||||
| Fichier | Couverture |
|
||||
| --- | --- |
|
||||
| `scripts/e2e_server.py` (côté app) | Serveur d'intégration : environnement isolé (config/films/téléchargements en temporaire), compte et films semés dans tous les états, front compilé servi par l'API, conversions en mode simulation. |
|
||||
| `helpers.ts` | `login` (connexion au compte semé), `ligneFilm` (localisateur de ligne — les lignes portent un rôle bouton), `attendreEtat` (attend une pastille d'état via le polling), `fermerNotifications` (dégager la zone des notifications avant d'agir). |
|
||||
| `01-auth` | Mauvais mot de passe refusé ; connexion/déconnexion ; persistance du thème. |
|
||||
| `02-config` | Avertissements ciblés au premier lancement, scan désactivé sans Radarr, badges orange ; enregistrement + test → badge rouge « Test échoué » ; scan échoue proprement avec Radarr injoignable. |
|
||||
| `03-dashboard` | Statistiques par état, colonnes d'activité, navigation entre pages. |
|
||||
| `04-traitements` | Onglets et pastilles, fiche d'un détecté (Esc), fiche d'un traité (deux chemins, renommage), fiche d'une erreur (message + journal), renommage groupé (échec signalé), suppression avec confirmation, sélection multiple. |
|
||||
| `05-responsive` | Parcours complets en 375/360 px : listes, fiches, boutons accessibles. |
|
||||
| `06-conversion` | Conversion complète (détection → validation → traité, la ligne change d'onglet toute seule) ; annulation (retour à détecté) ; reprise après échec. |
|
||||
|
||||
**Exécution** : `npm --prefix web run test:e2e` (Playwright démarre le serveur d'intégration, sert le `web/dist` compilé, exécute la suite). Job CI `web:e2e`.
|
||||
+14
-4
@@ -1,6 +1,6 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
ARG MAKEMKV_VERSION=2.0.0
|
||||
ARG MAKEMKV_VERSION=1.18.4
|
||||
|
||||
# --- Interface web ---
|
||||
FROM node:22-slim AS web
|
||||
@@ -31,9 +31,15 @@ RUN apt-get update \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# MakeMKV (makemkvcon) — version explicite, licence a fournir via makemkv.
|
||||
# 1.18.4 et non 2.0.0: la 2.0.0 a une regression qui fait planter makemkvcon
|
||||
# sur les ISO Blu-ray sans dossier AACS (non chiffrees / pre-dechiffrees) —
|
||||
# forum MakeMKV, fil "Version 2.0.0 won't open the disk structure (bug?)".
|
||||
# Les anciennes versions vivent sous /download/old/.
|
||||
RUN curl -fsSLO "https://www.makemkv.com/download/makemkv-oss-${MAKEMKV_VERSION}.tar.gz" \
|
||||
&& curl -fsSLO "https://www.makemkv.com/download/makemkv-bin-${MAKEMKV_VERSION}.tar.gz" \
|
||||
&& tar -xzf "makemkv-oss-${MAKEMKV_VERSION}.tar.gz" \
|
||||
|| curl -fsSLO "https://www.makemkv.com/download/old/makemkv-oss-${MAKEMKV_VERSION}.tar.gz"; \
|
||||
curl -fsSLO "https://www.makemkv.com/download/makemkv-bin-${MAKEMKV_VERSION}.tar.gz" \
|
||||
|| curl -fsSLO "https://www.makemkv.com/download/old/makemkv-bin-${MAKEMKV_VERSION}.tar.gz"; \
|
||||
tar -xzf "makemkv-oss-${MAKEMKV_VERSION}.tar.gz" \
|
||||
&& tar -xzf "makemkv-bin-${MAKEMKV_VERSION}.tar.gz" \
|
||||
&& cd "makemkv-oss-${MAKEMKV_VERSION}" \
|
||||
&& ./configure --disable-gui \
|
||||
@@ -56,7 +62,11 @@ COPY app/ app/
|
||||
COPY --from=web /web/dist /app/web/dist
|
||||
COPY docker/entrypoint.py /entrypoint.py
|
||||
|
||||
ENV MKVTOOL_CONFIG_DIR=/config \
|
||||
# HOME pointe vers /config pour que MakeMKV y lise et y ecrite sa
|
||||
# configuration (settings.conf, cle d'activation) : le processus tourne sous
|
||||
# PUID/PGID et ne peut pas acceder a /root, et /config est le volume persistant.
|
||||
ENV HOME=/config \
|
||||
MKVTOOL_CONFIG_DIR=/config \
|
||||
MKVTOOL_WEB_DIR=/app/web/dist \
|
||||
MKVTOOL_FILMS_DIR=/films \
|
||||
MKVTOOL_RADARR_FILMS_DIR=/nas_storage/jellyfin/films \
|
||||
|
||||
@@ -26,9 +26,59 @@ L'image est construite par la CI (job `container:image`, Kaniko) a chaque tag
|
||||
| `api` | `python:3.13-slim` | ffmpeg, MakeMKV compile depuis les sources, dependances `uv sync --no-dev` |
|
||||
|
||||
MakeMKV (`makemkvcon`) est compile dans l'image a partir de la version definie
|
||||
par l'argument de build `MAKEMKV_VERSION` (par defaut `2.0.0`). Le build local
|
||||
par l'argument de build `MAKEMKV_VERSION` (par defaut `1.18.4`). Le build local
|
||||
reste possible : `docker build -t mkvtool .`.
|
||||
|
||||
**Pourquoi 1.18.4 et pas 2.0.0** : la 2.0.0 a une regression confirmee qui
|
||||
fait planter `makemkvcon` sur les ISO Blu-ray sans dossier AACS (non chiffrees
|
||||
ou pre-dechiffrees — « AACS directory not present, assuming unencrypted disc »
|
||||
puis « Fatal error occurred »). Voir le forum MakeMKV, fil « Version 2.0.0
|
||||
won't open the disk structure (bug?) ». Les disques physiques chiffres ne
|
||||
sont pas affectes; si vous n'utilisez que ceux-la, `--build-arg
|
||||
MAKEMKV_VERSION=2.0.0` reste possible. Les anciennes versions sont
|
||||
telechargees depuis https://www.makemkv.com/download/old/ .
|
||||
|
||||
## Activation de MakeMKV
|
||||
|
||||
MakeMKV est shareware : sans clé d'activation, `makemkvcon` ne peut pas
|
||||
convertir en mode non interactif (il demande le lancement de la période
|
||||
d'évaluation, puis s'arrête). Deux options :
|
||||
|
||||
- **Clé bêta gratuite**, publiée par l'éditeur sur le forum officiel
|
||||
(https://forum.makemkv.com/forum/viewtopic.php?t=1053) et renouvelée tous
|
||||
les un à deux mois tant que MakeMKV reste en bêta. C'est la voie gratuite
|
||||
usuelle.
|
||||
- **Clé permanente** achetée (~60 USD, achat à vie).
|
||||
|
||||
La façon recommandée avec cette image est la variable d'environnement
|
||||
`MAKEMKV_KEY` : l'entrypoint l'écrit dans `/config/.MakeMKV/settings.conf`
|
||||
(entrée `app_Key`) à chaque démarrage, sous l'UID du service.
|
||||
|
||||
```yaml
|
||||
environment:
|
||||
MAKEMKV_KEY: "T-VOTRE-CLE"
|
||||
```
|
||||
|
||||
Manuellement, créez le fichier `<montage de /config>/.MakeMKV/settings.conf`
|
||||
sur l'hôte :
|
||||
|
||||
```
|
||||
app_Key = "T-VOTRE-CLE"
|
||||
```
|
||||
|
||||
Notes importantes :
|
||||
|
||||
- Le nom du paramètre est **`app_Key`** (pas `app_MakeMKV_key`, que
|
||||
`makemkvcon` ignore silencieusement).
|
||||
- La commande `makemkvcon reg <clé>` est peu fiable sur Linux (« Key not
|
||||
found or invalid » même avec une clé valide) : préférez le fichier.
|
||||
- L'image positionne `HOME=/config` et crée une entrée passwd pour
|
||||
PUID: c'est ainsi que `makemkvcon` trouve `/config/.MakeMKV`.
|
||||
|
||||
Si une conversion échoue avec le message d'activation, la clé a expiré :
|
||||
reprenez la clé courante sur le forum, mettez à jour `MAKEMKV_KEY` et
|
||||
redémarrez le conteneur.
|
||||
|
||||
## Variables d'environnement
|
||||
|
||||
| Variable | Defaut image | Role |
|
||||
@@ -42,7 +92,8 @@ reste possible : `docker build -t mkvtool .`.
|
||||
| `MKVTOOL_DOWNLOADS_DIR` | `/qbittorrentdownloads` | Racine des telechargements qBittorrent |
|
||||
| `MKVTOOL_SIMULATE_CONVERSION` | `false` | `true` = produit un faux MKV sans appeler MakeMKV (dev/tests) |
|
||||
| `MKVTOOL_WORKER_INTERVAL` | `10` | Secondes entre deux tours de la file de conversion |
|
||||
| `MAKEMKV_VERSION` | `2.0.0` | Version MakeMKV embarquee (visible dans `/api/health`) |
|
||||
| `MAKEMKV_KEY` | (vide) | Clé d'activation MakeMKV (voir « Activation de MakeMKV »), écrite dans `/config/.MakeMKV/settings.conf` par l'entrypoint |
|
||||
| `MAKEMKV_VERSION` | `1.18.4` | Version MakeMKV embarquee (visible dans `/api/health`) |
|
||||
|
||||
## Volumes
|
||||
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 59 KiB |
@@ -1,13 +1,33 @@
|
||||
# MKVTool
|
||||
|
||||
Documentation fonctionnelle (chaque méthode, chaque endpoint) : voir [DOCUMENTATION.md](DOCUMENTATION.md).
|
||||
|
||||
MKVTool sera un service web auto-hébergé consacré aux films. Il détecte les images ISO connues de Radarr, permet de lancer leur conversion manuellement, puis réimporte le MKV obtenu dans Radarr.
|
||||
|
||||
## Configuration (conf.json)
|
||||
|
||||
La configuration des services (Radarr, Sonarr, Prowlarr, Jellyfin, Overseerr/Seerr, qBittorrent) est stockée dans `./config/conf.json`.
|
||||
La configuration des services (Radarr, qBittorrent) est stockée dans `./config/conf.json`. (Les services Sonarr/Prowlarr/Jellyfin/Overseerr ont été retirés du périmètre ; la migration conf.json v1→v2 les supprime du fichier au démarrage.)
|
||||
|
||||
- Le backend lit ce fichier.
|
||||
- L'interface modifie ce fichier via l'API (écriture atomique côté backend).
|
||||
- Chaque service expose un statut dans la page Configuration: `Non configuré` (orange, URL ou clé API manquante), `Configuré · non testé` (bleu), `Testé` (vert, version affichée) ou `Test échoué` (rouge). Le résultat du dernier test est conservé dans `conf.json` (bloc `test`) et invalidé dès que l'URL ou les identifiants changent.
|
||||
- Les états de fichiers ont chacun une couleur (orange `Détecté`, bleu `En file`/`Conversion`, jaune `À valider`, vert `Terminé`, rouge `Erreur`), avec un spinner pendant les traitements actifs ; la liste se met à jour sans rechargement (3 s pendant une conversion, 10 s sinon).
|
||||
- Une conversion en cours ou en échec affiche dans la fiche du film un terminal reprenant la sortie MakeMKV en direct ; à l'état `À valider` et `Terminé`, la fiche affiche les chemins du MKV lié et du MKV brut.
|
||||
- Avant conversion, le dossier de travail est vérifié : des restes d'anciennes conversions bloquent la mise en file et la fiche propose « Tout supprimer et reprendre la conversion ».
|
||||
- À la validation, l'ISO est supprimée par son nom (tout le contenu du dossier du film part, sauf le MKV lié), le torrent qBittorrent est retiré SANS ses données (l'ISO est déjà effacée ; ainsi qBittorrent ne peut jamais ratisser le dossier du film où vit le MKV), puis MKVTool demande à Radarr de rescanner et renommer le fichier selon sa config Media Management (best effort : un échec remonte en avertissement sans invalider la validation).
|
||||
- Le MKV brut du dossier de travail qBittorrent est conservé après validation (même inode que le lien du dossier du film : aucun espace supplémentaire). La fiche d'un film traité affiche les deux chemins, actualisés en continu.
|
||||
- L'ISO du dossier de téléchargements qBittorrent n'est PAS supprimée à la validation : son chemin est capturé au moment de retirer le torrent, et la suppression est **manuelle**, depuis la fiche d'un film « Traité » (tag « ISO à supprimer » + bouton). Garde-fous : seul un fichier strictement sous la racine des téléchargements est supprimable, le dossier du film n'est retiré que s'il devient vide, la racine des téléchargements n'est jamais touchée.
|
||||
- Le scan met à jour les chemins des films traités : quand Radarr pointe un MKV (fichier converti), la ligne existante récupère le chemin courant, la taille et repasse « Radarr lié » — rattrapage automatique des traitements antérieurs lors d'un simple scan.
|
||||
- Le scan ne retient que les vraies images ISO : un fichier `.iso` dont l'en-tête est EBML (Matroska) est écarté.
|
||||
|
||||
## Migrations (base de données et conf.json)
|
||||
|
||||
Les évolutions de structure sont versionnées et appliquées automatiquement au démarrage (`app/migrations.py`):
|
||||
|
||||
- **Base de données**: chaque migration est un `DbMigration` numéroté, appliqué dans sa propre transaction et tracé dans la table `schema_migrations`. Une migration doit rester inoffensive sur un schéma déjà à jour (vérifier l'existence des tables/colonnes avant d'agir), car `create_all` crée déjà le schéma complet sur une base vierge.
|
||||
- **conf.json**: le fichier porte une clé `version` en tête. `CONF_MIGRATIONS` contient des fonctions `(dict) -> dict` qui transforment le contenu brut de la version N vers N+1, appliquées en chaîne jusqu'à la version courante. La valeur par défaut de `AppConfig.version` (dans `app/conf_store.py`) doit être mise à jour en même temps; un test vérifie cet invariant.
|
||||
|
||||
Pour ajouter une migration: ajouter l'entrée en fin de `DB_MIGRATIONS` ou de `CONF_MIGRATIONS` avec le numéro de version suivant, puis un test qui couvre la transformation depuis un état ancien.
|
||||
|
||||
Radarr (rappel API):
|
||||
|
||||
|
||||
+101
-11
@@ -1,30 +1,65 @@
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.config import settings
|
||||
|
||||
|
||||
class TestState(BaseModel):
|
||||
"""Resultat du dernier test de connexion (None = jamais teste)."""
|
||||
|
||||
at: str | None = None
|
||||
ok: bool | None = None
|
||||
version: str | None = None
|
||||
error: str | None = None
|
||||
|
||||
|
||||
class ApiServiceConfig(BaseModel):
|
||||
url: str | None = None
|
||||
port: int | None = None
|
||||
api_key: str | None = None
|
||||
test: TestState = Field(default_factory=TestState)
|
||||
|
||||
|
||||
class QbittorrentConfig(BaseModel):
|
||||
url: str | None = None
|
||||
port: int | None = None
|
||||
username: str | None = None
|
||||
password: str | None = None
|
||||
# Cle API native qBittorrent >= 5.2 (qbt_...), en-tete Authorization: Bearer.
|
||||
api_key: str | None = None
|
||||
test: TestState = Field(default_factory=TestState)
|
||||
|
||||
|
||||
def build_base_url(url: str | None, port: int | None = None) -> str | None:
|
||||
"""Normalise une adresse de service en URL de base.
|
||||
|
||||
Accepte une adresse locale sans schema ("http://" est deduit) et un port
|
||||
optionnel separe, applique seulement si l'URL n'en porte pas deja un.
|
||||
"""
|
||||
if not url:
|
||||
return None
|
||||
base = str(url).strip().rstrip("/")
|
||||
if "://" not in base:
|
||||
base = f"http://{base}"
|
||||
if port:
|
||||
parsed = urlparse(base)
|
||||
if parsed.port is None:
|
||||
base = f"{parsed.scheme}://{parsed.netloc}:{port}"
|
||||
return base
|
||||
|
||||
|
||||
class AppConfig(BaseModel):
|
||||
# Version de la structure du fichier, migree au demarrage
|
||||
# (voir app/migrations.py). Doit rester synchrone avec
|
||||
# current_conf_version(): un test verifie cet invariant.
|
||||
version: int = 2
|
||||
radarr: ApiServiceConfig = Field(default_factory=ApiServiceConfig)
|
||||
sonarr: ApiServiceConfig = Field(default_factory=ApiServiceConfig)
|
||||
prowlarr: ApiServiceConfig = Field(default_factory=ApiServiceConfig)
|
||||
jellyfin: ApiServiceConfig = Field(default_factory=ApiServiceConfig)
|
||||
seerr: ApiServiceConfig = Field(default_factory=ApiServiceConfig)
|
||||
qbittorrent: QbittorrentConfig = Field(default_factory=QbittorrentConfig)
|
||||
|
||||
|
||||
@@ -33,22 +68,73 @@ def config_path() -> Path:
|
||||
return settings.config_dir / "conf.json"
|
||||
|
||||
|
||||
def read_config() -> AppConfig:
|
||||
SERVICE_NAMES = ("radarr", "qbittorrent")
|
||||
|
||||
|
||||
def service_configured(service: ApiServiceConfig | QbittorrentConfig) -> bool:
|
||||
"""Un service est completement configure quand son URL (et sa cle API,
|
||||
quand il en faut une) est renseignee."""
|
||||
if isinstance(service, QbittorrentConfig):
|
||||
return bool(service.url)
|
||||
return bool(service.url and service.api_key)
|
||||
|
||||
|
||||
def service_status(service: ApiServiceConfig | QbittorrentConfig) -> str:
|
||||
"""Statut expose a l'UI: unconfigured | configured | tested | error."""
|
||||
if not service_configured(service):
|
||||
return "unconfigured"
|
||||
if service.test.ok is None:
|
||||
return "configured"
|
||||
return "tested" if service.test.ok else "error"
|
||||
|
||||
|
||||
def record_test(
|
||||
service_name: str, ok: bool, version: str | None = None, error: str | None = None
|
||||
) -> None:
|
||||
"""Persiste dans conf.json le resultat du dernier test de connexion."""
|
||||
if service_name not in SERVICE_NAMES:
|
||||
raise ValueError(f"Service inconnu: {service_name}")
|
||||
cfg = read_config()
|
||||
service = getattr(cfg, service_name)
|
||||
service.test = TestState(
|
||||
at=datetime.now(UTC).isoformat(),
|
||||
ok=ok,
|
||||
version=version if ok else None,
|
||||
error=None if ok else error,
|
||||
)
|
||||
write_config(cfg)
|
||||
|
||||
|
||||
def reset_test(service: ApiServiceConfig | QbittorrentConfig) -> None:
|
||||
"""Reinitialise le statut de test quand la configuration change."""
|
||||
service.test = TestState()
|
||||
|
||||
|
||||
def read_raw_config() -> dict | None:
|
||||
"""Contenu brut de conf.json (dict), ou None s'il est absent.
|
||||
|
||||
Sert aux migrations, qui transforment le fichier avant validation
|
||||
pydantic. Un contenu invalide (non-dict) est traite comme absent.
|
||||
"""
|
||||
path = config_path()
|
||||
if not path.exists():
|
||||
return AppConfig()
|
||||
return None
|
||||
raw = json.loads(path.read_text(encoding="utf-8"))
|
||||
if not isinstance(raw, dict):
|
||||
return raw if isinstance(raw, dict) else None
|
||||
|
||||
|
||||
def read_config() -> AppConfig:
|
||||
raw = read_raw_config()
|
||||
if raw is None:
|
||||
return AppConfig()
|
||||
return AppConfig.model_validate(raw)
|
||||
|
||||
|
||||
def write_config(config: AppConfig) -> None:
|
||||
def write_raw_config(data: dict) -> None:
|
||||
"""Ecriture atomique du contenu brut de conf.json."""
|
||||
path = config_path()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
serialized = config.model_dump(mode="json", exclude_none=True)
|
||||
|
||||
# Atomic write to avoid corrupting conf.json if the process is interrupted.
|
||||
tmp_dir = str(path.parent)
|
||||
with tempfile.NamedTemporaryFile(
|
||||
@@ -59,9 +145,13 @@ def write_config(config: AppConfig) -> None:
|
||||
suffix=".tmp",
|
||||
delete=False,
|
||||
) as handle:
|
||||
json.dump(serialized, handle, indent=2, ensure_ascii=False)
|
||||
json.dump(data, handle, indent=2, ensure_ascii=False)
|
||||
handle.write("\n")
|
||||
tmp_name = handle.name
|
||||
|
||||
os.replace(tmp_name, path)
|
||||
|
||||
|
||||
def write_config(config: AppConfig) -> None:
|
||||
write_raw_config(config.model_dump(mode="json", exclude_none=True))
|
||||
|
||||
+221
-37
@@ -2,14 +2,18 @@
|
||||
|
||||
Le MKV est écrit dans un dossier dédié sous le répertoire de téléchargements
|
||||
qBittorrent, puis lié (lien dur `ln`) dans le dossier du film sous la
|
||||
bibliothèque Jellyfin après nettoyage de ce dossier.
|
||||
bibliothèque Jellyfin après nettoyage de ce dossier. Apres validation, le MKV
|
||||
brut du dossier de travail est conservé: même inode que le lien, il n'occupe
|
||||
aucun espace supplémentaire et la fiche du film traité en affiche le chemin.
|
||||
"""
|
||||
|
||||
import errno
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
@@ -17,6 +21,12 @@ from app.config import settings
|
||||
from app.models import IsoMovie
|
||||
|
||||
INVALID_CHARACTERS = re.compile(r'[/\\:*?"<>|]')
|
||||
# Mode robot de makemkvcon: TINFO:<titre>,9,<code>,"H:MM:SS" par titre
|
||||
# (code 9 = duree, voir makemkv.com/developers/usage.txt).
|
||||
TITLE_DURATION = re.compile(r'TINFO:(\d+),9,\d+,"(\d+):(\d{2}):(\d{2})"')
|
||||
# En-tete EBML (Matroska): un fichier .iso qui commence par ces octets est
|
||||
# en realite un MKV renomme.
|
||||
EBML_MAGIC = b"\x1aE\xdf\xa3"
|
||||
|
||||
|
||||
def guarded_folder(folder: Path) -> Path:
|
||||
@@ -40,15 +50,15 @@ class ConversionPaths:
|
||||
destination_folder: Path
|
||||
|
||||
|
||||
def container_iso_path(movie: IsoMovie) -> Path:
|
||||
"""Chemin de l'ISO tel que vu dans le conteneur.
|
||||
def radarr_to_container_path(path: str) -> Path:
|
||||
"""Traduit un chemin Radarr vers son equivalent dans le conteneur.
|
||||
|
||||
Radarr rapporte ses chemins dans son propre referentiel
|
||||
(radarr_films_dir); si celui-ci differe du point de montage du conteneur
|
||||
(films_dir), on traduit. Sans radarr_films_dir, les chemins sont pris
|
||||
tels quels (montage "meme chemin").
|
||||
"""
|
||||
iso = Path(movie.path)
|
||||
iso = Path(path)
|
||||
radarr_root = settings.radarr_films_dir
|
||||
if radarr_root is not None:
|
||||
try:
|
||||
@@ -58,6 +68,27 @@ def container_iso_path(movie: IsoMovie) -> Path:
|
||||
return iso
|
||||
|
||||
|
||||
def container_iso_path(movie: IsoMovie) -> Path:
|
||||
"""Chemin de l'ISO tel que vu dans le conteneur."""
|
||||
return radarr_to_container_path(movie.path)
|
||||
|
||||
|
||||
def looks_like_iso(radarr_path: str) -> bool:
|
||||
"""Verifie qu'un fichier .iso est bien une image disque, pas un MKV renomme.
|
||||
|
||||
L'extension suffit a preslectionner, mais des MKV circulent parfois avec
|
||||
un nom en .iso: on ecarte tout fichier dont l'en-tete est EBML (Matroska).
|
||||
Si le contenu est illisible, on fait confiance a l'extension.
|
||||
"""
|
||||
if not radarr_path.lower().endswith(".iso"):
|
||||
return False
|
||||
try:
|
||||
with radarr_to_container_path(radarr_path).open("rb") as handle:
|
||||
return handle.read(4) != EBML_MAGIC
|
||||
except OSError:
|
||||
return True
|
||||
|
||||
|
||||
def conversion_paths(movie: IsoMovie) -> ConversionPaths:
|
||||
title = sanitize_component(movie.title)
|
||||
movie_name = f"{title} {movie.year}" if movie.year else title
|
||||
@@ -77,30 +108,165 @@ def conversion_paths(movie: IsoMovie) -> ConversionPaths:
|
||||
)
|
||||
|
||||
|
||||
def extract_mkv(movie: IsoMovie, mkv_path: Path) -> None:
|
||||
def workspace_files(folder: Path) -> list[str]:
|
||||
"""Contenu du dossier de travail (restes d'anciennes conversions)."""
|
||||
if not folder.is_dir():
|
||||
return []
|
||||
return sorted(entry.name for entry in folder.iterdir())
|
||||
|
||||
|
||||
def clear_workspace(folder: Path) -> int:
|
||||
"""Vide le dossier de travail; renvoie le nombre d'entrees supprimees."""
|
||||
removed = 0
|
||||
if not folder.is_dir():
|
||||
return removed
|
||||
for entry in folder.iterdir():
|
||||
_remove_entry(entry, "Nettoyage du dossier de travail")
|
||||
removed += 1
|
||||
return removed
|
||||
|
||||
|
||||
def _run_makemkv(args: list[str], on_line: Callable[[str], None] | None = None) -> tuple[int, str]:
|
||||
"""Execute makemkvcon et diffuse sa sortie ligne par ligne.
|
||||
|
||||
stderr est fusionne dans stdout (la sortie de MakeMKV n'est pas
|
||||
structuree). Renvoie (code de sortie, sortie complete).
|
||||
"""
|
||||
with subprocess.Popen( # noqa: S603 - arguments construits en interne
|
||||
args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1
|
||||
) as process:
|
||||
chunks: list[str] = []
|
||||
assert process.stdout is not None
|
||||
for line in process.stdout:
|
||||
chunks.append(line)
|
||||
if on_line is not None:
|
||||
on_line(line.rstrip("\n"))
|
||||
returncode = process.wait()
|
||||
return returncode, "".join(chunks)
|
||||
|
||||
|
||||
def longest_title_id(iso: Path, on_line: Callable[[str], None] | None = None) -> str:
|
||||
"""Identifiant du titre le plus long, via ``makemkvcon --robot info``.
|
||||
|
||||
Les identifiants ne suivent pas la duree: le titre 0 n'est pas
|
||||
forcement le film (souvent un bonus). En cas d'echec de l'analyse on
|
||||
retombe sur le titre 0. Le seuil minlength est laisse par defaut (120 s)
|
||||
pour que la numerotation concorde avec la commande ``mkv``.
|
||||
"""
|
||||
returncode, output = _run_makemkv(
|
||||
["makemkvcon", "--robot", "info", f"iso:{iso}"], on_line
|
||||
)
|
||||
best_title, best_seconds = "0", -1
|
||||
for line in output.splitlines():
|
||||
match = TITLE_DURATION.search(line)
|
||||
if not match:
|
||||
continue
|
||||
seconds = int(match[2]) * 3600 + int(match[3]) * 60 + int(match[4])
|
||||
if seconds > best_seconds:
|
||||
best_title, best_seconds = match[1], seconds
|
||||
return best_title if returncode == 0 or best_seconds >= 0 else "0"
|
||||
|
||||
|
||||
def extract_mkv(
|
||||
movie: IsoMovie,
|
||||
mkv_path: Path,
|
||||
on_line: Callable[[str], None] | None = None,
|
||||
) -> None:
|
||||
mkv_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if settings.simulate_conversion:
|
||||
# Simulation en attendant MakeMKV sur le NAS : fichier MKV de substitution.
|
||||
mkv_path.write_text(
|
||||
"MKV simule par MKVTool — MakeMKV n'est pas installe dans cet environnement.\n"
|
||||
)
|
||||
if on_line is not None:
|
||||
on_line("MKV simule par MKVTool (mode simulation).")
|
||||
return
|
||||
if shutil.which("makemkvcon") is None:
|
||||
raise RuntimeError("MakeMKV (makemkvcon) n'est pas installe sur le serveur")
|
||||
result = subprocess.run(
|
||||
["makemkvcon", "mkv", f"iso:{container_iso_path(movie)}", "0", str(mkv_path.parent)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
iso = container_iso_path(movie)
|
||||
title = longest_title_id(iso, on_line)
|
||||
returncode, output = _run_makemkv(
|
||||
["makemkvcon", "mkv", f"iso:{iso}", title, str(mkv_path.parent)], on_line
|
||||
)
|
||||
if result.returncode != 0:
|
||||
detail = result.stderr.strip() or result.stdout.strip()
|
||||
raise RuntimeError(f"MakeMKV a echoue: {detail}")
|
||||
if returncode != 0:
|
||||
if "purchase an activation key" in output or "evaluation period" in output:
|
||||
raise RuntimeError(
|
||||
"MakeMKV n'est pas activé: une clé est requise pour la conversion. "
|
||||
"Renseignez la variable d'environnement MAKEMKV_KEY (clé bêta gratuite "
|
||||
"du forum officiel MakeMKV ou clé achetée) et redémarrez le conteneur, "
|
||||
"ou ajoutez app_Key = \"<clé>\" dans /config/.MakeMKV/settings.conf "
|
||||
"(nom app_Key, pas app_MakeMKV_key). Voir IMAGE.md."
|
||||
)
|
||||
if returncode < 0:
|
||||
# Un code negatif signale un processus tue par un signal:
|
||||
# SIGKILL = en general le tueur OOM (manque de memoire).
|
||||
try:
|
||||
name = signal.Signals(-returncode).name
|
||||
except ValueError:
|
||||
name = f"signal {-returncode}"
|
||||
reason = f"processus tué par {name} — souvent un manque de mémoire"
|
||||
else:
|
||||
reason = f"code {returncode}"
|
||||
raise RuntimeError(f"MakeMKV a échoué ({reason}): {output.strip()}")
|
||||
produced = sorted(mkv_path.parent.glob("*.mkv"))
|
||||
if not produced:
|
||||
raise RuntimeError("MakeMKV n'a produit aucun fichier MKV")
|
||||
produced[0].replace(mkv_path)
|
||||
|
||||
|
||||
# Erreurs de gestion de fichier: chaque action les traduit en message
|
||||
# explicite pour l'interface (notification), plutot qu'un errno brut.
|
||||
FILE_ERRORS: dict[int, str] = {
|
||||
errno.EACCES: "erreur de droits (accès refusé)",
|
||||
errno.EPERM: "erreur de droits (opération non permise)",
|
||||
errno.EROFS: "erreur de droits (système de fichiers en lecture seule)",
|
||||
errno.ENOENT: "fichier ou dossier introuvable",
|
||||
errno.ENOSPC: "plus d'espace disque disponible",
|
||||
errno.EISDIR: "le chemin est un dossier",
|
||||
errno.ENOTDIR: "le chemin n'est pas un dossier",
|
||||
errno.EBUSY: "fichier occupé par un autre processus",
|
||||
errno.EXDEV: "les fichiers sont sur des systèmes de fichiers différents",
|
||||
}
|
||||
|
||||
|
||||
def file_error(error: OSError, action: str, path: Path | str) -> RuntimeError:
|
||||
"""Traduit une OSError en RuntimeError au message explicite."""
|
||||
detail = FILE_ERRORS.get(error.errno, f"erreur système (errno {error.errno})")
|
||||
return RuntimeError(f"{action} impossible — {detail}: {path} ({error.strerror})")
|
||||
|
||||
|
||||
def unlink_if_exists(path: Path) -> None:
|
||||
"""Supprime un fichier s'il existe; son absence n'est pas une erreur."""
|
||||
try:
|
||||
path.unlink()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
except OSError as error:
|
||||
raise file_error(error, "Suppression", path) from error
|
||||
|
||||
|
||||
def rmdir_if_empty(folder: Path) -> None:
|
||||
"""Supprime un dossier vide s'il existe; absence ou non-vide: sans erreur."""
|
||||
try:
|
||||
folder.rmdir()
|
||||
except (FileNotFoundError, OSError):
|
||||
# ENOTEMPTY, ENOENT...: le dossier reste ou est deja parti, on suit.
|
||||
pass
|
||||
|
||||
|
||||
def _remove_entry(entry: Path, action: str) -> None:
|
||||
"""Supprime une entree (fichier, lien ou dossier) avec erreurs traduites."""
|
||||
try:
|
||||
if entry.is_dir() and not entry.is_symlink():
|
||||
shutil.rmtree(entry)
|
||||
else:
|
||||
entry.unlink()
|
||||
except FileNotFoundError:
|
||||
pass # deja disparu entre l'inventaire et la suppression
|
||||
except OSError as error:
|
||||
raise file_error(error, action, entry) from error
|
||||
|
||||
|
||||
def clear_folder(destination_folder: Path, keep: list[Path]) -> None:
|
||||
"""Vide le dossier du film, sauf les chemins listés dans keep (l'ISO...)."""
|
||||
resolved = guarded_folder(destination_folder)
|
||||
@@ -110,10 +276,32 @@ def clear_folder(destination_folder: Path, keep: list[Path]) -> None:
|
||||
for entry in resolved.iterdir():
|
||||
if entry.resolve() in keep_resolved:
|
||||
continue
|
||||
if entry.is_dir() and not entry.is_symlink():
|
||||
shutil.rmtree(entry)
|
||||
else:
|
||||
entry.unlink()
|
||||
_remove_entry(entry, "Nettoyage du dossier du film")
|
||||
|
||||
|
||||
def link_or_copy(source: Path, target: Path, action: str) -> str:
|
||||
"""Crée le lien du MKV dans le dossier du film: lien dur si possible.
|
||||
|
||||
Les volumes de travail et de films sont parfois des montages distincts
|
||||
(EXDEV): un lien dur est alors impossible. Jamais de lien symbolique —
|
||||
son chemin absolu n'est valide que dans le conteneur MKVTool et casse
|
||||
les autres applications qui suivent le fichier (Jellyfin, Radarr).
|
||||
On retombe sur une copie independante, lisible partout.
|
||||
|
||||
Retourne ``"lien"`` ou ``"copie"`` selon la methode utilisee.
|
||||
"""
|
||||
try:
|
||||
os.link(source, target)
|
||||
return "lien"
|
||||
except OSError as error:
|
||||
if error.errno != errno.EXDEV:
|
||||
raise file_error(error, action, target) from error
|
||||
# Volumes différents: un lien dur est impossible, on copie.
|
||||
try:
|
||||
shutil.copyfile(source, target)
|
||||
except OSError as copy_error:
|
||||
raise file_error(copy_error, action, target) from copy_error
|
||||
return "copie"
|
||||
|
||||
|
||||
def import_mkv(
|
||||
@@ -127,21 +315,20 @@ def import_mkv(
|
||||
Ordre voulu: (1) suppression de tout ce qui traîne dans le dossier du
|
||||
film — sauf les chemins de `keep` (l'ISO reste en sécurité jusqu'à la
|
||||
validation manuelle) — puis (2) création du lien dur, nommé selon la
|
||||
configuration Media Management de Radarr (`target_name`).
|
||||
configuration Media Management de Radarr (`target_name`). Si les
|
||||
volumes sont distincts, une copie indépendante remplace le lien (voir
|
||||
`link_or_copy`).
|
||||
"""
|
||||
resolved = guarded_folder(destination_folder)
|
||||
resolved.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
resolved.mkdir(parents=True, exist_ok=True)
|
||||
except OSError as error:
|
||||
raise file_error(error, "Création du dossier", resolved) from error
|
||||
clear_folder(resolved, keep or [])
|
||||
target = resolved / (target_name or mkv_path.name)
|
||||
if target.exists() or target.is_symlink():
|
||||
target.unlink()
|
||||
try:
|
||||
os.link(mkv_path, target)
|
||||
except OSError as error:
|
||||
if error.errno != errno.EXDEV:
|
||||
raise
|
||||
# Volumes différents: un lien dur est impossible, on retombe sur un lien symbolique.
|
||||
os.symlink(mkv_path, target)
|
||||
unlink_if_exists(target)
|
||||
link_or_copy(mkv_path, target, "Création du lien du MKV")
|
||||
return target
|
||||
|
||||
|
||||
@@ -151,10 +338,7 @@ def finalize_validation(destination_folder: Path, keep_name: str) -> None:
|
||||
for entry in resolved.iterdir():
|
||||
if entry.name == keep_name:
|
||||
continue
|
||||
if entry.is_dir() and not entry.is_symlink():
|
||||
shutil.rmtree(entry)
|
||||
else:
|
||||
entry.unlink()
|
||||
_remove_entry(entry, "Suppression (validation)")
|
||||
|
||||
|
||||
def cancel_conversion(
|
||||
@@ -162,12 +346,12 @@ def cancel_conversion(
|
||||
) -> None:
|
||||
"""Annule une conversion en attente de validation.
|
||||
|
||||
Supprime le MKV converti et son lien dans le dossier du film (s'ils
|
||||
existent); l'ISO et le reste du dossier ne sont pas touches.
|
||||
Supprime le MKV converti et son lien dans le dossier du film; l'ISO et
|
||||
le reste du dossier ne sont pas touches. Les fichiers deja disparus
|
||||
sont tolérés (l'annulation reste valable); seule une erreur de droits
|
||||
interrompt, remontée avec un message explicite.
|
||||
"""
|
||||
target = destination_folder / (target_name or mkv_path.name)
|
||||
for path in (target, mkv_path):
|
||||
if path.is_symlink() or path.exists():
|
||||
path.unlink()
|
||||
if mkv_path.parent.is_dir() and not any(mkv_path.parent.iterdir()):
|
||||
mkv_path.parent.rmdir()
|
||||
unlink_if_exists(target)
|
||||
unlink_if_exists(mkv_path)
|
||||
rmdir_if_empty(mkv_path.parent)
|
||||
+534
-117
@@ -10,31 +10,57 @@ import httpx
|
||||
from fastapi import Cookie, Depends, FastAPI, HTTPException, Response
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy import inspect, select, text
|
||||
from sqlalchemy import select, update
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import auth
|
||||
from app.conf_store import read_config, write_config
|
||||
from app.converter import cancel_conversion, conversion_paths, finalize_validation
|
||||
from app import worker as conversion_queue
|
||||
from app.conf_store import (
|
||||
ApiServiceConfig,
|
||||
QbittorrentConfig,
|
||||
build_base_url,
|
||||
read_config,
|
||||
record_test,
|
||||
reset_test,
|
||||
service_status,
|
||||
write_config,
|
||||
)
|
||||
from app.config import settings
|
||||
from app.converter import (
|
||||
cancel_conversion,
|
||||
clear_workspace,
|
||||
conversion_paths,
|
||||
finalize_validation,
|
||||
link_or_copy,
|
||||
looks_like_iso,
|
||||
unlink_if_exists,
|
||||
workspace_files,
|
||||
)
|
||||
from app.database import Base, engine, get_db
|
||||
from app.migrations import migrate_conf_file, run_db_migrations
|
||||
from app.models import IsoMovie
|
||||
from app.qbittorrent import QbittorrentClient, match_torrent
|
||||
from app.radarr import RadarrClient, movie_file_path
|
||||
from app.schemas import (
|
||||
ApiServiceSettingsRead,
|
||||
AuthCredentialsWrite,
|
||||
AuthSetupWrite,
|
||||
AuthUserRead,
|
||||
BulkRenameFailure,
|
||||
BulkRenameResult,
|
||||
ConnectionResult,
|
||||
ConversionLogRead,
|
||||
HealthRead,
|
||||
IsoMovieDetailRead,
|
||||
IsoMovieRead,
|
||||
QbittorrentSettingsRead,
|
||||
QbittorrentSettingsWrite,
|
||||
RadarrSettingsRead,
|
||||
RadarrSettingsWrite,
|
||||
RepairLinkResult,
|
||||
ScanResult,
|
||||
SettingsRead,
|
||||
SettingsWrite,
|
||||
ValidationRead,
|
||||
)
|
||||
from app.worker import conversion_worker
|
||||
|
||||
@@ -43,26 +69,16 @@ from app.worker import conversion_worker
|
||||
async def lifespan(_: FastAPI):
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
# Very small "migration" helper for dev: add new columns if the SQLite DB already exists.
|
||||
# (SQLAlchemy create_all doesn't alter existing tables.)
|
||||
try:
|
||||
inspector = inspect(engine)
|
||||
columns = {col["name"] for col in inspector.get_columns("iso_movies")}
|
||||
migrations = {
|
||||
"processed_at": "DATETIME",
|
||||
"completed_at": "DATETIME",
|
||||
"failed_step": "TEXT",
|
||||
"last_error": "TEXT",
|
||||
"poster_url": "TEXT",
|
||||
}
|
||||
with engine.begin() as conn:
|
||||
for column, ddl in migrations.items():
|
||||
if column not in columns:
|
||||
conn.execute(text(f"ALTER TABLE iso_movies ADD COLUMN {column} {ddl}"))
|
||||
except Exception:
|
||||
# Don't fail app startup for a best-effort migration.
|
||||
pass
|
||||
# Migrations versionnees (base + conf.json), tracees au demarrage.
|
||||
db_applied = run_db_migrations(engine)
|
||||
if db_applied:
|
||||
print(f"migrations de base appliquees: {', '.join(db_applied)}", flush=True)
|
||||
conf_applied = migrate_conf_file()
|
||||
if conf_applied:
|
||||
print(f"migrations conf.json: {', '.join(conf_applied)}", flush=True)
|
||||
|
||||
auth.bootstrap_setup()
|
||||
_log_config_summary()
|
||||
worker_task = asyncio.create_task(conversion_worker())
|
||||
try:
|
||||
yield
|
||||
@@ -81,29 +97,43 @@ app.add_middleware(
|
||||
DbSession = Annotated[Session, Depends(get_db)]
|
||||
|
||||
|
||||
def _api_service_read(url: str | None, api_key: str | None) -> ApiServiceSettingsRead:
|
||||
return ApiServiceSettingsRead(url=url, api_key_configured=api_key is not None)
|
||||
def _api_service_read(service: ApiServiceConfig) -> RadarrSettingsRead:
|
||||
return RadarrSettingsRead(
|
||||
url=service.url,
|
||||
port=service.port,
|
||||
api_key_configured=service.api_key is not None,
|
||||
status=service_status(service),
|
||||
tested_version=service.test.version,
|
||||
tested_at=service.test.at,
|
||||
test_error=service.test.error,
|
||||
)
|
||||
|
||||
|
||||
def _qbittorrent_read(qb: QbittorrentConfig) -> QbittorrentSettingsRead:
|
||||
return QbittorrentSettingsRead(
|
||||
url=qb.url,
|
||||
port=qb.port,
|
||||
username=qb.username,
|
||||
password_configured=qb.password is not None,
|
||||
api_key_configured=qb.api_key is not None,
|
||||
status=service_status(qb),
|
||||
tested_version=qb.test.version,
|
||||
tested_at=qb.test.at,
|
||||
test_error=qb.test.error,
|
||||
)
|
||||
|
||||
|
||||
def _settings_read() -> SettingsRead:
|
||||
cfg = read_config()
|
||||
return SettingsRead(
|
||||
radarr=_api_service_read(cfg.radarr.url, cfg.radarr.api_key),
|
||||
sonarr=_api_service_read(cfg.sonarr.url, cfg.sonarr.api_key),
|
||||
prowlarr=_api_service_read(cfg.prowlarr.url, cfg.prowlarr.api_key),
|
||||
jellyfin=_api_service_read(cfg.jellyfin.url, cfg.jellyfin.api_key),
|
||||
seerr=_api_service_read(cfg.seerr.url, cfg.seerr.api_key),
|
||||
qbittorrent=QbittorrentSettingsRead(
|
||||
url=cfg.qbittorrent.url,
|
||||
username=cfg.qbittorrent.username,
|
||||
password_configured=cfg.qbittorrent.password is not None,
|
||||
),
|
||||
radarr=_api_service_read(cfg.radarr),
|
||||
qbittorrent=_qbittorrent_read(cfg.qbittorrent),
|
||||
)
|
||||
|
||||
|
||||
def client_from_config() -> RadarrClient:
|
||||
cfg = read_config()
|
||||
url = (cfg.radarr.url or "").rstrip("/")
|
||||
url = build_base_url(cfg.radarr.url, cfg.radarr.port)
|
||||
api_key = cfg.radarr.api_key
|
||||
if not url or not api_key:
|
||||
raise HTTPException(status_code=409, detail="La connexion Radarr n'est pas configurée")
|
||||
@@ -123,8 +153,7 @@ def health() -> HealthRead:
|
||||
|
||||
@app.get("/api/settings/radarr", response_model=RadarrSettingsRead)
|
||||
def get_radarr_settings() -> RadarrSettingsRead:
|
||||
cfg = read_config()
|
||||
return RadarrSettingsRead(url=cfg.radarr.url, api_key_configured=cfg.radarr.api_key is not None)
|
||||
return _api_service_read(read_config().radarr)
|
||||
|
||||
|
||||
@app.put("/api/settings/radarr", response_model=RadarrSettingsRead)
|
||||
@@ -132,12 +161,20 @@ def put_radarr_settings(
|
||||
payload: RadarrSettingsWrite,
|
||||
) -> RadarrSettingsRead:
|
||||
cfg = read_config()
|
||||
url = str(payload.url).rstrip("/")
|
||||
url = str(payload.url).strip().rstrip("/")
|
||||
# Toute modification de la connexion invalide le dernier test.
|
||||
if (
|
||||
url != (cfg.radarr.url or "")
|
||||
or payload.port != cfg.radarr.port
|
||||
or (payload.api_key and payload.api_key != cfg.radarr.api_key)
|
||||
):
|
||||
reset_test(cfg.radarr)
|
||||
cfg.radarr.url = url
|
||||
cfg.radarr.port = payload.port
|
||||
if payload.api_key:
|
||||
cfg.radarr.api_key = payload.api_key
|
||||
write_config(cfg)
|
||||
return RadarrSettingsRead(url=url, api_key_configured=cfg.radarr.api_key is not None)
|
||||
return _api_service_read(cfg.radarr)
|
||||
|
||||
|
||||
@app.get("/api/settings", response_model=SettingsRead)
|
||||
@@ -152,25 +189,36 @@ def put_settings(payload: SettingsWrite) -> SettingsRead:
|
||||
def apply_service(target, patch):
|
||||
if patch is None:
|
||||
return
|
||||
changed = False
|
||||
if patch.url is not None and str(patch.url).rstrip("/") != (target.url or ""):
|
||||
changed = True
|
||||
if patch.api_key and patch.api_key != target.api_key:
|
||||
changed = True
|
||||
if changed:
|
||||
reset_test(target)
|
||||
if patch.url is not None:
|
||||
target.url = str(patch.url).rstrip("/")
|
||||
if patch.api_key:
|
||||
target.api_key = patch.api_key
|
||||
|
||||
apply_service(cfg.radarr, payload.radarr)
|
||||
apply_service(cfg.sonarr, payload.sonarr)
|
||||
apply_service(cfg.prowlarr, payload.prowlarr)
|
||||
apply_service(cfg.jellyfin, payload.jellyfin)
|
||||
apply_service(cfg.seerr, payload.seerr)
|
||||
|
||||
if payload.qbittorrent is not None:
|
||||
qb = payload.qbittorrent
|
||||
qb_changed = bool(qb.url) and str(qb.url).rstrip("/") != (cfg.qbittorrent.url or "")
|
||||
qb_changed = qb_changed or bool(qb.username and qb.username != cfg.qbittorrent.username)
|
||||
qb_changed = qb_changed or bool(qb.password)
|
||||
qb_changed = qb_changed or bool(qb.api_key)
|
||||
if qb_changed:
|
||||
reset_test(cfg.qbittorrent)
|
||||
if qb.url is not None:
|
||||
cfg.qbittorrent.url = str(qb.url).rstrip("/")
|
||||
if qb.username:
|
||||
cfg.qbittorrent.username = qb.username
|
||||
if qb.password:
|
||||
cfg.qbittorrent.password = qb.password
|
||||
if qb.api_key:
|
||||
cfg.qbittorrent.api_key = qb.api_key
|
||||
|
||||
write_config(cfg)
|
||||
return _settings_read()
|
||||
@@ -182,43 +230,58 @@ async def test_radarr() -> ConnectionResult:
|
||||
try:
|
||||
status = await client.system_status()
|
||||
except (httpx.HTTPError, ValueError) as error:
|
||||
record_test("radarr", ok=False, error=str(error))
|
||||
raise HTTPException(
|
||||
status_code=502, detail=f"Connexion Radarr impossible: {error}"
|
||||
) from error
|
||||
version = str(status.get("version", "inconnue"))
|
||||
record_test("radarr", ok=True, version=version)
|
||||
return ConnectionResult(success=True, version=version, message=f"Radarr {version} accessible")
|
||||
|
||||
|
||||
def qbittorrent_from_config() -> QbittorrentClient:
|
||||
qb = read_config().qbittorrent
|
||||
if not qb.url or not qb.username or not qb.password:
|
||||
url = build_base_url(qb.url, qb.port)
|
||||
if not url:
|
||||
raise HTTPException(status_code=409, detail="La connexion qBittorrent n'est pas configurée")
|
||||
return QbittorrentClient(qb.url, qb.username, qb.password)
|
||||
return QbittorrentClient(url, qb.username, qb.password, qb.api_key)
|
||||
|
||||
|
||||
@app.get("/api/settings/qbittorrent", response_model=QbittorrentSettingsRead)
|
||||
def get_qbittorrent_settings() -> QbittorrentSettingsRead:
|
||||
qb = read_config().qbittorrent
|
||||
return QbittorrentSettingsRead(
|
||||
url=qb.url, username=qb.username, password_configured=qb.password is not None
|
||||
)
|
||||
return _qbittorrent_read(read_config().qbittorrent)
|
||||
|
||||
|
||||
@app.put("/api/settings/qbittorrent", response_model=QbittorrentSettingsRead)
|
||||
def put_qbittorrent_settings(payload: QbittorrentSettingsWrite) -> QbittorrentSettingsRead:
|
||||
cfg = read_config()
|
||||
if payload.url is not None:
|
||||
cfg.qbittorrent.url = str(payload.url).rstrip("/")
|
||||
if payload.username:
|
||||
cfg.qbittorrent.username = payload.username
|
||||
if payload.password:
|
||||
cfg.qbittorrent.password = payload.password
|
||||
write_config(cfg)
|
||||
return QbittorrentSettingsRead(
|
||||
url=cfg.qbittorrent.url,
|
||||
username=cfg.qbittorrent.username,
|
||||
password_configured=cfg.qbittorrent.password is not None,
|
||||
qb = cfg.qbittorrent
|
||||
qb_changed = payload.url is not None and str(payload.url).strip().rstrip("/") != (
|
||||
qb.url or ""
|
||||
)
|
||||
qb_changed = qb_changed or bool(payload.username and payload.username != qb.username)
|
||||
qb_changed = qb_changed or bool(payload.password)
|
||||
qb_changed = qb_changed or bool(payload.api_key)
|
||||
if qb_changed:
|
||||
reset_test(qb)
|
||||
if payload.url is not None:
|
||||
qb.url = str(payload.url).strip().rstrip("/")
|
||||
qb.port = payload.port
|
||||
if payload.username:
|
||||
qb.username = payload.username
|
||||
if payload.password:
|
||||
qb.password = payload.password
|
||||
elif payload.password:
|
||||
# Mot de passe seul: on conserve l'utilisateur existant.
|
||||
qb.password = payload.password
|
||||
else:
|
||||
# Champs vides: mode bypass d'authentification qBittorrent, sans identifiants.
|
||||
qb.username = None
|
||||
qb.password = None
|
||||
if payload.api_key:
|
||||
qb.api_key = payload.api_key
|
||||
write_config(cfg)
|
||||
return _qbittorrent_read(qb)
|
||||
|
||||
|
||||
@app.post("/api/settings/qbittorrent/test", response_model=ConnectionResult)
|
||||
@@ -227,9 +290,11 @@ async def test_qbittorrent() -> ConnectionResult:
|
||||
try:
|
||||
version = await client.version()
|
||||
except (httpx.HTTPError, ValueError) as error:
|
||||
record_test("qbittorrent", ok=False, error=str(error))
|
||||
raise HTTPException(
|
||||
status_code=502, detail=f"Connexion qBittorrent impossible: {error}"
|
||||
) from error
|
||||
record_test("qbittorrent", ok=True, version=version)
|
||||
return ConnectionResult(
|
||||
success=True, version=version, message=f"qBittorrent {version} accessible"
|
||||
)
|
||||
@@ -245,12 +310,69 @@ def list_files(db: DbSession) -> list[IsoMovie]:
|
||||
return list_movies(db)
|
||||
|
||||
|
||||
@app.get("/api/files/{file_id}", response_model=IsoMovieRead)
|
||||
def get_file(file_id: int, db: DbSession) -> IsoMovie:
|
||||
def _movie_detail(movie: IsoMovie) -> IsoMovieDetailRead:
|
||||
"""Fiche detaillee: chemins du MKV brut et du MKV lie, etat du dossier."""
|
||||
paths = conversion_paths(movie)
|
||||
linked = _linked_mkv(movie)
|
||||
detail = IsoMovieDetailRead.model_validate(movie)
|
||||
detail.work_mkv_path = str(paths.mkv_path) if paths.mkv_path.is_file() else None
|
||||
detail.linked_mkv_path = str(linked) if linked is not None else None
|
||||
detail.workspace_folder = str(paths.downloads_folder)
|
||||
detail.workspace_files = workspace_files(paths.downloads_folder)
|
||||
detail.qb_content_path = movie.qb_content_path
|
||||
detail.iso_to_delete = bool(
|
||||
movie.qb_content_path and Path(movie.qb_content_path).is_file()
|
||||
)
|
||||
detail.link_broken = bool(
|
||||
movie.status == "completed"
|
||||
and paths.mkv_path.is_file()
|
||||
and linked is None
|
||||
)
|
||||
detail.link_symbolic = bool(
|
||||
movie.status == "completed" and linked is not None and linked.is_symlink()
|
||||
)
|
||||
return detail
|
||||
|
||||
|
||||
@app.get("/api/files/{file_id}", response_model=IsoMovieDetailRead)
|
||||
def get_file(file_id: int, db: DbSession) -> IsoMovieDetailRead:
|
||||
item = db.get(IsoMovie, file_id)
|
||||
if item is None:
|
||||
raise HTTPException(status_code=404, detail="Fichier introuvable")
|
||||
return item
|
||||
return _movie_detail(item)
|
||||
|
||||
|
||||
@app.get("/api/movies/{movie_id}/log", response_model=ConversionLogRead)
|
||||
def get_conversion_log(movie_id: int, db: DbSession) -> ConversionLogRead:
|
||||
"""Journal de la conversion (terminal de suivi), conserve apres echec."""
|
||||
movie = db.get(IsoMovie, movie_id)
|
||||
if movie is None:
|
||||
raise HTTPException(status_code=404, detail="Film introuvable")
|
||||
return ConversionLogRead(
|
||||
lines=conversion_queue.conversion_log(movie_id),
|
||||
running=conversion_queue.is_converting(movie_id),
|
||||
)
|
||||
|
||||
|
||||
def _log_config_summary() -> None:
|
||||
"""Rend visible au lancement le chargement de conf.json."""
|
||||
cfg = read_config()
|
||||
configured = ["radarr"] if cfg.radarr.url else []
|
||||
if cfg.qbittorrent.url:
|
||||
if cfg.qbittorrent.api_key:
|
||||
mode = "cle API"
|
||||
elif cfg.qbittorrent.username:
|
||||
mode = "identifiants"
|
||||
else:
|
||||
mode = "bypass d'authentification"
|
||||
configured.append(f"qbittorrent ({mode})")
|
||||
if configured:
|
||||
print(f"conf.json charge: {', '.join(configured)}", flush=True)
|
||||
else:
|
||||
print(
|
||||
"conf.json: aucune connexion configuree — a renseigner dans la page Configuration.",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
def _poster_url(movie: dict) -> str | None:
|
||||
@@ -268,48 +390,76 @@ async def scan_radarr(db: DbSession) -> ScanResult:
|
||||
except (httpx.HTTPError, ValueError) as error:
|
||||
raise HTTPException(status_code=502, detail=f"Scan Radarr impossible: {error}") from error
|
||||
|
||||
iso_files = created = updated = 0
|
||||
iso_files = created = updated = refreshed = 0
|
||||
now = datetime.now(UTC)
|
||||
# Pastille "Radarr lie": on repart de zero, la boucle marque les films
|
||||
# toujours presents cote Radarr; les fichiers supprimes ou remplaces
|
||||
# passent donc a False.
|
||||
db.execute(update(IsoMovie).values(radarr_linked=False))
|
||||
for movie in movies:
|
||||
movie_file = movie.get("movieFile") or {}
|
||||
path = movie_file_path(movie)
|
||||
if not path or not path.lower().endswith(".iso"):
|
||||
if not path:
|
||||
continue
|
||||
movie_id = movie.get("id")
|
||||
movie_file_id = movie_file.get("id")
|
||||
if not isinstance(movie_id, int) or not isinstance(movie_file_id, int):
|
||||
continue
|
||||
iso_files += 1
|
||||
item = db.scalar(
|
||||
select(IsoMovie).where(
|
||||
IsoMovie.radarr_movie_id == movie_id,
|
||||
IsoMovie.radarr_movie_file_id == movie_file_id,
|
||||
# L'extension preslectionne, mais des MKV circulent parfois sous un
|
||||
# nom en .iso: on verifie l'en-tete du contenu.
|
||||
if looks_like_iso(path):
|
||||
iso_files += 1
|
||||
item = db.scalar(
|
||||
select(IsoMovie).where(
|
||||
IsoMovie.radarr_movie_id == movie_id,
|
||||
IsoMovie.radarr_movie_file_id == movie_file_id,
|
||||
)
|
||||
)
|
||||
if item is None:
|
||||
item = IsoMovie(
|
||||
radarr_movie_id=movie_id,
|
||||
radarr_movie_file_id=movie_file_id,
|
||||
title=str(movie.get("title", "Film sans titre")),
|
||||
year=movie.get("year"),
|
||||
path=path,
|
||||
size=movie_file.get("size"),
|
||||
poster_url=_poster_url(movie),
|
||||
radarr_linked=True,
|
||||
last_seen_at=now,
|
||||
)
|
||||
db.add(item)
|
||||
created += 1
|
||||
else:
|
||||
item.title = str(movie.get("title", item.title))
|
||||
item.year = movie.get("year")
|
||||
item.path = path
|
||||
item.size = movie_file.get("size")
|
||||
item.poster_url = _poster_url(movie)
|
||||
item.radarr_linked = True
|
||||
item.last_seen_at = now
|
||||
updated += 1
|
||||
continue
|
||||
# Fichier converti (MKV): Radarr pointe sur le fichier final. On met
|
||||
# a jour la ligne existante du film — chemin, taille, lien Radarr —
|
||||
# sans en creer. C'est ainsi que les films traites avant les
|
||||
# dernieres mises a jour rattrapent le chemin du MKV renomme.
|
||||
item = db.scalar(
|
||||
select(IsoMovie).where(IsoMovie.radarr_movie_id == movie_id)
|
||||
)
|
||||
if item is None:
|
||||
item = IsoMovie(
|
||||
radarr_movie_id=movie_id,
|
||||
radarr_movie_file_id=movie_file_id,
|
||||
title=str(movie.get("title", "Film sans titre")),
|
||||
year=movie.get("year"),
|
||||
path=path,
|
||||
size=movie_file.get("size"),
|
||||
poster_url=_poster_url(movie),
|
||||
last_seen_at=now,
|
||||
)
|
||||
db.add(item)
|
||||
created += 1
|
||||
else:
|
||||
item.title = str(movie.get("title", item.title))
|
||||
item.year = movie.get("year")
|
||||
item.path = path
|
||||
item.size = movie_file.get("size")
|
||||
item.poster_url = _poster_url(movie)
|
||||
item.last_seen_at = now
|
||||
updated += 1
|
||||
continue
|
||||
item.path = path
|
||||
item.size = movie_file.get("size")
|
||||
item.radarr_linked = True
|
||||
item.last_seen_at = now
|
||||
refreshed += 1
|
||||
db.commit()
|
||||
return ScanResult(
|
||||
scanned_movies=len(movies), iso_files=iso_files, created=created, updated=updated
|
||||
scanned_movies=len(movies),
|
||||
iso_files=iso_files,
|
||||
created=created,
|
||||
updated=updated,
|
||||
refreshed=refreshed,
|
||||
)
|
||||
|
||||
|
||||
@@ -334,23 +484,230 @@ def _linked_mkv(movie: IsoMovie) -> Path | None:
|
||||
return candidates[0]
|
||||
|
||||
|
||||
async def _delete_iso_torrent(iso_path: str) -> None:
|
||||
"""Supprime le torrent qBittorrent de l'ISO (best effort, sans bloquer)."""
|
||||
async def _delete_iso_torrent(iso_path: str) -> str | None:
|
||||
"""Retire le torrent qBittorrent de l'ISO (best effort, sans bloquer).
|
||||
|
||||
Fonctionne dans tous les modes d'authentification: cle API, identifiants
|
||||
ou bypass (l'URL doit simplement etre configuree). Le port separe est
|
||||
pris en compte via build_base_url.
|
||||
|
||||
Le torrent est retire SANS ses donnees (delete_files=False): le MKV
|
||||
converti vit dans le dossier du film, qBittorrent ne doit pouvoir y
|
||||
toucher en aucun cas. En retour, le chemin du contenu telecharge (l'ISO
|
||||
cote dossier de telechargements) est capture pour permettre sa
|
||||
suppression manuelle ulterieure sur l'etat "traite".
|
||||
"""
|
||||
qb = read_config().qbittorrent
|
||||
if not qb.url or not qb.username or not qb.password:
|
||||
return
|
||||
url = build_base_url(qb.url, qb.port)
|
||||
if not url:
|
||||
return None
|
||||
try:
|
||||
client = QbittorrentClient(qb.url, qb.username, qb.password)
|
||||
client = QbittorrentClient(url, qb.username, qb.password, qb.api_key)
|
||||
torrents = await client.torrents()
|
||||
match = match_torrent(torrents, iso_path)
|
||||
content_path = None
|
||||
if match is not None:
|
||||
content_path = str(match.get("content_path") or "") or None
|
||||
if match is not None and match.get("hash"):
|
||||
await client.delete([str(match["hash"])], delete_files=True)
|
||||
await client.delete([str(match["hash"])], delete_files=False)
|
||||
return content_path
|
||||
except Exception: # noqa: BLE001 - qBittorrent ne doit pas bloquer la validation
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
async def _sync_radarr_rename(movie: IsoMovie) -> None:
|
||||
"""Rescan puis renommage Radarr d'un film.
|
||||
|
||||
Radarr rescanne le dossier du film puis renomme ses fichiers selon sa
|
||||
config Media Management. Les commandes Radarr sont executees dans
|
||||
l'ordre d'envoi; le renommage preserve l'inode, le lien dur reste intact.
|
||||
"""
|
||||
radarr_client = client_from_config()
|
||||
await radarr_client.rescan_movie(movie.radarr_movie_id)
|
||||
await radarr_client.rename_movie(movie.radarr_movie_id)
|
||||
|
||||
|
||||
@app.post("/api/movies/{movie_id}/radarr-rename", response_model=IsoMovieRead)
|
||||
async def radarr_rename_movie(movie_id: int, db: DbSession) -> IsoMovie:
|
||||
"""Rescan + renommage Radarr pour un film deja traite.
|
||||
|
||||
Rattrapage des conversions faites avant l'automatisme: le MKV lie
|
||||
garde le nom de l'ISO, Radarr lui applique sa config Media Management.
|
||||
"""
|
||||
movie = db.get(IsoMovie, movie_id)
|
||||
if movie is None:
|
||||
raise HTTPException(status_code=404, detail="Film introuvable")
|
||||
if movie.status != "completed":
|
||||
raise HTTPException(
|
||||
status_code=409, detail="Seuls les films déjà traités peuvent être renommés via Radarr"
|
||||
)
|
||||
try:
|
||||
await _sync_radarr_rename(movie)
|
||||
except Exception as error: # noqa: BLE001 - message explicite pour l'UI
|
||||
raise HTTPException(
|
||||
status_code=409, detail=f"Renommage Radarr impossible: {error}"
|
||||
) from error
|
||||
return movie
|
||||
|
||||
|
||||
@app.post("/api/radarr/rename-processed", response_model=BulkRenameResult)
|
||||
async def radarr_rename_processed(db: DbSession) -> BulkRenameResult:
|
||||
"""Rescan + renommage Radarr de tous les films deja traites."""
|
||||
movies = list(
|
||||
db.scalars(select(IsoMovie).where(IsoMovie.status == "completed").order_by(IsoMovie.title))
|
||||
)
|
||||
renamed = 0
|
||||
failures: list[BulkRenameFailure] = []
|
||||
for movie in movies:
|
||||
try:
|
||||
await _sync_radarr_rename(movie)
|
||||
renamed += 1
|
||||
except Exception as error: # noqa: BLE001 - on continue avec les autres
|
||||
failures.append(BulkRenameFailure(title=movie.title, error=f"{error}"))
|
||||
return BulkRenameResult(renamed=renamed, failures=failures)
|
||||
|
||||
|
||||
@app.post("/api/movies/{movie_id}/delete-iso", response_model=IsoMovieRead)
|
||||
def delete_download_iso(movie_id: int, db: DbSession) -> IsoMovie:
|
||||
"""Supprime manuellement l'ISO du dossier de telechargements qBittorrent.
|
||||
|
||||
Reserve a l'etat "traite". Garde-fous stricts: le chemin doit designer
|
||||
un FICHIER strictement sous la racine des telechargements; le dossier du
|
||||
film dans les telechargements n'est retire que s'il devient vide — la
|
||||
racine des telechargements n'est jamais supprimable par cette action.
|
||||
"""
|
||||
movie = db.get(IsoMovie, movie_id)
|
||||
if movie is None:
|
||||
raise HTTPException(status_code=404, detail="Film introuvable")
|
||||
if movie.status != "completed":
|
||||
raise HTTPException(
|
||||
status_code=409, detail="Seul un film traité peut voir son ISO supprimée"
|
||||
)
|
||||
if not movie.qb_content_path:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="Chemin de l'ISO de téléchargement inconnu: elle a déjà été "
|
||||
"supprimée, ou le torrent était absent au moment de la validation",
|
||||
)
|
||||
iso = Path(movie.qb_content_path).resolve()
|
||||
downloads_root = settings.downloads_dir.resolve()
|
||||
if iso == downloads_root or downloads_root not in iso.parents:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="Refus par sécurité: le chemin n'est pas un fichier à l'intérieur "
|
||||
"du dossier des téléchargements",
|
||||
)
|
||||
if iso.is_dir():
|
||||
raise HTTPException(
|
||||
status_code=409, detail="Refus par sécurité: le chemin désigne un dossier"
|
||||
)
|
||||
if not iso.exists():
|
||||
# Deja supprimee: l'action est faite, rien a signaler.
|
||||
return movie
|
||||
try:
|
||||
unlink_if_exists(iso)
|
||||
except Exception as error: # noqa: BLE001 - message explicite pour l'UI
|
||||
raise HTTPException(
|
||||
status_code=409, detail=f"Suppression de l'ISO impossible: {error}"
|
||||
) from error
|
||||
# Dossier du film dans les telechargements: uniquement s'il est vide apres
|
||||
# la suppression, et strictement sous la racine. Jamais la racine.
|
||||
parent = iso.parent
|
||||
if parent != downloads_root and parent.is_dir() and not any(parent.iterdir()):
|
||||
try:
|
||||
parent.rmdir()
|
||||
except Exception as error: # noqa: BLE001 - message explicite pour l'UI
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail=f"ISO supprimée, mais suppression du dossier vide impossible: {error}",
|
||||
) from error
|
||||
return movie
|
||||
|
||||
|
||||
@app.post("/api/movies/{movie_id}/repair-link", response_model=RepairLinkResult)
|
||||
async def repair_movie_link(movie_id: int, db: DbSession) -> RepairLinkResult:
|
||||
"""Repare le lien du MKV dans le dossier du film a partir du MKV brut.
|
||||
|
||||
Cas visés: le lien du dossier du film a disparu (radarr, manipulation...)
|
||||
alors que le MKV brut du dossier de travail existe — meme inode, les
|
||||
donnees sont intactes; ou le lien est un vieux lien symbolique au chemin
|
||||
interne au conteneur, illisible depuis Jellyfin/Radarr. Le fichier est
|
||||
recree (lien dur, copie si volumes distincts) avec le nom attendu par
|
||||
Radarr (movieFile courant), puis Radarr rescanne le dossier.
|
||||
"""
|
||||
movie = db.get(IsoMovie, movie_id)
|
||||
if movie is None:
|
||||
raise HTTPException(status_code=404, detail="Film introuvable")
|
||||
if movie.status != "completed":
|
||||
raise HTTPException(
|
||||
status_code=409, detail="Seul un film traité peut voir son lien réparé"
|
||||
)
|
||||
paths = conversion_paths(movie)
|
||||
# MKV brut: le chemin attendu, sinon n'importe quel MKV du dossier de
|
||||
# travail (Radarr a pu renommer le brut au lieu du lien du dossier du
|
||||
# film — meme inode, les donnees sont intactes).
|
||||
brut = paths.mkv_path
|
||||
if not brut.is_file():
|
||||
candidates = sorted(
|
||||
entry for entry in paths.downloads_folder.glob("*.mkv") if entry.is_file()
|
||||
)
|
||||
if not candidates:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail=f"MKV brut introuvable dans le dossier de travail: {paths.downloads_folder}",
|
||||
)
|
||||
brut = candidates[0]
|
||||
|
||||
# Nom attendu du fichier: le movieFile courant cote Radarr (apres
|
||||
# renommage Media Management); a defaut, le nom du MKV brut.
|
||||
target_name = brut.name
|
||||
radarr_note = ""
|
||||
try:
|
||||
radarr_movie = await client_from_config().movie(movie.radarr_movie_id)
|
||||
radarr_path = movie_file_path(radarr_movie)
|
||||
if radarr_path:
|
||||
target_name = Path(radarr_path).name
|
||||
except Exception: # noqa: BLE001 - repli sur le nom du brut
|
||||
radarr_note = " (Radarr injoignable: nom du MKV brut utilisé)"
|
||||
target = paths.destination_folder / target_name
|
||||
|
||||
if target.is_symlink():
|
||||
# Lien symbolique hérité d'anciennes versions: son chemin absolu
|
||||
# n'est valide que dans le conteneur MKVTool — Jellyfin et Radarr
|
||||
# ne peuvent pas le suivre. On le remplace par un lien dur/copie.
|
||||
unlink_if_exists(target)
|
||||
elif target.is_file():
|
||||
return RepairLinkResult.model_validate(
|
||||
movie,
|
||||
).model_copy(update={"message": f"Le MKV est déjà en place: {target}"})
|
||||
|
||||
paths.destination_folder.mkdir(parents=True, exist_ok=True)
|
||||
kind = link_or_copy(brut, target, "Création du lien du MKV")
|
||||
db.commit()
|
||||
# Radarr rescanne le dossier: il voit le MKV reaparu.
|
||||
try:
|
||||
await client_from_config().rescan_movie(movie.radarr_movie_id)
|
||||
except Exception: # noqa: BLE001 - le lien est recree, le rescan est bonus
|
||||
radarr_note += " (rescan Radarr impossible: lancez-le dans Radarr)"
|
||||
return RepairLinkResult.model_validate(movie).model_copy(
|
||||
update={
|
||||
"message": (
|
||||
f"Lien du MKV recréé ({kind}): {target} — rescan Radarr lancé."
|
||||
+ radarr_note
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/movies/{movie_id}/convert", response_model=IsoMovieRead)
|
||||
def convert_movie(movie_id: int, db: DbSession) -> IsoMovie:
|
||||
def convert_movie(movie_id: int, db: DbSession, force: bool = False) -> IsoMovie:
|
||||
"""Met la conversion en file.
|
||||
|
||||
Refuse (409, code ``workspace_not_empty``) si le dossier de travail
|
||||
contient des restes d'anciennes conversions, sauf si ``force`` est vrai:
|
||||
le contenu est alors supprime pour qu'un seul MKV soit produit a la fin.
|
||||
Une reprise apres echec d'import (MKV deja extrait) n'est pas bloquee.
|
||||
"""
|
||||
movie = db.get(IsoMovie, movie_id)
|
||||
if movie is None:
|
||||
raise HTTPException(status_code=404, detail="Film introuvable")
|
||||
@@ -358,8 +715,31 @@ def convert_movie(movie_id: int, db: DbSession) -> IsoMovie:
|
||||
raise HTTPException(
|
||||
status_code=409, detail="Ce film n'est pas convertible dans son état actuel"
|
||||
)
|
||||
paths = conversion_paths(movie)
|
||||
resumable = movie.failed_step == "importing" and paths.mkv_path.is_file()
|
||||
leftovers = [
|
||||
name
|
||||
for name in workspace_files(paths.downloads_folder)
|
||||
if not (resumable and (paths.downloads_folder / name) == paths.mkv_path)
|
||||
]
|
||||
if leftovers and not force:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail={
|
||||
"code": "workspace_not_empty",
|
||||
"message": (
|
||||
"Le dossier de travail contient des fichiers issus d'une ancienne "
|
||||
"conversion. Supprimez-les pour ne garder qu'un seul MKV en fin "
|
||||
"de conversion."
|
||||
),
|
||||
"folder": str(paths.downloads_folder),
|
||||
"files": leftovers,
|
||||
},
|
||||
)
|
||||
if leftovers:
|
||||
clear_workspace(paths.downloads_folder)
|
||||
paths.downloads_folder.mkdir(parents=True, exist_ok=True)
|
||||
movie.status = "queued"
|
||||
movie.failed_step = None
|
||||
movie.last_error = None
|
||||
db.commit()
|
||||
return movie
|
||||
@@ -367,23 +747,40 @@ def convert_movie(movie_id: int, db: DbSession) -> IsoMovie:
|
||||
|
||||
@app.post("/api/movies/{movie_id}/cancel", response_model=IsoMovieRead)
|
||||
def cancel_movie(movie_id: int, db: DbSession) -> IsoMovie:
|
||||
"""Annule une conversion en attente de validation et supprime le MKV.
|
||||
|
||||
Reserve a l'etat ``validating``: avant cette etape le MKV converti
|
||||
n'existe pas. Les fichiers deja disparus sont toleres; seule une erreur
|
||||
de droits interrompt, remontee en erreur explicite.
|
||||
"""
|
||||
movie = db.get(IsoMovie, movie_id)
|
||||
if movie is None:
|
||||
raise HTTPException(status_code=404, detail="Film introuvable")
|
||||
if movie.status not in {"queued", "validating"}:
|
||||
if movie.status != "validating":
|
||||
raise HTTPException(status_code=409, detail="Aucune conversion à annuler")
|
||||
if movie.status == "validating":
|
||||
paths = conversion_paths(movie)
|
||||
linked = _linked_mkv(movie)
|
||||
cancel_conversion(paths.mkv_path, paths.destination_folder, linked.name if linked else None)
|
||||
paths = conversion_paths(movie)
|
||||
linked = _linked_mkv(movie)
|
||||
try:
|
||||
cancel_conversion(
|
||||
paths.mkv_path, paths.destination_folder, linked.name if linked else None
|
||||
)
|
||||
except Exception as error: # noqa: BLE001 - message explicite pour l'UI
|
||||
raise HTTPException(
|
||||
status_code=409, detail=f"Annulation impossible: {error}"
|
||||
) from error
|
||||
movie.status = "detected"
|
||||
movie.failed_step = None
|
||||
movie.last_error = None
|
||||
db.commit()
|
||||
return movie
|
||||
|
||||
|
||||
@app.post("/api/movies/{movie_id}/validate", response_model=IsoMovieRead)
|
||||
async def validate_movie(movie_id: int, db: DbSession) -> IsoMovie:
|
||||
"""Validation manuelle: supprime l'ISO, le torrent et le dossier de travail.
|
||||
@app.post("/api/movies/{movie_id}/validate", response_model=ValidationRead)
|
||||
async def validate_movie(movie_id: int, db: DbSession) -> ValidationRead:
|
||||
"""Validation manuelle: supprime l'ISO et le torrent, puis met a jour Radarr.
|
||||
|
||||
Le MKV brut du dossier de travail est conserve (meme inode que le lien
|
||||
du dossier du film): la fiche du film traite en affiche le chemin.
|
||||
|
||||
Le MKV lie dans le dossier du film reste en place (le lien dur etant sur
|
||||
le meme inode, les donnees restent intactes).
|
||||
@@ -400,21 +797,41 @@ async def validate_movie(movie_id: int, db: DbSession) -> IsoMovie:
|
||||
raise HTTPException(status_code=409, detail="Aucun MKV lié à valider")
|
||||
|
||||
# Supprime l'ISO et le reste du dossier du film, puis le torrent qBittorrent.
|
||||
finalize_validation(paths.destination_folder, linked.name)
|
||||
await _delete_iso_torrent(movie.path)
|
||||
try:
|
||||
finalize_validation(paths.destination_folder, linked.name)
|
||||
except Exception as error: # noqa: BLE001 - message explicite pour l'UI
|
||||
raise HTTPException(
|
||||
status_code=409, detail=f"Validation impossible (dossier du film): {error}"
|
||||
) from error
|
||||
movie.qb_content_path = await _delete_iso_torrent(movie.path)
|
||||
|
||||
# Nettoyage du dossier de travail (le lien dur garde les donnees).
|
||||
if linked.exists() and paths.mkv_path.exists():
|
||||
paths.mkv_path.unlink()
|
||||
if paths.mkv_path.parent.is_dir() and not any(paths.mkv_path.parent.iterdir()):
|
||||
paths.mkv_path.parent.rmdir()
|
||||
# Le MKV brut du dossier de travail est CONSERVE: meme inode que le lien
|
||||
# (aucun espace supplementaire), il reste accessible depuis la fiche du
|
||||
# film traite. Le dossier de travail n'est plus nettoye a la validation.
|
||||
# L'ISO du dossier de telechargements qBittorrent n'est PAS supprimee
|
||||
# ici: sa suppression est manuelle, sur l'etat "traite" (delete-iso).
|
||||
|
||||
movie.status = "completed"
|
||||
now = datetime.now(UTC)
|
||||
movie.processed_at = now
|
||||
movie.completed_at = now
|
||||
db.commit()
|
||||
return movie
|
||||
snapshot = ValidationRead.model_validate(movie)
|
||||
|
||||
# Rescan puis renommage Radarr (voir _sync_radarr_rename). Best effort:
|
||||
# un echec n'invalide pas la validation (l'ISO est deja supprimee),
|
||||
# il remonte en avertissement.
|
||||
rescan_warning: str | None = None
|
||||
try:
|
||||
await _sync_radarr_rename(movie)
|
||||
except Exception as error: # noqa: BLE001 - la validation reste acquise
|
||||
rescan_warning = (
|
||||
f"ISO supprimée, mais mise à jour Radarr impossible: {error}. "
|
||||
"Lancez un rescan puis un renommage du film dans Radarr pour "
|
||||
"qu'il détecte et renomme le MKV selon sa config."
|
||||
)
|
||||
snapshot.rescan_warning = rescan_warning
|
||||
return snapshot
|
||||
|
||||
|
||||
@app.delete("/api/movies/{movie_id}", response_model=IsoMovieRead)
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
"""Migrations versionnees de la base de donnees et de conf.json.
|
||||
|
||||
Chaque evolution de structure est une migration identifiee par un numero de
|
||||
version. Au demarrage, les migrations non appliquees sont jouees une seule
|
||||
fois et tracees :
|
||||
|
||||
- base de donnees : table ``schema_migrations`` (une ligne par version) ;
|
||||
- conf.json : cle ``version`` en tete du fichier.
|
||||
|
||||
Conventions importantes :
|
||||
|
||||
- ``Base.metadata.create_all`` cree deja le schema le plus recent sur une
|
||||
base vierge. Les migrations de base doivent donc etre inoffensives sur un
|
||||
schema deja a jour (verifier l'existence des tables/colonnes avant d'agir).
|
||||
- Les migrations sont appliquees dans l'ordre, chacune dans sa transaction,
|
||||
et enregistrees dans la meme transaction : une migration echouee laisse la
|
||||
base dans l'etat de la version precedente.
|
||||
|
||||
Pour ajouter une migration :
|
||||
|
||||
- base de donnees : ajouter un ``DbMigration`` en fin de ``DB_MIGRATIONS``
|
||||
avec le numero de version suivant ;
|
||||
- conf.json : ajouter une fonction ``(dict) -> dict`` en fin de
|
||||
``CONF_MIGRATIONS`` (elle transforme la version N vers N+1), puis mettre a
|
||||
jour la valeur par défaut de ``AppConfig.version`` dans conf_store.py.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import Connection, inspect, text
|
||||
from sqlalchemy.engine import Engine
|
||||
|
||||
from app.conf_store import read_raw_config, write_raw_config
|
||||
|
||||
|
||||
# --- Migrations de la base de donnees ---
|
||||
@dataclass(frozen=True)
|
||||
class DbMigration:
|
||||
"""Une migration de base : version cible, description, corps."""
|
||||
|
||||
version: int
|
||||
description: str
|
||||
upgrade: Callable[[Connection], None]
|
||||
|
||||
|
||||
def _upgrade_v1(conn: Connection) -> None:
|
||||
"""Colonnes de suivi des conversions (bases creees avant le systeme)."""
|
||||
inspector = inspect(conn)
|
||||
if not inspector.has_table("iso_movies"):
|
||||
return
|
||||
columns = {col["name"] for col in inspector.get_columns("iso_movies")}
|
||||
new_columns = {
|
||||
"processed_at": "DATETIME",
|
||||
"completed_at": "DATETIME",
|
||||
"failed_step": "TEXT",
|
||||
"last_error": "TEXT",
|
||||
"poster_url": "TEXT",
|
||||
"radarr_linked": "BOOLEAN DEFAULT 1",
|
||||
}
|
||||
for column, ddl in new_columns.items():
|
||||
if column not in columns:
|
||||
conn.execute(text(f"ALTER TABLE iso_movies ADD COLUMN {column} {ddl}"))
|
||||
|
||||
|
||||
DB_MIGRATIONS: list[DbMigration] = [
|
||||
DbMigration(
|
||||
version=1,
|
||||
description="iso_movies: colonnes de suivi des conversions",
|
||||
upgrade=_upgrade_v1,
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def _upgrade_v2(conn: Connection) -> None:
|
||||
"""Colonnes apparues dans les modeles sans migration a l'epoque.
|
||||
|
||||
Bases creees avant l'introduction de created_at / last_seen_at: elles
|
||||
manquent alors que les autres migrations les considerent acquises.
|
||||
"""
|
||||
inspector = inspect(conn)
|
||||
if not inspector.has_table("iso_movies"):
|
||||
return
|
||||
columns = {col["name"] for col in inspector.get_columns("iso_movies")}
|
||||
for column, ddl in (("created_at", "DATETIME"), ("last_seen_at", "DATETIME")):
|
||||
if column not in columns:
|
||||
conn.execute(text(f"ALTER TABLE iso_movies ADD COLUMN {column} {ddl}"))
|
||||
|
||||
|
||||
DB_MIGRATIONS.append(
|
||||
DbMigration(
|
||||
version=2,
|
||||
description="iso_movies: colonnes created_at/last_seen_at sur les bases anciennes",
|
||||
upgrade=_upgrade_v2,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _upgrade_v3(conn: Connection) -> None:
|
||||
"""Colonne du chemin ISO cote telechargements qBittorrent.
|
||||
|
||||
Capture au moment de la validation, elle permet la suppression
|
||||
manuelle de l'ISO sur l'etat "traite" (tag "ISO a supprimer").
|
||||
"""
|
||||
inspector = inspect(conn)
|
||||
if not inspector.has_table("iso_movies"):
|
||||
return
|
||||
columns = {col["name"] for col in inspector.get_columns("iso_movies")}
|
||||
if "qb_content_path" not in columns:
|
||||
conn.execute(text("ALTER TABLE iso_movies ADD COLUMN qb_content_path TEXT"))
|
||||
|
||||
|
||||
DB_MIGRATIONS.append(
|
||||
DbMigration(
|
||||
version=3,
|
||||
description="iso_movies: colonne qb_content_path (ISO cote telechargements)",
|
||||
upgrade=_upgrade_v3,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def run_db_migrations(engine: Engine) -> list[str]:
|
||||
"""Applique les migrations non jouees; renvoie leurs descriptions."""
|
||||
with engine.begin() as conn:
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version INTEGER PRIMARY KEY,
|
||||
description TEXT NOT NULL,
|
||||
applied_at TEXT NOT NULL
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
with engine.connect() as conn:
|
||||
applied = {
|
||||
row[0] for row in conn.execute(text("SELECT version FROM schema_migrations"))
|
||||
}
|
||||
|
||||
done: list[str] = []
|
||||
for migration in DB_MIGRATIONS:
|
||||
if migration.version in applied:
|
||||
continue
|
||||
with engine.begin() as conn:
|
||||
migration.upgrade(conn)
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO schema_migrations (version, description, applied_at)
|
||||
VALUES (:version, :description, :applied_at)
|
||||
"""
|
||||
),
|
||||
{
|
||||
"version": migration.version,
|
||||
"description": migration.description,
|
||||
"applied_at": datetime.now(UTC).isoformat(),
|
||||
},
|
||||
)
|
||||
done.append(migration.description)
|
||||
return done
|
||||
|
||||
|
||||
# --- Migrations de conf.json ---
|
||||
# CONF_MIGRATIONS[i] transforme le contenu brut du fichier de la version
|
||||
# i+1 vers i+2. La version courante de la structure suit la longueur de
|
||||
# cette liste; elle doit rester synchrone avec AppConfig.version par defaut.
|
||||
def _conf_v1_to_v2(data: dict) -> dict:
|
||||
"""v2: retrait des services hors perimetre (Sonarr, Prowlarr, Jellyfin, Seerr)."""
|
||||
for service in ("sonarr", "prowlarr", "jellyfin", "seerr"):
|
||||
data.pop(service, None)
|
||||
return data
|
||||
|
||||
|
||||
CONF_MIGRATIONS: list[Callable[[dict], dict]] = [_conf_v1_to_v2]
|
||||
|
||||
|
||||
def current_conf_version() -> int:
|
||||
return 1 + len(CONF_MIGRATIONS)
|
||||
|
||||
|
||||
def migrate_conf_file() -> list[str]:
|
||||
"""Migre conf.json vers la version courante de la structure.
|
||||
|
||||
Un fichier sans cle ``version`` est considere comme v1 (structure
|
||||
d'avant la mise en place du systeme). Renvoie la liste des migrations
|
||||
appliquees, pour trace au demarrage.
|
||||
"""
|
||||
raw = read_raw_config()
|
||||
if raw is None:
|
||||
return []
|
||||
|
||||
version = raw.get("version")
|
||||
if not isinstance(version, int):
|
||||
version = 1
|
||||
|
||||
applied: list[str] = []
|
||||
for step, migrate in enumerate(CONF_MIGRATIONS, start=1):
|
||||
if version > step:
|
||||
continue
|
||||
raw = migrate(raw)
|
||||
applied.append(f"conf.json v{step} -> v{step + 1}")
|
||||
|
||||
target = current_conf_version()
|
||||
if raw.get("version") != target:
|
||||
raw["version"] = target
|
||||
write_raw_config(raw)
|
||||
return applied
|
||||
+7
-1
@@ -1,6 +1,6 @@
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import BigInteger, DateTime, String, Text, UniqueConstraint, func
|
||||
from sqlalchemy import BigInteger, Boolean, DateTime, String, Text, UniqueConstraint, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.database import Base
|
||||
@@ -25,6 +25,8 @@ class IsoMovie(Base):
|
||||
path: Mapped[str] = mapped_column(Text)
|
||||
size: Mapped[int | None] = mapped_column(BigInteger)
|
||||
status: Mapped[str] = mapped_column(String(30), default="detected")
|
||||
# Le fichier ISO existe toujours tel quel cote Radarr (mis a jour au scan).
|
||||
radarr_linked: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
poster_url: Mapped[str | None] = mapped_column(Text)
|
||||
last_seen_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now()
|
||||
@@ -34,6 +36,10 @@ class IsoMovie(Base):
|
||||
completed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
failed_step: Mapped[str | None] = mapped_column(String(30))
|
||||
last_error: Mapped[str | None] = mapped_column(Text)
|
||||
# Chemin de l'ISO cote dossier de telechargements qBittorrent, capture au
|
||||
# moment de la validation: la suppression se fait ensuite manuellement
|
||||
# sur l'etat "traite" (voir /api/movies/{id}/delete-iso).
|
||||
qb_content_path: Mapped[str | None] = mapped_column(Text)
|
||||
|
||||
|
||||
class User(Base):
|
||||
|
||||
-112
@@ -1,112 +0,0 @@
|
||||
"""Nom du fichier MKV selon la configuration Media Management de Radarr.
|
||||
|
||||
Applique le "Standard Movie Format" de Radarr (/api/v3/config/naming) au
|
||||
fichier converti : les tokens usuels ({Movie Title}, {Release Year},
|
||||
{Quality Title}...) sont remplacés à partir des données du film et du
|
||||
movieFile. Si Radarr n'est pas configuré pour renommer (renameMovies=false),
|
||||
le nom d'origine du MKV est conservé.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
from app.converter import sanitize_component
|
||||
|
||||
_VIDEO_CODECS = {
|
||||
"h264": "x264",
|
||||
"x264": "x264",
|
||||
"h265": "x265",
|
||||
"hevc": "x265",
|
||||
"x265": "x265",
|
||||
"av1": "AV1",
|
||||
"mpeg2video": "MPEG2",
|
||||
"mpeg-2": "MPEG2",
|
||||
"vc1": "VC1",
|
||||
"vp9": "VP9",
|
||||
"xvid": "Xvid",
|
||||
"divx": "DivX",
|
||||
}
|
||||
|
||||
_AUDIO_CODECS = {
|
||||
"ac3": "AC3",
|
||||
"eac3": "EAC3",
|
||||
"dts": "DTS",
|
||||
"truehd": "TrueHD",
|
||||
"flac": "FLAC",
|
||||
"aac": "AAC",
|
||||
"mp3": "MP3",
|
||||
"opus": "Opus",
|
||||
"vorbis": "Vorbis",
|
||||
"pcm": "PCM",
|
||||
"lpcm": "PCM",
|
||||
}
|
||||
|
||||
_INVALID_TOKEN = re.compile(r"\{[^{}]*\}")
|
||||
|
||||
|
||||
def _media_info_tokens(movie_file: dict) -> dict[str, str]:
|
||||
media = movie_file.get("mediaInfo") or {}
|
||||
video = str(media.get("videoCodec", "") or "").lower()
|
||||
audio = str(media.get("audioCodec", "") or "").lower()
|
||||
channels = str(media.get("audioChannels", "") or "")
|
||||
simple = "-".join(part for part in (_VIDEO_CODECS.get(video, video.upper()), channels) if part)
|
||||
full = " ".join(
|
||||
part
|
||||
for part in (
|
||||
_VIDEO_CODECS.get(video, video.upper()),
|
||||
_AUDIO_CODECS.get(audio, audio.upper()),
|
||||
channels,
|
||||
)
|
||||
if part
|
||||
)
|
||||
return {"MediaInfo Simple": simple, "MediaInfo Full": full}
|
||||
|
||||
|
||||
def _quality_tokens(movie_file: dict) -> dict[str, str]:
|
||||
quality = (movie_file.get("quality") or {}).get("quality") or {}
|
||||
revision = (movie_file.get("quality") or {}).get("revision") or {}
|
||||
title = str(quality.get("name", "") or "")
|
||||
version = int(revision.get("version", 1) or 1)
|
||||
is_real = int(revision.get("real", 0) or 0)
|
||||
return {
|
||||
"Quality Title": title,
|
||||
"Quality Full": " ".join(
|
||||
part
|
||||
for part in (title, "Proper" if version > 1 else "", "Real" if is_real else "")
|
||||
if part
|
||||
),
|
||||
"Quality Proper": "Proper" if version > 1 else "",
|
||||
"Quality Real": "Real" if is_real else "",
|
||||
}
|
||||
|
||||
|
||||
def movie_file_name(naming: dict, movie: dict, movie_file: dict, fallback: str) -> str:
|
||||
"""Construit le nom de fichier (sans extension) attendu par Radarr."""
|
||||
if not naming.get("renameMovies"):
|
||||
return fallback
|
||||
|
||||
pattern = str(naming.get("standardMovieFormat", "") or "")
|
||||
if not pattern:
|
||||
return fallback
|
||||
|
||||
tokens = {
|
||||
"Movie Title": sanitize_component(str(movie.get("title", "") or "")),
|
||||
"Movie CleanTitle": sanitize_component(str(movie.get("title", "") or "")),
|
||||
"Movie OriginalTitle": sanitize_component(str(movie.get("originalTitle", "") or "")),
|
||||
"Release Year": str(movie.get("year", "") or ""),
|
||||
"Year": str(movie.get("year", "") or ""),
|
||||
"Tmdb Id": str(movie.get("tmdbId", "") or ""),
|
||||
"Imdb Id": str(movie.get("imdbId", "") or ""),
|
||||
"Edition": sanitize_component(str(movie_file.get("edition", "") or "")),
|
||||
"Release Group": sanitize_component(str(movie_file.get("releaseGroup", "") or "")),
|
||||
}
|
||||
tokens.update(_quality_tokens(movie_file))
|
||||
tokens.update(_media_info_tokens(movie_file))
|
||||
|
||||
result = pattern
|
||||
for token, value in tokens.items():
|
||||
result = result.replace("{" + token + "}", value)
|
||||
result = result.replace("{" + token.lower() + "}", value)
|
||||
# Tokens inconnus: retires pour ne pas laisser d'accolades dans le nom.
|
||||
result = _INVALID_TOKEN.sub("", result)
|
||||
result = sanitize_component(result)
|
||||
return result or fallback
|
||||
+36
-10
@@ -6,25 +6,51 @@ import httpx
|
||||
|
||||
|
||||
class QbittorrentClient:
|
||||
def __init__(self, url: str, username: str, password: str) -> None:
|
||||
"""Client WebUI (API v2).
|
||||
|
||||
Modes d'authentification, dans l'ordre de priorite:
|
||||
|
||||
1. Cle API (qBittorrent >= 5.2): envoyee en en-tete ``Authorization:
|
||||
Bearer <cle>`` sur chaque appel, sans login ni session.
|
||||
2. Identifiants (login ``POST /api/v2/auth/login`` + cookie de session).
|
||||
qBittorrent >= 5.2 repond 204 sans corps; les versions anterieures
|
||||
renvoient 200 avec le corps "Ok.".
|
||||
3. Sans rien: bypass d'authentification qBittorrent (la plage IP du
|
||||
conteneur doit etre autorisee dans la WebUI), aucune API key native
|
||||
n'existait avant la 5.2.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
url: str,
|
||||
username: str | None = None,
|
||||
password: str | None = None,
|
||||
api_key: str | None = None,
|
||||
) -> None:
|
||||
self._url = url.rstrip("/")
|
||||
self._username = username
|
||||
self._password = password
|
||||
self._api_key = api_key
|
||||
|
||||
async def _request(self, method: str, endpoint: str, **kwargs) -> httpx.Response:
|
||||
headers = {"Referer": self._url}
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
login = await client.post(
|
||||
f"{self._url}/api/v2/auth/login",
|
||||
data={"username": self._username, "password": self._password},
|
||||
headers={"Referer": self._url},
|
||||
)
|
||||
login.raise_for_status()
|
||||
if login.text.strip() != "Ok.":
|
||||
raise ValueError("Authentification qBittorrent refusée")
|
||||
if self._api_key:
|
||||
headers["Authorization"] = f"Bearer {self._api_key}"
|
||||
elif self._username and self._password:
|
||||
login = await client.post(
|
||||
f"{self._url}/api/v2/auth/login",
|
||||
data={"username": self._username, "password": self._password},
|
||||
headers={"Referer": self._url},
|
||||
)
|
||||
login.raise_for_status()
|
||||
# qBittorrent >= 5.2 renvoie 204 sans corps.
|
||||
if login.status_code != 204 and login.text.strip() != "Ok.":
|
||||
raise ValueError("Authentification qBittorrent refusée")
|
||||
response = await client.request(
|
||||
method,
|
||||
f"{self._url}{endpoint}",
|
||||
headers={"Referer": self._url},
|
||||
headers=headers,
|
||||
**kwargs,
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
+31
-7
@@ -28,18 +28,42 @@ class RadarrClient:
|
||||
raise ValueError("Réponse Radarr inattendue")
|
||||
return result
|
||||
|
||||
async def _command(self, payload: dict) -> None:
|
||||
"""Enfile une commande Radarr (traitees sequentiellement par Radarr)."""
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
response = await client.post(
|
||||
f"{self._url}/api/v3/command",
|
||||
headers=self._headers,
|
||||
json=payload,
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
async def movie(self, movie_id: int) -> dict:
|
||||
result = await self._get(f"movie/{movie_id}?includeMovieFile=true")
|
||||
"""Fiche Radarr d'un film (avec son movieFile): donne le chemin
|
||||
attendu du fichier, notamment apres renommage Media Management."""
|
||||
result = await self._get(f"movie/{movie_id}")
|
||||
if not isinstance(result, dict):
|
||||
raise ValueError("Réponse Radarr inattendue")
|
||||
return result
|
||||
|
||||
async def naming(self) -> dict:
|
||||
"""Configuration Media Management: formats de renommage."""
|
||||
result = await self._get("config/naming")
|
||||
if not isinstance(result, dict):
|
||||
raise ValueError("Réponse Radarr inattendue")
|
||||
return result
|
||||
async def rescan_movie(self, movie_id: int) -> None:
|
||||
"""Demande a Radarr de rescanner le dossier du film.
|
||||
|
||||
Apres validation d'une conversion, le dossier ne contient plus que
|
||||
le MKV lie (lien dur): Radarr l'adopte comme fichier du film a la
|
||||
place de l'ISO supprimee.
|
||||
"""
|
||||
await self._command({"name": "RescanMovie", "movieId": movie_id})
|
||||
|
||||
async def rename_movie(self, movie_id: int) -> None:
|
||||
"""Demande a Radarr de renommer les fichiers du film selon sa config
|
||||
Media Management.
|
||||
|
||||
Enchaine apres le rescan: le MKV lie prend le nom standard Radarr
|
||||
(l'ancien nom de l'ISO ne correspond pas au format attendu). Le
|
||||
renommage preserve l'inode, le lien dur reste intact.
|
||||
"""
|
||||
await self._command({"name": "RenameMovie", "movieId": movie_id})
|
||||
|
||||
|
||||
def movie_file_path(movie: dict) -> str | None:
|
||||
|
||||
+76
-24
@@ -1,55 +1,53 @@
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, HttpUrl
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class RadarrSettingsRead(BaseModel):
|
||||
url: str | None
|
||||
port: int | None = None
|
||||
api_key_configured: bool
|
||||
status: str
|
||||
tested_version: str | None = None
|
||||
tested_at: str | None = None
|
||||
test_error: str | None = None
|
||||
|
||||
|
||||
class RadarrSettingsWrite(BaseModel):
|
||||
url: HttpUrl
|
||||
api_key: str | None = Field(default=None, min_length=1)
|
||||
|
||||
|
||||
class ApiServiceSettingsRead(BaseModel):
|
||||
url: str | None
|
||||
api_key_configured: bool
|
||||
|
||||
|
||||
class ApiServiceSettingsWrite(BaseModel):
|
||||
url: HttpUrl | None = None
|
||||
url: str
|
||||
port: int | None = Field(default=None, ge=1, le=65535)
|
||||
api_key: str | None = Field(default=None, min_length=1)
|
||||
|
||||
|
||||
class QbittorrentSettingsRead(BaseModel):
|
||||
url: str | None
|
||||
port: int | None = None
|
||||
username: str | None
|
||||
password_configured: bool
|
||||
api_key_configured: bool
|
||||
status: str
|
||||
tested_version: str | None = None
|
||||
tested_at: str | None = None
|
||||
test_error: str | None = None
|
||||
|
||||
|
||||
class QbittorrentSettingsWrite(BaseModel):
|
||||
url: HttpUrl | None = None
|
||||
username: str | None = Field(default=None, min_length=1)
|
||||
url: str | None = None
|
||||
port: int | None = Field(default=None, ge=1, le=65535)
|
||||
# Utilisateur vide = bypass d'authentification qBittorrent.
|
||||
username: str | None = None
|
||||
password: str | None = Field(default=None, min_length=1)
|
||||
# Cle API native qBittorrent >= 5.2, prioritaire sur le login.
|
||||
api_key: str | None = Field(default=None, min_length=1)
|
||||
|
||||
|
||||
class SettingsRead(BaseModel):
|
||||
radarr: ApiServiceSettingsRead
|
||||
sonarr: ApiServiceSettingsRead
|
||||
prowlarr: ApiServiceSettingsRead
|
||||
jellyfin: ApiServiceSettingsRead
|
||||
seerr: ApiServiceSettingsRead
|
||||
radarr: RadarrSettingsRead
|
||||
qbittorrent: QbittorrentSettingsRead
|
||||
|
||||
|
||||
class SettingsWrite(BaseModel):
|
||||
radarr: ApiServiceSettingsWrite | None = None
|
||||
sonarr: ApiServiceSettingsWrite | None = None
|
||||
prowlarr: ApiServiceSettingsWrite | None = None
|
||||
jellyfin: ApiServiceSettingsWrite | None = None
|
||||
seerr: ApiServiceSettingsWrite | None = None
|
||||
radarr: RadarrSettingsWrite | None = None
|
||||
qbittorrent: QbittorrentSettingsWrite | None = None
|
||||
|
||||
|
||||
@@ -70,6 +68,7 @@ class IsoMovieRead(BaseModel):
|
||||
path: str
|
||||
size: int | None
|
||||
status: str
|
||||
radarr_linked: bool = True
|
||||
poster_url: str | None = None
|
||||
last_seen_at: datetime
|
||||
created_at: datetime | None = None
|
||||
@@ -79,11 +78,64 @@ class IsoMovieRead(BaseModel):
|
||||
last_error: str | None = None
|
||||
|
||||
|
||||
class IsoMovieDetailRead(IsoMovieRead):
|
||||
"""Fiche detaillee: chemins calcules et etat du dossier de travail."""
|
||||
|
||||
work_mkv_path: str | None = None
|
||||
linked_mkv_path: str | None = None
|
||||
workspace_folder: str | None = None
|
||||
workspace_files: list[str] = Field(default_factory=list)
|
||||
# ISO cote dossier de telechargements qBittorrent: presente tant qu'elle
|
||||
# n'a pas ete supprimee manuellement sur l'etat "traite".
|
||||
qb_content_path: str | None = None
|
||||
iso_to_delete: bool = False
|
||||
# Lien du MKV introuvable dans le dossier du film alors que le MKV brut
|
||||
# existe: la fiche propose la reparation.
|
||||
link_broken: bool = False
|
||||
# Le lien du dossier du film est un lien symbolique (herité d'anciennes
|
||||
# versions): son chemin n'est valide que dans le conteneur MKVTool,
|
||||
# Jellyfin ne peut pas le suivre. La fiche propose la reparation.
|
||||
link_symbolic: bool = False
|
||||
|
||||
|
||||
class ValidationRead(IsoMovieRead):
|
||||
"""Resultat de la validation: film + avertissement eventuel.
|
||||
|
||||
La validation reussit meme si le rescan Radarr echoue (l'ISO est deja
|
||||
supprimee); le champ rescan_warning le signale a l'interface.
|
||||
"""
|
||||
|
||||
rescan_warning: str | None = None
|
||||
|
||||
|
||||
class RepairLinkResult(IsoMovieRead):
|
||||
"""Resultat d'une reparation de lien: film + message explicite."""
|
||||
|
||||
message: str = ""
|
||||
|
||||
|
||||
class BulkRenameFailure(BaseModel):
|
||||
title: str
|
||||
error: str
|
||||
|
||||
|
||||
class BulkRenameResult(BaseModel):
|
||||
renamed: int
|
||||
failures: list[BulkRenameFailure] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ConversionLogRead(BaseModel):
|
||||
lines: list[str]
|
||||
running: bool
|
||||
|
||||
|
||||
class ScanResult(BaseModel):
|
||||
scanned_movies: int
|
||||
iso_files: int
|
||||
created: int
|
||||
updated: int
|
||||
# Films convertis dont le chemin stocke a ete rafraichi depuis Radarr.
|
||||
refreshed: int = 0
|
||||
|
||||
|
||||
class HealthRead(BaseModel):
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
"""Legacy module.
|
||||
|
||||
Historically, MKVTool stored connection settings inside SQLite.
|
||||
The project now externalises its configuration into ./config/conf.json.
|
||||
|
||||
This module is kept temporarily because some imports may still reference it.
|
||||
"""
|
||||
|
||||
from app.conf_store import read_config
|
||||
|
||||
|
||||
def radarr_credentials(_: object | None = None) -> tuple[str, str]:
|
||||
cfg = read_config()
|
||||
if not cfg.radarr.url or not cfg.radarr.api_key:
|
||||
raise ValueError("La connexion Radarr n'est pas configurée")
|
||||
return cfg.radarr.url.rstrip("/"), cfg.radarr.api_key
|
||||
+45
-32
@@ -1,4 +1,4 @@
|
||||
"""Worker de conversion: traite les films en file, une conversion à la fois."""
|
||||
"""Worker de conversion: traite les films en file, une conversion a la fois."""
|
||||
|
||||
import asyncio
|
||||
import traceback
|
||||
@@ -6,34 +6,66 @@ from pathlib import Path
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.conf_store import read_config
|
||||
from app.config import settings
|
||||
from app.converter import container_iso_path, conversion_paths, extract_mkv, import_mkv
|
||||
from app.database import SessionLocal
|
||||
from app.models import IsoMovie
|
||||
from app.naming import movie_file_name
|
||||
from app.radarr import RadarrClient
|
||||
|
||||
LOG_LIMIT = 500
|
||||
# Journal de la conversion en cours, par film (diffuse dans l'interface).
|
||||
_run_logs: dict[int, list[str]] = {}
|
||||
_current_movie_id: int | None = None
|
||||
|
||||
|
||||
def conversion_log(movie_id: int) -> list[str]:
|
||||
"""Lignes du journal de conversion du film (vide si jamais converti)."""
|
||||
return list(_run_logs.get(movie_id, []))
|
||||
|
||||
|
||||
def is_converting(movie_id: int) -> bool:
|
||||
"""Vrai si ce film est celui en cours de traitement par le worker."""
|
||||
return _current_movie_id == movie_id
|
||||
|
||||
|
||||
def _log(movie_id: int, line: str) -> None:
|
||||
log = _run_logs.setdefault(movie_id, [])
|
||||
log.append(line)
|
||||
if len(log) > LOG_LIMIT:
|
||||
del log[: len(log) - LOG_LIMIT]
|
||||
|
||||
|
||||
async def _process(movie_id: int) -> None:
|
||||
global _current_movie_id
|
||||
with SessionLocal() as db:
|
||||
movie = db.get(IsoMovie, movie_id)
|
||||
if movie is None or movie.status != "queued":
|
||||
return
|
||||
paths = conversion_paths(movie)
|
||||
step = "converting"
|
||||
_run_logs[movie_id] = []
|
||||
_current_movie_id = movie_id
|
||||
try:
|
||||
movie.status = "converting"
|
||||
movie.last_error = None
|
||||
db.commit()
|
||||
# Reprise: si le MKV existe deja (echec precedent apres l'extraction),
|
||||
# on ne relance pas MakeMKV et on reprend a l'import.
|
||||
if not paths.mkv_path.exists():
|
||||
await asyncio.to_thread(extract_mkv, movie, paths.mkv_path)
|
||||
# Reprise: uniquement si l'echec precedent a eu lieu APRES
|
||||
# l'extraction (import). Un MKV issu d'une extraction incomplete
|
||||
# n'est jamais repris: la conversion repart de zero.
|
||||
resumable = movie.failed_step == "importing" and paths.mkv_path.exists()
|
||||
if not resumable:
|
||||
_log(movie_id, "— Extraction MakeMKV en cours…")
|
||||
await asyncio.to_thread(
|
||||
extract_mkv, movie, paths.mkv_path, lambda line: _log(movie_id, line)
|
||||
)
|
||||
else:
|
||||
_log(movie_id, "— MKV déjà extrait, reprise à l'import.")
|
||||
step = "importing"
|
||||
movie.status = "importing"
|
||||
db.commit()
|
||||
target_name = await _target_name(movie)
|
||||
# Le MKV lié reprend le nom du fichier Radarr (l'ISO), seule
|
||||
# l'extension change.
|
||||
target_name = f"{Path(movie.path).stem}.mkv"
|
||||
_log(movie_id, "— Import: lien dans le dossier du film…")
|
||||
await asyncio.to_thread(
|
||||
import_mkv,
|
||||
paths.mkv_path,
|
||||
@@ -45,37 +77,18 @@ async def _process(movie_id: int) -> None:
|
||||
# via l'endpoint de validation apres verification par l'utilisateur.
|
||||
movie.status = "validating"
|
||||
movie.failed_step = None
|
||||
_log(movie_id, "— Conversion terminée: en attente de validation.")
|
||||
except Exception as error: # noqa: BLE001 - le worker doit survivre a toute erreur
|
||||
movie.status = "failed"
|
||||
movie.failed_step = step
|
||||
movie.last_error = f"{error}"
|
||||
_log(movie_id, f"— Échec ({step}): {error}")
|
||||
traceback.print_exc()
|
||||
finally:
|
||||
_current_movie_id = None
|
||||
db.commit()
|
||||
|
||||
|
||||
async def _target_name(movie: IsoMovie) -> str:
|
||||
"""Nom du lien selon la configuration Media Management de Radarr.
|
||||
|
||||
En cas d'erreur (Radarr non configuré, API injoignable), on retombe sur le
|
||||
nom du MKV produit par MakeMKV plutôt que de faire échouer la conversion.
|
||||
"""
|
||||
fallback = Path(conversion_paths(movie).mkv_path).name
|
||||
cfg = read_config()
|
||||
if not cfg.radarr.url or not cfg.radarr.api_key:
|
||||
return fallback
|
||||
try:
|
||||
client = RadarrClient(cfg.radarr.url, cfg.radarr.api_key)
|
||||
radarr_movie = await client.movie(movie.radarr_movie_id)
|
||||
naming = await client.naming()
|
||||
name = movie_file_name(
|
||||
naming, radarr_movie, radarr_movie.get("movieFile") or {}, fallback
|
||||
)
|
||||
return name if name.lower().endswith(".mkv") else f"{name}.mkv"
|
||||
except Exception: # noqa: BLE001 - le nommage ne doit pas bloquer la conversion
|
||||
traceback.print_exc()
|
||||
return fallback
|
||||
|
||||
|
||||
async def _process_next() -> bool:
|
||||
with SessionLocal() as db:
|
||||
movie_id = db.scalar(
|
||||
|
||||
+6
-1
@@ -7,7 +7,9 @@ services:
|
||||
build:
|
||||
context: .
|
||||
args:
|
||||
MAKEMKV_VERSION: "2.0.0"
|
||||
# 1.18.4: la 2.0.0 plante sur les ISO Blu-ray non chiffrees
|
||||
# (regression connue, voir IMAGE.md).
|
||||
MAKEMKV_VERSION: "1.18.4"
|
||||
container_name: mkvtool
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
@@ -27,6 +29,9 @@ services:
|
||||
# Chemin de la bibliotheque tel que Radarr le rapporte (traduction ISO).
|
||||
MKVTOOL_RADARR_FILMS_DIR: /nas_storage/jellyfin/films
|
||||
MKVTOOL_DOWNLOADS_DIR: /qbittorrentdownloads
|
||||
# Clé d'activation MakeMKV: clé bêta gratuite du forum officiel
|
||||
# (rotation tous les 1-2 mois) ou clé permanente — voir IMAGE.md.
|
||||
MAKEMKV_KEY: "T-VOTRE-CLE"
|
||||
volumes:
|
||||
# La bibliotheque Jellyfin est montee en /films dans le conteneur; les
|
||||
# chemins Radarr (MKVTOOL_RADARR_FILMS_DIR) sont traduits par l'API.
|
||||
|
||||
+50
-9
@@ -15,19 +15,60 @@ puisse créer, supprimer et lier des fichiers dedans, sans que le bit
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
puid = int(os.environ.get("PUID", "0") or "0")
|
||||
pgid = int(os.environ.get("PGID", "0") or "0")
|
||||
config_dir = os.environ.get("MKVTOOL_CONFIG_DIR", "/config")
|
||||
|
||||
if os.geteuid() == 0 and puid:
|
||||
if os.path.isdir(config_dir):
|
||||
subprocess.run(
|
||||
["chown", "-R", f"{puid}:{pgid or puid}", config_dir], check=False
|
||||
)
|
||||
os.setgroups([pgid] if pgid else [])
|
||||
if pgid:
|
||||
os.setgid(pgid)
|
||||
os.setuid(puid)
|
||||
|
||||
def write_makemkv_key() -> None:
|
||||
"""Ecrit la cle MakeMKV (env MAKEMKV_KEY) dans settings.conf.
|
||||
|
||||
MakeMKV lit ``app_Key`` dans ``/config/.MakeMKV/settings.conf``
|
||||
(la commande ``makemkvcon reg <cle>`` est peu fiable sur Linux).
|
||||
La cle bêta courante: forum officiel MakeMKV, fil « MakeMKV is free
|
||||
while in beta » (rotation tous les un a deux mois).
|
||||
"""
|
||||
key = os.environ.get("MAKEMKV_KEY", "").strip()
|
||||
if not key:
|
||||
return
|
||||
settings_path = Path(config_dir) / ".MakeMKV" / "settings.conf"
|
||||
settings_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
lines = []
|
||||
if settings_path.exists():
|
||||
lines = [
|
||||
line
|
||||
for line in settings_path.read_text(encoding="utf-8").splitlines()
|
||||
if not line.strip().startswith("app_Key")
|
||||
]
|
||||
lines.append(f'app_Key = "{key}"')
|
||||
settings_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
if os.geteuid() == 0:
|
||||
write_makemkv_key()
|
||||
if puid:
|
||||
if os.path.isdir(config_dir):
|
||||
subprocess.run(
|
||||
["chown", "-R", f"{puid}:{pgid or puid}", config_dir], check=False
|
||||
)
|
||||
# Entree passwd pour PUID: certains binaires (MakeMKV) resolvent le
|
||||
# repertoire utilisateur via getpwuid et non via $HOME. Sans entree,
|
||||
# makemkvcon ne trouve pas sa configuration (/config/.MakeMKV).
|
||||
try:
|
||||
with open("/etc/passwd", encoding="utf-8") as handle:
|
||||
known_uids = {line.split(":")[2] for line in handle if ":" in line}
|
||||
if str(puid) not in known_uids:
|
||||
with open("/etc/passwd", "a", encoding="utf-8") as handle:
|
||||
handle.write(
|
||||
f"mkvtool:x:{puid}:{pgid or puid}::{config_dir}:/usr/sbin/nologin\n"
|
||||
)
|
||||
except OSError:
|
||||
pass
|
||||
os.setgroups([pgid] if pgid else [])
|
||||
if pgid:
|
||||
os.setgid(pgid)
|
||||
os.setuid(puid)
|
||||
|
||||
os.execvp(sys.argv[1], sys.argv[1:])
|
||||
@@ -22,6 +22,7 @@ dev = [
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
pythonpath = ["."]
|
||||
asyncio_mode = "auto"
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 100
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Serveur d'integration pour les tests Playwright.
|
||||
|
||||
Prepare un environnement completement isole (config, bibliotheque et
|
||||
telechargements en temporaire), seme un compte utilisateur et quelques films
|
||||
dans tous les etats, sert le front construit (web/dist) via l'API, puis
|
||||
tourne avec les conversions en mode simulation — exactement les conditions
|
||||
d'une conversion reelle, sans Radarr ni qBittorrent.
|
||||
"""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parent.parent
|
||||
E2E_HOME = Path(os.environ.get("MKVTOOL_E2E_HOME", "/tmp/mkvtool-e2e"))
|
||||
|
||||
# Environnement neuf a chaque lancement.
|
||||
shutil.rmtree(E2E_HOME, ignore_errors=True)
|
||||
config_dir = E2E_HOME / "config"
|
||||
films = E2E_HOME / "films"
|
||||
radarr_ref = E2E_HOME / "radarr"
|
||||
downloads = E2E_HOME / "downloads"
|
||||
for folder in (config_dir, films, radarr_ref, downloads):
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
os.environ.update(
|
||||
{
|
||||
"MKVTOOL_CONFIG_DIR": str(config_dir),
|
||||
"MKVTOOL_FILMS_DIR": str(films),
|
||||
"MKVTOOL_RADARR_FILMS_DIR": str(radarr_ref),
|
||||
"MKVTOOL_DOWNLOADS_DIR": str(downloads),
|
||||
"MKVTOOL_SIMULATE_CONVERSION": "true",
|
||||
"MKVTOOL_WORKER_INTERVAL": "0.05",
|
||||
"MKVTOOL_WEB_DIR": str(REPO / "web" / "dist"),
|
||||
}
|
||||
)
|
||||
sys.path.insert(0, str(REPO))
|
||||
|
||||
from app import auth, models # noqa: E402,F401 - modeles SQLAlchemy
|
||||
from app.database import Base, SessionLocal, engine # noqa: E402
|
||||
from app.models import IsoMovie # noqa: E402
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
|
||||
def fake_iso(folder: str, name: str) -> Path:
|
||||
target = radarr_ref / folder
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
iso = target / name
|
||||
iso.write_bytes(b"\x00CD001 fausse image")
|
||||
return iso
|
||||
|
||||
|
||||
def seed_movie(movie_id: int, file_id: int, title: str, year: int, iso_path: Path, **fields):
|
||||
return IsoMovie(
|
||||
radarr_movie_id=movie_id,
|
||||
radarr_movie_file_id=file_id,
|
||||
title=title,
|
||||
year=year,
|
||||
path=str(iso_path),
|
||||
last_seen_at=datetime.now(UTC),
|
||||
**fields,
|
||||
)
|
||||
|
||||
|
||||
with SessionLocal() as db:
|
||||
# Films detectes: chacun a son role, les scenarios sont independants.
|
||||
pacific = fake_iso("Pacific Rim (2013)", "PACIFIC_RIM_UHD.iso")
|
||||
db.add(seed_movie(10, 20, "Pacific Rim", 2013, pacific, status="detected", size=42))
|
||||
autre = fake_iso("Autre Film (2022)", "AUTRE_FILM.iso")
|
||||
db.add(seed_movie(13, 23, "Autre Film", 2022, autre, status="detected", size=7))
|
||||
for mid, fid, title, year in [
|
||||
(14, 24, "Film Liste", 2019),
|
||||
(15, 25, "Film Jetable 1", 2018),
|
||||
(16, 26, "Film Jetable 2", 2017),
|
||||
(18, 28, "Film Jetable 3", 2016),
|
||||
(19, 29, "Film Jetable 4", 2015),
|
||||
]:
|
||||
iso = fake_iso(f"{title} ({year})", f"{title.upper().replace(' ', '_')}.ISO")
|
||||
db.add(seed_movie(mid, fid, title, year, iso, status="detected", size=5))
|
||||
# Un film termine: MKV lie dans le dossier du film, brut conserve
|
||||
# (meme inode, comme une vraie validation).
|
||||
cars_iso = fake_iso("Cars (2006)", "Cars.iso")
|
||||
cars_folder = films / "Cars (2006)"
|
||||
cars_folder.mkdir(parents=True, exist_ok=True)
|
||||
linked = cars_folder / "Cars (2006).mkv"
|
||||
linked.write_text("mkv lie")
|
||||
workspace = downloads / "Cars 2006"
|
||||
workspace.mkdir(parents=True, exist_ok=True)
|
||||
os.link(linked, workspace / "Cars (2006).mkv")
|
||||
db.add(
|
||||
seed_movie(
|
||||
11, 21, "Cars", 2006, cars_iso, status="completed", size=21
|
||||
)
|
||||
)
|
||||
# Un film en echec avec sa trace d'erreur (fiche/journal) et un autre
|
||||
# pour le scenario de reprise (conversion.spec).
|
||||
for mid, fid, title, year in [
|
||||
(12, 22, "Film Erreur", 2020),
|
||||
(17, 27, "Film Erreur Bis", 2021),
|
||||
]:
|
||||
erreur = fake_iso(f"{title} ({year})", "ERREUR.iso")
|
||||
db.add(
|
||||
seed_movie(
|
||||
mid,
|
||||
fid,
|
||||
title,
|
||||
year,
|
||||
erreur,
|
||||
status="failed",
|
||||
failed_step="converting",
|
||||
last_error="MakeMKV a échoué (code 10): sortie de test",
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
auth.create_user("admin", "mot-de-passe-123")
|
||||
|
||||
import uvicorn # noqa: E402
|
||||
|
||||
from app.main import app # noqa: E402
|
||||
|
||||
uvicorn.run(app, host="127.0.0.1", port=8123, log_level="info")
|
||||
@@ -9,3 +9,11 @@ os.environ["MKVTOOL_RADARR_FILMS_DIR"] = str(_test_config / "radarr")
|
||||
os.environ["MKVTOOL_DOWNLOADS_DIR"] = str(_test_config / "downloads")
|
||||
os.environ["MKVTOOL_SIMULATE_CONVERSION"] = "true"
|
||||
os.environ["MKVTOOL_WORKER_INTERVAL"] = "0.05"
|
||||
|
||||
# Tables creees des l'import des tests: les modules qui touchent la base
|
||||
# sans demarrer l'application (SessionLocal directe) restent utilisables
|
||||
# meme executes seuls (pytest tests/test_conversion.py).
|
||||
from app import models # noqa: E402,F401 - modeles; import apres l'environnement
|
||||
from app.database import Base, engine # noqa: E402
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
+235
-5
@@ -4,8 +4,11 @@ import respx
|
||||
from fastapi.testclient import TestClient
|
||||
from httpx import Response
|
||||
|
||||
from app import auth as auth_module
|
||||
from app.conf_store import config_path
|
||||
from app.database import SessionLocal
|
||||
from app.main import app
|
||||
from app.models import User
|
||||
|
||||
|
||||
def configure_radarr(client: TestClient) -> None:
|
||||
@@ -35,6 +38,89 @@ def test_radarr_connection() -> None:
|
||||
assert response.json()["version"] == "5.27.0"
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_service_status_lifecycle() -> None:
|
||||
"""Statut par service: configured -> tested apres un test reussi, puis
|
||||
retour a configured quand la configuration change.
|
||||
|
||||
Utilise une URL distincte des autres tests: conf.json etant partage entre
|
||||
les tests, il faut garantir un reset du statut herite.
|
||||
"""
|
||||
respx.get("http://radarr-lifecycle:7878/api/v3/system/status").mock(
|
||||
return_value=Response(200, json={"version": "5.27.0"})
|
||||
)
|
||||
with TestClient(app) as client:
|
||||
response = client.put(
|
||||
"/api/settings/radarr",
|
||||
json={"url": "http://radarr-lifecycle:7878", "api_key": "test-key"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
# Configure mais pas encore teste.
|
||||
settings = client.get("/api/settings").json()
|
||||
assert settings["radarr"]["status"] == "configured"
|
||||
assert settings["qbittorrent"]["status"] in {"configured", "unconfigured"}
|
||||
|
||||
client.post("/api/settings/radarr/test")
|
||||
settings = client.get("/api/settings").json()
|
||||
assert settings["radarr"]["status"] == "tested"
|
||||
assert settings["radarr"]["tested_version"] == "5.27.0"
|
||||
assert settings["radarr"]["tested_at"] is not None
|
||||
|
||||
# Le resultat du test est persiste dans conf.json.
|
||||
raw = json.loads(config_path().read_text(encoding="utf-8"))
|
||||
assert raw["radarr"]["test"]["ok"] is True
|
||||
assert raw["radarr"]["test"]["version"] == "5.27.0"
|
||||
|
||||
# Modifier l'URL invalide le statut de test.
|
||||
client.put(
|
||||
"/api/settings/radarr",
|
||||
json={"url": "http://radarr-alt:7878", "api_key": None},
|
||||
)
|
||||
settings = client.get("/api/settings").json()
|
||||
assert settings["radarr"]["status"] == "configured"
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_failed_test_marks_service_as_error() -> None:
|
||||
respx.get("http://radarr-fail:7878/api/v3/system/status").mock(
|
||||
return_value=Response(500, text="boom")
|
||||
)
|
||||
with TestClient(app) as client:
|
||||
client.put(
|
||||
"/api/settings/radarr",
|
||||
json={"url": "http://radarr-fail:7878", "api_key": "test-key"},
|
||||
)
|
||||
response = client.post("/api/settings/radarr/test")
|
||||
assert response.status_code == 502
|
||||
settings = client.get("/api/settings").json()
|
||||
assert settings["radarr"]["status"] == "error"
|
||||
assert settings["radarr"]["test_error"] is not None
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_qbittorrent_status_lifecycle() -> None:
|
||||
respx.get("http://qbit-lifecycle:8080/api/v2/app/version").mock(
|
||||
return_value=Response(200, text="v5.0.2")
|
||||
)
|
||||
with TestClient(app) as client:
|
||||
client.put(
|
||||
"/api/settings/qbittorrent",
|
||||
json={"url": "http://qbit-lifecycle:8080", "port": 8080},
|
||||
)
|
||||
assert client.post("/api/settings/qbittorrent/test").status_code == 200
|
||||
settings = client.get("/api/settings").json()
|
||||
assert settings["qbittorrent"]["status"] == "tested"
|
||||
assert settings["qbittorrent"]["tested_version"] == "v5.0.2"
|
||||
|
||||
# Un nouvel enregistrement (URL differente) reinitialise le statut de test.
|
||||
client.put(
|
||||
"/api/settings/qbittorrent",
|
||||
json={"url": "http://qbit-alt:8080", "port": 8080},
|
||||
)
|
||||
settings = client.get("/api/settings").json()
|
||||
assert settings["qbittorrent"]["status"] == "configured"
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_scan_only_imports_iso_files() -> None:
|
||||
respx.get("http://radarr:7878/api/v3/movie?includeMovieFile=true").mock(
|
||||
@@ -76,35 +162,179 @@ def test_scan_only_imports_iso_files() -> None:
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_qbittorrent_connection() -> None:
|
||||
respx.post("http://qbit:8080/api/v2/auth/login").mock(
|
||||
def test_qbittorrent_connection_local_address_with_port() -> None:
|
||||
# Adresse locale sans schema + port separe: l'URL de base doit etre
|
||||
# reconstruite en http://192.168.1.50:8080.
|
||||
respx.post("http://192.168.1.50:8080/api/v2/auth/login").mock(
|
||||
return_value=Response(200, text="Ok.")
|
||||
)
|
||||
respx.get("http://qbit:8080/api/v2/app/version").mock(
|
||||
respx.get("http://192.168.1.50:8080/api/v2/app/version").mock(
|
||||
return_value=Response(200, text="v5.0.2")
|
||||
)
|
||||
with TestClient(app) as client:
|
||||
response = client.put(
|
||||
"/api/settings/qbittorrent",
|
||||
json={"url": "http://qbit:8080", "username": "admin", "password": "pass"},
|
||||
json={
|
||||
"url": "192.168.1.50",
|
||||
"port": 8080,
|
||||
"username": "admin",
|
||||
"password": "pass",
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["port"] == 8080
|
||||
test = client.post("/api/settings/qbittorrent/test")
|
||||
assert test.status_code == 200
|
||||
assert test.json()["version"] == "v5.0.2"
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_qbittorrent_connection_without_credentials() -> None:
|
||||
"""Sans identifiants (bypass d'authentification qBittorrent): aucun login,
|
||||
l'API est appelee directement."""
|
||||
respx.post("http://192.168.1.50:8555/api/v2/auth/login").mock(
|
||||
return_value=Response(404)
|
||||
)
|
||||
respx.get("http://192.168.1.50:8555/api/v2/app/version").mock(
|
||||
return_value=Response(200, text="v5.0.2")
|
||||
)
|
||||
with TestClient(app) as client:
|
||||
put = client.put(
|
||||
"/api/settings/qbittorrent",
|
||||
json={"url": "192.168.1.50", "port": 8555, "username": "", "password": None},
|
||||
)
|
||||
assert put.status_code == 200
|
||||
assert put.json()["password_configured"] is False
|
||||
test = client.post("/api/settings/qbittorrent/test")
|
||||
assert test.status_code == 200
|
||||
assert test.json()["version"] == "v5.0.2"
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_qbittorrent_login_204_modern() -> None:
|
||||
"""qBittorrent >= 5.2: le login repond 204 sans corps (plus "200 Ok.")."""
|
||||
respx.post("http://192.168.1.50:8080/api/v2/auth/login").mock(
|
||||
return_value=Response(204)
|
||||
)
|
||||
respx.get("http://192.168.1.50:8080/api/v2/app/version").mock(
|
||||
return_value=Response(200, text="v5.2.0")
|
||||
)
|
||||
with TestClient(app) as client:
|
||||
client.put(
|
||||
"/api/settings/qbittorrent",
|
||||
json={
|
||||
"url": "192.168.1.50",
|
||||
"port": 8080,
|
||||
"username": "admin",
|
||||
"password": "pass",
|
||||
},
|
||||
)
|
||||
test = client.post("/api/settings/qbittorrent/test")
|
||||
assert test.status_code == 200
|
||||
assert test.json()["version"] == "v5.2.0"
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_qbittorrent_api_key_mode() -> None:
|
||||
"""Cle API native (qBittorrent >= 5.2): en-tete Authorization: Bearer sur
|
||||
chaque appel, aucun login."""
|
||||
login_route = respx.post("http://192.168.1.50:8080/api/v2/auth/login").mock(
|
||||
return_value=Response(404)
|
||||
)
|
||||
version_route = respx.get("http://192.168.1.50:8080/api/v2/app/version").mock(
|
||||
return_value=Response(200, text="v5.2.0")
|
||||
)
|
||||
with TestClient(app) as client:
|
||||
put = client.put(
|
||||
"/api/settings/qbittorrent",
|
||||
json={"url": "192.168.1.50", "port": 8080, "api_key": "qbt_test_key"},
|
||||
)
|
||||
assert put.json()["api_key_configured"] is True
|
||||
test = client.post("/api/settings/qbittorrent/test")
|
||||
raw = json.loads(config_path().read_text(encoding="utf-8"))
|
||||
assert test.status_code == 200
|
||||
assert test.json()["version"] == "v5.2.0"
|
||||
assert not login_route.called
|
||||
assert version_route.called
|
||||
assert (
|
||||
version_route.calls.last.request.headers["authorization"] == "Bearer qbt_test_key"
|
||||
)
|
||||
assert raw["qbittorrent"]["api_key"] == "qbt_test_key"
|
||||
|
||||
|
||||
def test_settings_persist_to_conf_json() -> None:
|
||||
with TestClient(app) as client:
|
||||
put = client.put(
|
||||
"/api/settings/qbittorrent",
|
||||
json={"url": "http://qbit:8080/", "username": "admin", "password": "pass"},
|
||||
json={
|
||||
"url": "http://qbit:8080/",
|
||||
"port": 8080,
|
||||
"username": "admin",
|
||||
"password": "pass",
|
||||
},
|
||||
)
|
||||
got = client.get("/api/settings/qbittorrent")
|
||||
assert put.status_code == 200
|
||||
assert put.json()["password_configured"] is True
|
||||
assert got.json()["url"] == "http://qbit:8080"
|
||||
assert got.json()["port"] == 8080
|
||||
raw = json.loads(config_path().read_text(encoding="utf-8"))
|
||||
assert raw["qbittorrent"]["url"] == "http://qbit:8080"
|
||||
assert raw["qbittorrent"]["port"] == 8080
|
||||
assert raw["qbittorrent"]["username"] == "admin"
|
||||
assert raw["qbittorrent"]["password"] == "pass"
|
||||
|
||||
|
||||
def test_setup_link_only_without_existing_account() -> None:
|
||||
"""Le lien de premier lancement ne doit pas apparaitre si un compte existe.
|
||||
|
||||
Verifie aussi que l'endpoint de setup refuse tout second compte, meme avec
|
||||
un jeton valide.
|
||||
"""
|
||||
with TestClient(app) as client:
|
||||
client.post("/api/auth/setup", json={"token": "invalide", "username": "x", "password": "y"})
|
||||
# Nettoyage: la base de test est partagee entre les tests.
|
||||
with SessionLocal() as db:
|
||||
db.query(User).delete()
|
||||
db.commit()
|
||||
# Simule un redemarrage: le lifespan relance bootstrap_setup.
|
||||
with TestClient(app):
|
||||
assert auth_module.setup_token is not None
|
||||
with TestClient(app) as client:
|
||||
response = client.post(
|
||||
"/api/auth/setup",
|
||||
json={
|
||||
"token": auth_module.setup_token,
|
||||
"username": "admin",
|
||||
"password": "pass",
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
# Le jeton est consomme apres creation du compte.
|
||||
assert auth_module.setup_token is None
|
||||
# Nouveau demarrage: un compte existe -> plus aucun jeton genere,
|
||||
# et la creation d'un second compte est refusee.
|
||||
with TestClient(app) as client:
|
||||
assert auth_module.setup_token is None
|
||||
response = client.post(
|
||||
"/api/auth/setup",
|
||||
json={"token": "peu-importe", "username": "autre", "password": "z"},
|
||||
)
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
def test_startup_logs_conf_json_summary(capsys) -> None:
|
||||
"""Au lancement, le log indique si conf.json est charge et ce qu'il contient."""
|
||||
from app.conf_store import AppConfig, write_config
|
||||
|
||||
with TestClient(app) as client:
|
||||
# Repart d'une conf vierge: les tests precedents remplissent conf.json.
|
||||
write_config(AppConfig())
|
||||
client.put(
|
||||
"/api/settings/qbittorrent",
|
||||
json={"url": "192.168.1.50", "port": 8555},
|
||||
)
|
||||
with TestClient(app):
|
||||
captured = capsys.readouterr()
|
||||
assert "conf.json charge" in captured.out
|
||||
assert "qbittorrent (bypass d'authentification)" in captured.out
|
||||
+902
-51
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,192 @@
|
||||
import json
|
||||
|
||||
from sqlalchemy import create_engine, inspect, text
|
||||
|
||||
from app import models # noqa: F401 - enregistre les modeles SQLAlchemy
|
||||
from app.conf_store import AppConfig, config_path, write_raw_config
|
||||
from app.database import Base
|
||||
from app.migrations import (
|
||||
CONF_MIGRATIONS,
|
||||
current_conf_version,
|
||||
migrate_conf_file,
|
||||
run_db_migrations,
|
||||
)
|
||||
|
||||
|
||||
def test_db_migration_from_legacy_schema(tmp_path) -> None:
|
||||
"""Une base 'legacy' (colonnes v1 absentes) est migree, sans perdre les
|
||||
donnees, et la migration n'est jouee qu'une seule fois."""
|
||||
engine = create_engine(f"sqlite:///{tmp_path / 'legacy.db'}")
|
||||
with engine.begin() as conn:
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE iso_movies (
|
||||
id INTEGER PRIMARY KEY,
|
||||
radarr_movie_id INTEGER,
|
||||
radarr_movie_file_id INTEGER,
|
||||
title TEXT,
|
||||
path TEXT,
|
||||
status TEXT,
|
||||
last_seen_at DATETIME
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
conn.execute(
|
||||
text(
|
||||
"INSERT INTO iso_movies (radarr_movie_id, radarr_movie_file_id,"
|
||||
" title, path, status) VALUES (10, 20, 'ISO Movie', '/x.iso', 'detected')"
|
||||
)
|
||||
)
|
||||
|
||||
applied = run_db_migrations(engine)
|
||||
|
||||
assert applied == [
|
||||
"iso_movies: colonnes de suivi des conversions",
|
||||
"iso_movies: colonnes created_at/last_seen_at sur les bases anciennes",
|
||||
"iso_movies: colonne qb_content_path (ISO cote telechargements)",
|
||||
]
|
||||
columns = {col["name"] for col in inspect(engine).get_columns("iso_movies")}
|
||||
assert {
|
||||
"processed_at",
|
||||
"completed_at",
|
||||
"failed_step",
|
||||
"last_error",
|
||||
"poster_url",
|
||||
"radarr_linked",
|
||||
"created_at",
|
||||
"qb_content_path",
|
||||
} <= columns
|
||||
|
||||
# Les donnees existantes sont conservees.
|
||||
with engine.connect() as conn:
|
||||
rows = list(conn.execute(text("SELECT title, radarr_linked FROM iso_movies")))
|
||||
assert rows == [("ISO Movie", 1)]
|
||||
|
||||
# Les versions sont tracees et les migrations ne sont pas rejouees.
|
||||
with engine.connect() as conn:
|
||||
recorded = list(conn.execute(text("SELECT version FROM schema_migrations")))
|
||||
assert [row[0] for row in recorded] == [1, 2, 3]
|
||||
assert run_db_migrations(engine) == []
|
||||
|
||||
|
||||
def test_db_migration_fresh_database(tmp_path) -> None:
|
||||
"""Sur une base vierge, create_all cree deja le schema complet: la
|
||||
migration v1 est inoffensive mais reste tracee."""
|
||||
engine = create_engine(f"sqlite:///{tmp_path / 'fresh.db'}")
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
applied = run_db_migrations(engine)
|
||||
|
||||
assert applied == [
|
||||
"iso_movies: colonnes de suivi des conversions",
|
||||
"iso_movies: colonnes created_at/last_seen_at sur les bases anciennes",
|
||||
"iso_movies: colonne qb_content_path (ISO cote telechargements)",
|
||||
]
|
||||
assert run_db_migrations(engine) == []
|
||||
|
||||
|
||||
def test_conf_file_stamped_with_version() -> None:
|
||||
"""Un conf.json d'avant le systeme (sans cle version) est charge tel quel
|
||||
et estampille avec la version courante."""
|
||||
write_raw_config(
|
||||
{
|
||||
"radarr": {"url": "http://radarr:7878", "api_key": "k"},
|
||||
"sonarr": {"url": "http://sonarr:8989", "api_key": "k"},
|
||||
"jellyfin": {"url": "http://jf:8096"},
|
||||
}
|
||||
)
|
||||
|
||||
applied = migrate_conf_file()
|
||||
|
||||
# v1 -> v2 retire les services hors perimetre, puis etampille la version.
|
||||
assert applied == ["conf.json v1 -> v2"]
|
||||
raw = json.loads(config_path().read_text(encoding="utf-8"))
|
||||
assert raw["version"] == current_conf_version()
|
||||
assert raw["radarr"]["url"] == "http://radarr:7878"
|
||||
assert raw["radarr"]["api_key"] == "k"
|
||||
assert "sonarr" not in raw
|
||||
assert "jellyfin" not in raw
|
||||
|
||||
# Deja a jour: plus rien a appliquer.
|
||||
assert migrate_conf_file() == []
|
||||
|
||||
|
||||
def test_conf_migration_transforms_content(monkeypatch) -> None:
|
||||
"""Une migration conf.json transforme le contenu et incremente la version,
|
||||
en chaine jusqu'a la version courante."""
|
||||
def v1_to_v2(data: dict) -> dict:
|
||||
data["jellyfin"] = data.pop("jellyfin_old", {})
|
||||
return data
|
||||
|
||||
def v2_to_v3(data: dict) -> dict:
|
||||
data["prowlarr"] = {"url": None}
|
||||
return data
|
||||
|
||||
monkeypatch.setattr("app.migrations.CONF_MIGRATIONS", [v1_to_v2, v2_to_v3])
|
||||
assert current_conf_version() == 3
|
||||
write_raw_config({"version": 1, "jellyfin_old": {"url": "http://jf:8096"}})
|
||||
|
||||
applied = migrate_conf_file()
|
||||
|
||||
assert applied == ["conf.json v1 -> v2", "conf.json v2 -> v3"]
|
||||
raw = json.loads(config_path().read_text(encoding="utf-8"))
|
||||
assert raw["version"] == 3
|
||||
assert raw["jellyfin"] == {"url": "http://jf:8096"}
|
||||
assert "jellyfin_old" not in raw
|
||||
assert raw["prowlarr"] == {"url": None}
|
||||
|
||||
# Deja a jour: plus aucune migration a appliquer.
|
||||
assert migrate_conf_file() == []
|
||||
|
||||
|
||||
def test_appconfig_version_matches_registry(monkeypatch) -> None:
|
||||
"""Invariant: la version par defaut d'AppConfig suit le registre de
|
||||
migrations conf.json."""
|
||||
monkeypatch.setattr("app.migrations.CONF_MIGRATIONS", CONF_MIGRATIONS)
|
||||
assert AppConfig().version == current_conf_version()
|
||||
|
||||
|
||||
def test_db_migration_adds_created_at_on_very_old_database(tmp_path) -> None:
|
||||
"""Une base d'epoque, sans created_at/last_seen_at, est reparee par la
|
||||
migration v2 et redevient utilisable par l'application."""
|
||||
from sqlalchemy import create_engine, inspect, text
|
||||
|
||||
from app.database import Base
|
||||
from app.migrations import run_db_migrations
|
||||
|
||||
engine = create_engine(f"sqlite:///{tmp_path / 'old.db'}")
|
||||
with engine.begin() as conn:
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE iso_movies (
|
||||
id INTEGER PRIMARY KEY,
|
||||
radarr_movie_id INTEGER,
|
||||
radarr_movie_file_id INTEGER,
|
||||
title TEXT,
|
||||
year INTEGER,
|
||||
path TEXT,
|
||||
size INTEGER,
|
||||
status TEXT
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
conn.execute(
|
||||
text(
|
||||
"INSERT INTO iso_movies (radarr_movie_id, radarr_movie_file_id,"
|
||||
" title, status) VALUES (1, 2, 'Vieux Film', 'detected')"
|
||||
)
|
||||
)
|
||||
|
||||
run_db_migrations(engine)
|
||||
|
||||
columns = {col["name"] for col in inspect(engine).get_columns("iso_movies")}
|
||||
assert {"created_at", "last_seen_at", "radarr_linked", "last_error"} <= columns
|
||||
with engine.connect() as conn:
|
||||
rows = list(conn.execute(text("SELECT title, status FROM iso_movies")))
|
||||
assert rows == [("Vieux Film", "detected")]
|
||||
# La table est conforme au modele: create_all ne change rien.
|
||||
Base.metadata.create_all(bind=engine)
|
||||
@@ -0,0 +1,425 @@
|
||||
"""Tests unitaires et fonctionnels des composants de l'app.
|
||||
|
||||
Couvre en particulier les classes de problemes rencontrees depuis le debut:
|
||||
transitions d'etats interdites, erreurs de gestion de fichiers, modes
|
||||
d'authentification qBittorrent, analyse des titres MakeMKV, cas limites de
|
||||
conf.json et garde-fous des endpoints.
|
||||
"""
|
||||
|
||||
import errno
|
||||
import json
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
import respx
|
||||
from fastapi.testclient import TestClient
|
||||
from httpx import Response
|
||||
|
||||
from app import auth
|
||||
from app.conf_store import read_config, write_raw_config
|
||||
from app.config import settings
|
||||
from app.converter import (
|
||||
conversion_paths,
|
||||
file_error,
|
||||
guarded_folder,
|
||||
import_mkv,
|
||||
link_or_copy,
|
||||
longest_title_id,
|
||||
sanitize_component,
|
||||
unlink_if_exists,
|
||||
)
|
||||
from app.main import app
|
||||
from app.models import IsoMovie
|
||||
from app.qbittorrent import QbittorrentClient, match_torrent
|
||||
from app.radarr import movie_file_path
|
||||
|
||||
|
||||
def make_movie(**overrides) -> IsoMovie:
|
||||
values = {
|
||||
"radarr_movie_id": 10,
|
||||
"radarr_movie_file_id": 20,
|
||||
"title": "Film Test",
|
||||
"year": 2025,
|
||||
"path": str(settings.radarr_films_dir / "Film Test (2025)" / "Film Test (2025).iso"),
|
||||
"status": "detected",
|
||||
"last_seen_at": datetime(2026, 1, 1, tzinfo=UTC),
|
||||
}
|
||||
values.update(overrides)
|
||||
return IsoMovie(**values)
|
||||
|
||||
|
||||
# --- Conversion de chemins et noms ---
|
||||
def test_sanitize_component() -> None:
|
||||
assert sanitize_component("Film: un *grand* jour ?") == "Film un grand jour"
|
||||
assert sanitize_component(" Espaces multiples\t") == "Espaces multiples"
|
||||
assert sanitize_component("///") == "Sans titre"
|
||||
|
||||
|
||||
def test_guarded_folder_refuse_hors_bibliotheque(tmp_path) -> None:
|
||||
try:
|
||||
guarded_folder(Path("/tmp/dossier-hors-films"))
|
||||
except RuntimeError as error:
|
||||
assert "hors de" in str(error)
|
||||
else:
|
||||
raise AssertionError("RuntimeError attendue")
|
||||
|
||||
|
||||
def test_conversion_paths_follow_movie_folder() -> None:
|
||||
movie = make_movie()
|
||||
paths = conversion_paths(movie)
|
||||
# Dossier de travail: "Titre Annee" sous les telechargements.
|
||||
assert paths.downloads_folder == settings.downloads_dir / "Film Test 2025"
|
||||
# Le MKV prend le nom standard "Titre (Annee).mkv".
|
||||
assert paths.mkv_path.name == "Film Test (2025).mkv"
|
||||
# La destination est le dossier de l'ISO (bibliotheque).
|
||||
assert paths.destination_folder.name == "Film Test (2025)"
|
||||
|
||||
|
||||
def test_link_or_copy_prefers_hardlink() -> None:
|
||||
"""Meme volume: lien dur, meme inode, aucune donnee dupliquee."""
|
||||
source = settings.downloads_dir / "Film Test 2025" / "Film Test (2025).mkv"
|
||||
source.parent.mkdir(parents=True, exist_ok=True)
|
||||
source.write_text("donnees")
|
||||
target = settings.films_dir / "Film Test (2025)" / "Film Test (2025).mkv"
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
kind = link_or_copy(source, target, "Création du lien du MKV")
|
||||
assert kind == "lien"
|
||||
assert target.read_text() == "donnees"
|
||||
assert target.stat().st_ino == source.stat().st_ino
|
||||
|
||||
|
||||
def test_import_mkv_copies_when_hardlink_impossible(monkeypatch) -> None:
|
||||
"""Volumes distincts (EXDEV): copie de secours — jamais de lien
|
||||
symbolique, dont le chemin absolu serait interne au conteneur et
|
||||
illisible depuis Jellyfin ou Radarr."""
|
||||
source = settings.downloads_dir / "Film Test 2025" / "Film Test (2025).mkv"
|
||||
source.parent.mkdir(parents=True, exist_ok=True)
|
||||
source.write_text("donnees du mkv")
|
||||
|
||||
def refuse_cross_volume(src, dst, **kwargs):
|
||||
raise OSError(errno.EXDEV, "Invalid cross-device link", str(src))
|
||||
|
||||
monkeypatch.setattr("app.converter.os.link", refuse_cross_volume)
|
||||
target = import_mkv(source, settings.films_dir / "Film Test (2025)")
|
||||
assert target.is_file()
|
||||
assert not target.is_symlink()
|
||||
assert target.read_text() == "donnees du mkv"
|
||||
# Copie independante: modifier la cible ne touche pas le brut.
|
||||
target.write_text("modifie")
|
||||
assert source.read_text() == "donnees du mkv"
|
||||
|
||||
|
||||
# --- Traduction des erreurs de fichiers ---
|
||||
def test_file_error_translates_errnos() -> None:
|
||||
error = file_error(
|
||||
PermissionError(errno.EACCES, "Permission denied", "/x"), "Suppression", "/x"
|
||||
)
|
||||
assert "erreur de droits" in str(error)
|
||||
error = file_error(FileNotFoundError(errno.ENOENT, "No entry", "/x"), "Lecture", "/x")
|
||||
assert "introuvable" in str(error)
|
||||
# Errno inconnu: message generique avec le code.
|
||||
error = file_error(OSError(9999, "bizarre", "/x"), "Action", "/x")
|
||||
assert "errno 9999" in str(error)
|
||||
|
||||
|
||||
def test_unlink_if_exists_tolerates_missing_file(tmp_path) -> None:
|
||||
gone = tmp_path / "absent.mkv"
|
||||
unlink_if_exists(gone) # aucune erreur
|
||||
present = tmp_path / "present.mkv"
|
||||
present.write_text("x")
|
||||
unlink_if_exists(present)
|
||||
assert not present.exists()
|
||||
|
||||
|
||||
def test_unlink_if_exists_translates_permission_error(
|
||||
monkeypatch, tmp_path
|
||||
) -> None:
|
||||
def refuse(self):
|
||||
raise PermissionError(errno.EACCES, "Permission denied", str(self))
|
||||
|
||||
monkeypatch.setattr(Path, "unlink", refuse)
|
||||
try:
|
||||
unlink_if_exists(tmp_path / "verrouille.mkv")
|
||||
except RuntimeError as error:
|
||||
assert "erreur de droits" in str(error)
|
||||
else:
|
||||
raise AssertionError("RuntimeError attendue")
|
||||
|
||||
|
||||
# --- Selection du titre MakeMKV ---
|
||||
class FakeCtxPopen:
|
||||
"""Popen simulé supportant le protocole de contexte (with)."""
|
||||
|
||||
def __init__(self, lines: list[str], returncode: int) -> None:
|
||||
self.stdout = iter(line + "\n" for line in lines)
|
||||
self._returncode = returncode
|
||||
|
||||
def __enter__(self) -> "FakeCtxPopen":
|
||||
return self
|
||||
|
||||
def __exit__(self, *args: object) -> bool:
|
||||
return False
|
||||
|
||||
def wait(self) -> int:
|
||||
return self._returncode
|
||||
|
||||
|
||||
def test_longest_title_falls_back_to_zero_without_titles(monkeypatch) -> None:
|
||||
monkeypatch.setattr(
|
||||
"app.converter.subprocess.Popen",
|
||||
lambda args, **kwargs: FakeCtxPopen(["MSG:1005,0,1,\"rien\""], 0),
|
||||
)
|
||||
# Pas de TINFO: pas de titres analysables, retour au titre 0.
|
||||
assert longest_title_id(Path("/x.iso")) == "0"
|
||||
|
||||
|
||||
# --- Client qBittorrent: modes d'authentification ---
|
||||
@respx.mock
|
||||
async def test_qbittorrent_client_legacy_login() -> None:
|
||||
login = respx.post("http://qb:8080/api/v2/auth/login").mock(
|
||||
return_value=Response(200, text="Ok.")
|
||||
)
|
||||
respx.get("http://qb:8080/api/v2/app/version").mock(
|
||||
return_value=Response(200, text="v4.6.0")
|
||||
)
|
||||
client = QbittorrentClient("http://qb:8080", "admin", "pass")
|
||||
assert await client.version() == "v4.6.0"
|
||||
assert login.called
|
||||
assert "username=admin" in login.calls.last.request.content.decode()
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_qbittorrent_client_refused_login() -> None:
|
||||
respx.post("http://qb:8080/api/v2/auth/login").mock(
|
||||
return_value=Response(200, text="Fails.")
|
||||
)
|
||||
client = QbittorrentClient("http://qb:8080", "admin", "mauvais")
|
||||
try:
|
||||
await client.version()
|
||||
except ValueError as error:
|
||||
assert "refusée" in str(error)
|
||||
else:
|
||||
raise AssertionError("ValueError attendue")
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_qbittorrent_client_api_key_skips_login() -> None:
|
||||
login = respx.post("http://qb:8080/api/v2/auth/login").mock(
|
||||
return_value=Response(404)
|
||||
)
|
||||
version = respx.get("http://qb:8080/api/v2/app/version").mock(
|
||||
return_value=Response(200, text="v5.2.0")
|
||||
)
|
||||
client = QbittorrentClient("http://qb:8080", api_key="qbt_cle")
|
||||
assert await client.version() == "v5.2.0"
|
||||
assert not login.called
|
||||
assert version.calls.last.request.headers["authorization"] == "Bearer qbt_cle"
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_qbittorrent_client_bypass_calls_no_login() -> None:
|
||||
login = respx.post("http://qb:8080/api/v2/auth/login").mock(
|
||||
return_value=Response(404)
|
||||
)
|
||||
respx.get("http://qb:8080/api/v2/app/version").mock(
|
||||
return_value=Response(200, text="v5.2.0")
|
||||
)
|
||||
client = QbittorrentClient("http://qb:8080")
|
||||
assert await client.version() == "v5.2.0"
|
||||
assert not login.called
|
||||
|
||||
|
||||
def test_match_torrent_variants() -> None:
|
||||
torrents = [
|
||||
{"hash": "h1", "name": "film.iso", "content_path": "/x/film.iso"},
|
||||
{"hash": "h2", "name": "Autre", "content_path": "/y/Dossier/FILM UHD.ISO"},
|
||||
{"hash": "h3", "name": "film", "content_path": ""},
|
||||
]
|
||||
assert match_torrent(torrents, "/q/film.iso")["hash"] == "h1" # nom exact
|
||||
assert match_torrent(torrents, "/q/film")["hash"] == "h3" # torrent sans extension
|
||||
assert match_torrent(torrents, "/q/Dossier/FILM UHD.ISO")["hash"] == "h2" # contenu
|
||||
assert match_torrent(torrents, "/q/inconnu.iso") is None
|
||||
|
||||
|
||||
# --- Radarr: analyse des chemins ---
|
||||
def test_movie_file_path_variants() -> None:
|
||||
direct = {"movieFile": {"path": "/films/Film/Film.iso"}}
|
||||
assert movie_file_path(direct) == "/films/Film/Film.iso"
|
||||
relative = {
|
||||
"path": "/films/Film",
|
||||
"movieFile": {"relativePath": "Film.iso"},
|
||||
}
|
||||
assert movie_file_path(relative) == "/films/Film/Film.iso"
|
||||
assert movie_file_path({"movieFile": {}}) is None
|
||||
assert movie_file_path({}) is None
|
||||
|
||||
|
||||
# --- Authentification ---
|
||||
def test_auth_hash_and_verify_roundtrip() -> None:
|
||||
stored = auth.hash_password("mot-de-passe-123")
|
||||
assert auth.verify_password("mot-de-passe-123", stored)
|
||||
assert not auth.verify_password("autre", stored)
|
||||
# Schéma inconnu: refus plutôt qu'exception.
|
||||
assert not auth.verify_password("x", "md5$1$ab$cd")
|
||||
|
||||
|
||||
def test_auth_login_me_logout_flow() -> None:
|
||||
auth.create_user("utilitaire", "mot-de-passe-123")
|
||||
with TestClient(app) as client:
|
||||
# Mauvais mot de passe: refuse.
|
||||
bad = client.post(
|
||||
"/api/auth/login", json={"username": "utilitaire", "password": "faux"}
|
||||
)
|
||||
assert bad.status_code == 401
|
||||
# Bon mot de passe: session posee.
|
||||
good = client.post(
|
||||
"/api/auth/login", json={"username": "utilitaire", "password": "mot-de-passe-123"}
|
||||
)
|
||||
assert good.status_code == 200
|
||||
me = client.get("/api/auth/me")
|
||||
assert me.json()["username"] == "utilitaire"
|
||||
# Deconnexion: plus de session.
|
||||
client.post("/api/auth/logout")
|
||||
assert client.get("/api/auth/me").status_code == 401
|
||||
|
||||
|
||||
def test_auth_setup_requires_valid_token() -> None:
|
||||
with TestClient(app) as client:
|
||||
assert client.post(
|
||||
"/api/auth/setup",
|
||||
json={"token": "invalide", "username": "a", "password": "mot-de-passe-123"},
|
||||
).status_code == 403
|
||||
|
||||
|
||||
# --- Endpoints: garde-fous et 404 ---
|
||||
def test_endpoints_unknown_movie_return_404() -> None:
|
||||
with TestClient(app) as client:
|
||||
assert client.get("/api/files/999999").status_code == 404
|
||||
assert client.get("/api/movies/999999/log").status_code == 404
|
||||
assert client.post("/api/movies/999999/convert").status_code == 404
|
||||
assert client.post("/api/movies/999999/validate").status_code == 404
|
||||
assert client.post("/api/movies/999999/cancel").status_code == 404
|
||||
assert client.delete("/api/movies/999999").status_code == 404
|
||||
assert client.post("/api/movies/999999/radarr-rename").status_code == 404
|
||||
|
||||
|
||||
def test_conversion_log_empty_for_never_converted_movie() -> None:
|
||||
from app.database import SessionLocal
|
||||
|
||||
with SessionLocal() as db:
|
||||
movie = make_movie(
|
||||
radarr_movie_id=5001,
|
||||
radarr_movie_file_id=5002,
|
||||
title="Jamais Converti",
|
||||
path="/films/Jamais Converti (2025).iso",
|
||||
)
|
||||
db.add(movie)
|
||||
db.commit()
|
||||
movie_id = movie.id
|
||||
with TestClient(app) as client:
|
||||
log = client.get(f"/api/movies/{movie_id}/log")
|
||||
assert log.status_code == 200
|
||||
assert log.json() == {"lines": [], "running": False}
|
||||
|
||||
|
||||
# --- Transitions d'etats: matrice complete ---
|
||||
_seed_counter = {"n": 0}
|
||||
|
||||
|
||||
def seed_movie(status: str) -> int:
|
||||
from app.database import SessionLocal
|
||||
|
||||
_seed_counter["n"] += 1
|
||||
n = _seed_counter["n"]
|
||||
with SessionLocal() as db:
|
||||
movie = make_movie(
|
||||
radarr_movie_id=1000 + n,
|
||||
radarr_movie_file_id=2000 + n,
|
||||
title=f"Film {status} {n}",
|
||||
path=f"/films/Film {status} {n}.iso",
|
||||
status=status,
|
||||
)
|
||||
db.add(movie)
|
||||
db.commit()
|
||||
return movie.id
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_status_transition_matrix() -> None:
|
||||
"""Chaque action n'est autorisee que depuis ses etats valides.
|
||||
|
||||
Convert: detected/ready/failed. Cancel et validate: validating.
|
||||
Radarr-rename: completed. Les autres combinaisons: 409.
|
||||
"""
|
||||
allowed_convert = {"detected", "ready", "failed"}
|
||||
only_validating = {"validating"}
|
||||
only_completed = {"completed"}
|
||||
statuses = [
|
||||
"detected",
|
||||
"ready",
|
||||
"queued",
|
||||
"converting",
|
||||
"importing",
|
||||
"validating",
|
||||
"completed",
|
||||
"failed",
|
||||
]
|
||||
respx.post("http://radarr:7878/api/v3/command").mock(
|
||||
return_value=Response(201, json={"id": 1})
|
||||
)
|
||||
with TestClient(app) as client:
|
||||
from tests.test_api import configure_radarr
|
||||
|
||||
configure_radarr(client)
|
||||
for status in statuses:
|
||||
movie_id = seed_movie(status)
|
||||
convert = client.post(f"/api/movies/{movie_id}/convert")
|
||||
assert convert.status_code == (200 if status in allowed_convert else 409), status
|
||||
|
||||
movie_id = seed_movie(status)
|
||||
cancel = client.post(f"/api/movies/{movie_id}/cancel")
|
||||
assert cancel.status_code == (200 if status in only_validating else 409), status
|
||||
|
||||
movie_id = seed_movie(status)
|
||||
# La validation exige un MKV lie dans le dossier du film: on le
|
||||
# cree pour le cas "validating".
|
||||
if status == "validating":
|
||||
from app.database import SessionLocal
|
||||
|
||||
with SessionLocal() as db:
|
||||
movie = db.get(IsoMovie, movie_id)
|
||||
folder = conversion_paths(movie).destination_folder
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
(folder / "Film.mkv").write_text("mkv")
|
||||
validate = client.post(f"/api/movies/{movie_id}/validate")
|
||||
assert validate.status_code == (200 if status in only_validating else 409), status
|
||||
|
||||
movie_id = seed_movie(status)
|
||||
rename = client.post(f"/api/movies/{movie_id}/radarr-rename")
|
||||
assert rename.status_code == (200 if status in only_completed else 409), status
|
||||
|
||||
# La suppression d'inventaire est bloquee pendant une conversion.
|
||||
movie_id = seed_movie(status)
|
||||
delete = client.delete(f"/api/movies/{movie_id}")
|
||||
busy = {"queued", "converting", "importing", "validating"}
|
||||
assert delete.status_code == (409 if status in busy else 200), status
|
||||
|
||||
|
||||
# --- conf.json: cas limites ---
|
||||
def test_read_config_treats_invalid_content_as_absent() -> None:
|
||||
write_raw_config(["ceci", "nest", "pas", "un", "dict"])
|
||||
assert read_config().version == 2 # valeurs par defaut
|
||||
# Cles inconnues: ignorees sans erreur (champs du fichier plus recents).
|
||||
write_raw_config({"version": 2, "radarr": {"url": "http://r:7878"}, "futur": {"x": 1}})
|
||||
config = read_config()
|
||||
assert config.radarr.url == "http://r:7878"
|
||||
assert config.version == 2
|
||||
|
||||
|
||||
def test_conf_raw_helpers_roundtrip() -> None:
|
||||
from app.conf_store import config_path
|
||||
|
||||
write_raw_config({"version": 2, "radarr": {"url": "http://radarr:7878"}})
|
||||
raw = json.loads(config_path().read_text(encoding="utf-8"))
|
||||
assert raw["version"] == 2
|
||||
assert raw["radarr"]["url"] == "http://radarr:7878"
|
||||
@@ -0,0 +1,33 @@
|
||||
import {expect, test} from "@playwright/test";
|
||||
|
||||
import {login} from "./helpers";
|
||||
|
||||
test("la connexion refuse un mauvais mot de passe", async ({page}) => {
|
||||
await page.goto("/");
|
||||
await page.getByLabel("Nom d’utilisateur").fill("admin");
|
||||
await page.getByLabel("Mot de passe").fill("faux");
|
||||
await page.getByRole("button", {name: "Se connecter"}).click();
|
||||
await expect(page.getByText("Identifiants incorrects")).toBeVisible();
|
||||
await expect(page.getByRole("button", {name: "Se connecter"})).toBeVisible();
|
||||
});
|
||||
|
||||
test("la connexion réussie mène au tableau de bord, la déconnexion revient au login", async ({
|
||||
page,
|
||||
}) => {
|
||||
await login(page);
|
||||
await expect(page.getByRole("button", {name: "Tableau de bord"})).toBeVisible();
|
||||
|
||||
// Menu utilisateur: theme + déconnexion.
|
||||
await page.getByRole("button", {name: "Menu utilisateur"}).click();
|
||||
await page.getByRole("menuitem", {name: "Déconnexion"}).click();
|
||||
await expect(page.getByRole("button", {name: "Se connecter"})).toBeVisible();
|
||||
});
|
||||
|
||||
test("le basculement de thème persiste", async ({page}) => {
|
||||
await login(page);
|
||||
await page.getByRole("button", {name: "Menu utilisateur"}).click();
|
||||
await page.getByRole("menuitem", {name: "Passer en thème clair"}).click();
|
||||
await expect(page.locator("html")).toHaveAttribute("data-theme", "light");
|
||||
await page.reload();
|
||||
await expect(page.locator("html")).toHaveAttribute("data-theme", "light");
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import {expect, test} from "@playwright/test";
|
||||
|
||||
import {fermerNotifications, login} from "./helpers";
|
||||
|
||||
test("au premier lancement sans config: avertissements ciblés, scan désactivé", async ({page}) => {
|
||||
await login(page);
|
||||
|
||||
// Avertissement Radarr (obligatoire) + info qBittorrent (optionnel).
|
||||
await expect(
|
||||
page.locator(".notification.warning", {hasText: /Connexion Radarr non configurée/}),
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
page.locator(".notification.info", {hasText: /qBittorrent non configuré/}),
|
||||
).toBeVisible();
|
||||
|
||||
// Le scan est impossible sans Radarr.
|
||||
await expect(page.getByRole("button", {name: "Scanner maintenant"})).toBeDisabled();
|
||||
|
||||
// Badges orange "non configuré".
|
||||
await page.getByRole("button", {name: "Configuration"}).click();
|
||||
await expect(
|
||||
page.locator(".status.st-detected", {hasText: "Radarr non configuré"}),
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
page.locator(".status.st-detected", {hasText: "qBittorrent non configuré"}),
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test("enregistrement et test de connexion: échec explicite en badge rouge", async ({page}) => {
|
||||
await login(page);
|
||||
await page.getByRole("button", {name: "Configuration"}).click();
|
||||
|
||||
// Radarr: on configure une URL (injoignable dans l'environnement de test).
|
||||
await fermerNotifications(page);
|
||||
await page.getByLabel("URL Radarr").fill("http://127.0.0.1:59999");
|
||||
await page.getByLabel("Clé API", {exact: true}).fill("cle-de-test");
|
||||
await page.getByRole("button", {name: "Enregistrer et tester"}).first().click();
|
||||
|
||||
// Le test échoue: notification d'erreur, badge "Test échoué" persistant.
|
||||
await expect(
|
||||
page.locator(".notification.error", {hasText: /Connexion Radarr impossible/}),
|
||||
).toBeVisible();
|
||||
await expect(page.locator(".status.error", {hasText: "Test échoué"}).first()).toBeVisible();
|
||||
|
||||
// Avec Radarr configuré, le scan devient actif (et échoue proprement).
|
||||
await expect(page.getByRole("button", {name: "Scanner maintenant"})).toBeEnabled();
|
||||
await page.getByRole("button", {name: "Scanner maintenant"}).click();
|
||||
await expect(
|
||||
page.locator(".notification.error", {hasText: /Scan Radarr impossible/}),
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test("qBittorrent: enregistrement puis échec de test en badge rouge", async ({page}) => {
|
||||
await login(page);
|
||||
await page.getByRole("button", {name: "Configuration"}).click();
|
||||
|
||||
await fermerNotifications(page);
|
||||
await page.getByLabel("URL qBittorrent").fill("http://127.0.0.1:59998");
|
||||
await page.getByLabel("Utilisateur (optionnel)").fill("admin");
|
||||
await page
|
||||
.locator("section")
|
||||
.filter({hasText: "Connexion qBittorrent"})
|
||||
.getByRole("button", {name: "Enregistrer et tester"})
|
||||
.click();
|
||||
|
||||
await expect(
|
||||
page.locator(".notification.error", {hasText: /Connexion qBittorrent impossible/}),
|
||||
).toBeVisible();
|
||||
// Le badge repasse en rouge "Test échoué" après le rechargement du statut.
|
||||
await expect(
|
||||
page.locator(".status.error", {hasText: "Test échoué"}).first(),
|
||||
).toBeVisible({timeout: 10_000});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import {expect, test} from "@playwright/test";
|
||||
|
||||
import {login} from "./helpers";
|
||||
|
||||
test("le tableau de bord affiche les statistiques et l'activité", async ({page}) => {
|
||||
await login(page);
|
||||
await expect(page.locator(".stat", {hasText: "À traiter"})).toContainText("7");
|
||||
await expect(page.locator(".stat", {hasText: "En cours"})).toContainText("0");
|
||||
await expect(page.locator(".stat", {hasText: "Traités"})).toContainText("1");
|
||||
await expect(page.locator(".stat", {hasText: "Erreurs"})).toContainText("2");
|
||||
|
||||
// Colonnes d'activité: aucune conversion en cours, une terminée (Cars).
|
||||
await expect(page.getByText("Aucun traitement en cours.")).toBeVisible();
|
||||
await expect(
|
||||
page.locator(".activity-col", {hasText: "Traitement terminé"}).getByText("Cars"),
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test("la navigation entre les pages fonctionne", async ({page}) => {
|
||||
await login(page);
|
||||
await page.getByRole("button", {name: "Traitements"}).click();
|
||||
await expect(page.getByRole("heading", {name: "Films ISO"})).toBeVisible();
|
||||
await page.getByRole("button", {name: "Configuration"}).click();
|
||||
await expect(page.getByRole("heading", {name: "Connexion Radarr"})).toBeVisible();
|
||||
await page.getByRole("button", {name: "Tableau de bord"}).click();
|
||||
await expect(page.getByRole("heading", {name: "Activité"})).toBeVisible();
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
import {expect, test} from "@playwright/test";
|
||||
|
||||
import {ligneFilm, login} from "./helpers";
|
||||
|
||||
test("les onglets affichent les films dans la bonne catégorie", async ({page}) => {
|
||||
await login(page);
|
||||
await page.getByRole("button", {name: "Traitements"}).click();
|
||||
|
||||
// Onglet par défaut: les films détectés sémés.
|
||||
await expect(ligneFilm(page, "Pacific Rim")).toBeVisible();
|
||||
await expect(ligneFilm(page, "Film Liste")).toBeVisible();
|
||||
|
||||
// Traités: Cars, avec sa pastille verte.
|
||||
await page.getByRole("button", {name: "Traités"}).click();
|
||||
await expect(ligneFilm(page, "Cars")).toBeVisible();
|
||||
await expect(page.locator(".status.st-completed", {hasText: "Terminé"})).toBeVisible();
|
||||
|
||||
// Erreurs: Film Erreur.
|
||||
await page.getByRole("button", {name: "Erreurs"}).click();
|
||||
await expect(ligneFilm(page, "^Film Erreur$")).toBeVisible();
|
||||
await expect(page.locator(".status.error", {hasText: "Erreur"}).first()).toBeVisible();
|
||||
});
|
||||
|
||||
test("la fiche d'un film détecté montre l'état et l'emplacement", async ({page}) => {
|
||||
await login(page);
|
||||
await page.getByRole("button", {name: "Traitements"}).click();
|
||||
await ligneFilm(page, "Film Liste").click();
|
||||
|
||||
const modal = page.locator(".modal");
|
||||
await expect(modal.getByRole("heading", {name: "Film Liste", level: 2})).toBeVisible();
|
||||
await expect(modal.getByText("Détecté")).toBeVisible();
|
||||
await expect(modal.getByRole("button", {name: "Convertir en MKV"})).toBeEnabled();
|
||||
|
||||
// Fermeture par Échap.
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(modal).toBeHidden();
|
||||
});
|
||||
|
||||
test("la fiche d'un film traité affiche les deux chemins et le bouton de renommage", async ({
|
||||
page,
|
||||
}) => {
|
||||
await login(page);
|
||||
await page.getByRole("button", {name: "Traitements"}).click();
|
||||
await page.getByRole("button", {name: "Traités"}).click();
|
||||
await ligneFilm(page, "Cars").click();
|
||||
|
||||
await expect(page.getByText("MKV lié (dossier du film)")).toBeVisible();
|
||||
await expect(page.getByText("MKV brut (dossier de travail)")).toBeVisible();
|
||||
await expect(page.getByRole("button", {name: "Renommer via Radarr"})).toBeVisible();
|
||||
// Le MKV lié porte bien le nom du film.
|
||||
await expect(page.locator("code", {hasText: "Cars (2006).mkv"}).first()).toBeVisible();
|
||||
});
|
||||
|
||||
test("la fiche d'un film en erreur montre l'erreur et le journal", async ({page}) => {
|
||||
await login(page);
|
||||
await page.getByRole("button", {name: "Traitements"}).click();
|
||||
await page.getByRole("button", {name: "Erreurs"}).click();
|
||||
await ligneFilm(page, "^Film Erreur$").click();
|
||||
|
||||
const modal = page.locator(".modal");
|
||||
await expect(modal.getByText(/MakeMKV a échoué/)).toBeVisible();
|
||||
await expect(modal.getByText("Journal de la dernière conversion")).toBeVisible();
|
||||
await expect(
|
||||
modal.getByRole("button", {name: "Reprendre la conversion en MKV"}),
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test("l'onglet Traités propose le renommage Radarr groupé", async ({page}) => {
|
||||
await login(page);
|
||||
await page.getByRole("button", {name: "Traitements"}).click();
|
||||
await page.getByRole("button", {name: "Traités"}).click();
|
||||
|
||||
const bouton = page.getByRole("button", {name: "Renommer les traités via Radarr"});
|
||||
await expect(bouton).toBeVisible();
|
||||
await bouton.click();
|
||||
// Radarr n'est pas joignable dans l'environnement de test: échec signalé.
|
||||
await expect(page.locator(".notification.error")).toContainText(/en échec/);
|
||||
});
|
||||
|
||||
test("la suppression d'une ligne passe par une confirmation", async ({page}) => {
|
||||
await login(page);
|
||||
await page.getByRole("button", {name: "Traitements"}).click();
|
||||
await ligneFilm(page, "Film Jetable 1").getByRole("button", {name: "Supprimer"}).click();
|
||||
// Le modal de confirmation porte bien le nom du film visé.
|
||||
await expect(
|
||||
page.locator(".modal.confirm").getByRole("heading", {name: "Film Jetable 1", level: 2}),
|
||||
).toBeVisible();
|
||||
await page
|
||||
.locator(".modal.confirm")
|
||||
.getByRole("button", {name: "Supprimer", exact: true})
|
||||
.click();
|
||||
|
||||
await expect(
|
||||
page.locator(".notification", {hasText: /retiré de l'inventaire/}),
|
||||
).toBeVisible();
|
||||
await expect(ligneFilm(page, "Film Jetable 1")).toBeHidden();
|
||||
});
|
||||
|
||||
test("la sélection multiple supprime plusieurs lignes", async ({page}) => {
|
||||
await login(page);
|
||||
await page.getByRole("button", {name: "Traitements"}).click();
|
||||
await page.getByRole("button", {name: "Sélection multiple"}).click();
|
||||
await ligneFilm(page, "Film Jetable 3").click();
|
||||
await ligneFilm(page, "Film Jetable 4").click();
|
||||
await expect(page.getByText("2 sélectionné(s)")).toBeVisible();
|
||||
|
||||
await page.getByRole("button", {name: "Supprimer la sélection"}).click();
|
||||
await page.locator(".modal.confirm").getByRole("button", {name: "Supprimer", exact: true}).click();
|
||||
await expect(
|
||||
page.locator(".notification", {hasText: /ligne\(s\) retirée\(s\)/}),
|
||||
).toBeVisible();
|
||||
// Les deux lignes jetables ont disparu, les autres films restent.
|
||||
await expect(ligneFilm(page, "Film Jetable 3")).toBeHidden();
|
||||
await expect(ligneFilm(page, "Film Jetable 4")).toBeHidden();
|
||||
await expect(ligneFilm(page, "Film Liste")).toBeVisible();
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import {expect, test} from "@playwright/test";
|
||||
|
||||
import {ligneFilm, login} from "./helpers";
|
||||
|
||||
test("l'interface reste utilisable sur mobile", async ({page}) => {
|
||||
await page.setViewportSize({width: 375, height: 812});
|
||||
await login(page);
|
||||
|
||||
// Navigation par onglets défilants, tous accessibles.
|
||||
await expect(page.getByRole("button", {name: "Traitements"})).toBeVisible();
|
||||
await page.getByRole("button", {name: "Traitements"}).click();
|
||||
|
||||
// Les fiches restent lisibles et cliquables: pastille + actions.
|
||||
const ligne = ligneFilm(page, "Pacific Rim");
|
||||
await expect(ligne).toBeVisible();
|
||||
await expect(ligne.locator(".status", {hasText: "Détecté"})).toBeVisible();
|
||||
await ligne.click();
|
||||
await expect(page.locator(".modal").getByRole("heading", {name: "Pacific Rim", level: 2})).toBeVisible();
|
||||
await expect(page.getByRole("button", {name: "Convertir en MKV"})).toBeVisible();
|
||||
});
|
||||
|
||||
test("la fiche reste lisible sur écran étroit", async ({page}) => {
|
||||
await page.setViewportSize({width: 360, height: 740});
|
||||
await login(page);
|
||||
await page.getByRole("button", {name: "Traitements"}).click();
|
||||
await page.getByRole("button", {name: "Traités"}).click();
|
||||
await ligneFilm(page, "Cars").click();
|
||||
|
||||
// Le tableau de la fiche passe en une colonne, contenu complet visible.
|
||||
await expect(page.getByText("MKV lié (dossier du film)")).toBeVisible();
|
||||
await expect(page.getByText("MKV brut (dossier de travail)")).toBeVisible();
|
||||
await page.locator(".modal").getByRole("button", {name: "Fermer"}).click();
|
||||
await expect(page.locator(".modal")).toBeHidden();
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import {expect, test} from "@playwright/test";
|
||||
|
||||
import {attendreEtat, fermerNotifications, ligneFilm, login} from "./helpers";
|
||||
|
||||
test("conversion complète: détection → validation → traité", async ({page}) => {
|
||||
await login(page);
|
||||
await page.getByRole("button", {name: "Traitements"}).click();
|
||||
|
||||
// Lancement depuis la fiche.
|
||||
await ligneFilm(page, "Pacific Rim").click();
|
||||
await page.getByRole("button", {name: "Convertir en MKV"}).click();
|
||||
await expect(
|
||||
page.locator(".notification", {hasText: /mise en file d'attente/}),
|
||||
).toBeVisible();
|
||||
|
||||
// Le statut passe par les états actifs puis "À valider", sans recharger.
|
||||
await attendreEtat(page, "Pacific Rim", "À valider");
|
||||
|
||||
// Fiche: les deux chemins et le bouton de validation.
|
||||
await ligneFilm(page, "Pacific Rim").click();
|
||||
await expect(page.getByText("MKV lié (dossier du film)")).toBeVisible();
|
||||
await expect(page.getByText("MKV brut (dossier de travail)")).toBeVisible();
|
||||
|
||||
// Validation: Radarr est absent dans l'environnement de test, la
|
||||
// validation réussit avec un avertissement.
|
||||
await fermerNotifications(page);
|
||||
await page.getByRole("button", {name: "Valider la conversion"}).click();
|
||||
await expect(page.locator(".notification.warning").last()).toContainText(
|
||||
/mise à jour Radarr impossible/,
|
||||
);
|
||||
|
||||
// La ligne a changé de catégorie toute seule: elle est dans "Traités".
|
||||
await page.getByRole("button", {name: "Traités"}).click();
|
||||
await expect(ligneFilm(page, "Pacific Rim")).toBeVisible();
|
||||
await expect(
|
||||
ligneFilm(page, "Pacific Rim").locator(".status", {hasText: "Terminé"}),
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test("annulation d'une conversion à valider: retour à détecté", async ({page}) => {
|
||||
await login(page);
|
||||
await page.getByRole("button", {name: "Traitements"}).click();
|
||||
|
||||
await ligneFilm(page, "Autre Film").click();
|
||||
await page.getByRole("button", {name: "Convertir en MKV"}).click();
|
||||
await attendreEtat(page, "Autre Film", "À valider");
|
||||
|
||||
await ligneFilm(page, "Autre Film").click();
|
||||
await fermerNotifications(page);
|
||||
await page.getByRole("button", {name: "Annuler"}).click();
|
||||
await expect(
|
||||
page.locator(".notification", {hasText: /annulée/}),
|
||||
).toBeVisible();
|
||||
|
||||
// Retour dans "À traiter" avec l'état détecté, MKV et lien supprimés.
|
||||
await attendreEtat(page, "Autre Film", "Détecté");
|
||||
await page.getByRole("button", {name: "À traiter"}).click();
|
||||
await expect(ligneFilm(page, "Autre Film")).toBeVisible();
|
||||
});
|
||||
|
||||
test("reprise d'une conversion après échec", async ({page}) => {
|
||||
await login(page);
|
||||
await page.getByRole("button", {name: "Traitements"}).click();
|
||||
await page.getByRole("button", {name: "Erreurs"}).click();
|
||||
await ligneFilm(page, "Film Erreur Bis").click();
|
||||
await page.getByRole("button", {name: "Reprendre la conversion en MKV"}).click();
|
||||
await expect(
|
||||
page.locator(".notification", {hasText: /mise en file d'attente/}),
|
||||
).toBeVisible();
|
||||
|
||||
// Pendant la conversion la ligne quitte "Erreurs": on la suit dans
|
||||
// l'onglet "En cours" jusqu'a "À valider".
|
||||
await page.getByRole("button", {name: "En cours"}).click();
|
||||
await attendreEtat(page, "Film Erreur Bis", "À valider");
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import type {Page} from "@playwright/test";
|
||||
import {expect} from "@playwright/test";
|
||||
|
||||
/** Connexion au compte seme par le serveur d'integration. */
|
||||
export async function login(page: Page) {
|
||||
await page.goto("/");
|
||||
await page.getByLabel("Nom d’utilisateur").fill("admin");
|
||||
await page.getByLabel("Mot de passe").fill("mot-de-passe-123");
|
||||
await page.getByRole("button", {name: "Se connecter"}).click();
|
||||
await expect(page.getByRole("button", {name: "Scanner maintenant"})).toBeVisible();
|
||||
}
|
||||
|
||||
/** Ligne d'un film dans la liste: l'article portant le titre en en-tete. */
|
||||
export function ligneFilm(page: Page, titre: string) {
|
||||
return page
|
||||
.locator("article")
|
||||
.filter({has: page.getByRole("heading", {name: new RegExp(titre)})});
|
||||
}
|
||||
|
||||
/** Referme les notifications empilees en bas a droite.
|
||||
|
||||
* Elles couvrent les boutons d'action des formulaires et des fiches: on les
|
||||
* degage avant d'interagir.
|
||||
*/
|
||||
export async function fermerNotifications(page: Page) {
|
||||
const boutons = page.getByRole("button", {name: "Supprimer la notification"});
|
||||
for (let i = (await boutons.count()) - 1; i >= 0; i--) {
|
||||
await boutons.nth(i).click();
|
||||
}
|
||||
}
|
||||
|
||||
/** Attend que la pastille du film atteigne l'etat voulu (polling de 3 s). */
|
||||
export async function attendreEtat(page: Page, titre: string, etat: string) {
|
||||
await expect(ligneFilm(page, titre).locator(".status", {hasText: etat})).toBeVisible({
|
||||
timeout: 20_000,
|
||||
});
|
||||
}
|
||||
Generated
+46
-58
@@ -11,12 +11,12 @@
|
||||
"@vitejs/plugin-react": "latest",
|
||||
"react": "latest",
|
||||
"react-dom": "latest",
|
||||
"react-router-dom": "latest",
|
||||
"typescript": "latest",
|
||||
"vite": "latest"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "latest",
|
||||
"@playwright/test": "^1.64.0",
|
||||
"@types/react": "latest",
|
||||
"@types/react-dom": "latest",
|
||||
"eslint": "latest",
|
||||
@@ -567,6 +567,22 @@
|
||||
"url": "https://github.com/sponsors/oxc-project"
|
||||
}
|
||||
},
|
||||
"node_modules/@playwright/test": {
|
||||
"version": "1.64.0",
|
||||
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.0.tgz",
|
||||
"integrity": "sha512-oTN9FNYuN6bqQMwiho6jJKLCG2/QOYCixGXuCjRmzOq23eODeukuY2XiAVoVpAECbuezMt1MHQjAiQxK8F+Y+g==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright": "1.64.0"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-android-arm-eabi": {
|
||||
"version": "1.2.13",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.13.tgz",
|
||||
@@ -1278,19 +1294,6 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/cookie": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",
|
||||
"integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/cross-spawn": {
|
||||
"version": "7.0.6",
|
||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
||||
@@ -2275,6 +2278,35 @@
|
||||
"url": "https://github.com/sponsors/jonschlinkert"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright": {
|
||||
"version": "1.64.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.0.tgz",
|
||||
"integrity": "sha512-kVzTnYFYEyQ9RGzBjNCd2+yEqWmVbxl3AHPynv3qQ6JTjv4a+kwRcnqQwIpuP3NnrnIrE/Q6wWAIAvMfIE2/Yg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.64.0"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.64.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.0.tgz",
|
||||
"integrity": "sha512-T9r+MZkTECl2+oUcZ26YgZzTrYidTsIhYYkJix+6iDOymOb1FB2RLLSOxRGnZGv5DStt+aduIVbt+E8WygXYpg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/postcss": {
|
||||
"version": "8.5.29",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.29.tgz",
|
||||
@@ -2364,44 +2396,6 @@
|
||||
"react": "^19.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-router": {
|
||||
"version": "7.18.4",
|
||||
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.4.tgz",
|
||||
"integrity": "sha512-PUPQcMhMGRAslLcvtlPz/kmzBEWPhLdgLFrL7pLNepBL6dX0lWj4WD2cUYVgYCuT3jxvghYFg81cDTj44DhetQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cookie": "^1.0.1",
|
||||
"set-cookie-parser": "^2.6.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=18",
|
||||
"react-dom": ">=18"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"react-dom": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/react-router-dom": {
|
||||
"version": "7.18.4",
|
||||
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.4.tgz",
|
||||
"integrity": "sha512-yrfmJHIpDG7taCpqKjT1G5B6q3O2K+RN8/fgNf0lTjCwiPbQ0ei6vXX9ZjQR+7ld8Tr7Z5xmyMnZ8YJrphWQUw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"react-router": "7.18.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=18",
|
||||
"react-dom": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/rolldown": {
|
||||
"version": "1.2.13",
|
||||
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.13.tgz",
|
||||
@@ -2451,12 +2445,6 @@
|
||||
"semver": "bin/semver.js"
|
||||
}
|
||||
},
|
||||
"node_modules/set-cookie-parser": {
|
||||
"version": "2.7.2",
|
||||
"resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz",
|
||||
"integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/shebang-command": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
|
||||
|
||||
+8
-7
@@ -6,24 +6,25 @@
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"lint": "eslint ."
|
||||
"lint": "eslint .",
|
||||
"test:e2e": "playwright test"
|
||||
},
|
||||
"dependencies": {
|
||||
"@vitejs/plugin-react": "latest",
|
||||
"vite": "latest",
|
||||
"typescript": "latest",
|
||||
"react": "latest",
|
||||
"react-dom": "latest",
|
||||
"react-router-dom": "latest"
|
||||
"typescript": "latest",
|
||||
"vite": "latest"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "latest",
|
||||
"@playwright/test": "^1.64.0",
|
||||
"@types/react": "latest",
|
||||
"@types/react-dom": "latest",
|
||||
"eslint": "latest",
|
||||
"@eslint/js": "latest",
|
||||
"typescript-eslint": "latest",
|
||||
"eslint-plugin-react-hooks": "latest",
|
||||
"eslint-plugin-react-refresh": "latest",
|
||||
"globals": "latest"
|
||||
"globals": "latest",
|
||||
"typescript-eslint": "latest"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import {fileURLToPath} from "node:url";
|
||||
import {defineConfig, devices} from "@playwright/test";
|
||||
|
||||
const webDir = fileURLToPath(new URL(".", import.meta.url));
|
||||
|
||||
/**
|
||||
* Tests fonctionnels (Playwright) du web.
|
||||
*
|
||||
* Le serveur d'integration (scripts/e2e_server.py) prepare un environnement
|
||||
* isole, seme un compte (admin / mot-de-passe-123) et des films dans tous
|
||||
* les etats, sert le front construit (web/dist) via l'API sur le port 8123.
|
||||
* Les conversions tournent en mode simulation: les parcours utilisateur sont
|
||||
* reels, sans Radarr ni qBittorrent.
|
||||
*/
|
||||
export default defineConfig({
|
||||
testDir: "./e2e",
|
||||
timeout: 90_000,
|
||||
fullyParallel: false,
|
||||
workers: 1,
|
||||
reporter: [["list"], ["html", {outputFolder: ".e2e-report", open: "never"}]],
|
||||
outputDir: ".e2e-results",
|
||||
use: {
|
||||
baseURL: "http://127.0.0.1:8123",
|
||||
actionTimeout: 15_000,
|
||||
expect: {timeout: 15_000},
|
||||
trace: "on-first-retry",
|
||||
},
|
||||
projects: [
|
||||
{
|
||||
name: "chromium",
|
||||
use: {...devices["Desktop Chrome"]},
|
||||
},
|
||||
],
|
||||
webServer: {
|
||||
command: "../.venv/bin/python ../scripts/e2e_server.py",
|
||||
cwd: webDir,
|
||||
url: "http://127.0.0.1:8123/api/health",
|
||||
reuseExistingServer: false,
|
||||
timeout: 120_000,
|
||||
},
|
||||
});
|
||||
+512
-49
@@ -10,20 +10,45 @@ type Movie = {
|
||||
size: number | null;
|
||||
poster_url: string | null;
|
||||
status: string;
|
||||
radarr_linked: boolean;
|
||||
completed_at: string | null;
|
||||
last_error: string | null;
|
||||
failed_step: string | null;
|
||||
last_seen_at: string;
|
||||
};
|
||||
|
||||
type RadarrSettings = { url: string | null; api_key_configured: boolean };
|
||||
type MovieDetail = Movie & {
|
||||
work_mkv_path?: string | null;
|
||||
linked_mkv_path?: string | null;
|
||||
workspace_folder?: string | null;
|
||||
workspace_files?: string[];
|
||||
qb_content_path?: string | null;
|
||||
iso_to_delete?: boolean;
|
||||
link_broken?: boolean;
|
||||
link_symbolic?: boolean;
|
||||
};
|
||||
|
||||
type ServiceStatus = {
|
||||
status: "unconfigured" | "configured" | "tested" | "error";
|
||||
tested_version?: string | null;
|
||||
tested_at?: string | null;
|
||||
test_error?: string | null;
|
||||
};
|
||||
|
||||
type RadarrSettings = ServiceStatus & {
|
||||
url: string | null;
|
||||
port: number | null;
|
||||
api_key_configured: boolean;
|
||||
};
|
||||
|
||||
type NotificationKind = "info" | "error" | "warning";
|
||||
type Notification = { id: number; text: string; kind: NotificationKind };
|
||||
type QbittorrentSettings = {
|
||||
type QbittorrentSettings = ServiceStatus & {
|
||||
url: string | null;
|
||||
port: number | null;
|
||||
username: string | null;
|
||||
password_configured: boolean;
|
||||
api_key_configured: boolean;
|
||||
};
|
||||
|
||||
const jsonHeaders = { "Content-Type": "application/json" };
|
||||
@@ -63,7 +88,18 @@ async function api<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const response = await fetch(path, init);
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => null);
|
||||
throw new Error(body?.detail ?? `Erreur HTTP ${response.status}`);
|
||||
const detail = body?.detail;
|
||||
if (typeof detail === "string") {
|
||||
throw new Error(detail);
|
||||
}
|
||||
if (detail && typeof detail === "object" && "message" in detail) {
|
||||
const error = new Error(String(detail.message)) as Error & {
|
||||
detail?: { code?: string; files?: string[]; folder?: string };
|
||||
};
|
||||
error.detail = detail;
|
||||
throw error;
|
||||
}
|
||||
throw new Error(`Erreur HTTP ${response.status}`);
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
@@ -77,6 +113,59 @@ function statusLabel(status: string): string {
|
||||
return STATUS_LABELS[status] ?? status;
|
||||
}
|
||||
|
||||
// Classe CSS par etat: chaque etat a sa couleur, les etats actifs ont un
|
||||
// spinner (voir style.css).
|
||||
const STATUS_CLASSES: Record<string, string> = {
|
||||
detected: "status st-detected",
|
||||
ready: "status st-detected",
|
||||
queued: "status st-queued",
|
||||
converting: "status st-active",
|
||||
importing: "status st-active",
|
||||
validating: "status st-validating",
|
||||
completed: "status st-completed",
|
||||
failed: "status error",
|
||||
missing: "status error",
|
||||
};
|
||||
|
||||
function statusClass(status: string): string {
|
||||
return STATUS_CLASSES[status] ?? "status";
|
||||
}
|
||||
|
||||
function isSpinning(status: string): boolean {
|
||||
return ["queued", "converting", "importing"].includes(status);
|
||||
}
|
||||
|
||||
function StatusPill({status}: { status: string }) {
|
||||
return (
|
||||
<span className={statusClass(status)}>
|
||||
{isSpinning(status) && <span className="spinner" aria-hidden="true" />}
|
||||
{statusLabel(status)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
// Badge de statut de connexion pour la page Configuration.
|
||||
function ServiceBadge({state, label}: { state: ServiceStatus; label: string }) {
|
||||
if (state.status === "tested") {
|
||||
return (
|
||||
<span className="status st-completed" title={state.test_error ?? undefined}>
|
||||
Testé{state.tested_version ? ` · ${state.tested_version}` : ""}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (state.status === "error") {
|
||||
return (
|
||||
<span className="status error" title={state.test_error ?? undefined}>
|
||||
Test échoué
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (state.status === "configured") {
|
||||
return <span className="status st-queued">Configuré · non testé</span>;
|
||||
}
|
||||
return <span className="status st-detected">{label} non configuré</span>;
|
||||
}
|
||||
|
||||
function formatDateTime(iso: string): string {
|
||||
const date = new Date(iso);
|
||||
return Number.isNaN(date.getTime()) ? "—" : dateFormatter.format(date);
|
||||
@@ -104,14 +193,23 @@ export default function App() {
|
||||
const [page, setPage] = useState<Page>("dashboard");
|
||||
const [movies, setMovies] = useState<Movie[]>([]);
|
||||
const [tab, setTab] = useState<Tab>("pending");
|
||||
const [linkedOnly, setLinkedOnly] = useState(false);
|
||||
const [url, setUrl] = useState("");
|
||||
const [radarrPort, setRadarrPort] = useState("");
|
||||
const [apiKey, setApiKey] = useState("");
|
||||
const [keyConfigured, setKeyConfigured] = useState(false);
|
||||
const [qbitUrl, setQbitUrl] = useState("");
|
||||
const [qbitPort, setQbitPort] = useState("");
|
||||
const [qbitUsername, setQbitUsername] = useState("");
|
||||
const [qbitPassword, setQbitPassword] = useState("");
|
||||
const [qbitApiKey, setQbitApiKey] = useState("");
|
||||
const [qbitConfigured, setQbitConfigured] = useState(false);
|
||||
const [selected, setSelected] = useState<Movie | null>(null);
|
||||
const [radarrState, setRadarrState] = useState<ServiceStatus | null>(null);
|
||||
const [qbittorrentState, setQbittorrentState] = useState<ServiceStatus | null>(null);
|
||||
const [logLines, setLogLines] = useState<string[]>([]);
|
||||
const [logRunning, setLogRunning] = useState(false);
|
||||
const terminalRef = useRef<HTMLPreElement | null>(null);
|
||||
const [selected, setSelected] = useState<MovieDetail | null>(null);
|
||||
const [posterUrl, setPosterUrl] = useState<string | null>(null);
|
||||
const [modalBusy, setModalBusy] = useState(false);
|
||||
const [modalMessage, setModalMessage] = useState("");
|
||||
@@ -197,15 +295,30 @@ export default function App() {
|
||||
])
|
||||
.then(([radarr, qbittorrent]) => {
|
||||
setUrl(radarr.url ?? "");
|
||||
setRadarrPort(radarr.port?.toString() ?? "");
|
||||
setKeyConfigured(radarr.api_key_configured);
|
||||
setQbitUrl(qbittorrent.url ?? "");
|
||||
setQbitPort(qbittorrent.port?.toString() ?? "");
|
||||
setQbitUsername(qbittorrent.username ?? "");
|
||||
setQbitConfigured(qbittorrent.password_configured);
|
||||
if (!radarr.api_key_configured || !qbittorrent.password_configured) {
|
||||
setQbitConfigured(qbittorrent.status !== "unconfigured");
|
||||
setRadarrState(radarr);
|
||||
setQbittorrentState(qbittorrent);
|
||||
if (radarr.status === "unconfigured") {
|
||||
notify(
|
||||
"Configuration incomplète — renseignez les connexions Radarr et qBittorrent dans la page Configuration.",
|
||||
"Connexion Radarr non configurée — renseignez-la dans la page Configuration.",
|
||||
"warning",
|
||||
);
|
||||
} else if (radarr.status === "error") {
|
||||
notify(
|
||||
"Connexion Radarr en échec au dernier test — vérifiez la page Configuration.",
|
||||
"warning",
|
||||
);
|
||||
}
|
||||
if (qbittorrent.status === "unconfigured") {
|
||||
notify(
|
||||
"qBittorrent non configuré — la suppression du torrent à la validation sera désactivée.",
|
||||
"info",
|
||||
);
|
||||
}
|
||||
})
|
||||
.catch((error: Error) => {
|
||||
@@ -213,13 +326,128 @@ export default function App() {
|
||||
});
|
||||
}, [authState, loadMovies]);
|
||||
|
||||
const hasActive = movies.some((movie) =>
|
||||
["queued", "converting", "importing"].includes(movie.status),
|
||||
);
|
||||
useEffect(() => {
|
||||
if (authState !== "authed") return;
|
||||
const timer = setInterval(() => {
|
||||
loadMovies().catch(() => undefined);
|
||||
}, 10_000);
|
||||
}, hasActive ? 3_000 : 10_000);
|
||||
return () => clearInterval(timer);
|
||||
}, [authState, loadMovies]);
|
||||
}, [authState, loadMovies, hasActive]);
|
||||
|
||||
// Fiche ouverte: rafraichit en continu le detail (le chemin du lien suit
|
||||
// le renommage Radarr, asynchrone apres la validation) et le terminal
|
||||
// de conversion pendant les etats actifs ou apres un echec.
|
||||
useEffect(() => {
|
||||
if (!selected) return;
|
||||
let cancelled = false;
|
||||
const timer = setInterval(async () => {
|
||||
const detail = await api<MovieDetail>(`/api/files/${selected.id}`).catch(() => null);
|
||||
const log = await api<{ lines: string[]; running: boolean }>(
|
||||
`/api/movies/${selected.id}/log`,
|
||||
).catch(() => null);
|
||||
if (cancelled) return;
|
||||
// Ne re-rend la fiche que si son contenu change reellement: le
|
||||
// rafraichissement continu ne doit pas re-creer les boutons en pleine
|
||||
// interaction (clic, focus).
|
||||
if (detail && JSON.stringify(detail) !== JSON.stringify(selected)) {
|
||||
setSelected(detail);
|
||||
}
|
||||
if (log && (log.running !== logRunning || log.lines.length !== logLines.length)) {
|
||||
setLogLines(log.lines);
|
||||
setLogRunning(log.running);
|
||||
}
|
||||
}, 2_000);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
clearInterval(timer);
|
||||
};
|
||||
}, [selected]);
|
||||
|
||||
// Terminal: reste colle en bas de la sortie.
|
||||
useEffect(() => {
|
||||
if (terminalRef.current) {
|
||||
terminalRef.current.scrollTop = terminalRef.current.scrollHeight;
|
||||
}
|
||||
}, [logLines]);
|
||||
|
||||
async function radarrRename(movie: MovieDetail) {
|
||||
setModalBusy(true);
|
||||
try {
|
||||
await api<Movie>(`/api/movies/${movie.id}/radarr-rename`, { method: "POST" });
|
||||
await loadMovies();
|
||||
notify(
|
||||
`« ${movie.title} » envoyé à Radarr — rescan puis renommage selon sa config Media Management.`,
|
||||
);
|
||||
} catch (error) {
|
||||
notify(`Renommage de « ${movie.title} » impossible : ${(error as Error).message}`, "error");
|
||||
} finally {
|
||||
setModalBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function radarrRenameAll() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const result = await api<{
|
||||
renamed: number;
|
||||
failures: { title: string; error: string }[];
|
||||
}>("/api/radarr/rename-processed", { method: "POST" });
|
||||
if (result.failures.length === 0) {
|
||||
notify(
|
||||
`${result.renamed} film(s) traité(s) envoyé(s) à Radarr — renommage selon sa config.`,
|
||||
);
|
||||
} else {
|
||||
notify(
|
||||
`${result.renamed} renommé(s), ${result.failures.length} en échec (ex: ${result.failures[0].title}: ${result.failures[0].error}).`,
|
||||
"error",
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
notify((error as Error).message, "error");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function repairMovieLink(movie: MovieDetail) {
|
||||
setModalBusy(true);
|
||||
try {
|
||||
const result = await api<Movie & {message: string}>(
|
||||
`/api/movies/${movie.id}/repair-link`,
|
||||
{method: "POST"},
|
||||
);
|
||||
const fresh = await api<MovieDetail>(`/api/files/${movie.id}`).catch(() => null);
|
||||
if (fresh) setSelected(fresh);
|
||||
notify(result.message);
|
||||
} catch (error) {
|
||||
notify(`Réparation du lien impossible : ${(error as Error).message}`, "error");
|
||||
} finally {
|
||||
setModalBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteDownloadIso(movie: MovieDetail) {
|
||||
setModalBusy(true);
|
||||
try {
|
||||
await api<Movie>(`/api/movies/${movie.id}/delete-iso`, { method: "POST" });
|
||||
await loadMovies();
|
||||
const fresh = await api<MovieDetail>(`/api/files/${movie.id}`).catch(() => null);
|
||||
if (fresh) setSelected(fresh);
|
||||
notify(`ISO de « ${movie.title} » supprimée du dossier de téléchargements.`);
|
||||
} catch (error) {
|
||||
notify(`Suppression de l'ISO impossible : ${(error as Error).message}`, "error");
|
||||
} finally {
|
||||
setModalBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
function copyPath(path: string) {
|
||||
navigator.clipboard.writeText(path).catch(() => undefined);
|
||||
notify("Chemin copié dans le presse-papiers.");
|
||||
}
|
||||
|
||||
function toggleTheme() {
|
||||
setTheme((current) => {
|
||||
@@ -294,16 +522,25 @@ export default function App() {
|
||||
const settings = await api<RadarrSettings>("/api/settings/radarr", {
|
||||
method: "PUT",
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({ url, api_key: apiKey || null }),
|
||||
body: JSON.stringify({ url, port: radarrPort ? Number(radarrPort) : null, api_key: apiKey || null }),
|
||||
});
|
||||
setKeyConfigured(settings.api_key_configured);
|
||||
setApiKey("");
|
||||
setRadarrState(settings);
|
||||
const result = await api<{ message: string }>("/api/settings/radarr/test", {
|
||||
method: "POST",
|
||||
});
|
||||
notify(result.message);
|
||||
// Le resultat du test est persiste: on recharge le statut.
|
||||
const fresh = await api<RadarrSettings>("/api/settings/radarr").catch(() => null);
|
||||
if (fresh) {
|
||||
setRadarrState(fresh);
|
||||
setKeyConfigured(fresh.api_key_configured);
|
||||
}
|
||||
} catch (error) {
|
||||
notify((error as Error).message, "error");
|
||||
const fresh = await api<RadarrSettings>("/api/settings/radarr").catch(() => null);
|
||||
if (fresh) setRadarrState(fresh);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -318,18 +555,29 @@ export default function App() {
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({
|
||||
url: qbitUrl,
|
||||
port: qbitPort ? Number(qbitPort) : null,
|
||||
username: qbitUsername,
|
||||
password: qbitPassword || null,
|
||||
api_key: qbitApiKey || null,
|
||||
}),
|
||||
});
|
||||
setQbitConfigured(settings.password_configured);
|
||||
setQbitConfigured(settings.status !== "unconfigured");
|
||||
setQbittorrentState(settings);
|
||||
setQbitPassword("");
|
||||
setQbitApiKey("");
|
||||
const result = await api<{ message: string }>("/api/settings/qbittorrent/test", {
|
||||
method: "POST",
|
||||
});
|
||||
notify(result.message);
|
||||
const fresh = await api<QbittorrentSettings>("/api/settings/qbittorrent").catch(() => null);
|
||||
if (fresh) {
|
||||
setQbittorrentState(fresh);
|
||||
setQbitConfigured(fresh.status !== "unconfigured");
|
||||
}
|
||||
} catch (error) {
|
||||
notify((error as Error).message, "error");
|
||||
const fresh = await api<QbittorrentSettings>("/api/settings/qbittorrent").catch(() => null);
|
||||
if (fresh) setQbittorrentState(fresh);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -338,12 +586,17 @@ export default function App() {
|
||||
async function scan() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const result = await api<{ iso_files: number; scanned_movies: number }>(
|
||||
"/api/scans",
|
||||
{ method: "POST" },
|
||||
);
|
||||
const result = await api<{
|
||||
iso_files: number;
|
||||
scanned_movies: number;
|
||||
refreshed: number;
|
||||
}>("/api/scans", { method: "POST" });
|
||||
await loadMovies();
|
||||
notify(`${result.iso_files} ISO trouvée(s) sur ${result.scanned_movies} film(s)`);
|
||||
let message = `${result.iso_files} ISO trouvée(s) sur ${result.scanned_movies} film(s)`;
|
||||
if (result.refreshed > 0) {
|
||||
message += ` — ${result.refreshed} chemin(s) de film(s) traité(s) mis à jour depuis Radarr`;
|
||||
}
|
||||
notify(message);
|
||||
} catch (error) {
|
||||
notify((error as Error).message, "error");
|
||||
} finally {
|
||||
@@ -362,7 +615,9 @@ export default function App() {
|
||||
};
|
||||
}, [movies]);
|
||||
|
||||
const visible = movies.filter((movie) => inGroup(movie.status, tab));
|
||||
const visible = movies.filter(
|
||||
(movie) => inGroup(movie.status, tab) && (!linkedOnly || movie.radarr_linked),
|
||||
);
|
||||
const lastDone = [...groups.done].sort(
|
||||
(a, b) => Date.parse(b.last_seen_at) - Date.parse(a.last_seen_at),
|
||||
);
|
||||
@@ -423,11 +678,23 @@ export default function App() {
|
||||
setDeleting(false);
|
||||
}
|
||||
|
||||
function openMovie(movie: Movie) {
|
||||
async function openMovie(movie: Movie) {
|
||||
setSelected(movie);
|
||||
setPosterUrl(movie.poster_url);
|
||||
setModalMessage("");
|
||||
setModalError(false);
|
||||
setLogLines([]);
|
||||
setLogRunning(false);
|
||||
const detail = await api<MovieDetail>(`/api/files/${movie.id}`).catch(() => null);
|
||||
if (detail) {
|
||||
setSelected(detail);
|
||||
api<{ lines: string[]; running: boolean }>(`/api/movies/${movie.id}/log`)
|
||||
.then((log) => {
|
||||
setLogLines(log.lines);
|
||||
setLogRunning(log.running);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
function closeModal() {
|
||||
@@ -437,19 +704,32 @@ export default function App() {
|
||||
setModalError(false);
|
||||
}
|
||||
|
||||
async function convert(movie: Movie) {
|
||||
async function convert(movie: MovieDetail, force = false) {
|
||||
setModalBusy(true);
|
||||
setModalMessage("");
|
||||
try {
|
||||
await api<Movie>(`/api/movies/${movie.id}/convert`, { method: "POST" });
|
||||
await api<Movie>(
|
||||
`/api/movies/${movie.id}/convert${force ? "?force=true" : ""}`,
|
||||
{ method: "POST" },
|
||||
);
|
||||
await loadMovies();
|
||||
setModalMessage("Conversion mise en file d'attente.");
|
||||
setModalError(false);
|
||||
closeModal();
|
||||
notify(`Conversion de « ${movie.title} » mise en file d'attente.`);
|
||||
} catch (error) {
|
||||
setModalMessage((error as Error).message);
|
||||
setModalError(true);
|
||||
const detail = (error as { detail?: { code?: string } }).detail;
|
||||
if (detail?.code === "workspace_not_empty") {
|
||||
// Restes d'anciennes conversions: la fiche les affiche avec le
|
||||
// bouton de suppression.
|
||||
setModalMessage((error as Error).message);
|
||||
setModalError(true);
|
||||
const fresh = await api<MovieDetail>(`/api/files/${movie.id}`).catch(() => null);
|
||||
if (fresh) setSelected(fresh);
|
||||
} else {
|
||||
setModalMessage((error as Error).message);
|
||||
setModalError(true);
|
||||
}
|
||||
} finally {
|
||||
setModalBusy(false);
|
||||
}
|
||||
@@ -467,14 +747,23 @@ export default function App() {
|
||||
if (fromModal) setModalBusy(true);
|
||||
else setValidatingId(movie.id);
|
||||
try {
|
||||
await api<Movie>(`/api/movies/${movie.id}/validate`, { method: "POST" });
|
||||
const result = await api<Movie & { rescan_warning?: string | null }>(
|
||||
`/api/movies/${movie.id}/validate`,
|
||||
{ method: "POST" },
|
||||
);
|
||||
await loadMovies();
|
||||
if (fromModal) {
|
||||
closeModal();
|
||||
notify(`« ${movie.title} » validé — ISO supprimée, film complètement converti.`);
|
||||
}
|
||||
if (result.rescan_warning) {
|
||||
notify(`« ${movie.title} » validé — ISO supprimée. Attention: ${result.rescan_warning}`, "warning");
|
||||
} else {
|
||||
notify(`« ${movie.title} » validé — ISO supprimée, Radarr rescanné et MKV renommé selon sa config.`);
|
||||
}
|
||||
} catch (error) {
|
||||
setError((error as Error).message);
|
||||
const message = (error as Error).message;
|
||||
setError(message);
|
||||
notify(`Validation de « ${movie.title} » impossible : ${message}`, "error");
|
||||
} finally {
|
||||
setModalBusy(false);
|
||||
setValidatingId(null);
|
||||
@@ -490,8 +779,10 @@ export default function App() {
|
||||
closeModal();
|
||||
notify(`Conversion de « ${movie.title} » annulée — MKV et lien supprimés, film remis à « Détecté ».`,);
|
||||
} catch (error) {
|
||||
setModalMessage((error as Error).message);
|
||||
const message = (error as Error).message;
|
||||
setModalMessage(message);
|
||||
setModalError(true);
|
||||
notify(`Annulation de « ${movie.title} » impossible : ${message}`, "error");
|
||||
} finally {
|
||||
setModalBusy(false);
|
||||
}
|
||||
@@ -773,6 +1064,11 @@ export default function App() {
|
||||
</div>
|
||||
<div className="title-actions">
|
||||
<span>{movies.length} détecté(s)</span>
|
||||
{tab === "done" && groups.done.length > 0 && (
|
||||
<button className="small" disabled={busy} onClick={radarrRenameAll}>
|
||||
Renommer les traités via Radarr
|
||||
</button>
|
||||
)}
|
||||
{selectMode ? (
|
||||
<button className="small" onClick={exitSelectMode}>Quitter la sélection</button>
|
||||
) : (
|
||||
@@ -813,6 +1109,13 @@ export default function App() {
|
||||
<span className="count">{groups[id].length}</span>
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
className={linkedOnly ? "tab active" : "tab"}
|
||||
onClick={() => setLinkedOnly((value) => !value)}
|
||||
title="N’afficher que les films dont le fichier est toujours présent tel quel côté Radarr"
|
||||
>
|
||||
Radarr lié
|
||||
</button>
|
||||
</nav>
|
||||
{visible.length === 0 ? (
|
||||
<div className="empty">Aucun film dans cette catégorie.</div>
|
||||
@@ -877,9 +1180,8 @@ export default function App() {
|
||||
Supprimer
|
||||
</button>
|
||||
)}
|
||||
<span className={BROKEN.includes(movie.status) ? "status error" : "status"}>
|
||||
{statusLabel(movie.status)}
|
||||
</span>
|
||||
{movie.radarr_linked && <span className="status linked">Radarr lié</span>}
|
||||
<StatusPill status={movie.status} />
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
@@ -893,20 +1195,34 @@ export default function App() {
|
||||
<section className="panel settings">
|
||||
<div className="panel-head">
|
||||
<p className="eyebrow">CONFIGURATION</p>
|
||||
<h2>Connexion Radarr</h2>
|
||||
<h2>
|
||||
Connexion Radarr{" "}
|
||||
{radarrState && <ServiceBadge state={radarrState} label="Radarr" />}
|
||||
</h2>
|
||||
<p>L’URL doit être accessible depuis le conteneur MKVTool.</p>
|
||||
</div>
|
||||
<form onSubmit={saveSettings}>
|
||||
<label>
|
||||
URL Radarr
|
||||
<input
|
||||
type="url"
|
||||
type="text"
|
||||
required
|
||||
placeholder="http://radarr:7878"
|
||||
placeholder="http://radarr:7878 ou 192.168.1.50"
|
||||
value={url}
|
||||
onChange={(event) => setUrl(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Port (optionnel)
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
max={65535}
|
||||
placeholder="7878"
|
||||
value={radarrPort}
|
||||
onChange={(event) => setRadarrPort(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Clé API
|
||||
<input
|
||||
@@ -925,7 +1241,10 @@ export default function App() {
|
||||
<section className="panel settings">
|
||||
<div className="panel-head">
|
||||
<p className="eyebrow">CONFIGURATION</p>
|
||||
<h2>Connexion qBittorrent</h2>
|
||||
<h2>
|
||||
Connexion qBittorrent{" "}
|
||||
{qbittorrentState && <ServiceBadge state={qbittorrentState} label="qBittorrent" />}
|
||||
</h2>
|
||||
<p>
|
||||
Utilisée pour supprimer le torrent et ses données lors de la validation
|
||||
finale d’une conversion.
|
||||
@@ -935,33 +1254,55 @@ export default function App() {
|
||||
<label>
|
||||
URL qBittorrent
|
||||
<input
|
||||
type="url"
|
||||
type="text"
|
||||
required
|
||||
placeholder="http://qbittorrent:8080"
|
||||
placeholder="http://qbittorrent:8080 ou 192.168.1.50"
|
||||
value={qbitUrl}
|
||||
onChange={(event) => setQbitUrl(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Utilisateur
|
||||
Port (optionnel)
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
max={65535}
|
||||
placeholder="8080"
|
||||
value={qbitPort}
|
||||
onChange={(event) => setQbitPort(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Utilisateur (optionnel)
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
placeholder="admin"
|
||||
placeholder="admin — vide = bypass qBittorrent"
|
||||
value={qbitUsername}
|
||||
onChange={(event) => setQbitUsername(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Mot de passe
|
||||
Mot de passe (optionnel)
|
||||
<input
|
||||
type="password"
|
||||
required={!qbitConfigured}
|
||||
placeholder={qbitConfigured ? "Configuré — laisser vide pour conserver" : "Mot de passe WebUI"}
|
||||
placeholder={
|
||||
qbitConfigured
|
||||
? "Configuré — laisser vide pour conserver, tout vider = bypass"
|
||||
: "Vide = bypass d'authentification qBittorrent"
|
||||
}
|
||||
value={qbitPassword}
|
||||
onChange={(event) => setQbitPassword(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Clé API (optionnel — qBittorrent ≥ 5.2)
|
||||
<input
|
||||
type="password"
|
||||
placeholder="qbt_... — prioritaire sur les identifiants"
|
||||
value={qbitApiKey}
|
||||
onChange={(event) => setQbitApiKey(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button disabled={busy}>Enregistrer et tester</button>
|
||||
</form>
|
||||
{qbitConfigured && (
|
||||
@@ -1003,7 +1344,7 @@ export default function App() {
|
||||
<dl className="modal-grid">
|
||||
<div>
|
||||
<dt>État</dt>
|
||||
<dd>{statusLabel(selected.status)}</dd>
|
||||
<dd><StatusPill status={selected.status} /></dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Taille de l’ISO</dt>
|
||||
@@ -1033,10 +1374,125 @@ export default function App() {
|
||||
<dt>Emplacement</dt>
|
||||
<dd><code>{selected.path}</code></dd>
|
||||
</div>
|
||||
{["validating", "completed"].includes(selected.status) && selected.linked_mkv_path && (
|
||||
<div className="modal-path">
|
||||
<dt>MKV lié (dossier du film)</dt>
|
||||
<dd className="path-row">
|
||||
<code>{selected.linked_mkv_path}</code>
|
||||
<button className="small copy" onClick={() => copyPath(selected.linked_mkv_path ?? "")}>
|
||||
Copier
|
||||
</button>
|
||||
</dd>
|
||||
</div>
|
||||
)}
|
||||
{["validating", "completed"].includes(selected.status) && selected.work_mkv_path && (
|
||||
<div className="modal-path">
|
||||
<dt>MKV brut (dossier de travail)</dt>
|
||||
<dd className="path-row">
|
||||
<code>{selected.work_mkv_path}</code>
|
||||
<button className="small copy" onClick={() => copyPath(selected.work_mkv_path ?? "")}>
|
||||
Copier
|
||||
</button>
|
||||
</dd>
|
||||
</div>
|
||||
)}
|
||||
</dl>
|
||||
|
||||
{selected.last_error && <p className="message error">{selected.last_error}</p>}
|
||||
|
||||
{selected.status === "completed" && selected.link_symbolic && (
|
||||
<div className="workspace-warning">
|
||||
<span className="status error">Lien symbolique fragile</span>
|
||||
<p>
|
||||
Le MKV du dossier du film est un lien symbolique hérité
|
||||
d'une ancienne version : il pointe vers un chemin interne
|
||||
au conteneur que Jellyfin et Radarr ne peuvent pas suivre.
|
||||
La réparation le remplace par un vrai fichier (lien dur ou
|
||||
copie) avec le nom attendu par Radarr.
|
||||
</p>
|
||||
<button
|
||||
className="primary"
|
||||
disabled={modalBusy}
|
||||
onClick={() => repairMovieLink(selected)}
|
||||
>
|
||||
{modalBusy ? "Réparation…" : "Réparer le lien du MKV"}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selected.status === "completed" && selected.link_broken && (
|
||||
<div className="workspace-warning">
|
||||
<span className="status error">Lien du MKV introuvable</span>
|
||||
<p>
|
||||
Le MKV lié a disparu du dossier du film, mais le MKV brut du
|
||||
dossier de travail est intact — les données sont conservées.
|
||||
Le lien peut être recréé avec le nom attendu par Radarr.
|
||||
</p>
|
||||
<button
|
||||
className="primary"
|
||||
disabled={modalBusy}
|
||||
onClick={() => repairMovieLink(selected)}
|
||||
>
|
||||
{modalBusy ? "Réparation…" : "Réparer le lien du MKV"}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selected.status === "completed" && selected.iso_to_delete && (
|
||||
<div className="workspace-warning iso-warning">
|
||||
<span className="status st-detected">ISO à supprimer</span>
|
||||
<p>
|
||||
L’ISO du dossier de téléchargements qBittorrent est encore présente :{" "}
|
||||
<code>{selected.qb_content_path}</code>. Supprimez-la quand le film
|
||||
vous convient — le MKV du dossier du film ne dépend plus d’elle.
|
||||
</p>
|
||||
<button
|
||||
className="danger"
|
||||
disabled={modalBusy}
|
||||
onClick={() => deleteDownloadIso(selected)}
|
||||
>
|
||||
{modalBusy ? "Suppression…" : "Supprimer l’ISO du dossier de téléchargements"}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{convertible && (selected.workspace_files?.length ?? 0) > 0 && (
|
||||
<div className="workspace-warning">
|
||||
<p>
|
||||
Des fichiers issus d’anciennes conversions sont présents dans le dossier
|
||||
de travail <code>{selected.workspace_folder}</code> :
|
||||
</p>
|
||||
<ul>
|
||||
{(selected.workspace_files ?? []).map((name) => (
|
||||
<li key={name}><code>{name}</code></li>
|
||||
))}
|
||||
</ul>
|
||||
<button
|
||||
className="danger"
|
||||
disabled={modalBusy}
|
||||
onClick={() => convert(selected, true)}
|
||||
>
|
||||
{modalBusy ? "Nettoyage…" : "Tout supprimer et reprendre la conversion"}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{["converting", "importing", "failed"].includes(selected.status) && (
|
||||
<div className="terminal-box">
|
||||
<div className="terminal-head">
|
||||
<span className={logRunning ? "dotpulse" : "dot"} aria-hidden="true" />
|
||||
<span>
|
||||
{logRunning
|
||||
? "Terminal de conversion — en direct"
|
||||
: "Journal de la dernière conversion"}
|
||||
</span>
|
||||
</div>
|
||||
<pre className="terminal" ref={terminalRef}>
|
||||
{logLines.length > 0 ? logLines.join("\n") : "En attente de sortie…"}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="modal-explain">
|
||||
La conversion extrait le film du disque ISO vers un fichier MKV avec MakeMKV,
|
||||
sans réencodage : vidéo, audio et sous-titres sont conservés à l’identique.
|
||||
@@ -1064,13 +1520,20 @@ export default function App() {
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<button className="primary" disabled={modalBusy || !convertible} onClick={() => convert(selected)}>
|
||||
{modalBusy
|
||||
? "Envoi…"
|
||||
: resuming
|
||||
? "Reprendre la conversion en MKV"
|
||||
: "Convertir en MKV"}
|
||||
</button>
|
||||
<>
|
||||
<button className="primary" disabled={modalBusy || !convertible} onClick={() => convert(selected)}>
|
||||
{modalBusy
|
||||
? "Envoi…"
|
||||
: resuming
|
||||
? "Reprendre la conversion en MKV"
|
||||
: "Convertir en MKV"}
|
||||
</button>
|
||||
{selected.status === "completed" && (
|
||||
<button disabled={modalBusy} onClick={() => radarrRename(selected)}>
|
||||
{modalBusy ? "Envoi…" : "Renommer via Radarr"}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{selected.status === "validating" ? (
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
export default function StatusBadge({status}: { status: string }) {
|
||||
const normalized = status.toLowerCase();
|
||||
|
||||
let variant: "neutral" | "warn" | "info" | "success" = "neutral";
|
||||
if (["processing", "in_progress", "converting", "moving"].includes(normalized)) variant = "info";
|
||||
if (["detected", "new", "pending", "todo", "unprocessed"].includes(normalized)) variant = "warn";
|
||||
if (["processed", "done", "completed", "success"].includes(normalized)) variant = "success";
|
||||
|
||||
return <span className={`badge badge--${variant}`}>{status}</span>;
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
export const jsonHeaders = {"Content-Type": "application/json"};
|
||||
|
||||
export async function api<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const response = await fetch(path, init);
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => null);
|
||||
throw new Error(body?.detail ?? `Erreur HTTP ${response.status}`);
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export function readableSize(size: number | null): string {
|
||||
if (size === null) return "—";
|
||||
return `${(size / 1024 ** 3).toFixed(1)} Go`;
|
||||
}
|
||||
|
||||
export function formatDateTime(iso: string | null | undefined): string {
|
||||
if (!iso) return "—";
|
||||
const date = new Date(iso);
|
||||
if (Number.isNaN(date.getTime())) return iso;
|
||||
return new Intl.DateTimeFormat("fr-FR", {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
}).format(date);
|
||||
}
|
||||
+1
-4
@@ -1,13 +1,10 @@
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { BrowserRouter } from "react-router-dom";
|
||||
import App from "./App";
|
||||
import "./style.css";
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -1,166 +0,0 @@
|
||||
import {useEffect, useMemo, useState} from "react";
|
||||
|
||||
import {api, formatDateTime, readableSize} from "../lib/api";
|
||||
import type {Movie, SettingsRead} from "../types";
|
||||
import StatusBadge from "../components/StatusBadge";
|
||||
|
||||
type Props = {
|
||||
onOpenFile: (id: number) => void;
|
||||
onOpenFiles: () => void;
|
||||
onOpenSettings: () => void;
|
||||
};
|
||||
|
||||
function isProcessing(status: string): boolean {
|
||||
return ["processing", "in_progress", "converting", "moving"].includes(status.toLowerCase());
|
||||
}
|
||||
|
||||
function isProcessed(status: string): boolean {
|
||||
return ["processed", "done", "completed", "success"].includes(status.toLowerCase());
|
||||
}
|
||||
|
||||
export default function Dashboard({onOpenFile, onOpenFiles, onOpenSettings}: Props) {
|
||||
const [movies, setMovies] = useState<Movie[]>([]);
|
||||
const [settings, setSettings] = useState<SettingsRead | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState<string>("");
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([api<Movie[]>("/api/movies"), api<SettingsRead>("/api/settings")])
|
||||
.then(([m, s]) => {
|
||||
setMovies(m);
|
||||
setSettings(s);
|
||||
})
|
||||
.catch((e: Error) => setMessage(e.message));
|
||||
}, []);
|
||||
|
||||
const canScan = settings?.radarr.api_key_configured ?? false;
|
||||
|
||||
async function scan() {
|
||||
setBusy(true);
|
||||
setMessage("");
|
||||
try {
|
||||
const result = await api<{ iso_files: number; scanned_movies: number }>("/api/scans", {method: "POST"});
|
||||
setMovies(await api<Movie[]>("/api/movies"));
|
||||
setMessage(`${result.iso_files} ISO trouvée(s) sur ${result.scanned_movies} film(s)`);
|
||||
} catch (e) {
|
||||
setMessage((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const stats = useMemo(() => {
|
||||
const total = movies.length;
|
||||
const processing = movies.filter((m) => isProcessing(m.status));
|
||||
const processed = movies.filter((m) => isProcessed(m.status));
|
||||
const unprocessed = total - processing.length - processed.length;
|
||||
|
||||
const recentlyProcessed = [...processed]
|
||||
.filter((m) => !!m.processed_at)
|
||||
.sort((a, b) => (b.processed_at ?? "").localeCompare(a.processed_at ?? ""))
|
||||
.slice(0, 6);
|
||||
|
||||
return {total, processing, processed, unprocessed, recentlyProcessed};
|
||||
}, [movies]);
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<section className="hero">
|
||||
<div className="hero__row">
|
||||
<div>
|
||||
<h2>Dashboard</h2>
|
||||
<p className="muted">
|
||||
Vue rapide sur l’état de vos fichiers. Pour afficher “tout juste traités”, le backend doit
|
||||
renseigner
|
||||
<code> processed_at</code> à la fin du workflow.
|
||||
</p>
|
||||
</div>
|
||||
<div className="hero__actions">
|
||||
<button className="btn" onClick={scan} disabled={busy || !canScan}>
|
||||
Scanner maintenant
|
||||
</button>
|
||||
{!canScan && (
|
||||
<button className="btn btn--ghost" type="button" onClick={onOpenSettings}>
|
||||
Configurer Radarr
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="kpis">
|
||||
<div className="kpi">
|
||||
<div className="kpi__label">Total</div>
|
||||
<div className="kpi__value">{stats.total}</div>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<div className="kpi__label">Non traités</div>
|
||||
<div className="kpi__value">{stats.unprocessed}</div>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<div className="kpi__label">En cours</div>
|
||||
<div className="kpi__value">{stats.processing.length}</div>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<div className="kpi__label">Traités</div>
|
||||
<div className="kpi__value">{stats.processed.length}</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{message && <div className="toast">{message}</div>}
|
||||
|
||||
<section className="grid-2">
|
||||
<section className="card">
|
||||
<div className="card__head">
|
||||
<h3>En cours de traitement</h3>
|
||||
<button className="btn btn--ghost" type="button" onClick={onOpenFiles}>
|
||||
Voir tous
|
||||
</button>
|
||||
</div>
|
||||
{stats.processing.length === 0 ? (
|
||||
<div className="empty">Aucun traitement en cours.</div>
|
||||
) : (
|
||||
<div className="list">
|
||||
{stats.processing.slice(0, 6).map((m) => (
|
||||
<button key={m.id} className="list__row" type="button" onClick={() => onOpenFile(m.id)}>
|
||||
<div>
|
||||
<div className="list__title">{m.title}</div>
|
||||
<div
|
||||
className="muted">{m.year ?? "Année inconnue"} · {readableSize(m.size)}</div>
|
||||
</div>
|
||||
<StatusBadge status={m.status}/>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="card">
|
||||
<div className="card__head">
|
||||
<h3>Tout juste traités</h3>
|
||||
<button className="btn btn--ghost" type="button" onClick={onOpenFiles}>
|
||||
Voir tous
|
||||
</button>
|
||||
</div>
|
||||
{stats.recentlyProcessed.length === 0 ? (
|
||||
<div className="empty">
|
||||
Aucun élément récent (champ <code>processed_at</code> non renseigné).
|
||||
</div>
|
||||
) : (
|
||||
<div className="list">
|
||||
{stats.recentlyProcessed.map((m) => (
|
||||
<button key={m.id} className="list__row" type="button" onClick={() => onOpenFile(m.id)}>
|
||||
<div>
|
||||
<div className="list__title">{m.title}</div>
|
||||
<div className="muted">Fini le {formatDateTime(m.processed_at)}</div>
|
||||
</div>
|
||||
<StatusBadge status={m.status}/>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
import {useEffect, useState} from "react";
|
||||
|
||||
import {api, formatDateTime, readableSize} from "../lib/api";
|
||||
import type {Movie} from "../types";
|
||||
import StatusBadge from "../components/StatusBadge";
|
||||
|
||||
type Props = {
|
||||
id: number;
|
||||
onBack: () => void;
|
||||
};
|
||||
|
||||
export default function FileDetails({id, onBack}: Props) {
|
||||
const [item, setItem] = useState<Movie | null>(null);
|
||||
const [error, setError] = useState<string>("");
|
||||
|
||||
useEffect(() => {
|
||||
setError("");
|
||||
setItem(null);
|
||||
api<Movie>(`/api/files/${id}`)
|
||||
.then(setItem)
|
||||
.catch((e: Error) => setError(e.message));
|
||||
}, [id]);
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<section className="hero hero--compact">
|
||||
<div className="hero__row">
|
||||
<div>
|
||||
<h2>Détails du fichier</h2>
|
||||
<p className="muted">Informations liées au fichier détecté et à son état de traitement.</p>
|
||||
</div>
|
||||
<div className="hero__actions">
|
||||
<button className="btn btn--ghost" type="button" onClick={onBack}>
|
||||
← Retour
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{error && <div className="toast toast--danger">{error}</div>}
|
||||
|
||||
{!item ? (
|
||||
<section className="card">
|
||||
<div className="skeleton"/>
|
||||
</section>
|
||||
) : (
|
||||
<>
|
||||
<section className="card">
|
||||
<div className="detail-head">
|
||||
<div>
|
||||
<h3>{item.title}</h3>
|
||||
<p className="muted">{item.year ?? "Année inconnue"}</p>
|
||||
</div>
|
||||
<StatusBadge status={item.status}/>
|
||||
</div>
|
||||
|
||||
<div className="detail-grid">
|
||||
<div className="kv">
|
||||
<div className="kv__k">Chemin</div>
|
||||
<div className="kv__v">
|
||||
<code>{item.path}</code>
|
||||
</div>
|
||||
</div>
|
||||
<div className="kv">
|
||||
<div className="kv__k">Taille</div>
|
||||
<div className="kv__v">{readableSize(item.size)}</div>
|
||||
</div>
|
||||
<div className="kv">
|
||||
<div className="kv__k">Détecté</div>
|
||||
<div className="kv__v">{formatDateTime(item.created_at)}</div>
|
||||
</div>
|
||||
<div className="kv">
|
||||
<div className="kv__k">Dernière présence</div>
|
||||
<div className="kv__v">{formatDateTime(item.last_seen_at)}</div>
|
||||
</div>
|
||||
<div className="kv">
|
||||
<div className="kv__k">Fin de traitement</div>
|
||||
<div className="kv__v">{formatDateTime(item.processed_at)}</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="card">
|
||||
<h3>Actions (à venir)</h3>
|
||||
<p className="muted">
|
||||
Ici on pourra ajouter: relancer un traitement, ouvrir le dossier, suppression, etc.
|
||||
</p>
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
import {useEffect, useMemo, useState} from "react";
|
||||
|
||||
import {api, readableSize} from "../lib/api";
|
||||
import type {Movie} from "../types";
|
||||
import StatusBadge from "../components/StatusBadge";
|
||||
|
||||
type Props = {
|
||||
onOpenFile: (id: number) => void;
|
||||
};
|
||||
|
||||
type UiStatus = "non_traite" | "en_cours" | "traite";
|
||||
|
||||
function mapStatus(status: string): UiStatus {
|
||||
const s = status.toLowerCase();
|
||||
if (["processing", "in_progress", "converting", "moving"].includes(s)) return "en_cours";
|
||||
if (["processed", "done", "completed", "success"].includes(s)) return "traite";
|
||||
return "non_traite";
|
||||
}
|
||||
|
||||
export default function Files({onOpenFile}: Props) {
|
||||
const [items, setItems] = useState<Movie[]>([]);
|
||||
const [filter, setFilter] = useState<UiStatus | "all">("all");
|
||||
const [query, setQuery] = useState("");
|
||||
const [error, setError] = useState<string>("");
|
||||
|
||||
useEffect(() => {
|
||||
api<Movie[]>("/api/files")
|
||||
.then(setItems)
|
||||
.catch((e: Error) => setError(e.message));
|
||||
}, []);
|
||||
|
||||
const groups = useMemo(() => {
|
||||
const base = items
|
||||
.filter((x) => (filter === "all" ? true : mapStatus(x.status) === filter))
|
||||
.filter((x) => {
|
||||
const q = query.trim().toLowerCase();
|
||||
if (!q) return true;
|
||||
return `${x.title} ${x.year ?? ""} ${x.path}`.toLowerCase().includes(q);
|
||||
});
|
||||
|
||||
const counts = {
|
||||
all: items.length,
|
||||
non_traite: items.filter((x) => mapStatus(x.status) === "non_traite").length,
|
||||
en_cours: items.filter((x) => mapStatus(x.status) === "en_cours").length,
|
||||
traite: items.filter((x) => mapStatus(x.status) === "traite").length,
|
||||
};
|
||||
|
||||
return {base, counts};
|
||||
}, [items, filter, query]);
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<section className="hero hero--compact">
|
||||
<div className="hero__row">
|
||||
<div>
|
||||
<h2>Gestion des fichiers</h2>
|
||||
<p className="muted">Filtrez l’inventaire et ouvrez un fichier pour consulter le détail.</p>
|
||||
</div>
|
||||
<div className="hero__actions">
|
||||
<div className="segmented">
|
||||
<button
|
||||
type="button"
|
||||
className={filter === "all" ? "segmented__btn segmented__btn--active" : "segmented__btn"}
|
||||
onClick={() => setFilter("all")}
|
||||
>
|
||||
Tous <span className="segmented__count">{groups.counts.all}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={
|
||||
filter === "non_traite" ? "segmented__btn segmented__btn--active" : "segmented__btn"
|
||||
}
|
||||
onClick={() => setFilter("non_traite")}
|
||||
>
|
||||
Non traités <span className="segmented__count">{groups.counts.non_traite}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={
|
||||
filter === "en_cours" ? "segmented__btn segmented__btn--active" : "segmented__btn"
|
||||
}
|
||||
onClick={() => setFilter("en_cours")}
|
||||
>
|
||||
En cours <span className="segmented__count">{groups.counts.en_cours}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={filter === "traite" ? "segmented__btn segmented__btn--active" : "segmented__btn"}
|
||||
onClick={() => setFilter("traite")}
|
||||
>
|
||||
Traités <span className="segmented__count">{groups.counts.traite}</span>
|
||||
</button>
|
||||
</div>
|
||||
<input
|
||||
className="search"
|
||||
placeholder="Rechercher (titre, année, chemin…)"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{error && <div className="toast toast--danger">{error}</div>}
|
||||
|
||||
<section className="card">
|
||||
<div className="table">
|
||||
<div className="table__head">
|
||||
<div>Titre</div>
|
||||
<div>Fichier</div>
|
||||
<div>Taille</div>
|
||||
<div>Statut</div>
|
||||
</div>
|
||||
|
||||
{groups.base.length === 0 ? (
|
||||
<div className="empty">Aucun résultat.</div>
|
||||
) : (
|
||||
groups.base.map((movie) => (
|
||||
<button
|
||||
key={movie.id}
|
||||
className="table__row"
|
||||
type="button"
|
||||
onClick={() => onOpenFile(movie.id)}
|
||||
>
|
||||
<div className="table__cell">
|
||||
<div className="table__title">{movie.title}</div>
|
||||
<div className="muted">{movie.year ?? "Année inconnue"}</div>
|
||||
</div>
|
||||
<div className="table__cell">
|
||||
<code>{movie.path}</code>
|
||||
</div>
|
||||
<div className="table__cell">{readableSize(movie.size)}</div>
|
||||
<div className="table__cell">
|
||||
<StatusBadge status={movie.status}/>
|
||||
</div>
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,356 +0,0 @@
|
||||
import {useCallback, useEffect, useMemo, useState} from "react";
|
||||
import type React from "react";
|
||||
|
||||
import {api, jsonHeaders} from "../lib/api";
|
||||
import type {SettingsRead} from "../types";
|
||||
|
||||
export default function Settings() {
|
||||
const [radarrUrl, setRadarrUrl] = useState("");
|
||||
const [radarrApiKey, setRadarrApiKey] = useState("");
|
||||
const [radarrKeyConfigured, setRadarrKeyConfigured] = useState(false);
|
||||
|
||||
const [sonarrUrl, setSonarrUrl] = useState("");
|
||||
const [sonarrApiKey, setSonarrApiKey] = useState("");
|
||||
const [sonarrKeyConfigured, setSonarrKeyConfigured] = useState(false);
|
||||
|
||||
const [prowlarrUrl, setProwlarrUrl] = useState("");
|
||||
const [prowlarrApiKey, setProwlarrApiKey] = useState("");
|
||||
const [prowlarrKeyConfigured, setProwlarrKeyConfigured] = useState(false);
|
||||
|
||||
const [jellyfinUrl, setJellyfinUrl] = useState("");
|
||||
const [jellyfinApiKey, setJellyfinApiKey] = useState("");
|
||||
const [jellyfinKeyConfigured, setJellyfinKeyConfigured] = useState(false);
|
||||
|
||||
const [seerrUrl, setSeerrUrl] = useState("");
|
||||
const [seerrApiKey, setSeerrApiKey] = useState("");
|
||||
const [seerrKeyConfigured, setSeerrKeyConfigured] = useState(false);
|
||||
|
||||
const [qbitUrl, setQbitUrl] = useState("");
|
||||
const [qbitUsername, setQbitUsername] = useState("");
|
||||
const [qbitPassword, setQbitPassword] = useState("");
|
||||
const [qbitPasswordConfigured, setQbitPasswordConfigured] = useState(false);
|
||||
|
||||
const [message, setMessage] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const serviceHelp = useMemo(() => "L’URL doit être accessible depuis le conteneur MKVTool.", []);
|
||||
|
||||
const hydrateSettings = useCallback((settings: SettingsRead) => {
|
||||
setRadarrUrl(settings.radarr.url ?? "");
|
||||
setRadarrKeyConfigured(settings.radarr.api_key_configured);
|
||||
|
||||
setSonarrUrl(settings.sonarr.url ?? "");
|
||||
setSonarrKeyConfigured(settings.sonarr.api_key_configured);
|
||||
|
||||
setProwlarrUrl(settings.prowlarr.url ?? "");
|
||||
setProwlarrKeyConfigured(settings.prowlarr.api_key_configured);
|
||||
|
||||
setJellyfinUrl(settings.jellyfin.url ?? "");
|
||||
setJellyfinKeyConfigured(settings.jellyfin.api_key_configured);
|
||||
|
||||
setSeerrUrl(settings.seerr.url ?? "");
|
||||
setSeerrKeyConfigured(settings.seerr.api_key_configured);
|
||||
|
||||
setQbitUrl(settings.qbittorrent.url ?? "");
|
||||
setQbitUsername(settings.qbittorrent.username ?? "");
|
||||
setQbitPasswordConfigured(settings.qbittorrent.password_configured);
|
||||
}, []);
|
||||
|
||||
const refreshSettings = useCallback(async () => {
|
||||
hydrateSettings(await api<SettingsRead>("/api/settings"));
|
||||
}, [hydrateSettings]);
|
||||
|
||||
useEffect(() => {
|
||||
refreshSettings().catch((error: Error) => setMessage(error.message));
|
||||
}, [refreshSettings]);
|
||||
|
||||
async function saveRadarr(event: React.FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setMessage("");
|
||||
try {
|
||||
await api<SettingsRead>("/api/settings", {
|
||||
method: "PUT",
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({
|
||||
radarr: {
|
||||
url: radarrUrl || null,
|
||||
api_key: radarrApiKey || null,
|
||||
},
|
||||
}),
|
||||
});
|
||||
setRadarrApiKey("");
|
||||
await refreshSettings();
|
||||
const result = await api<{ message: string }>("/api/settings/radarr/test", {method: "POST"});
|
||||
setMessage(result.message);
|
||||
} catch (error) {
|
||||
setMessage((error as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveApiService(
|
||||
name: "sonarr" | "prowlarr" | "jellyfin" | "seerr",
|
||||
event: React.FormEvent<HTMLFormElement>,
|
||||
) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setMessage("");
|
||||
|
||||
const model = {
|
||||
sonarr: {url: sonarrUrl || null, api_key: sonarrApiKey || null},
|
||||
prowlarr: {url: prowlarrUrl || null, api_key: prowlarrApiKey || null},
|
||||
jellyfin: {url: jellyfinUrl || null, api_key: jellyfinApiKey || null},
|
||||
seerr: {url: seerrUrl || null, api_key: seerrApiKey || null},
|
||||
}[name];
|
||||
|
||||
try {
|
||||
await api<SettingsRead>("/api/settings", {
|
||||
method: "PUT",
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({[name]: model}),
|
||||
});
|
||||
|
||||
if (name === "sonarr") setSonarrApiKey("");
|
||||
if (name === "prowlarr") setProwlarrApiKey("");
|
||||
if (name === "jellyfin") setJellyfinApiKey("");
|
||||
if (name === "seerr") setSeerrApiKey("");
|
||||
|
||||
await refreshSettings();
|
||||
setMessage("Configuration enregistrée");
|
||||
} catch (error) {
|
||||
setMessage((error as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveQbittorrent(event: React.FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setMessage("");
|
||||
try {
|
||||
await api<SettingsRead>("/api/settings", {
|
||||
method: "PUT",
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({
|
||||
qbittorrent: {
|
||||
url: qbitUrl || null,
|
||||
username: qbitUsername || null,
|
||||
password: qbitPassword || null,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
setQbitPassword("");
|
||||
await refreshSettings();
|
||||
setMessage("Configuration enregistrée");
|
||||
} catch (error) {
|
||||
setMessage((error as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<section className="hero">
|
||||
<div>
|
||||
<h2>Connexions</h2>
|
||||
<p className="muted">
|
||||
Configurez vos services. Les secrets ne sont pas affichés et seront conservés si vous laissez
|
||||
les champs
|
||||
vides.
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="card grid-2">
|
||||
<div>
|
||||
<h3>Radarr</h3>
|
||||
<p className="muted">Obligatoire pour le scan et la détection des films.</p>
|
||||
</div>
|
||||
<form onSubmit={saveRadarr} className="form-2">
|
||||
<label>
|
||||
URL Radarr
|
||||
<input
|
||||
type="url"
|
||||
required
|
||||
placeholder="http://radarr:7878"
|
||||
value={radarrUrl}
|
||||
onChange={(event) => setRadarrUrl(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Clé API {radarrKeyConfigured && <span>· configurée</span>}
|
||||
<input
|
||||
type="password"
|
||||
required={!radarrKeyConfigured}
|
||||
placeholder={radarrKeyConfigured ? "Laisser vide pour conserver" : "Clé API Radarr"}
|
||||
value={radarrApiKey}
|
||||
onChange={(event) => setRadarrApiKey(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button disabled={busy}>Enregistrer et tester</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section className="card grid-2">
|
||||
<div>
|
||||
<h3>Sonarr</h3>
|
||||
<p className="muted">Optionnel (hors périmètre MVP), mais stocké dans conf.json.</p>
|
||||
</div>
|
||||
<form onSubmit={(e) => saveApiService("sonarr", e)} className="form-2">
|
||||
<label>
|
||||
URL Sonarr
|
||||
<input
|
||||
type="url"
|
||||
placeholder="http://sonarr:8989"
|
||||
value={sonarrUrl}
|
||||
onChange={(event) => setSonarrUrl(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Clé API {sonarrKeyConfigured && <span>· configurée</span>}
|
||||
<input
|
||||
type="password"
|
||||
placeholder={sonarrKeyConfigured ? "Laisser vide pour conserver" : "Clé API Sonarr"}
|
||||
value={sonarrApiKey}
|
||||
onChange={(event) => setSonarrApiKey(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button disabled={busy}>Enregistrer</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section className="card grid-2">
|
||||
<div>
|
||||
<h3>Prowlarr</h3>
|
||||
<p className="muted">Optionnel (hors périmètre MVP), mais stocké dans conf.json.</p>
|
||||
</div>
|
||||
<form onSubmit={(e) => saveApiService("prowlarr", e)} className="form-2">
|
||||
<label>
|
||||
URL Prowlarr
|
||||
<input
|
||||
type="url"
|
||||
placeholder="http://prowlarr:9696"
|
||||
value={prowlarrUrl}
|
||||
onChange={(event) => setProwlarrUrl(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Clé API {prowlarrKeyConfigured && <span>· configurée</span>}
|
||||
<input
|
||||
type="password"
|
||||
placeholder={prowlarrKeyConfigured ? "Laisser vide pour conserver" : "Clé API Prowlarr"}
|
||||
value={prowlarrApiKey}
|
||||
onChange={(event) => setProwlarrApiKey(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button disabled={busy}>Enregistrer</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section className="card grid-2">
|
||||
<div>
|
||||
<h3>Jellyfin</h3>
|
||||
<p className="muted">Optionnel (hors périmètre MVP), mais stocké dans conf.json.</p>
|
||||
</div>
|
||||
<form onSubmit={(e) => saveApiService("jellyfin", e)} className="form-2">
|
||||
<label>
|
||||
URL Jellyfin
|
||||
<input
|
||||
type="url"
|
||||
placeholder="http://jellyfin:8096"
|
||||
value={jellyfinUrl}
|
||||
onChange={(event) => setJellyfinUrl(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Clé API {jellyfinKeyConfigured && <span>· configurée</span>}
|
||||
<input
|
||||
type="password"
|
||||
placeholder={jellyfinKeyConfigured ? "Laisser vide pour conserver" : "Clé API Jellyfin"}
|
||||
value={jellyfinApiKey}
|
||||
onChange={(event) => setJellyfinApiKey(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button disabled={busy}>Enregistrer</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section className="card grid-2">
|
||||
<div>
|
||||
<h3>Overseerr</h3>
|
||||
<p className="muted">Optionnel (hors périmètre MVP), mais stocké dans conf.json.</p>
|
||||
</div>
|
||||
<form onSubmit={(e) => saveApiService("seerr", e)} className="form-2">
|
||||
<label>
|
||||
URL Seerr
|
||||
<input
|
||||
type="url"
|
||||
placeholder="http://seerr:5055"
|
||||
value={seerrUrl}
|
||||
onChange={(event) => setSeerrUrl(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Clé API {seerrKeyConfigured && <span>· configurée</span>}
|
||||
<input
|
||||
type="password"
|
||||
placeholder={seerrKeyConfigured ? "Laisser vide pour conserver" : "Clé API Seerr"}
|
||||
value={seerrApiKey}
|
||||
onChange={(event) => setSeerrApiKey(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button disabled={busy}>Enregistrer</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section className="card grid-2">
|
||||
<div>
|
||||
<h3>qBittorrent</h3>
|
||||
<p className="muted">Optionnel: nécessaire pour supprimer torrent + données après import validé.</p>
|
||||
</div>
|
||||
<form onSubmit={saveQbittorrent} className="form-3">
|
||||
<label>
|
||||
URL WebUI
|
||||
<input
|
||||
type="url"
|
||||
placeholder="http://qbittorrent:8080"
|
||||
value={qbitUrl}
|
||||
onChange={(event) => setQbitUrl(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Utilisateur
|
||||
<input
|
||||
type="text"
|
||||
placeholder="admin"
|
||||
value={qbitUsername}
|
||||
onChange={(event) => setQbitUsername(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Mot de passe {qbitPasswordConfigured && <span>· configuré</span>}
|
||||
<input
|
||||
type="password"
|
||||
placeholder={qbitPasswordConfigured ? "Laisser vide pour conserver" : "Mot de passe"}
|
||||
value={qbitPassword}
|
||||
onChange={(event) => setQbitPassword(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button disabled={busy}>Enregistrer</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section className="card">
|
||||
<h3>Aide</h3>
|
||||
<p className="muted">{serviceHelp}</p>
|
||||
</section>
|
||||
|
||||
{message && <div className="toast">{message}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -127,6 +127,7 @@ h1 {
|
||||
background: var(--surface);
|
||||
}
|
||||
.settings { display: grid; grid-template-columns: 1fr 2fr; gap: 2.5rem; }
|
||||
.service-head { display: flex; align-items: center; gap: 0.75rem; }
|
||||
.panel-head h2 { font-size: 1.15rem; font-weight: 650; margin-bottom: 0.4rem; }
|
||||
.settings p, article p { color: var(--text-muted); }
|
||||
form { display: grid; grid-template-columns: 1fr 1fr auto; align-items: end; gap: 0.75rem; }
|
||||
@@ -197,6 +198,14 @@ code { color: var(--text-muted); font-size: 0.8rem; overflow-wrap: anywhere; }
|
||||
}
|
||||
|
||||
.status.error { color: var(--danger); border-color: rgba(248, 113, 113, 0.4); }
|
||||
.status.linked {
|
||||
color: #4ade80;
|
||||
border-color: rgba(74, 222, 128, 0.4);
|
||||
}
|
||||
.status.warn {
|
||||
color: #fbbf24;
|
||||
border-color: rgba(251, 191, 36, 0.4);
|
||||
}
|
||||
|
||||
.row-actions { display: flex; align-items: center; gap: 0.75rem; flex-shrink: 0; }
|
||||
button.small { padding: 0.45rem 0.9rem; font-size: 0.85rem; border-radius: 8px; }
|
||||
@@ -550,3 +559,154 @@ button.danger:hover:not(:disabled) {
|
||||
background: var(--surface-raised);
|
||||
border-color: transparent;
|
||||
}
|
||||
|
||||
/* --- Pastilles d'etat: une couleur par etat --- */
|
||||
.status.st-detected {
|
||||
color: #fbbf24;
|
||||
border-color: rgba(251, 191, 36, 0.45);
|
||||
}
|
||||
.status.st-queued {
|
||||
color: #93c5fd;
|
||||
border-color: rgba(147, 197, 253, 0.45);
|
||||
}
|
||||
.status.st-active {
|
||||
color: #93c5fd;
|
||||
border-color: rgba(147, 197, 253, 0.45);
|
||||
}
|
||||
.status.st-validating {
|
||||
color: #fbbf24;
|
||||
border-color: rgba(251, 191, 36, 0.45);
|
||||
}
|
||||
.status.st-completed {
|
||||
color: #4ade80;
|
||||
border-color: rgba(74, 222, 128, 0.45);
|
||||
}
|
||||
|
||||
/* --- Spinner (etats actifs) --- */
|
||||
.spinner {
|
||||
display: inline-block;
|
||||
width: 0.65rem;
|
||||
height: 0.65rem;
|
||||
margin-right: 0.35rem;
|
||||
vertical-align: -1px;
|
||||
border: 2px solid rgba(147, 197, 253, 0.35);
|
||||
border-top-color: #93c5fd;
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
/* --- Terminal de conversion --- */
|
||||
.terminal-box {
|
||||
margin-top: 1.25rem;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.terminal-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.55rem;
|
||||
padding: 0.5rem 0.85rem;
|
||||
background: var(--surface-raised);
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-size: 0.78rem;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.dotpulse {
|
||||
width: 0.55rem;
|
||||
height: 0.55rem;
|
||||
border-radius: 50%;
|
||||
background: #4ade80;
|
||||
animation: pulse 1.2s ease-in-out infinite;
|
||||
}
|
||||
@keyframes pulse {
|
||||
0%, 100% { opacity: 1; }
|
||||
50% { opacity: 0.25; }
|
||||
}
|
||||
.terminal {
|
||||
margin: 0;
|
||||
padding: 0.85rem;
|
||||
max-height: 280px;
|
||||
overflow-y: auto;
|
||||
background: #0a0a0b;
|
||||
color: #d4d4d8;
|
||||
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
|
||||
font-size: 0.72rem;
|
||||
line-height: 1.45;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
/* --- Restes d'anciennes conversions --- */
|
||||
.workspace-warning {
|
||||
margin-top: 1.25rem;
|
||||
padding: 1rem 1.1rem;
|
||||
border: 1px solid rgba(251, 191, 36, 0.45);
|
||||
border-left: 3px solid #fbbf24;
|
||||
border-radius: 10px;
|
||||
background: var(--surface);
|
||||
}
|
||||
.workspace-warning p { margin: 0 0 0.5rem; font-size: 0.9rem; }
|
||||
.workspace-warning ul {
|
||||
margin: 0 0 0.9rem;
|
||||
padding-left: 1.2rem;
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
/* --- Lignes de chemin copiables --- */
|
||||
.path-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.55rem;
|
||||
}
|
||||
.path-row code { flex: 1; }
|
||||
button.copy { color: var(--text-muted); border-color: transparent; }
|
||||
button.copy:hover:not(:disabled) {
|
||||
color: var(--text);
|
||||
border-color: var(--border-strong);
|
||||
}
|
||||
|
||||
/* --- Responsive --- */
|
||||
@media (max-width: 760px) {
|
||||
header {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 1rem;
|
||||
}
|
||||
.header-actions { justify-content: space-between; }
|
||||
.pages { overflow-x: auto; flex-wrap: nowrap; -webkit-overflow-scrolling: touch; }
|
||||
.page-link, .tab { white-space: nowrap; }
|
||||
.stats { grid-template-columns: repeat(2, 1fr); }
|
||||
.activity { grid-template-columns: 1fr; }
|
||||
.settings { grid-template-columns: 1fr; }
|
||||
form, form.wide { grid-template-columns: 1fr; }
|
||||
form > button { width: 100%; }
|
||||
article { flex-direction: column; align-items: flex-start; }
|
||||
.row-actions { width: 100%; justify-content: flex-start; flex-wrap: wrap; }
|
||||
article code { font-size: 0.68rem; }
|
||||
.modal { width: calc(100vw - 1.5rem); max-height: 92vh; padding: 1.25rem; }
|
||||
.modal-head { flex-direction: column; gap: 0.5rem; }
|
||||
.modal-head .modal-close { align-self: flex-end; }
|
||||
.modal-grid { grid-template-columns: 1fr; }
|
||||
.modal-poster { max-width: 45%; }
|
||||
.modal-actions { flex-direction: column-reverse; align-items: stretch; }
|
||||
.bulk-bar { flex-wrap: wrap; gap: 0.75rem; }
|
||||
.tabs { overflow-x: auto; flex-wrap: nowrap; }
|
||||
.notifications { left: 0.5rem; right: 0.5rem; }
|
||||
}
|
||||
|
||||
/* --- ISO de telechargement a supprimer (film traite) --- */
|
||||
.iso-warning .status {
|
||||
display: inline-block;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
.iso-warning code {
|
||||
display: block;
|
||||
margin: 0.25rem 0;
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
export type Movie = {
|
||||
id: number;
|
||||
title: string;
|
||||
year: number | null;
|
||||
path: string;
|
||||
size: number | null;
|
||||
status: string;
|
||||
created_at?: string | null;
|
||||
last_seen_at?: string | null;
|
||||
processed_at?: string | null;
|
||||
};
|
||||
|
||||
export type ApiServiceSettingsRead = { url: string | null; api_key_configured: boolean };
|
||||
export type QbittorrentSettingsRead = {
|
||||
url: string | null;
|
||||
username: string | null;
|
||||
password_configured: boolean;
|
||||
};
|
||||
|
||||
export type SettingsRead = {
|
||||
radarr: ApiServiceSettingsRead;
|
||||
sonarr: ApiServiceSettingsRead;
|
||||
prowlarr: ApiServiceSettingsRead;
|
||||
jellyfin: ApiServiceSettingsRead;
|
||||
seerr: ApiServiceSettingsRead;
|
||||
qbittorrent: QbittorrentSettingsRead;
|
||||
};
|
||||
Reference in new issue
Block a user