Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5fccc71326 | ||
|
|
f7379c67df | ||
|
|
ba90ba3675 | ||
|
|
c793411595 | ||
|
|
6191b32bf7 | ||
|
|
70ce0b95a8 | ||
|
|
078905e944 | ||
|
|
39319b7caa | ||
|
|
10830f3562 | ||
|
|
87fd6b39fd | ||
|
|
acc1609b4d | ||
|
|
8e76fb7112 |
No files matched your search
+14
-4
@@ -1,6 +1,6 @@
|
|||||||
# syntax=docker/dockerfile:1
|
# syntax=docker/dockerfile:1
|
||||||
|
|
||||||
ARG MAKEMKV_VERSION=2.0.0
|
ARG MAKEMKV_VERSION=1.18.4
|
||||||
|
|
||||||
# --- Interface web ---
|
# --- Interface web ---
|
||||||
FROM node:22-slim AS web
|
FROM node:22-slim AS web
|
||||||
@@ -31,9 +31,15 @@ RUN apt-get update \
|
|||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
# MakeMKV (makemkvcon) — version explicite, licence a fournir via makemkv.
|
# 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" \
|
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" \
|
|| curl -fsSLO "https://www.makemkv.com/download/old/makemkv-oss-${MAKEMKV_VERSION}.tar.gz"; \
|
||||||
&& tar -xzf "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" \
|
&& tar -xzf "makemkv-bin-${MAKEMKV_VERSION}.tar.gz" \
|
||||||
&& cd "makemkv-oss-${MAKEMKV_VERSION}" \
|
&& cd "makemkv-oss-${MAKEMKV_VERSION}" \
|
||||||
&& ./configure --disable-gui \
|
&& ./configure --disable-gui \
|
||||||
@@ -56,7 +62,11 @@ COPY app/ app/
|
|||||||
COPY --from=web /web/dist /app/web/dist
|
COPY --from=web /web/dist /app/web/dist
|
||||||
COPY docker/entrypoint.py /entrypoint.py
|
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_WEB_DIR=/app/web/dist \
|
||||||
MKVTOOL_FILMS_DIR=/films \
|
MKVTOOL_FILMS_DIR=/films \
|
||||||
MKVTOOL_RADARR_FILMS_DIR=/nas_storage/jellyfin/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` |
|
| `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
|
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 .`.
|
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
|
## Variables d'environnement
|
||||||
|
|
||||||
| Variable | Defaut image | Role |
|
| Variable | Defaut image | Role |
|
||||||
@@ -42,7 +92,8 @@ reste possible : `docker build -t mkvtool .`.
|
|||||||
| `MKVTOOL_DOWNLOADS_DIR` | `/qbittorrentdownloads` | Racine des telechargements qBittorrent |
|
| `MKVTOOL_DOWNLOADS_DIR` | `/qbittorrentdownloads` | Racine des telechargements qBittorrent |
|
||||||
| `MKVTOOL_SIMULATE_CONVERSION` | `false` | `true` = produit un faux MKV sans appeler MakeMKV (dev/tests) |
|
| `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 |
|
| `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
|
## Volumes
|
||||||
|
|
||||||
|
|||||||
@@ -4,11 +4,16 @@ MKVTool sera un service web auto-hébergé consacré aux films. Il détecte les
|
|||||||
|
|
||||||
## Configuration (conf.json)
|
## 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.
|
- Le backend lit ce fichier.
|
||||||
- L'interface modifie ce fichier via l'API (écriture atomique côté backend).
|
- L'interface modifie ce fichier via l'API (écriture atomique côté backend).
|
||||||
- Chaque service expose un statut dans la page Configuration: `Non configuré` (URL ou clé API manquante), `Configuré · non testé`, `Testé` (dernier test de connexion réussi, version affichée) ou `Test échoué`. Le résultat du dernier test est conservé dans `conf.json` (bloc `test`) et invalidé dès que l'URL ou les identifiants changent.
|
- 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, en plus de supprimer l'ISO et son torrent, MKVTool demande à Radarr de rescanner le dossier du film pour qu'il adopte le MKV lié comme fichier du film (best effort : un échec remonte en avertissement sans invalider la validation).
|
||||||
|
- 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)
|
## Migrations (base de données et conf.json)
|
||||||
|
|
||||||
|
|||||||
+4
-6
@@ -31,6 +31,8 @@ class QbittorrentConfig(BaseModel):
|
|||||||
port: int | None = None
|
port: int | None = None
|
||||||
username: str | None = None
|
username: str | None = None
|
||||||
password: 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)
|
test: TestState = Field(default_factory=TestState)
|
||||||
|
|
||||||
|
|
||||||
@@ -56,12 +58,8 @@ class AppConfig(BaseModel):
|
|||||||
# Version de la structure du fichier, migree au demarrage
|
# Version de la structure du fichier, migree au demarrage
|
||||||
# (voir app/migrations.py). Doit rester synchrone avec
|
# (voir app/migrations.py). Doit rester synchrone avec
|
||||||
# current_conf_version(): un test verifie cet invariant.
|
# current_conf_version(): un test verifie cet invariant.
|
||||||
version: int = 1
|
version: int = 2
|
||||||
radarr: ApiServiceConfig = Field(default_factory=ApiServiceConfig)
|
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)
|
qbittorrent: QbittorrentConfig = Field(default_factory=QbittorrentConfig)
|
||||||
|
|
||||||
|
|
||||||
@@ -70,7 +68,7 @@ def config_path() -> Path:
|
|||||||
return settings.config_dir / "conf.json"
|
return settings.config_dir / "conf.json"
|
||||||
|
|
||||||
|
|
||||||
SERVICE_NAMES = ("radarr", "sonarr", "prowlarr", "jellyfin", "seerr", "qbittorrent")
|
SERVICE_NAMES = ("radarr", "qbittorrent")
|
||||||
|
|
||||||
|
|
||||||
def service_configured(service: ApiServiceConfig | QbittorrentConfig) -> bool:
|
def service_configured(service: ApiServiceConfig | QbittorrentConfig) -> bool:
|
||||||
|
|||||||
+194
-30
@@ -9,7 +9,9 @@ import errno
|
|||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import shutil
|
import shutil
|
||||||
|
import signal
|
||||||
import subprocess
|
import subprocess
|
||||||
|
from collections.abc import Callable
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
@@ -17,6 +19,12 @@ from app.config import settings
|
|||||||
from app.models import IsoMovie
|
from app.models import IsoMovie
|
||||||
|
|
||||||
INVALID_CHARACTERS = re.compile(r'[/\\:*?"<>|]')
|
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:
|
def guarded_folder(folder: Path) -> Path:
|
||||||
@@ -40,15 +48,15 @@ class ConversionPaths:
|
|||||||
destination_folder: Path
|
destination_folder: Path
|
||||||
|
|
||||||
|
|
||||||
def container_iso_path(movie: IsoMovie) -> Path:
|
def radarr_to_container_path(path: str) -> Path:
|
||||||
"""Chemin de l'ISO tel que vu dans le conteneur.
|
"""Traduit un chemin Radarr vers son equivalent dans le conteneur.
|
||||||
|
|
||||||
Radarr rapporte ses chemins dans son propre referentiel
|
Radarr rapporte ses chemins dans son propre referentiel
|
||||||
(radarr_films_dir); si celui-ci differe du point de montage du conteneur
|
(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
|
(films_dir), on traduit. Sans radarr_films_dir, les chemins sont pris
|
||||||
tels quels (montage "meme chemin").
|
tels quels (montage "meme chemin").
|
||||||
"""
|
"""
|
||||||
iso = Path(movie.path)
|
iso = Path(path)
|
||||||
radarr_root = settings.radarr_films_dir
|
radarr_root = settings.radarr_films_dir
|
||||||
if radarr_root is not None:
|
if radarr_root is not None:
|
||||||
try:
|
try:
|
||||||
@@ -58,6 +66,27 @@ def container_iso_path(movie: IsoMovie) -> Path:
|
|||||||
return iso
|
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:
|
def conversion_paths(movie: IsoMovie) -> ConversionPaths:
|
||||||
title = sanitize_component(movie.title)
|
title = sanitize_component(movie.title)
|
||||||
movie_name = f"{title} {movie.year}" if movie.year else title
|
movie_name = f"{title} {movie.year}" if movie.year else title
|
||||||
@@ -77,30 +106,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)
|
mkv_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
if settings.simulate_conversion:
|
if settings.simulate_conversion:
|
||||||
# Simulation en attendant MakeMKV sur le NAS : fichier MKV de substitution.
|
# Simulation en attendant MakeMKV sur le NAS : fichier MKV de substitution.
|
||||||
mkv_path.write_text(
|
mkv_path.write_text(
|
||||||
"MKV simule par MKVTool — MakeMKV n'est pas installe dans cet environnement.\n"
|
"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
|
return
|
||||||
if shutil.which("makemkvcon") is None:
|
if shutil.which("makemkvcon") is None:
|
||||||
raise RuntimeError("MakeMKV (makemkvcon) n'est pas installe sur le serveur")
|
raise RuntimeError("MakeMKV (makemkvcon) n'est pas installe sur le serveur")
|
||||||
result = subprocess.run(
|
iso = container_iso_path(movie)
|
||||||
["makemkvcon", "mkv", f"iso:{container_iso_path(movie)}", "0", str(mkv_path.parent)],
|
title = longest_title_id(iso, on_line)
|
||||||
capture_output=True,
|
returncode, output = _run_makemkv(
|
||||||
text=True,
|
["makemkvcon", "mkv", f"iso:{iso}", title, str(mkv_path.parent)], on_line
|
||||||
)
|
)
|
||||||
if result.returncode != 0:
|
if returncode != 0:
|
||||||
detail = result.stderr.strip() or result.stdout.strip()
|
if "purchase an activation key" in output or "evaluation period" in output:
|
||||||
raise RuntimeError(f"MakeMKV a echoue: {detail}")
|
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"))
|
produced = sorted(mkv_path.parent.glob("*.mkv"))
|
||||||
if not produced:
|
if not produced:
|
||||||
raise RuntimeError("MakeMKV n'a produit aucun fichier MKV")
|
raise RuntimeError("MakeMKV n'a produit aucun fichier MKV")
|
||||||
produced[0].replace(mkv_path)
|
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:
|
def clear_folder(destination_folder: Path, keep: list[Path]) -> None:
|
||||||
"""Vide le dossier du film, sauf les chemins listés dans keep (l'ISO...)."""
|
"""Vide le dossier du film, sauf les chemins listés dans keep (l'ISO...)."""
|
||||||
resolved = guarded_folder(destination_folder)
|
resolved = guarded_folder(destination_folder)
|
||||||
@@ -110,10 +274,7 @@ def clear_folder(destination_folder: Path, keep: list[Path]) -> None:
|
|||||||
for entry in resolved.iterdir():
|
for entry in resolved.iterdir():
|
||||||
if entry.resolve() in keep_resolved:
|
if entry.resolve() in keep_resolved:
|
||||||
continue
|
continue
|
||||||
if entry.is_dir() and not entry.is_symlink():
|
_remove_entry(entry, "Nettoyage du dossier du film")
|
||||||
shutil.rmtree(entry)
|
|
||||||
else:
|
|
||||||
entry.unlink()
|
|
||||||
|
|
||||||
|
|
||||||
def import_mkv(
|
def import_mkv(
|
||||||
@@ -130,18 +291,24 @@ def import_mkv(
|
|||||||
configuration Media Management de Radarr (`target_name`).
|
configuration Media Management de Radarr (`target_name`).
|
||||||
"""
|
"""
|
||||||
resolved = guarded_folder(destination_folder)
|
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 [])
|
clear_folder(resolved, keep or [])
|
||||||
target = resolved / (target_name or mkv_path.name)
|
target = resolved / (target_name or mkv_path.name)
|
||||||
if target.exists() or target.is_symlink():
|
if target.exists() or target.is_symlink():
|
||||||
target.unlink()
|
unlink_if_exists(target)
|
||||||
try:
|
try:
|
||||||
os.link(mkv_path, target)
|
os.link(mkv_path, target)
|
||||||
except OSError as error:
|
except OSError as error:
|
||||||
if error.errno != errno.EXDEV:
|
if error.errno != errno.EXDEV:
|
||||||
raise
|
raise file_error(error, "Création du lien du MKV", target) from error
|
||||||
# Volumes différents: un lien dur est impossible, on retombe sur un lien symbolique.
|
# Volumes différents: un lien dur est impossible, on retombe sur un lien symbolique.
|
||||||
os.symlink(mkv_path, target)
|
try:
|
||||||
|
os.symlink(mkv_path, target)
|
||||||
|
except OSError as symlink_error:
|
||||||
|
raise file_error(symlink_error, "Création du lien du MKV", target) from symlink_error
|
||||||
return target
|
return target
|
||||||
|
|
||||||
|
|
||||||
@@ -151,10 +318,7 @@ def finalize_validation(destination_folder: Path, keep_name: str) -> None:
|
|||||||
for entry in resolved.iterdir():
|
for entry in resolved.iterdir():
|
||||||
if entry.name == keep_name:
|
if entry.name == keep_name:
|
||||||
continue
|
continue
|
||||||
if entry.is_dir() and not entry.is_symlink():
|
_remove_entry(entry, "Suppression (validation)")
|
||||||
shutil.rmtree(entry)
|
|
||||||
else:
|
|
||||||
entry.unlink()
|
|
||||||
|
|
||||||
|
|
||||||
def cancel_conversion(
|
def cancel_conversion(
|
||||||
@@ -162,12 +326,12 @@ def cancel_conversion(
|
|||||||
) -> None:
|
) -> None:
|
||||||
"""Annule une conversion en attente de validation.
|
"""Annule une conversion en attente de validation.
|
||||||
|
|
||||||
Supprime le MKV converti et son lien dans le dossier du film (s'ils
|
Supprime le MKV converti et son lien dans le dossier du film; l'ISO et
|
||||||
existent); l'ISO et le reste du dossier ne sont pas touches.
|
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)
|
target = destination_folder / (target_name or mkv_path.name)
|
||||||
for path in (target, mkv_path):
|
unlink_if_exists(target)
|
||||||
if path.is_symlink() or path.exists():
|
unlink_if_exists(mkv_path)
|
||||||
path.unlink()
|
rmdir_if_empty(mkv_path.parent)
|
||||||
if mkv_path.parent.is_dir() and not any(mkv_path.parent.iterdir()):
|
|
||||||
mkv_path.parent.rmdir()
|
|
||||||
+152
-110
@@ -14,6 +14,7 @@ from sqlalchemy import select, update
|
|||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from app import auth
|
from app import auth
|
||||||
|
from app import worker as conversion_queue
|
||||||
from app.conf_store import (
|
from app.conf_store import (
|
||||||
ApiServiceConfig,
|
ApiServiceConfig,
|
||||||
QbittorrentConfig,
|
QbittorrentConfig,
|
||||||
@@ -21,23 +22,32 @@ from app.conf_store import (
|
|||||||
read_config,
|
read_config,
|
||||||
record_test,
|
record_test,
|
||||||
reset_test,
|
reset_test,
|
||||||
service_configured,
|
|
||||||
service_status,
|
service_status,
|
||||||
write_config,
|
write_config,
|
||||||
)
|
)
|
||||||
from app.converter import cancel_conversion, conversion_paths, finalize_validation
|
from app.converter import (
|
||||||
|
cancel_conversion,
|
||||||
|
clear_workspace,
|
||||||
|
conversion_paths,
|
||||||
|
finalize_validation,
|
||||||
|
looks_like_iso,
|
||||||
|
rmdir_if_empty,
|
||||||
|
unlink_if_exists,
|
||||||
|
workspace_files,
|
||||||
|
)
|
||||||
from app.database import Base, engine, get_db
|
from app.database import Base, engine, get_db
|
||||||
from app.migrations import migrate_conf_file, run_db_migrations
|
from app.migrations import migrate_conf_file, run_db_migrations
|
||||||
from app.models import IsoMovie
|
from app.models import IsoMovie
|
||||||
from app.qbittorrent import QbittorrentClient, match_torrent
|
from app.qbittorrent import QbittorrentClient, match_torrent
|
||||||
from app.radarr import RadarrClient, movie_file_path
|
from app.radarr import RadarrClient, movie_file_path
|
||||||
from app.schemas import (
|
from app.schemas import (
|
||||||
ApiServiceSettingsRead,
|
|
||||||
AuthCredentialsWrite,
|
AuthCredentialsWrite,
|
||||||
AuthSetupWrite,
|
AuthSetupWrite,
|
||||||
AuthUserRead,
|
AuthUserRead,
|
||||||
ConnectionResult,
|
ConnectionResult,
|
||||||
|
ConversionLogRead,
|
||||||
HealthRead,
|
HealthRead,
|
||||||
|
IsoMovieDetailRead,
|
||||||
IsoMovieRead,
|
IsoMovieRead,
|
||||||
QbittorrentSettingsRead,
|
QbittorrentSettingsRead,
|
||||||
QbittorrentSettingsWrite,
|
QbittorrentSettingsWrite,
|
||||||
@@ -46,6 +56,7 @@ from app.schemas import (
|
|||||||
ScanResult,
|
ScanResult,
|
||||||
SettingsRead,
|
SettingsRead,
|
||||||
SettingsWrite,
|
SettingsWrite,
|
||||||
|
ValidationRead,
|
||||||
)
|
)
|
||||||
from app.worker import conversion_worker
|
from app.worker import conversion_worker
|
||||||
|
|
||||||
@@ -82,8 +93,8 @@ app.add_middleware(
|
|||||||
DbSession = Annotated[Session, Depends(get_db)]
|
DbSession = Annotated[Session, Depends(get_db)]
|
||||||
|
|
||||||
|
|
||||||
def _api_service_read(service: ApiServiceConfig) -> ApiServiceSettingsRead:
|
def _api_service_read(service: ApiServiceConfig) -> RadarrSettingsRead:
|
||||||
return ApiServiceSettingsRead(
|
return RadarrSettingsRead(
|
||||||
url=service.url,
|
url=service.url,
|
||||||
port=service.port,
|
port=service.port,
|
||||||
api_key_configured=service.api_key is not None,
|
api_key_configured=service.api_key is not None,
|
||||||
@@ -100,6 +111,7 @@ def _qbittorrent_read(qb: QbittorrentConfig) -> QbittorrentSettingsRead:
|
|||||||
port=qb.port,
|
port=qb.port,
|
||||||
username=qb.username,
|
username=qb.username,
|
||||||
password_configured=qb.password is not None,
|
password_configured=qb.password is not None,
|
||||||
|
api_key_configured=qb.api_key is not None,
|
||||||
status=service_status(qb),
|
status=service_status(qb),
|
||||||
tested_version=qb.test.version,
|
tested_version=qb.test.version,
|
||||||
tested_at=qb.test.at,
|
tested_at=qb.test.at,
|
||||||
@@ -111,10 +123,6 @@ def _settings_read() -> SettingsRead:
|
|||||||
cfg = read_config()
|
cfg = read_config()
|
||||||
return SettingsRead(
|
return SettingsRead(
|
||||||
radarr=_api_service_read(cfg.radarr),
|
radarr=_api_service_read(cfg.radarr),
|
||||||
sonarr=_api_service_read(cfg.sonarr),
|
|
||||||
prowlarr=_api_service_read(cfg.prowlarr),
|
|
||||||
jellyfin=_api_service_read(cfg.jellyfin),
|
|
||||||
seerr=_api_service_read(cfg.seerr),
|
|
||||||
qbittorrent=_qbittorrent_read(cfg.qbittorrent),
|
qbittorrent=_qbittorrent_read(cfg.qbittorrent),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -190,16 +198,13 @@ def put_settings(payload: SettingsWrite) -> SettingsRead:
|
|||||||
target.api_key = patch.api_key
|
target.api_key = patch.api_key
|
||||||
|
|
||||||
apply_service(cfg.radarr, payload.radarr)
|
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:
|
if payload.qbittorrent is not None:
|
||||||
qb = payload.qbittorrent
|
qb = payload.qbittorrent
|
||||||
qb_changed = bool(qb.url) and str(qb.url).rstrip("/") != (cfg.qbittorrent.url or "")
|
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.username and qb.username != cfg.qbittorrent.username)
|
||||||
qb_changed = qb_changed or bool(qb.password)
|
qb_changed = qb_changed or bool(qb.password)
|
||||||
|
qb_changed = qb_changed or bool(qb.api_key)
|
||||||
if qb_changed:
|
if qb_changed:
|
||||||
reset_test(cfg.qbittorrent)
|
reset_test(cfg.qbittorrent)
|
||||||
if qb.url is not None:
|
if qb.url is not None:
|
||||||
@@ -208,6 +213,8 @@ def put_settings(payload: SettingsWrite) -> SettingsRead:
|
|||||||
cfg.qbittorrent.username = qb.username
|
cfg.qbittorrent.username = qb.username
|
||||||
if qb.password:
|
if qb.password:
|
||||||
cfg.qbittorrent.password = qb.password
|
cfg.qbittorrent.password = qb.password
|
||||||
|
if qb.api_key:
|
||||||
|
cfg.qbittorrent.api_key = qb.api_key
|
||||||
|
|
||||||
write_config(cfg)
|
write_config(cfg)
|
||||||
return _settings_read()
|
return _settings_read()
|
||||||
@@ -228,80 +235,12 @@ async def test_radarr() -> ConnectionResult:
|
|||||||
return ConnectionResult(success=True, version=version, message=f"Radarr {version} accessible")
|
return ConnectionResult(success=True, version=version, message=f"Radarr {version} accessible")
|
||||||
|
|
||||||
|
|
||||||
# --- Tests de connexion des autres services API (Sonarr, Prowlarr, Jellyfin,
|
|
||||||
# Overseerr). Chacun expose un endpoint systeme et une version. ---
|
|
||||||
API_SERVICE_TESTS: dict[str, tuple[str, str, str]] = {
|
|
||||||
# service: (endpoint, nom de l'en-tete d'authentification, cle de version)
|
|
||||||
"sonarr": ("api/v3/system/status", "X-Api-Key", "version"),
|
|
||||||
"prowlarr": ("api/v1/system/status", "X-Api-Key", "version"),
|
|
||||||
"jellyfin": ("System/Info", "X-Emby-Token", "Version"),
|
|
||||||
"seerr": ("api/v1/status", "X-Api-Key", "version"),
|
|
||||||
}
|
|
||||||
|
|
||||||
SERVICE_LABELS = {
|
|
||||||
"sonarr": "Sonarr",
|
|
||||||
"prowlarr": "Prowlarr",
|
|
||||||
"jellyfin": "Jellyfin",
|
|
||||||
"seerr": "Overseerr",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
async def _test_api_service(name: str) -> ConnectionResult:
|
|
||||||
service = getattr(read_config(), name)
|
|
||||||
label = SERVICE_LABELS[name]
|
|
||||||
url = build_base_url(service.url, service.port)
|
|
||||||
if not service_configured(service):
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=409, detail=f"La connexion {label} n'est pas configurée"
|
|
||||||
)
|
|
||||||
endpoint, auth_header, version_key = API_SERVICE_TESTS[name]
|
|
||||||
try:
|
|
||||||
async with httpx.AsyncClient(timeout=30) as client:
|
|
||||||
response = await client.get(
|
|
||||||
f"{url}/{endpoint}", headers={auth_header: service.api_key}
|
|
||||||
)
|
|
||||||
response.raise_for_status()
|
|
||||||
data = response.json()
|
|
||||||
except (httpx.HTTPError, ValueError) as error:
|
|
||||||
record_test(name, ok=False, error=str(error))
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=502, detail=f"Connexion {label} impossible: {error}"
|
|
||||||
) from error
|
|
||||||
if not isinstance(data, dict):
|
|
||||||
error = "Réponse inattendue du service"
|
|
||||||
record_test(name, ok=False, error=error)
|
|
||||||
raise HTTPException(status_code=502, detail=f"Connexion {label} impossible: {error}")
|
|
||||||
version = str(data.get(version_key, "inconnue"))
|
|
||||||
record_test(name, ok=True, version=version)
|
|
||||||
return ConnectionResult(success=True, version=version, message=f"{label} {version} accessible")
|
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/settings/sonarr/test", response_model=ConnectionResult)
|
|
||||||
async def test_sonarr() -> ConnectionResult:
|
|
||||||
return await _test_api_service("sonarr")
|
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/settings/prowlarr/test", response_model=ConnectionResult)
|
|
||||||
async def test_prowlarr() -> ConnectionResult:
|
|
||||||
return await _test_api_service("prowlarr")
|
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/settings/jellyfin/test", response_model=ConnectionResult)
|
|
||||||
async def test_jellyfin() -> ConnectionResult:
|
|
||||||
return await _test_api_service("jellyfin")
|
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/settings/seerr/test", response_model=ConnectionResult)
|
|
||||||
async def test_seerr() -> ConnectionResult:
|
|
||||||
return await _test_api_service("seerr")
|
|
||||||
|
|
||||||
|
|
||||||
def qbittorrent_from_config() -> QbittorrentClient:
|
def qbittorrent_from_config() -> QbittorrentClient:
|
||||||
qb = read_config().qbittorrent
|
qb = read_config().qbittorrent
|
||||||
url = build_base_url(qb.url, qb.port)
|
url = build_base_url(qb.url, qb.port)
|
||||||
if not url:
|
if not url:
|
||||||
raise HTTPException(status_code=409, detail="La connexion qBittorrent n'est pas configurée")
|
raise HTTPException(status_code=409, detail="La connexion qBittorrent n'est pas configurée")
|
||||||
return QbittorrentClient(url, qb.username, qb.password)
|
return QbittorrentClient(url, qb.username, qb.password, qb.api_key)
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/settings/qbittorrent", response_model=QbittorrentSettingsRead)
|
@app.get("/api/settings/qbittorrent", response_model=QbittorrentSettingsRead)
|
||||||
@@ -318,6 +257,7 @@ def put_qbittorrent_settings(payload: QbittorrentSettingsWrite) -> QbittorrentSe
|
|||||||
)
|
)
|
||||||
qb_changed = qb_changed or bool(payload.username and payload.username != qb.username)
|
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.password)
|
||||||
|
qb_changed = qb_changed or bool(payload.api_key)
|
||||||
if qb_changed:
|
if qb_changed:
|
||||||
reset_test(qb)
|
reset_test(qb)
|
||||||
if payload.url is not None:
|
if payload.url is not None:
|
||||||
@@ -334,6 +274,8 @@ def put_qbittorrent_settings(payload: QbittorrentSettingsWrite) -> QbittorrentSe
|
|||||||
# Champs vides: mode bypass d'authentification qBittorrent, sans identifiants.
|
# Champs vides: mode bypass d'authentification qBittorrent, sans identifiants.
|
||||||
qb.username = None
|
qb.username = None
|
||||||
qb.password = None
|
qb.password = None
|
||||||
|
if payload.api_key:
|
||||||
|
qb.api_key = payload.api_key
|
||||||
write_config(cfg)
|
write_config(cfg)
|
||||||
return _qbittorrent_read(qb)
|
return _qbittorrent_read(qb)
|
||||||
|
|
||||||
@@ -364,24 +306,49 @@ def list_files(db: DbSession) -> list[IsoMovie]:
|
|||||||
return list_movies(db)
|
return list_movies(db)
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/files/{file_id}", response_model=IsoMovieRead)
|
def _movie_detail(movie: IsoMovie) -> IsoMovieDetailRead:
|
||||||
def get_file(file_id: int, db: DbSession) -> IsoMovie:
|
"""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)
|
||||||
|
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)
|
item = db.get(IsoMovie, file_id)
|
||||||
if item is None:
|
if item is None:
|
||||||
raise HTTPException(status_code=404, detail="Fichier introuvable")
|
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:
|
def _log_config_summary() -> None:
|
||||||
"""Rend visible au lancement le chargement de conf.json."""
|
"""Rend visible au lancement le chargement de conf.json."""
|
||||||
cfg = read_config()
|
cfg = read_config()
|
||||||
configured = [
|
configured = ["radarr"] if cfg.radarr.url else []
|
||||||
name
|
|
||||||
for name in ("radarr", "sonarr", "prowlarr", "jellyfin", "seerr")
|
|
||||||
if getattr(cfg, name).url
|
|
||||||
]
|
|
||||||
if cfg.qbittorrent.url:
|
if cfg.qbittorrent.url:
|
||||||
mode = "identifiants" if cfg.qbittorrent.username else "bypass d'authentification"
|
if cfg.qbittorrent.api_key:
|
||||||
|
mode = "cle API"
|
||||||
|
elif cfg.qbittorrent.username:
|
||||||
|
mode = "identifiants"
|
||||||
|
else:
|
||||||
|
mode = "bypass d'authentification"
|
||||||
configured.append(f"qbittorrent ({mode})")
|
configured.append(f"qbittorrent ({mode})")
|
||||||
if configured:
|
if configured:
|
||||||
print(f"conf.json charge: {', '.join(configured)}", flush=True)
|
print(f"conf.json charge: {', '.join(configured)}", flush=True)
|
||||||
@@ -416,7 +383,9 @@ async def scan_radarr(db: DbSession) -> ScanResult:
|
|||||||
for movie in movies:
|
for movie in movies:
|
||||||
movie_file = movie.get("movieFile") or {}
|
movie_file = movie.get("movieFile") or {}
|
||||||
path = movie_file_path(movie)
|
path = movie_file_path(movie)
|
||||||
if not path or not path.lower().endswith(".iso"):
|
# L'extension preslectionne, mais des MKV circulent parfois sous un
|
||||||
|
# nom en .iso: on verifie l'en-tete du contenu.
|
||||||
|
if not path or not looks_like_iso(path):
|
||||||
continue
|
continue
|
||||||
movie_id = movie.get("id")
|
movie_id = movie.get("id")
|
||||||
movie_file_id = movie_file.get("id")
|
movie_file_id = movie_file.get("id")
|
||||||
@@ -480,12 +449,18 @@ def _linked_mkv(movie: IsoMovie) -> Path | None:
|
|||||||
|
|
||||||
|
|
||||||
async def _delete_iso_torrent(iso_path: str) -> None:
|
async def _delete_iso_torrent(iso_path: str) -> None:
|
||||||
"""Supprime le torrent qBittorrent de l'ISO (best effort, sans bloquer)."""
|
"""Supprime 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.
|
||||||
|
"""
|
||||||
qb = read_config().qbittorrent
|
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:
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
client = QbittorrentClient(qb.url, qb.username, qb.password)
|
client = QbittorrentClient(url, qb.username, qb.password, qb.api_key)
|
||||||
torrents = await client.torrents()
|
torrents = await client.torrents()
|
||||||
match = match_torrent(torrents, iso_path)
|
match = match_torrent(torrents, iso_path)
|
||||||
if match is not None and match.get("hash"):
|
if match is not None and match.get("hash"):
|
||||||
@@ -495,7 +470,14 @@ async def _delete_iso_torrent(iso_path: str) -> None:
|
|||||||
|
|
||||||
|
|
||||||
@app.post("/api/movies/{movie_id}/convert", response_model=IsoMovieRead)
|
@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)
|
movie = db.get(IsoMovie, movie_id)
|
||||||
if movie is None:
|
if movie is None:
|
||||||
raise HTTPException(status_code=404, detail="Film introuvable")
|
raise HTTPException(status_code=404, detail="Film introuvable")
|
||||||
@@ -503,8 +485,31 @@ def convert_movie(movie_id: int, db: DbSession) -> IsoMovie:
|
|||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=409, detail="Ce film n'est pas convertible dans son état actuel"
|
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.status = "queued"
|
||||||
movie.failed_step = None
|
|
||||||
movie.last_error = None
|
movie.last_error = None
|
||||||
db.commit()
|
db.commit()
|
||||||
return movie
|
return movie
|
||||||
@@ -512,22 +517,36 @@ def convert_movie(movie_id: int, db: DbSession) -> IsoMovie:
|
|||||||
|
|
||||||
@app.post("/api/movies/{movie_id}/cancel", response_model=IsoMovieRead)
|
@app.post("/api/movies/{movie_id}/cancel", response_model=IsoMovieRead)
|
||||||
def cancel_movie(movie_id: int, db: DbSession) -> IsoMovie:
|
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)
|
movie = db.get(IsoMovie, movie_id)
|
||||||
if movie is None:
|
if movie is None:
|
||||||
raise HTTPException(status_code=404, detail="Film introuvable")
|
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")
|
raise HTTPException(status_code=409, detail="Aucune conversion à annuler")
|
||||||
if movie.status == "validating":
|
paths = conversion_paths(movie)
|
||||||
paths = conversion_paths(movie)
|
linked = _linked_mkv(movie)
|
||||||
linked = _linked_mkv(movie)
|
try:
|
||||||
cancel_conversion(paths.mkv_path, paths.destination_folder, linked.name if linked else None)
|
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.status = "detected"
|
||||||
|
movie.failed_step = None
|
||||||
|
movie.last_error = None
|
||||||
db.commit()
|
db.commit()
|
||||||
return movie
|
return movie
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/movies/{movie_id}/validate", response_model=IsoMovieRead)
|
@app.post("/api/movies/{movie_id}/validate", response_model=ValidationRead)
|
||||||
async def validate_movie(movie_id: int, db: DbSession) -> IsoMovie:
|
async def validate_movie(movie_id: int, db: DbSession) -> ValidationRead:
|
||||||
"""Validation manuelle: supprime l'ISO, le torrent et le dossier de travail.
|
"""Validation manuelle: supprime l'ISO, le torrent et le dossier de travail.
|
||||||
|
|
||||||
Le MKV lie dans le dossier du film reste en place (le lien dur etant sur
|
Le MKV lie dans le dossier du film reste en place (le lien dur etant sur
|
||||||
@@ -545,21 +564,44 @@ async def validate_movie(movie_id: int, db: DbSession) -> IsoMovie:
|
|||||||
raise HTTPException(status_code=409, detail="Aucun MKV lié à valider")
|
raise HTTPException(status_code=409, detail="Aucun MKV lié à valider")
|
||||||
|
|
||||||
# Supprime l'ISO et le reste du dossier du film, puis le torrent qBittorrent.
|
# Supprime l'ISO et le reste du dossier du film, puis le torrent qBittorrent.
|
||||||
finalize_validation(paths.destination_folder, linked.name)
|
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
|
||||||
await _delete_iso_torrent(movie.path)
|
await _delete_iso_torrent(movie.path)
|
||||||
|
|
||||||
# Nettoyage du dossier de travail (le lien dur garde les donnees).
|
# Nettoyage du dossier de travail (le lien dur garde les donnees).
|
||||||
if linked.exists() and paths.mkv_path.exists():
|
try:
|
||||||
paths.mkv_path.unlink()
|
unlink_if_exists(paths.mkv_path)
|
||||||
if paths.mkv_path.parent.is_dir() and not any(paths.mkv_path.parent.iterdir()):
|
rmdir_if_empty(paths.mkv_path.parent)
|
||||||
paths.mkv_path.parent.rmdir()
|
except Exception as error: # noqa: BLE001 - message explicite pour l'UI
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=409, detail=f"Validation impossible (dossier de travail): {error}"
|
||||||
|
) from error
|
||||||
|
|
||||||
movie.status = "completed"
|
movie.status = "completed"
|
||||||
now = datetime.now(UTC)
|
now = datetime.now(UTC)
|
||||||
movie.processed_at = now
|
movie.processed_at = now
|
||||||
movie.completed_at = now
|
movie.completed_at = now
|
||||||
db.commit()
|
db.commit()
|
||||||
return movie
|
snapshot = ValidationRead.model_validate(movie)
|
||||||
|
|
||||||
|
# Rescan Radarr: le dossier ne contient plus que le MKV lie; Radarr le
|
||||||
|
# prend comme nouveau fichier du film a la place de l'ISO. 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 client_from_config().rescan_movie(movie.radarr_movie_id)
|
||||||
|
except Exception as error: # noqa: BLE001 - la validation reste acquise
|
||||||
|
rescan_warning = (
|
||||||
|
f"ISO supprimée, mais rescan Radarr impossible: {error}. "
|
||||||
|
"Lancez un rescan du film dans Radarr pour qu'il détecte le MKV."
|
||||||
|
)
|
||||||
|
snapshot.rescan_warning = rescan_warning
|
||||||
|
return snapshot
|
||||||
|
|
||||||
|
|
||||||
@app.delete("/api/movies/{movie_id}", response_model=IsoMovieRead)
|
@app.delete("/api/movies/{movie_id}", response_model=IsoMovieRead)
|
||||||
|
|||||||
+32
-1
@@ -73,6 +73,30 @@ DB_MIGRATIONS: list[DbMigration] = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
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 run_db_migrations(engine: Engine) -> list[str]:
|
def run_db_migrations(engine: Engine) -> list[str]:
|
||||||
"""Applique les migrations non jouees; renvoie leurs descriptions."""
|
"""Applique les migrations non jouees; renvoie leurs descriptions."""
|
||||||
with engine.begin() as conn:
|
with engine.begin() as conn:
|
||||||
@@ -120,7 +144,14 @@ def run_db_migrations(engine: Engine) -> list[str]:
|
|||||||
# CONF_MIGRATIONS[i] transforme le contenu brut du fichier de la version
|
# 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
|
# 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.
|
# cette liste; elle doit rester synchrone avec AppConfig.version par defaut.
|
||||||
CONF_MIGRATIONS: list[Callable[[dict], dict]] = []
|
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:
|
def current_conf_version() -> int:
|
||||||
|
|||||||
+26
-7
@@ -6,32 +6,51 @@ import httpx
|
|||||||
|
|
||||||
|
|
||||||
class QbittorrentClient:
|
class QbittorrentClient:
|
||||||
"""Client WebUI (API v2). Identifiants optionnels: sans eux, aucun login
|
"""Client WebUI (API v2).
|
||||||
n'est effectue — qBittorrent doit alors autoriser la plage IP (bypass
|
|
||||||
d'authentification), car il n'existe pas d'API key cote qBittorrent."""
|
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__(
|
def __init__(
|
||||||
self, url: str, username: str | None = None, password: str | None = None
|
self,
|
||||||
|
url: str,
|
||||||
|
username: str | None = None,
|
||||||
|
password: str | None = None,
|
||||||
|
api_key: str | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
self._url = url.rstrip("/")
|
self._url = url.rstrip("/")
|
||||||
self._username = username
|
self._username = username
|
||||||
self._password = password
|
self._password = password
|
||||||
|
self._api_key = api_key
|
||||||
|
|
||||||
async def _request(self, method: str, endpoint: str, **kwargs) -> httpx.Response:
|
async def _request(self, method: str, endpoint: str, **kwargs) -> httpx.Response:
|
||||||
|
headers = {"Referer": self._url}
|
||||||
async with httpx.AsyncClient(timeout=30) as client:
|
async with httpx.AsyncClient(timeout=30) as client:
|
||||||
if self._username and self._password:
|
if self._api_key:
|
||||||
|
headers["Authorization"] = f"Bearer {self._api_key}"
|
||||||
|
elif self._username and self._password:
|
||||||
login = await client.post(
|
login = await client.post(
|
||||||
f"{self._url}/api/v2/auth/login",
|
f"{self._url}/api/v2/auth/login",
|
||||||
data={"username": self._username, "password": self._password},
|
data={"username": self._username, "password": self._password},
|
||||||
headers={"Referer": self._url},
|
headers={"Referer": self._url},
|
||||||
)
|
)
|
||||||
login.raise_for_status()
|
login.raise_for_status()
|
||||||
if login.text.strip() != "Ok.":
|
# qBittorrent >= 5.2 renvoie 204 sans corps.
|
||||||
|
if login.status_code != 204 and login.text.strip() != "Ok.":
|
||||||
raise ValueError("Authentification qBittorrent refusée")
|
raise ValueError("Authentification qBittorrent refusée")
|
||||||
response = await client.request(
|
response = await client.request(
|
||||||
method,
|
method,
|
||||||
f"{self._url}{endpoint}",
|
f"{self._url}{endpoint}",
|
||||||
headers={"Referer": self._url},
|
headers=headers,
|
||||||
**kwargs,
|
**kwargs,
|
||||||
)
|
)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
|
|||||||
@@ -28,6 +28,21 @@ class RadarrClient:
|
|||||||
raise ValueError("Réponse Radarr inattendue")
|
raise ValueError("Réponse Radarr inattendue")
|
||||||
return result
|
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.
|
||||||
|
"""
|
||||||
|
async with httpx.AsyncClient(timeout=30) as client:
|
||||||
|
response = await client.post(
|
||||||
|
f"{self._url}/api/v3/command",
|
||||||
|
headers=self._headers,
|
||||||
|
json={"name": "RescanMovie", "movieId": movie_id},
|
||||||
|
)
|
||||||
|
response.raise_for_status()
|
||||||
|
|
||||||
|
|
||||||
def movie_file_path(movie: dict) -> str | None:
|
def movie_file_path(movie: dict) -> str | None:
|
||||||
movie_file = movie.get("movieFile") or {}
|
movie_file = movie.get("movieFile") or {}
|
||||||
|
|||||||
+29
-26
@@ -19,27 +19,12 @@ class RadarrSettingsWrite(BaseModel):
|
|||||||
api_key: str | None = Field(default=None, min_length=1)
|
api_key: str | None = Field(default=None, min_length=1)
|
||||||
|
|
||||||
|
|
||||||
class ApiServiceSettingsRead(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 ApiServiceSettingsWrite(BaseModel):
|
|
||||||
url: str | None = None
|
|
||||||
port: int | None = Field(default=None, ge=1, le=65535)
|
|
||||||
api_key: str | None = Field(default=None, min_length=1)
|
|
||||||
|
|
||||||
|
|
||||||
class QbittorrentSettingsRead(BaseModel):
|
class QbittorrentSettingsRead(BaseModel):
|
||||||
url: str | None
|
url: str | None
|
||||||
port: int | None = None
|
port: int | None = None
|
||||||
username: str | None
|
username: str | None
|
||||||
password_configured: bool
|
password_configured: bool
|
||||||
|
api_key_configured: bool
|
||||||
status: str
|
status: str
|
||||||
tested_version: str | None = None
|
tested_version: str | None = None
|
||||||
tested_at: str | None = None
|
tested_at: str | None = None
|
||||||
@@ -52,23 +37,17 @@ class QbittorrentSettingsWrite(BaseModel):
|
|||||||
# Utilisateur vide = bypass d'authentification qBittorrent.
|
# Utilisateur vide = bypass d'authentification qBittorrent.
|
||||||
username: str | None = None
|
username: str | None = None
|
||||||
password: str | None = Field(default=None, min_length=1)
|
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):
|
class SettingsRead(BaseModel):
|
||||||
radarr: ApiServiceSettingsRead
|
radarr: RadarrSettingsRead
|
||||||
sonarr: ApiServiceSettingsRead
|
|
||||||
prowlarr: ApiServiceSettingsRead
|
|
||||||
jellyfin: ApiServiceSettingsRead
|
|
||||||
seerr: ApiServiceSettingsRead
|
|
||||||
qbittorrent: QbittorrentSettingsRead
|
qbittorrent: QbittorrentSettingsRead
|
||||||
|
|
||||||
|
|
||||||
class SettingsWrite(BaseModel):
|
class SettingsWrite(BaseModel):
|
||||||
radarr: ApiServiceSettingsWrite | None = None
|
radarr: RadarrSettingsWrite | None = None
|
||||||
sonarr: ApiServiceSettingsWrite | None = None
|
|
||||||
prowlarr: ApiServiceSettingsWrite | None = None
|
|
||||||
jellyfin: ApiServiceSettingsWrite | None = None
|
|
||||||
seerr: ApiServiceSettingsWrite | None = None
|
|
||||||
qbittorrent: QbittorrentSettingsWrite | None = None
|
qbittorrent: QbittorrentSettingsWrite | None = None
|
||||||
|
|
||||||
|
|
||||||
@@ -99,6 +78,30 @@ class IsoMovieRead(BaseModel):
|
|||||||
last_error: str | None = None
|
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)
|
||||||
|
|
||||||
|
|
||||||
|
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 ConversionLogRead(BaseModel):
|
||||||
|
lines: list[str]
|
||||||
|
running: bool
|
||||||
|
|
||||||
|
|
||||||
class ScanResult(BaseModel):
|
class ScanResult(BaseModel):
|
||||||
scanned_movies: int
|
scanned_movies: int
|
||||||
iso_files: int
|
iso_files: int
|
||||||
|
|||||||
+42
-5
@@ -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 asyncio
|
||||||
import traceback
|
import traceback
|
||||||
@@ -11,28 +11,61 @@ from app.converter import container_iso_path, conversion_paths, extract_mkv, imp
|
|||||||
from app.database import SessionLocal
|
from app.database import SessionLocal
|
||||||
from app.models import IsoMovie
|
from app.models import IsoMovie
|
||||||
|
|
||||||
|
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:
|
async def _process(movie_id: int) -> None:
|
||||||
|
global _current_movie_id
|
||||||
with SessionLocal() as db:
|
with SessionLocal() as db:
|
||||||
movie = db.get(IsoMovie, movie_id)
|
movie = db.get(IsoMovie, movie_id)
|
||||||
if movie is None or movie.status != "queued":
|
if movie is None or movie.status != "queued":
|
||||||
return
|
return
|
||||||
paths = conversion_paths(movie)
|
paths = conversion_paths(movie)
|
||||||
step = "converting"
|
step = "converting"
|
||||||
|
_run_logs[movie_id] = []
|
||||||
|
_current_movie_id = movie_id
|
||||||
try:
|
try:
|
||||||
movie.status = "converting"
|
movie.status = "converting"
|
||||||
movie.last_error = None
|
movie.last_error = None
|
||||||
db.commit()
|
db.commit()
|
||||||
# Reprise: si le MKV existe deja (echec precedent apres l'extraction),
|
# Reprise: uniquement si l'echec precedent a eu lieu APRES
|
||||||
# on ne relance pas MakeMKV et on reprend a l'import.
|
# l'extraction (import). Un MKV issu d'une extraction incomplete
|
||||||
if not paths.mkv_path.exists():
|
# n'est jamais repris: la conversion repart de zero.
|
||||||
await asyncio.to_thread(extract_mkv, movie, paths.mkv_path)
|
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"
|
step = "importing"
|
||||||
movie.status = "importing"
|
movie.status = "importing"
|
||||||
db.commit()
|
db.commit()
|
||||||
# Le MKV lié reprend le nom du fichier Radarr (l'ISO), seule
|
# Le MKV lié reprend le nom du fichier Radarr (l'ISO), seule
|
||||||
# l'extension change.
|
# l'extension change.
|
||||||
target_name = f"{Path(movie.path).stem}.mkv"
|
target_name = f"{Path(movie.path).stem}.mkv"
|
||||||
|
_log(movie_id, "— Import: lien dans le dossier du film…")
|
||||||
await asyncio.to_thread(
|
await asyncio.to_thread(
|
||||||
import_mkv,
|
import_mkv,
|
||||||
paths.mkv_path,
|
paths.mkv_path,
|
||||||
@@ -44,11 +77,15 @@ async def _process(movie_id: int) -> None:
|
|||||||
# via l'endpoint de validation apres verification par l'utilisateur.
|
# via l'endpoint de validation apres verification par l'utilisateur.
|
||||||
movie.status = "validating"
|
movie.status = "validating"
|
||||||
movie.failed_step = None
|
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
|
except Exception as error: # noqa: BLE001 - le worker doit survivre a toute erreur
|
||||||
movie.status = "failed"
|
movie.status = "failed"
|
||||||
movie.failed_step = step
|
movie.failed_step = step
|
||||||
movie.last_error = f"{error}"
|
movie.last_error = f"{error}"
|
||||||
|
_log(movie_id, f"— Échec ({step}): {error}")
|
||||||
traceback.print_exc()
|
traceback.print_exc()
|
||||||
|
finally:
|
||||||
|
_current_movie_id = None
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+6
-1
@@ -7,7 +7,9 @@ services:
|
|||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
args:
|
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
|
container_name: mkvtool
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
ports:
|
ports:
|
||||||
@@ -27,6 +29,9 @@ services:
|
|||||||
# Chemin de la bibliotheque tel que Radarr le rapporte (traduction ISO).
|
# Chemin de la bibliotheque tel que Radarr le rapporte (traduction ISO).
|
||||||
MKVTOOL_RADARR_FILMS_DIR: /nas_storage/jellyfin/films
|
MKVTOOL_RADARR_FILMS_DIR: /nas_storage/jellyfin/films
|
||||||
MKVTOOL_DOWNLOADS_DIR: /qbittorrentdownloads
|
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:
|
volumes:
|
||||||
# La bibliotheque Jellyfin est montee en /films dans le conteneur; les
|
# La bibliotheque Jellyfin est montee en /films dans le conteneur; les
|
||||||
# chemins Radarr (MKVTOOL_RADARR_FILMS_DIR) sont traduits par l'API.
|
# 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 os
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
puid = int(os.environ.get("PUID", "0") or "0")
|
puid = int(os.environ.get("PUID", "0") or "0")
|
||||||
pgid = int(os.environ.get("PGID", "0") or "0")
|
pgid = int(os.environ.get("PGID", "0") or "0")
|
||||||
config_dir = os.environ.get("MKVTOOL_CONFIG_DIR", "/config")
|
config_dir = os.environ.get("MKVTOOL_CONFIG_DIR", "/config")
|
||||||
|
|
||||||
if os.geteuid() == 0 and puid:
|
|
||||||
if os.path.isdir(config_dir):
|
def write_makemkv_key() -> None:
|
||||||
subprocess.run(
|
"""Ecrit la cle MakeMKV (env MAKEMKV_KEY) dans settings.conf.
|
||||||
["chown", "-R", f"{puid}:{pgid or puid}", config_dir], check=False
|
|
||||||
)
|
MakeMKV lit ``app_Key`` dans ``/config/.MakeMKV/settings.conf``
|
||||||
os.setgroups([pgid] if pgid else [])
|
(la commande ``makemkvcon reg <cle>`` est peu fiable sur Linux).
|
||||||
if pgid:
|
La cle bêta courante: forum officiel MakeMKV, fil « MakeMKV is free
|
||||||
os.setgid(pgid)
|
while in beta » (rotation tous les un a deux mois).
|
||||||
os.setuid(puid)
|
"""
|
||||||
|
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:])
|
os.execvp(sys.argv[1], sys.argv[1:])
|
||||||
@@ -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_DOWNLOADS_DIR"] = str(_test_config / "downloads")
|
||||||
os.environ["MKVTOOL_SIMULATE_CONVERSION"] = "true"
|
os.environ["MKVTOOL_SIMULATE_CONVERSION"] = "true"
|
||||||
os.environ["MKVTOOL_WORKER_INTERVAL"] = "0.05"
|
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)
|
||||||
+56
-20
@@ -97,26 +97,6 @@ def test_failed_test_marks_service_as_error() -> None:
|
|||||||
assert settings["radarr"]["test_error"] is not None
|
assert settings["radarr"]["test_error"] is not None
|
||||||
|
|
||||||
|
|
||||||
@respx.mock
|
|
||||||
def test_sonarr_connection() -> None:
|
|
||||||
"""Les services optionnels ont aussi un endpoint de test."""
|
|
||||||
route = respx.get("http://sonarr:8989/api/v3/system/status").mock(
|
|
||||||
return_value=Response(200, json={"version": "4.0.12"})
|
|
||||||
)
|
|
||||||
with TestClient(app) as client:
|
|
||||||
client.put(
|
|
||||||
"/api/settings",
|
|
||||||
json={"sonarr": {"url": "http://sonarr:8989", "api_key": "sonarr-key"}},
|
|
||||||
)
|
|
||||||
response = client.post("/api/settings/sonarr/test")
|
|
||||||
settings = client.get("/api/settings").json()
|
|
||||||
assert response.status_code == 200
|
|
||||||
assert response.json()["version"] == "4.0.12"
|
|
||||||
assert settings["sonarr"]["status"] == "tested"
|
|
||||||
assert route.called
|
|
||||||
assert "sonarr-key" in route.calls.last.request.headers["x-api-key"]
|
|
||||||
|
|
||||||
|
|
||||||
@respx.mock
|
@respx.mock
|
||||||
def test_qbittorrent_status_lifecycle() -> None:
|
def test_qbittorrent_status_lifecycle() -> None:
|
||||||
respx.get("http://qbit-lifecycle:8080/api/v2/app/version").mock(
|
respx.get("http://qbit-lifecycle:8080/api/v2/app/version").mock(
|
||||||
@@ -230,6 +210,58 @@ def test_qbittorrent_connection_without_credentials() -> None:
|
|||||||
assert test.json()["version"] == "v5.0.2"
|
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:
|
def test_settings_persist_to_conf_json() -> None:
|
||||||
with TestClient(app) as client:
|
with TestClient(app) as client:
|
||||||
put = client.put(
|
put = client.put(
|
||||||
@@ -293,7 +325,11 @@ def test_setup_link_only_without_existing_account() -> None:
|
|||||||
|
|
||||||
def test_startup_logs_conf_json_summary(capsys) -> None:
|
def test_startup_logs_conf_json_summary(capsys) -> None:
|
||||||
"""Au lancement, le log indique si conf.json est charge et ce qu'il contient."""
|
"""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:
|
with TestClient(app) as client:
|
||||||
|
# Repart d'une conf vierge: les tests precedents remplissent conf.json.
|
||||||
|
write_config(AppConfig())
|
||||||
client.put(
|
client.put(
|
||||||
"/api/settings/qbittorrent",
|
"/api/settings/qbittorrent",
|
||||||
json={"url": "192.168.1.50", "port": 8555},
|
json={"url": "192.168.1.50", "port": 8555},
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import errno
|
||||||
|
import json
|
||||||
import shutil
|
import shutil
|
||||||
import time
|
import time
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -7,6 +9,7 @@ from fastapi.testclient import TestClient
|
|||||||
from httpx import Response
|
from httpx import Response
|
||||||
|
|
||||||
from app.config import settings
|
from app.config import settings
|
||||||
|
from app.converter import extract_mkv
|
||||||
from app.database import SessionLocal
|
from app.database import SessionLocal
|
||||||
from app.main import app
|
from app.main import app
|
||||||
from app.models import IsoMovie
|
from app.models import IsoMovie
|
||||||
@@ -98,9 +101,17 @@ def test_conversion_order_and_radarr_file_name() -> None:
|
|||||||
entries = sorted(entry.name for entry in folder.iterdir())
|
entries = sorted(entry.name for entry in folder.iterdir())
|
||||||
assert entries == [ISO_NAME, MKV_NAME]
|
assert entries == [ISO_NAME, MKV_NAME]
|
||||||
|
|
||||||
|
rescan_route = respx.post("http://radarr:7878/api/v3/command").mock(
|
||||||
|
return_value=Response(201, json={"id": 1})
|
||||||
|
)
|
||||||
validate = client.post(f"/api/movies/{movie_id}/validate")
|
validate = client.post(f"/api/movies/{movie_id}/validate")
|
||||||
assert validate.status_code == 200
|
assert validate.status_code == 200
|
||||||
assert validate.json()["status"] == "completed"
|
assert validate.json()["status"] == "completed"
|
||||||
|
# La validation declenche un rescan Radarr du dossier du film pour
|
||||||
|
# qu'il adopte le MKV lie comme fichier du film.
|
||||||
|
assert rescan_route.called
|
||||||
|
rescan_body = json.loads(rescan_route.calls.last.request.content)
|
||||||
|
assert rescan_body == {"name": "RescanMovie", "movieId": 10}
|
||||||
|
|
||||||
# Validation: l'ISO est supprimee, seul le MKV reste.
|
# Validation: l'ISO est supprimee, seul le MKV reste.
|
||||||
entries = sorted(entry.name for entry in folder.iterdir())
|
entries = sorted(entry.name for entry in folder.iterdir())
|
||||||
@@ -161,3 +172,293 @@ def test_scan_marks_missing_radarr_files_as_unlinked() -> None:
|
|||||||
movie = client.get("/api/movies").json()[0]
|
movie = client.get("/api/movies").json()[0]
|
||||||
assert movie["radarr_linked"] is False
|
assert movie["radarr_linked"] is False
|
||||||
assert movie["status"] == "detected"
|
assert movie["status"] == "detected"
|
||||||
|
|
||||||
|
|
||||||
|
class FakePopen:
|
||||||
|
"""Remplace subprocess.Popen pour les tests: sortie en flux + code retour."""
|
||||||
|
|
||||||
|
def __init__(self, lines: list[str], returncode: int) -> None:
|
||||||
|
self.stdout = iter(line if line.endswith("\n") else line + "\n" for line in lines)
|
||||||
|
self._returncode = returncode
|
||||||
|
|
||||||
|
def __enter__(self) -> "FakePopen":
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *args: object) -> bool:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def wait(self) -> int:
|
||||||
|
return self._returncode
|
||||||
|
|
||||||
|
|
||||||
|
SHAREWARE_OUTPUT = [
|
||||||
|
"This functionality is shareware. You may evaluate it for 30 days "
|
||||||
|
"after what you would need to purchase an activation key.",
|
||||||
|
"Do you want to start evaluation period now?",
|
||||||
|
"Evaluation version, 30 day(s) out of 30 remaining",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_extract_fails_with_activation_error_when_makemkv_unactivated(
|
||||||
|
monkeypatch, tmp_path
|
||||||
|
) -> None:
|
||||||
|
"""Sans cle MakeMKV (message shareware), l'erreur guide vers l'activation."""
|
||||||
|
monkeypatch.setattr(settings, "simulate_conversion", False)
|
||||||
|
monkeypatch.setattr("app.converter.shutil.which", lambda _: "/usr/bin/makemkvcon")
|
||||||
|
monkeypatch.setattr(
|
||||||
|
"app.converter.subprocess.Popen",
|
||||||
|
lambda args, **kwargs: FakePopen(SHAREWARE_OUTPUT, 10),
|
||||||
|
)
|
||||||
|
movie = IsoMovie(
|
||||||
|
radarr_movie_id=1, radarr_movie_file_id=2, title="ISO Movie", path="/x.iso"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
extract_mkv(movie, tmp_path / "out" / "movie.mkv")
|
||||||
|
except RuntimeError as error:
|
||||||
|
assert "MakeMKV n'est pas activé" in str(error)
|
||||||
|
assert "MAKEMKV_KEY" in str(error)
|
||||||
|
else:
|
||||||
|
raise AssertionError("RuntimeError attendue")
|
||||||
|
|
||||||
|
|
||||||
|
def test_extract_reports_signal_kill(monkeypatch, tmp_path) -> None:
|
||||||
|
"""Un processus tue par signal (ex: OOM) est identifie dans l'erreur."""
|
||||||
|
monkeypatch.setattr(settings, "simulate_conversion", False)
|
||||||
|
monkeypatch.setattr("app.converter.shutil.which", lambda _: "/usr/bin/makemkvcon")
|
||||||
|
monkeypatch.setattr(
|
||||||
|
"app.converter.subprocess.Popen",
|
||||||
|
lambda args, **kwargs: FakePopen([], -9),
|
||||||
|
)
|
||||||
|
movie = IsoMovie(
|
||||||
|
radarr_movie_id=1, radarr_movie_file_id=2, title="ISO Movie", path="/x.iso"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
extract_mkv(movie, tmp_path / "out" / "movie.mkv")
|
||||||
|
except RuntimeError as error:
|
||||||
|
assert "SIGKILL" in str(error)
|
||||||
|
else:
|
||||||
|
raise AssertionError("RuntimeError attendue")
|
||||||
|
|
||||||
|
|
||||||
|
def test_extract_picks_longest_title_and_streams_log(monkeypatch, tmp_path) -> None:
|
||||||
|
"""Le titre extrait est le plus long, et la sortie est diffusee en flux."""
|
||||||
|
robot_info = [
|
||||||
|
'MSG:1005,0,1,"MakeMKV started"',
|
||||||
|
'TINFO:0,9,0,"0:02:30"',
|
||||||
|
'TINFO:1,9,0,"1:57:00"',
|
||||||
|
'TINFO:2,9,0,"0:24:13"',
|
||||||
|
]
|
||||||
|
seen_lines: list[str] = []
|
||||||
|
|
||||||
|
def fake_popen(args, **kwargs):
|
||||||
|
if "--robot" in args:
|
||||||
|
return FakePopen(robot_info, 0)
|
||||||
|
assert args[3] == "1", f"titre attendu: 1, commande: {args}"
|
||||||
|
out = tmp_path / "out"
|
||||||
|
out.mkdir(parents=True, exist_ok=True)
|
||||||
|
(out / "movie.mkv").write_text("mkv")
|
||||||
|
return FakePopen(["Saving 1 titles", "1 titles saved"], 0)
|
||||||
|
|
||||||
|
monkeypatch.setattr(settings, "simulate_conversion", False)
|
||||||
|
monkeypatch.setattr("app.converter.shutil.which", lambda _: "/usr/bin/makemkvcon")
|
||||||
|
monkeypatch.setattr("app.converter.subprocess.Popen", fake_popen)
|
||||||
|
movie = IsoMovie(
|
||||||
|
radarr_movie_id=1, radarr_movie_file_id=2, title="ISO Movie", path="/x.iso"
|
||||||
|
)
|
||||||
|
extract_mkv(
|
||||||
|
movie, tmp_path / "out" / "movie.mkv", lambda line: seen_lines.append(line)
|
||||||
|
)
|
||||||
|
assert (tmp_path / "out" / "movie.mkv").exists()
|
||||||
|
# Les lignes des deux commandes (info + mkv) ont ete diffusees.
|
||||||
|
assert any("TINFO" in line for line in seen_lines)
|
||||||
|
assert "1 titles saved" in seen_lines
|
||||||
|
|
||||||
|
|
||||||
|
def test_looks_like_iso_rejects_renamed_mkv() -> None:
|
||||||
|
"""Un fichier .iso dont l'en-tete est EBML est un MKV renomme: ecarte."""
|
||||||
|
from app.converter import EBML_MAGIC, looks_like_iso
|
||||||
|
|
||||||
|
iso_file = settings.films_dir / "Dossier"
|
||||||
|
iso_file.mkdir(parents=True, exist_ok=True)
|
||||||
|
real_iso = iso_file / "Film (2025).iso"
|
||||||
|
fake_iso = iso_file / "Renomme (2025).iso"
|
||||||
|
real_iso.write_bytes(b"\x00CD001 fake image")
|
||||||
|
fake_iso.write_bytes(EBML_MAGIC + b"matroska data")
|
||||||
|
|
||||||
|
assert looks_like_iso(str(settings.radarr_films_dir / "Dossier" / "Film (2025).iso"))
|
||||||
|
assert not looks_like_iso(
|
||||||
|
str(settings.radarr_films_dir / "Dossier" / "Renomme (2025).iso")
|
||||||
|
)
|
||||||
|
# Extension non iso: refuse.
|
||||||
|
assert not looks_like_iso("/quelque/chose.mkv")
|
||||||
|
# Fichier illisible mais extension iso: accepte par defaut.
|
||||||
|
assert looks_like_iso(str(settings.radarr_films_dir / "Dossier" / "Absent.iso"))
|
||||||
|
|
||||||
|
|
||||||
|
@respx.mock
|
||||||
|
def test_scan_skips_mkv_renamed_as_iso() -> None:
|
||||||
|
"""Le scan n'importe pas les MKV renommes en .iso (contenu EBML)."""
|
||||||
|
reset_state()
|
||||||
|
folder = film_dir()
|
||||||
|
folder.mkdir(parents=True, exist_ok=True)
|
||||||
|
(folder / ISO_NAME).write_bytes(b"\x00CD001 vraie image")
|
||||||
|
(folder / "FAKE.iso").write_bytes(b"\x1aE\xdf\xa3 mkv renomme")
|
||||||
|
movies = [
|
||||||
|
radarr_movie(str(settings.radarr_films_dir / FILM_FOLDER)),
|
||||||
|
{
|
||||||
|
"id": 11,
|
||||||
|
"title": "Renomme",
|
||||||
|
"year": 2024,
|
||||||
|
"path": str(settings.radarr_films_dir / FILM_FOLDER),
|
||||||
|
"movieFile": {"id": 21, "relativePath": "FAKE.iso", "size": 42},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
respx.get("http://radarr:7878/api/v3/movie?includeMovieFile=true").mock(
|
||||||
|
return_value=Response(200, json=movies)
|
||||||
|
)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
configure_radarr(client)
|
||||||
|
scan = client.post("/api/scans")
|
||||||
|
assert scan.json()["iso_files"] == 1
|
||||||
|
titles = [movie["title"] for movie in client.get("/api/movies").json()]
|
||||||
|
assert titles == ["ISO Movie"]
|
||||||
|
|
||||||
|
|
||||||
|
@respx.mock
|
||||||
|
def test_convert_blocked_by_workspace_leftovers() -> None:
|
||||||
|
"""Des restes dans le dossier de travail bloquent la conversion jusqu'a
|
||||||
|
confirmation; force=true les supprime et reprend."""
|
||||||
|
reset_state()
|
||||||
|
create_film_folder()
|
||||||
|
mock_radarr(str(settings.radarr_films_dir / FILM_FOLDER))
|
||||||
|
with TestClient(app) as client:
|
||||||
|
configure_radarr(client)
|
||||||
|
client.post("/api/scans")
|
||||||
|
movie_id = client.get("/api/movies").json()[0]["id"]
|
||||||
|
workspace = settings.downloads_dir / "ISO Movie 2025"
|
||||||
|
workspace.mkdir(parents=True, exist_ok=True)
|
||||||
|
(workspace / "ancien_titre.mkv").write_bytes(b"restes")
|
||||||
|
(workspace / "partial.mkv").write_bytes(b"restes")
|
||||||
|
|
||||||
|
blocked = client.post(f"/api/movies/{movie_id}/convert")
|
||||||
|
assert blocked.status_code == 409
|
||||||
|
detail = blocked.json()["detail"]
|
||||||
|
assert detail["code"] == "workspace_not_empty"
|
||||||
|
assert sorted(detail["files"]) == ["ancien_titre.mkv", "partial.mkv"]
|
||||||
|
|
||||||
|
# La fiche detaillee expose aussi l'etat du dossier.
|
||||||
|
fiche = client.get(f"/api/files/{movie_id}").json()
|
||||||
|
assert fiche["workspace_files"] == ["ancien_titre.mkv", "partial.mkv"]
|
||||||
|
|
||||||
|
forced = client.post(f"/api/movies/{movie_id}/convert?force=true")
|
||||||
|
assert forced.status_code == 200
|
||||||
|
assert forced.json()["status"] == "queued"
|
||||||
|
# Le nettoyage a supprime les restes. Le MKV fraichement produit par
|
||||||
|
# le worker peut deja etre present: course avec le worker (rapide en
|
||||||
|
# mode simulation), on ne verifie que l'absence des anciens fichiers.
|
||||||
|
remaining = workspace_files_dir(workspace)
|
||||||
|
assert "ancien_titre.mkv" not in remaining
|
||||||
|
assert "partial.mkv" not in remaining
|
||||||
|
|
||||||
|
movie = wait_for_status(client, "validating")
|
||||||
|
assert movie["status"] == "validating"
|
||||||
|
|
||||||
|
|
||||||
|
def workspace_files_dir(folder: Path) -> list[str]:
|
||||||
|
return sorted(entry.name for entry in folder.iterdir())
|
||||||
|
|
||||||
|
|
||||||
|
@respx.mock
|
||||||
|
def test_cancel_only_at_validating_and_tolerates_missing_files() -> None:
|
||||||
|
"""L'annulation n'est possible qu'a l'etat "a valider". Un MKV deja
|
||||||
|
disparu est tolere: l'annulation reste valable, retour a "detecte"."""
|
||||||
|
reset_state()
|
||||||
|
create_film_folder()
|
||||||
|
mock_radarr(str(settings.radarr_films_dir / FILM_FOLDER))
|
||||||
|
with TestClient(app) as client:
|
||||||
|
configure_radarr(client)
|
||||||
|
client.post("/api/scans")
|
||||||
|
movie_id = client.get("/api/movies").json()[0]["id"]
|
||||||
|
|
||||||
|
# Hors "a valider": refus (le MKV converti n'existe pas avant).
|
||||||
|
early = client.post(f"/api/movies/{movie_id}/cancel")
|
||||||
|
assert early.status_code == 409
|
||||||
|
|
||||||
|
convert = client.post(f"/api/movies/{movie_id}/convert")
|
||||||
|
assert convert.status_code == 200
|
||||||
|
|
||||||
|
# Apres conversion, on supprime physiquement le MKV et son lien
|
||||||
|
# pour simuler des fichiers deja disparus.
|
||||||
|
wait_for_status(client, "validating")
|
||||||
|
folder = film_dir()
|
||||||
|
for entry in folder.iterdir():
|
||||||
|
if entry.suffix == ".mkv":
|
||||||
|
entry.unlink()
|
||||||
|
workspace = settings.downloads_dir / "ISO Movie 2025"
|
||||||
|
if workspace.is_dir():
|
||||||
|
shutil.rmtree(workspace)
|
||||||
|
|
||||||
|
cancel = client.post(f"/api/movies/{movie_id}/cancel")
|
||||||
|
assert cancel.status_code == 200
|
||||||
|
assert cancel.json()["status"] == "detected"
|
||||||
|
|
||||||
|
|
||||||
|
@respx.mock
|
||||||
|
def test_cancel_reports_permission_error(monkeypatch) -> None:
|
||||||
|
"""Une erreur de droits pendant l'annulation remonte un message
|
||||||
|
explicite (via notification) et le film reste "a valider"."""
|
||||||
|
reset_state()
|
||||||
|
create_film_folder()
|
||||||
|
mock_radarr(str(settings.radarr_films_dir / FILM_FOLDER))
|
||||||
|
import app.converter as converter_module
|
||||||
|
|
||||||
|
def refuse_unlink(path: Path) -> None:
|
||||||
|
# Comme le vrai unlink_if_exists: l'OSError est traduite en message
|
||||||
|
# explicite avant de remonter.
|
||||||
|
raise converter_module.file_error(
|
||||||
|
PermissionError(errno.EACCES, "Permission denied", str(path)),
|
||||||
|
"Suppression",
|
||||||
|
path,
|
||||||
|
)
|
||||||
|
|
||||||
|
monkeypatch.setattr(converter_module, "unlink_if_exists", refuse_unlink)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
configure_radarr(client)
|
||||||
|
client.post("/api/scans")
|
||||||
|
movie_id = client.get("/api/movies").json()[0]["id"]
|
||||||
|
convert = client.post(f"/api/movies/{movie_id}/convert")
|
||||||
|
assert convert.status_code == 200
|
||||||
|
wait_for_status(client, "validating")
|
||||||
|
|
||||||
|
cancel = client.post(f"/api/movies/{movie_id}/cancel")
|
||||||
|
assert cancel.status_code == 409
|
||||||
|
assert "erreur de droits" in cancel.json()["detail"]
|
||||||
|
assert "Annulation impossible" in cancel.json()["detail"]
|
||||||
|
|
||||||
|
movie = client.get("/api/movies").json()[0]
|
||||||
|
assert movie["status"] == "validating"
|
||||||
|
|
||||||
|
|
||||||
|
@respx.mock
|
||||||
|
def test_validate_survives_radarr_rescan_failure() -> None:
|
||||||
|
"""Un echec du rescan Radarr n'invalide pas la validation: le film passe
|
||||||
|
quand meme en "termine" et l'avertissement remonte a l'interface."""
|
||||||
|
reset_state()
|
||||||
|
create_film_folder()
|
||||||
|
mock_radarr(str(settings.radarr_films_dir / FILM_FOLDER))
|
||||||
|
with TestClient(app) as client:
|
||||||
|
configure_radarr(client)
|
||||||
|
client.post("/api/scans")
|
||||||
|
movie_id = client.get("/api/movies").json()[0]["id"]
|
||||||
|
client.post(f"/api/movies/{movie_id}/convert")
|
||||||
|
wait_for_status(client, "validating")
|
||||||
|
|
||||||
|
respx.post("http://radarr:7878/api/v3/command").mock(
|
||||||
|
return_value=Response(500, text="boom")
|
||||||
|
)
|
||||||
|
validate = client.post(f"/api/movies/{movie_id}/validate")
|
||||||
|
assert validate.status_code == 200
|
||||||
|
body = validate.json()
|
||||||
|
assert body["status"] == "completed"
|
||||||
|
assert body["rescan_warning"] is not None
|
||||||
|
assert "rescan Radarr impossible" in body["rescan_warning"]
|
||||||
@@ -42,7 +42,10 @@ def test_db_migration_from_legacy_schema(tmp_path) -> None:
|
|||||||
|
|
||||||
applied = run_db_migrations(engine)
|
applied = run_db_migrations(engine)
|
||||||
|
|
||||||
assert applied == ["iso_movies: colonnes de suivi des conversions"]
|
assert applied == [
|
||||||
|
"iso_movies: colonnes de suivi des conversions",
|
||||||
|
"iso_movies: colonnes created_at/last_seen_at sur les bases anciennes",
|
||||||
|
]
|
||||||
columns = {col["name"] for col in inspect(engine).get_columns("iso_movies")}
|
columns = {col["name"] for col in inspect(engine).get_columns("iso_movies")}
|
||||||
assert {
|
assert {
|
||||||
"processed_at",
|
"processed_at",
|
||||||
@@ -51,6 +54,7 @@ def test_db_migration_from_legacy_schema(tmp_path) -> None:
|
|||||||
"last_error",
|
"last_error",
|
||||||
"poster_url",
|
"poster_url",
|
||||||
"radarr_linked",
|
"radarr_linked",
|
||||||
|
"created_at",
|
||||||
} <= columns
|
} <= columns
|
||||||
|
|
||||||
# Les donnees existantes sont conservees.
|
# Les donnees existantes sont conservees.
|
||||||
@@ -58,10 +62,10 @@ def test_db_migration_from_legacy_schema(tmp_path) -> None:
|
|||||||
rows = list(conn.execute(text("SELECT title, radarr_linked FROM iso_movies")))
|
rows = list(conn.execute(text("SELECT title, radarr_linked FROM iso_movies")))
|
||||||
assert rows == [("ISO Movie", 1)]
|
assert rows == [("ISO Movie", 1)]
|
||||||
|
|
||||||
# La version est tracee et la migration n'est pas rejouee.
|
# Les versions sont tracees et les migrations ne sont pas rejouees.
|
||||||
with engine.connect() as conn:
|
with engine.connect() as conn:
|
||||||
recorded = list(conn.execute(text("SELECT version FROM schema_migrations")))
|
recorded = list(conn.execute(text("SELECT version FROM schema_migrations")))
|
||||||
assert [row[0] for row in recorded] == [1]
|
assert [row[0] for row in recorded] == [1, 2]
|
||||||
assert run_db_migrations(engine) == []
|
assert run_db_migrations(engine) == []
|
||||||
|
|
||||||
|
|
||||||
@@ -73,22 +77,37 @@ def test_db_migration_fresh_database(tmp_path) -> None:
|
|||||||
|
|
||||||
applied = run_db_migrations(engine)
|
applied = run_db_migrations(engine)
|
||||||
|
|
||||||
assert applied == ["iso_movies: colonnes de suivi des conversions"]
|
assert applied == [
|
||||||
|
"iso_movies: colonnes de suivi des conversions",
|
||||||
|
"iso_movies: colonnes created_at/last_seen_at sur les bases anciennes",
|
||||||
|
]
|
||||||
assert run_db_migrations(engine) == []
|
assert run_db_migrations(engine) == []
|
||||||
|
|
||||||
|
|
||||||
def test_conf_file_stamped_with_version() -> None:
|
def test_conf_file_stamped_with_version() -> None:
|
||||||
"""Un conf.json d'avant le systeme (sans cle version) est charge tel quel
|
"""Un conf.json d'avant le systeme (sans cle version) est charge tel quel
|
||||||
et estampille avec la version courante."""
|
et estampille avec la version courante."""
|
||||||
write_raw_config({"radarr": {"url": "http://radarr:7878", "api_key": "k"}})
|
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()
|
applied = migrate_conf_file()
|
||||||
|
|
||||||
assert applied == []
|
# 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"))
|
raw = json.loads(config_path().read_text(encoding="utf-8"))
|
||||||
assert raw["version"] == current_conf_version()
|
assert raw["version"] == current_conf_version()
|
||||||
assert raw["radarr"]["url"] == "http://radarr:7878"
|
assert raw["radarr"]["url"] == "http://radarr:7878"
|
||||||
assert raw["radarr"]["api_key"] == "k"
|
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:
|
def test_conf_migration_transforms_content(monkeypatch) -> None:
|
||||||
@@ -124,3 +143,47 @@ def test_appconfig_version_matches_registry(monkeypatch) -> None:
|
|||||||
migrations conf.json."""
|
migrations conf.json."""
|
||||||
monkeypatch.setattr("app.migrations.CONF_MIGRATIONS", CONF_MIGRATIONS)
|
monkeypatch.setattr("app.migrations.CONF_MIGRATIONS", CONF_MIGRATIONS)
|
||||||
assert AppConfig().version == current_conf_version()
|
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)
|
||||||
+291
-25
@@ -17,7 +17,21 @@ type Movie = {
|
|||||||
last_seen_at: string;
|
last_seen_at: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
type RadarrSettings = {
|
type MovieDetail = Movie & {
|
||||||
|
work_mkv_path?: string | null;
|
||||||
|
linked_mkv_path?: string | null;
|
||||||
|
workspace_folder?: string | null;
|
||||||
|
workspace_files?: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
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;
|
url: string | null;
|
||||||
port: number | null;
|
port: number | null;
|
||||||
api_key_configured: boolean;
|
api_key_configured: boolean;
|
||||||
@@ -25,11 +39,12 @@ type RadarrSettings = {
|
|||||||
|
|
||||||
type NotificationKind = "info" | "error" | "warning";
|
type NotificationKind = "info" | "error" | "warning";
|
||||||
type Notification = { id: number; text: string; kind: NotificationKind };
|
type Notification = { id: number; text: string; kind: NotificationKind };
|
||||||
type QbittorrentSettings = {
|
type QbittorrentSettings = ServiceStatus & {
|
||||||
url: string | null;
|
url: string | null;
|
||||||
port: number | null;
|
port: number | null;
|
||||||
username: string | null;
|
username: string | null;
|
||||||
password_configured: boolean;
|
password_configured: boolean;
|
||||||
|
api_key_configured: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
const jsonHeaders = { "Content-Type": "application/json" };
|
const jsonHeaders = { "Content-Type": "application/json" };
|
||||||
@@ -69,7 +84,18 @@ async function api<T>(path: string, init?: RequestInit): Promise<T> {
|
|||||||
const response = await fetch(path, init);
|
const response = await fetch(path, init);
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const body = await response.json().catch(() => null);
|
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();
|
return response.json();
|
||||||
}
|
}
|
||||||
@@ -83,6 +109,59 @@ function statusLabel(status: string): string {
|
|||||||
return STATUS_LABELS[status] ?? status;
|
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 {
|
function formatDateTime(iso: string): string {
|
||||||
const date = new Date(iso);
|
const date = new Date(iso);
|
||||||
return Number.isNaN(date.getTime()) ? "—" : dateFormatter.format(date);
|
return Number.isNaN(date.getTime()) ? "—" : dateFormatter.format(date);
|
||||||
@@ -119,8 +198,14 @@ export default function App() {
|
|||||||
const [qbitPort, setQbitPort] = useState("");
|
const [qbitPort, setQbitPort] = useState("");
|
||||||
const [qbitUsername, setQbitUsername] = useState("");
|
const [qbitUsername, setQbitUsername] = useState("");
|
||||||
const [qbitPassword, setQbitPassword] = useState("");
|
const [qbitPassword, setQbitPassword] = useState("");
|
||||||
|
const [qbitApiKey, setQbitApiKey] = useState("");
|
||||||
const [qbitConfigured, setQbitConfigured] = useState(false);
|
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 [posterUrl, setPosterUrl] = useState<string | null>(null);
|
||||||
const [modalBusy, setModalBusy] = useState(false);
|
const [modalBusy, setModalBusy] = useState(false);
|
||||||
const [modalMessage, setModalMessage] = useState("");
|
const [modalMessage, setModalMessage] = useState("");
|
||||||
@@ -211,12 +296,25 @@ export default function App() {
|
|||||||
setQbitUrl(qbittorrent.url ?? "");
|
setQbitUrl(qbittorrent.url ?? "");
|
||||||
setQbitPort(qbittorrent.port?.toString() ?? "");
|
setQbitPort(qbittorrent.port?.toString() ?? "");
|
||||||
setQbitUsername(qbittorrent.username ?? "");
|
setQbitUsername(qbittorrent.username ?? "");
|
||||||
setQbitConfigured(qbittorrent.password_configured);
|
setQbitConfigured(qbittorrent.status !== "unconfigured");
|
||||||
if (!radarr.api_key_configured || !qbittorrent.password_configured) {
|
setRadarrState(radarr);
|
||||||
|
setQbittorrentState(qbittorrent);
|
||||||
|
if (radarr.status === "unconfigured") {
|
||||||
notify(
|
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",
|
"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) => {
|
.catch((error: Error) => {
|
||||||
@@ -224,13 +322,54 @@ export default function App() {
|
|||||||
});
|
});
|
||||||
}, [authState, loadMovies]);
|
}, [authState, loadMovies]);
|
||||||
|
|
||||||
|
const hasActive = movies.some((movie) =>
|
||||||
|
["queued", "converting", "importing"].includes(movie.status),
|
||||||
|
);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (authState !== "authed") return;
|
if (authState !== "authed") return;
|
||||||
const timer = setInterval(() => {
|
const timer = setInterval(() => {
|
||||||
loadMovies().catch(() => undefined);
|
loadMovies().catch(() => undefined);
|
||||||
}, 10_000);
|
}, hasActive ? 3_000 : 10_000);
|
||||||
return () => clearInterval(timer);
|
return () => clearInterval(timer);
|
||||||
}, [authState, loadMovies]);
|
}, [authState, loadMovies, hasActive]);
|
||||||
|
|
||||||
|
// Fiche ouverte: rafraichit le detail et le terminal de conversion pendant
|
||||||
|
// les etats actifs ou apres un echec.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!selected) return;
|
||||||
|
if (!["queued", "converting", "importing", "failed"].includes(selected.status)) {
|
||||||
|
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;
|
||||||
|
if (detail) setSelected(detail);
|
||||||
|
if (log) {
|
||||||
|
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]);
|
||||||
|
|
||||||
|
function copyPath(path: string) {
|
||||||
|
navigator.clipboard.writeText(path).catch(() => undefined);
|
||||||
|
notify("Chemin copié dans le presse-papiers.");
|
||||||
|
}
|
||||||
|
|
||||||
function toggleTheme() {
|
function toggleTheme() {
|
||||||
setTheme((current) => {
|
setTheme((current) => {
|
||||||
@@ -309,12 +448,21 @@ export default function App() {
|
|||||||
});
|
});
|
||||||
setKeyConfigured(settings.api_key_configured);
|
setKeyConfigured(settings.api_key_configured);
|
||||||
setApiKey("");
|
setApiKey("");
|
||||||
|
setRadarrState(settings);
|
||||||
const result = await api<{ message: string }>("/api/settings/radarr/test", {
|
const result = await api<{ message: string }>("/api/settings/radarr/test", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
});
|
});
|
||||||
notify(result.message);
|
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) {
|
} catch (error) {
|
||||||
notify((error as Error).message, "error");
|
notify((error as Error).message, "error");
|
||||||
|
const fresh = await api<RadarrSettings>("/api/settings/radarr").catch(() => null);
|
||||||
|
if (fresh) setRadarrState(fresh);
|
||||||
} finally {
|
} finally {
|
||||||
setBusy(false);
|
setBusy(false);
|
||||||
}
|
}
|
||||||
@@ -332,16 +480,26 @@ export default function App() {
|
|||||||
port: qbitPort ? Number(qbitPort) : null,
|
port: qbitPort ? Number(qbitPort) : null,
|
||||||
username: qbitUsername,
|
username: qbitUsername,
|
||||||
password: qbitPassword || null,
|
password: qbitPassword || null,
|
||||||
|
api_key: qbitApiKey || null,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
setQbitConfigured(settings.password_configured);
|
setQbitConfigured(settings.status !== "unconfigured");
|
||||||
|
setQbittorrentState(settings);
|
||||||
setQbitPassword("");
|
setQbitPassword("");
|
||||||
|
setQbitApiKey("");
|
||||||
const result = await api<{ message: string }>("/api/settings/qbittorrent/test", {
|
const result = await api<{ message: string }>("/api/settings/qbittorrent/test", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
});
|
});
|
||||||
notify(result.message);
|
notify(result.message);
|
||||||
|
const fresh = await api<QbittorrentSettings>("/api/settings/qbittorrent").catch(() => null);
|
||||||
|
if (fresh) {
|
||||||
|
setQbittorrentState(fresh);
|
||||||
|
setQbitConfigured(fresh.status !== "unconfigured");
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
notify((error as Error).message, "error");
|
notify((error as Error).message, "error");
|
||||||
|
const fresh = await api<QbittorrentSettings>("/api/settings/qbittorrent").catch(() => null);
|
||||||
|
if (fresh) setQbittorrentState(fresh);
|
||||||
} finally {
|
} finally {
|
||||||
setBusy(false);
|
setBusy(false);
|
||||||
}
|
}
|
||||||
@@ -437,11 +595,23 @@ export default function App() {
|
|||||||
setDeleting(false);
|
setDeleting(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
function openMovie(movie: Movie) {
|
async function openMovie(movie: Movie) {
|
||||||
setSelected(movie);
|
setSelected(movie);
|
||||||
setPosterUrl(movie.poster_url);
|
setPosterUrl(movie.poster_url);
|
||||||
setModalMessage("");
|
setModalMessage("");
|
||||||
setModalError(false);
|
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() {
|
function closeModal() {
|
||||||
@@ -451,19 +621,32 @@ export default function App() {
|
|||||||
setModalError(false);
|
setModalError(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function convert(movie: Movie) {
|
async function convert(movie: MovieDetail, force = false) {
|
||||||
setModalBusy(true);
|
setModalBusy(true);
|
||||||
setModalMessage("");
|
setModalMessage("");
|
||||||
try {
|
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();
|
await loadMovies();
|
||||||
setModalMessage("Conversion mise en file d'attente.");
|
setModalMessage("Conversion mise en file d'attente.");
|
||||||
setModalError(false);
|
setModalError(false);
|
||||||
closeModal();
|
closeModal();
|
||||||
notify(`Conversion de « ${movie.title} » mise en file d'attente.`);
|
notify(`Conversion de « ${movie.title} » mise en file d'attente.`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setModalMessage((error as Error).message);
|
const detail = (error as { detail?: { code?: string } }).detail;
|
||||||
setModalError(true);
|
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 {
|
} finally {
|
||||||
setModalBusy(false);
|
setModalBusy(false);
|
||||||
}
|
}
|
||||||
@@ -481,14 +664,23 @@ export default function App() {
|
|||||||
if (fromModal) setModalBusy(true);
|
if (fromModal) setModalBusy(true);
|
||||||
else setValidatingId(movie.id);
|
else setValidatingId(movie.id);
|
||||||
try {
|
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();
|
await loadMovies();
|
||||||
if (fromModal) {
|
if (fromModal) {
|
||||||
closeModal();
|
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 mis à jour sur le MKV.`);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setError((error as Error).message);
|
const message = (error as Error).message;
|
||||||
|
setError(message);
|
||||||
|
notify(`Validation de « ${movie.title} » impossible : ${message}`, "error");
|
||||||
} finally {
|
} finally {
|
||||||
setModalBusy(false);
|
setModalBusy(false);
|
||||||
setValidatingId(null);
|
setValidatingId(null);
|
||||||
@@ -504,8 +696,10 @@ export default function App() {
|
|||||||
closeModal();
|
closeModal();
|
||||||
notify(`Conversion de « ${movie.title} » annulée — MKV et lien supprimés, film remis à « Détecté ».`,);
|
notify(`Conversion de « ${movie.title} » annulée — MKV et lien supprimés, film remis à « Détecté ».`,);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setModalMessage((error as Error).message);
|
const message = (error as Error).message;
|
||||||
|
setModalMessage(message);
|
||||||
setModalError(true);
|
setModalError(true);
|
||||||
|
notify(`Annulation de « ${movie.title} » impossible : ${message}`, "error");
|
||||||
} finally {
|
} finally {
|
||||||
setModalBusy(false);
|
setModalBusy(false);
|
||||||
}
|
}
|
||||||
@@ -899,9 +1093,7 @@ export default function App() {
|
|||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
{movie.radarr_linked && <span className="status linked">Radarr lié</span>}
|
{movie.radarr_linked && <span className="status linked">Radarr lié</span>}
|
||||||
<span className={BROKEN.includes(movie.status) ? "status error" : "status"}>
|
<StatusPill status={movie.status} />
|
||||||
{statusLabel(movie.status)}
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
</article>
|
</article>
|
||||||
))}
|
))}
|
||||||
@@ -915,7 +1107,10 @@ export default function App() {
|
|||||||
<section className="panel settings">
|
<section className="panel settings">
|
||||||
<div className="panel-head">
|
<div className="panel-head">
|
||||||
<p className="eyebrow">CONFIGURATION</p>
|
<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>
|
<p>L’URL doit être accessible depuis le conteneur MKVTool.</p>
|
||||||
</div>
|
</div>
|
||||||
<form onSubmit={saveSettings}>
|
<form onSubmit={saveSettings}>
|
||||||
@@ -958,7 +1153,10 @@ export default function App() {
|
|||||||
<section className="panel settings">
|
<section className="panel settings">
|
||||||
<div className="panel-head">
|
<div className="panel-head">
|
||||||
<p className="eyebrow">CONFIGURATION</p>
|
<p className="eyebrow">CONFIGURATION</p>
|
||||||
<h2>Connexion qBittorrent</h2>
|
<h2>
|
||||||
|
Connexion qBittorrent{" "}
|
||||||
|
{qbittorrentState && <ServiceBadge state={qbittorrentState} label="qBittorrent" />}
|
||||||
|
</h2>
|
||||||
<p>
|
<p>
|
||||||
Utilisée pour supprimer le torrent et ses données lors de la validation
|
Utilisée pour supprimer le torrent et ses données lors de la validation
|
||||||
finale d’une conversion.
|
finale d’une conversion.
|
||||||
@@ -1008,6 +1206,15 @@ export default function App() {
|
|||||||
onChange={(event) => setQbitPassword(event.target.value)}
|
onChange={(event) => setQbitPassword(event.target.value)}
|
||||||
/>
|
/>
|
||||||
</label>
|
</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>
|
<button disabled={busy}>Enregistrer et tester</button>
|
||||||
</form>
|
</form>
|
||||||
{qbitConfigured && (
|
{qbitConfigured && (
|
||||||
@@ -1049,7 +1256,7 @@ export default function App() {
|
|||||||
<dl className="modal-grid">
|
<dl className="modal-grid">
|
||||||
<div>
|
<div>
|
||||||
<dt>État</dt>
|
<dt>État</dt>
|
||||||
<dd>{statusLabel(selected.status)}</dd>
|
<dd><StatusPill status={selected.status} /></dd>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<dt>Taille de l’ISO</dt>
|
<dt>Taille de l’ISO</dt>
|
||||||
@@ -1079,10 +1286,69 @@ export default function App() {
|
|||||||
<dt>Emplacement</dt>
|
<dt>Emplacement</dt>
|
||||||
<dd><code>{selected.path}</code></dd>
|
<dd><code>{selected.path}</code></dd>
|
||||||
</div>
|
</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>
|
</dl>
|
||||||
|
|
||||||
{selected.last_error && <p className="message error">{selected.last_error}</p>}
|
{selected.last_error && <p className="message error">{selected.last_error}</p>}
|
||||||
|
|
||||||
|
{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">
|
<p className="modal-explain">
|
||||||
La conversion extrait le film du disque ISO vers un fichier MKV avec MakeMKV,
|
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.
|
sans réencodage : vidéo, audio et sous-titres sont conservés à l’identique.
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
import type {ServiceStatus} from "../types";
|
|
||||||
|
|
||||||
type Props = ServiceStatus;
|
|
||||||
|
|
||||||
export default function ServiceStatusBadge({status, tested_version: version, test_error: error}: Props) {
|
|
||||||
if (status === "tested") {
|
|
||||||
return (
|
|
||||||
<span className="status linked" title={error ?? undefined}>
|
|
||||||
Testé{version ? ` · ${version}` : ""}
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (status === "error") {
|
|
||||||
return (
|
|
||||||
<span className="status error" title={error ?? undefined}>
|
|
||||||
Test échoué
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (status === "configured") {
|
|
||||||
return <span className="status warn">Configuré · non testé</span>;
|
|
||||||
}
|
|
||||||
return <span className="status">Non configuré</span>;
|
|
||||||
}
|
|
||||||
@@ -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,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,396 +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";
|
|
||||||
import ServiceStatusBadge from "../components/ServiceStatusBadge";
|
|
||||||
|
|
||||||
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 [settings, setSettings] = useState<SettingsRead | null>(null);
|
|
||||||
|
|
||||||
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 (): Promise<SettingsRead> => {
|
|
||||||
const fresh = await api<SettingsRead>("/api/settings");
|
|
||||||
hydrateSettings(fresh);
|
|
||||||
setSettings(fresh);
|
|
||||||
return fresh;
|
|
||||||
}, [hydrateSettings]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
refreshSettings().catch((error: Error) => setMessage(error.message));
|
|
||||||
}, [refreshSettings]);
|
|
||||||
|
|
||||||
async function testService(name: "radarr" | "sonarr" | "prowlarr" | "jellyfin" | "seerr" | "qbittorrent"): Promise<void> {
|
|
||||||
try {
|
|
||||||
const result = await api<{ message: string }>(`/api/settings/${name}/test`, {method: "POST"});
|
|
||||||
setMessage(result.message);
|
|
||||||
} catch (error) {
|
|
||||||
setMessage((error as Error).message);
|
|
||||||
}
|
|
||||||
await refreshSettings().catch(() => undefined);
|
|
||||||
}
|
|
||||||
|
|
||||||
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();
|
|
||||||
await testService("radarr");
|
|
||||||
} 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("");
|
|
||||||
|
|
||||||
const fresh = await refreshSettings();
|
|
||||||
if (fresh[name].status === "unconfigured") {
|
|
||||||
setMessage("Configuration enregistrée");
|
|
||||||
} else {
|
|
||||||
await testService(name);
|
|
||||||
}
|
|
||||||
} 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("");
|
|
||||||
const fresh = await refreshSettings();
|
|
||||||
if (fresh.qbittorrent.status === "unconfigured") {
|
|
||||||
setMessage("Configuration enregistrée");
|
|
||||||
} else {
|
|
||||||
await testService("qbittorrent");
|
|
||||||
}
|
|
||||||
} 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>
|
|
||||||
<div className="service-head">
|
|
||||||
<h3>Radarr</h3>
|
|
||||||
{settings && <ServiceStatusBadge {...settings.radarr}/>}
|
|
||||||
</div>
|
|
||||||
<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>
|
|
||||||
<div className="service-head">
|
|
||||||
<h3>Sonarr</h3>
|
|
||||||
{settings && <ServiceStatusBadge {...settings.sonarr}/>}
|
|
||||||
</div>
|
|
||||||
<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 et tester</button>
|
|
||||||
</form>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section className="card grid-2">
|
|
||||||
<div>
|
|
||||||
<div className="service-head">
|
|
||||||
<h3>Prowlarr</h3>
|
|
||||||
{settings && <ServiceStatusBadge {...settings.prowlarr}/>}
|
|
||||||
</div>
|
|
||||||
<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 et tester</button>
|
|
||||||
</form>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section className="card grid-2">
|
|
||||||
<div>
|
|
||||||
<div className="service-head">
|
|
||||||
<h3>Jellyfin</h3>
|
|
||||||
{settings && <ServiceStatusBadge {...settings.jellyfin}/>}
|
|
||||||
</div>
|
|
||||||
<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 et tester</button>
|
|
||||||
</form>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section className="card grid-2">
|
|
||||||
<div>
|
|
||||||
<div className="service-head">
|
|
||||||
<h3>Overseerr</h3>
|
|
||||||
{settings && <ServiceStatusBadge {...settings.seerr}/>}
|
|
||||||
</div>
|
|
||||||
<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 et tester</button>
|
|
||||||
</form>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section className="card grid-2">
|
|
||||||
<div>
|
|
||||||
<div className="service-head">
|
|
||||||
<h3>qBittorrent</h3>
|
|
||||||
{settings && <ServiceStatusBadge {...settings.qbittorrent}/>}
|
|
||||||
</div>
|
|
||||||
<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 et tester</button>
|
|
||||||
</form>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section className="card">
|
|
||||||
<h3>Aide</h3>
|
|
||||||
<p className="muted">{serviceHelp}</p>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
{message && <div className="toast">{message}</div>}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -559,3 +559,143 @@ button.danger:hover:not(:disabled) {
|
|||||||
background: var(--surface-raised);
|
background: var(--surface-raised);
|
||||||
border-color: transparent;
|
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; }
|
||||||
|
}
|
||||||
@@ -1,34 +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 ServiceStatus = {
|
|
||||||
status: "unconfigured" | "configured" | "tested" | "error";
|
|
||||||
tested_version?: string | null;
|
|
||||||
tested_at?: string | null;
|
|
||||||
test_error?: string | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ApiServiceSettingsRead = ServiceStatus & { url: string | null; api_key_configured: boolean };
|
|
||||||
export type QbittorrentSettingsRead = ServiceStatus & {
|
|
||||||
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