Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
acc1609b4d | ||
|
|
8e76fb7112 | ||
|
|
c7344f8988 | ||
|
|
3a75527135 | ||
|
|
23132c6219 | ||
|
|
514f417c15 | ||
|
|
e8bbbc7d1e | ||
|
|
95e5ead67a | ||
|
|
76dbd7e425 | ||
|
|
f0b5f2b21e | ||
|
|
78e6b0bb22 | ||
|
|
2d2ebde4f6 | ||
|
|
198a014967 | ||
|
|
cfc0c54181 | ||
|
|
de4a9b212f | ||
|
|
c19bc48318 |
No files matched your search
+9
-1
@@ -56,8 +56,16 @@ COPY app/ app/
|
||||
COPY --from=web /web/dist /app/web/dist
|
||||
COPY docker/entrypoint.py /entrypoint.py
|
||||
|
||||
ENV MKVTOOL_CONFIG_DIR=/config \
|
||||
# HOME pointe vers /config pour que MakeMKV y lise et y ecrite sa
|
||||
# configuration (settings.conf, cle d'activation) : le processus tourne sous
|
||||
# PUID/PGID et ne peut pas acceder a /root, et /config est le volume persistant.
|
||||
ENV HOME=/config \
|
||||
MKVTOOL_CONFIG_DIR=/config \
|
||||
MKVTOOL_WEB_DIR=/app/web/dist \
|
||||
MKVTOOL_FILMS_DIR=/films \
|
||||
MKVTOOL_RADARR_FILMS_DIR=/nas_storage/jellyfin/films \
|
||||
MKVTOOL_DOWNLOADS_DIR=/qbittorrentdownloads \
|
||||
MKVTOOL_SIMULATE_CONVERSION=false \
|
||||
MAKEMKV_VERSION=${MAKEMKV_VERSION}
|
||||
RUN mkdir -p /config
|
||||
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
# Image Docker MKVTool
|
||||
|
||||
Image de l'application complète : API FastAPI, interface web, worker de
|
||||
conversion ISO vers MKV, MakeMKV et ffmpeg. Une image est publiée dans le
|
||||
Container Registry GitLab a chaque release.
|
||||
|
||||
## Recuperer l'image
|
||||
|
||||
```bash
|
||||
docker login registry-gitlab.orionis-home.fr
|
||||
docker pull registry-gitlab.orionis-home.fr/deposit/mkvtool:v1.0.7
|
||||
```
|
||||
|
||||
Les tags disponibles : `vX.Y.Z` (une version par release GitLab) et `latest`.
|
||||
L'authentification se fait avec un compte GitLab (ou un Personal Access Token
|
||||
scopes `read_registry`).
|
||||
|
||||
## Construction de l'image
|
||||
|
||||
L'image est construite par la CI (job `container:image`, Kaniko) a chaque tag
|
||||
`vX.Y.Z`. Le `Dockerfile` est multi-etapes :
|
||||
|
||||
| Etape | Base | Role |
|
||||
|---|---|---|
|
||||
| `web` | `node:22-slim` | `npm ci` + `vite build` → `web/dist` |
|
||||
| `api` | `python:3.13-slim` | ffmpeg, MakeMKV compile depuis les sources, dependances `uv sync --no-dev` |
|
||||
|
||||
MakeMKV (`makemkvcon`) est compile dans l'image a partir de la version definie
|
||||
par l'argument de build `MAKEMKV_VERSION` (par defaut `2.0.0`). Le build local
|
||||
reste possible : `docker build -t mkvtool .`.
|
||||
|
||||
## 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) — l'achat est
|
||||
ponctuellement indisponible côté éditeur, la clé bêta fait alors foi.
|
||||
|
||||
L'image positionne `HOME=/config` : MakeMKV lit et écrit sa configuration
|
||||
dans `/config/.MakeMKV/settings.conf`, donc sur le volume persistant. Pour
|
||||
activer :
|
||||
|
||||
```bash
|
||||
docker exec mkvtool makemkvcon reg T-VOTRE-CLE
|
||||
```
|
||||
|
||||
Ou en créant le fichier `<montage de /config>/.MakeMKV/settings.conf` sur
|
||||
l'hôte :
|
||||
|
||||
```
|
||||
app_MakeMKV_key = "T-VOTRE-CLE"
|
||||
```
|
||||
|
||||
Si une conversion échoue avec le message d'activation, la clé a expiré :
|
||||
reprenez la clé courante sur le forum et relancez la commande ci-dessus.
|
||||
|
||||
## Variables d'environnement
|
||||
|
||||
| Variable | Defaut image | Role |
|
||||
|---|---|---|
|
||||
| `PUID` / `PGID` | `0` / `0` | UID/GID sous lesquels le service tourne (modele LinuxServer.io) |
|
||||
| `TZ` | `UTC` | Fuseau horaire |
|
||||
| `MKVTOOL_CONFIG_DIR` | `/config` | Dossier de conf et base SQLite (`mkvtool.db`, `conf.json`) |
|
||||
| `MKVTOOL_WEB_DIR` | `/app/web/dist` | Emplacement du front servi par l'API |
|
||||
| `MKVTOOL_FILMS_DIR` | `/films` | Racine de la bibliotheque Jellyfin dans le conteneur |
|
||||
| `MKVTOOL_RADARR_FILMS_DIR` | `/nas_storage/jellyfin/films` | Racine telle que Radarr la rapporte ; les chemins ISO sont traduits vers `MKVTOOL_FILMS_DIR` |
|
||||
| `MKVTOOL_DOWNLOADS_DIR` | `/qbittorrentdownloads` | Racine des telechargements qBittorrent |
|
||||
| `MKVTOOL_SIMULATE_CONVERSION` | `false` | `true` = produit un faux MKV sans appeler MakeMKV (dev/tests) |
|
||||
| `MKVTOOL_WORKER_INTERVAL` | `10` | Secondes entre deux tours de la file de conversion |
|
||||
| `MAKEMKV_VERSION` | `2.0.0` | Version MakeMKV embarquee (visible dans `/api/health`) |
|
||||
|
||||
## Volumes
|
||||
|
||||
| Chemin conteneur | Contenu |
|
||||
|---|---|
|
||||
| `/config` | `conf.json` (connexions Radarr/qBittorrent, mis a jour par l'interface), `mkvtool.db` (inventaire + sessions) |
|
||||
| `/films` | Bibliotheque Jellyfin : dossiers des films, ISO sources et MKV finaux |
|
||||
| `/qbittorrentdownloads` | Telechargements qBittorrent : dossier de travail ou le MKV est extrait avant le lien dur |
|
||||
|
||||
La bibliotheque est montee en `/films` dans le conteneur. Radarr rapporte ses
|
||||
propres chemins (`MKVTOOL_RADARR_FILMS_DIR`, par defaut
|
||||
`/nas_storage/jellyfin/films`) : l'API traduit automatiquement les chemins ISO
|
||||
vers `/films` au moment de la conversion. Si Radarr utilise un autre chemin
|
||||
d'installation, ajustez `MKVTOOL_RADARR_FILMS_DIR`. Les telechargements
|
||||
qBittorrent restent montes au meme chemin pour que le lien dur soit possible.
|
||||
|
||||
## Ports
|
||||
|
||||
| Port | Service |
|
||||
|---|---|
|
||||
| `8000` | API + interface web (uvicorn) |
|
||||
|
||||
## Fonctionnement au demarrage
|
||||
|
||||
1. Le conteneur demarre en root, attribue `/config` a `PUID:PGID`, puis baisse
|
||||
les privileges et lance uvicorn sous cette identite.
|
||||
2. Premier lancement : une banniere dans les logs affiche un lien
|
||||
`/setup?token=...` a usage unique pour creer le compte (jeton regenere a
|
||||
chaque redemarrage tant qu'aucun compte n'existe).
|
||||
3. Le worker de conversion demarre et traite la file (une conversion a la
|
||||
fois) toutes les `MKVTOOL_WORKER_INTERVAL` secondes.
|
||||
|
||||
## Cycle de conversion d'un film
|
||||
|
||||
1. **Conversion** : MakeMKV extrait le MKV vers
|
||||
`$MKVTOOL_DOWNLOADS_DIR/<Film>/`.
|
||||
2. **Nettoyage** : le dossier du film dans Jellyfin (`/films/...` dans le
|
||||
conteneur) est vide (tout sauf l'ISO, gardee jusqu'a la validation).
|
||||
3. **Lien** : le MKV est lie par `ln` dans le dossier du film, nomme selon le
|
||||
Media Management de Radarr (`{Movie Title} ({Release Year})...`). Si
|
||||
Radarr ne renomme pas ou est injoignable, le nom MakeMKV est conserve.
|
||||
L'ISO et le torrent sont conserves tant que la conversion n'est pas validee.
|
||||
4. **Validation manuelle** (bouton dans l'interface) : supprime l'ISO, le
|
||||
torrent qBittorrent correspondant et le dossier de travail. Le MKV lie
|
||||
reste (lien dur, meme inode : aucune donnee n'est recopiee).
|
||||
|
||||
## Exemple docker run
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
--name mkvtool \
|
||||
--restart unless-stopped \
|
||||
-p 8000:8000 \
|
||||
-e PUID=1020 -e PGID=100 -e TZ=Europe/Paris \
|
||||
-e MKVTOOL_SIMULATE_CONVERSION=false \
|
||||
-v /volume1/docker/mkvtool:/config \
|
||||
-v /qbittorrentdownloads:/qbittorrentdownloads \
|
||||
-v /nas_storage/jellyfin/films:/films \
|
||||
registry-gitlab.orionis-home.fr/deposit/mkvtool:latest
|
||||
```
|
||||
|
||||
## Mise a jour
|
||||
|
||||
```bash
|
||||
docker pull registry-gitlab.orionis-home.fr/deposit/mkvtool:latest
|
||||
docker rm -f mkvtool
|
||||
# puis relancer la commande ci-dessus
|
||||
```
|
||||
|
||||
La base SQLite est migree automatiquement au demarrage (ajout de colonnes
|
||||
manquantes) ; `/config` doit donc etre un volume persistant.
|
||||
|
||||
## Sante
|
||||
|
||||
`GET /api/health` renvoie l'etat de la base et la disponibilite de
|
||||
`makemkvcon` — utile pour verifier que l'image est fonctionnelle :
|
||||
|
||||
```bash
|
||||
curl http://localhost:8000/api/health
|
||||
```
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 59 KiB |
@@ -8,6 +8,16 @@ La configuration des services (Radarr, Sonarr, Prowlarr, Jellyfin, Overseerr/See
|
||||
|
||||
- Le backend lit ce fichier.
|
||||
- L'interface modifie ce fichier via l'API (écriture atomique côté backend).
|
||||
- Chaque service expose un statut dans la page Configuration: `Non configuré` (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.
|
||||
|
||||
## Migrations (base de données et conf.json)
|
||||
|
||||
Les évolutions de structure sont versionnées et appliquées automatiquement au démarrage (`app/migrations.py`):
|
||||
|
||||
- **Base de données**: chaque migration est un `DbMigration` numéroté, appliqué dans sa propre transaction et tracé dans la table `schema_migrations`. Une migration doit rester inoffensive sur un schéma déjà à jour (vérifier l'existence des tables/colonnes avant d'agir), car `create_all` crée déjà le schéma complet sur une base vierge.
|
||||
- **conf.json**: le fichier porte une clé `version` en tête. `CONF_MIGRATIONS` contient des fonctions `(dict) -> dict` qui transforment le contenu brut de la version N vers N+1, appliquées en chaîne jusqu'à la version courante. La valeur par défaut de `AppConfig.version` (dans `app/conf_store.py`) doit être mise à jour en même temps; un test vérifie cet invariant.
|
||||
|
||||
Pour ajouter une migration: ajouter l'entrée en fin de `DB_MIGRATIONS` ou de `CONF_MIGRATIONS` avec le numéro de version suivant, puis un test qui couvre la transformation depuis un état ancien.
|
||||
|
||||
Radarr (rappel API):
|
||||
|
||||
|
||||
@@ -102,3 +102,9 @@ def current_user(
|
||||
if user_id is None:
|
||||
raise HTTPException(status_code=401, detail="Non authentifié")
|
||||
return user_id
|
||||
|
||||
|
||||
def get_username(user_id: int) -> str | None:
|
||||
with SessionLocal() as db:
|
||||
user = db.get(User, user_id)
|
||||
return user.username if user else None
|
||||
+101
-7
@@ -1,25 +1,64 @@
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.config import settings
|
||||
|
||||
|
||||
class TestState(BaseModel):
|
||||
"""Resultat du dernier test de connexion (None = jamais teste)."""
|
||||
|
||||
at: str | None = None
|
||||
ok: bool | None = None
|
||||
version: str | None = None
|
||||
error: str | None = None
|
||||
|
||||
|
||||
class ApiServiceConfig(BaseModel):
|
||||
url: str | None = None
|
||||
port: int | None = None
|
||||
api_key: str | None = None
|
||||
test: TestState = Field(default_factory=TestState)
|
||||
|
||||
|
||||
class QbittorrentConfig(BaseModel):
|
||||
url: str | None = None
|
||||
port: int | None = None
|
||||
username: str | None = None
|
||||
password: str | None = None
|
||||
# Cle API native qBittorrent >= 5.2 (qbt_...), en-tete Authorization: Bearer.
|
||||
api_key: str | None = None
|
||||
test: TestState = Field(default_factory=TestState)
|
||||
|
||||
|
||||
def build_base_url(url: str | None, port: int | None = None) -> str | None:
|
||||
"""Normalise une adresse de service en URL de base.
|
||||
|
||||
Accepte une adresse locale sans schema ("http://" est deduit) et un port
|
||||
optionnel separe, applique seulement si l'URL n'en porte pas deja un.
|
||||
"""
|
||||
if not url:
|
||||
return None
|
||||
base = str(url).strip().rstrip("/")
|
||||
if "://" not in base:
|
||||
base = f"http://{base}"
|
||||
if port:
|
||||
parsed = urlparse(base)
|
||||
if parsed.port is None:
|
||||
base = f"{parsed.scheme}://{parsed.netloc}:{port}"
|
||||
return base
|
||||
|
||||
|
||||
class AppConfig(BaseModel):
|
||||
# Version de la structure du fichier, migree au demarrage
|
||||
# (voir app/migrations.py). Doit rester synchrone avec
|
||||
# current_conf_version(): un test verifie cet invariant.
|
||||
version: int = 1
|
||||
radarr: ApiServiceConfig = Field(default_factory=ApiServiceConfig)
|
||||
sonarr: ApiServiceConfig = Field(default_factory=ApiServiceConfig)
|
||||
prowlarr: ApiServiceConfig = Field(default_factory=ApiServiceConfig)
|
||||
@@ -33,22 +72,73 @@ def config_path() -> Path:
|
||||
return settings.config_dir / "conf.json"
|
||||
|
||||
|
||||
def read_config() -> AppConfig:
|
||||
SERVICE_NAMES = ("radarr", "sonarr", "prowlarr", "jellyfin", "seerr", "qbittorrent")
|
||||
|
||||
|
||||
def service_configured(service: ApiServiceConfig | QbittorrentConfig) -> bool:
|
||||
"""Un service est completement configure quand son URL (et sa cle API,
|
||||
quand il en faut une) est renseignee."""
|
||||
if isinstance(service, QbittorrentConfig):
|
||||
return bool(service.url)
|
||||
return bool(service.url and service.api_key)
|
||||
|
||||
|
||||
def service_status(service: ApiServiceConfig | QbittorrentConfig) -> str:
|
||||
"""Statut expose a l'UI: unconfigured | configured | tested | error."""
|
||||
if not service_configured(service):
|
||||
return "unconfigured"
|
||||
if service.test.ok is None:
|
||||
return "configured"
|
||||
return "tested" if service.test.ok else "error"
|
||||
|
||||
|
||||
def record_test(
|
||||
service_name: str, ok: bool, version: str | None = None, error: str | None = None
|
||||
) -> None:
|
||||
"""Persiste dans conf.json le resultat du dernier test de connexion."""
|
||||
if service_name not in SERVICE_NAMES:
|
||||
raise ValueError(f"Service inconnu: {service_name}")
|
||||
cfg = read_config()
|
||||
service = getattr(cfg, service_name)
|
||||
service.test = TestState(
|
||||
at=datetime.now(UTC).isoformat(),
|
||||
ok=ok,
|
||||
version=version if ok else None,
|
||||
error=None if ok else error,
|
||||
)
|
||||
write_config(cfg)
|
||||
|
||||
|
||||
def reset_test(service: ApiServiceConfig | QbittorrentConfig) -> None:
|
||||
"""Reinitialise le statut de test quand la configuration change."""
|
||||
service.test = TestState()
|
||||
|
||||
|
||||
def read_raw_config() -> dict | None:
|
||||
"""Contenu brut de conf.json (dict), ou None s'il est absent.
|
||||
|
||||
Sert aux migrations, qui transforment le fichier avant validation
|
||||
pydantic. Un contenu invalide (non-dict) est traite comme absent.
|
||||
"""
|
||||
path = config_path()
|
||||
if not path.exists():
|
||||
return AppConfig()
|
||||
return None
|
||||
raw = json.loads(path.read_text(encoding="utf-8"))
|
||||
if not isinstance(raw, dict):
|
||||
return raw if isinstance(raw, dict) else None
|
||||
|
||||
|
||||
def read_config() -> AppConfig:
|
||||
raw = read_raw_config()
|
||||
if raw is None:
|
||||
return AppConfig()
|
||||
return AppConfig.model_validate(raw)
|
||||
|
||||
|
||||
def write_config(config: AppConfig) -> None:
|
||||
def write_raw_config(data: dict) -> None:
|
||||
"""Ecriture atomique du contenu brut de conf.json."""
|
||||
path = config_path()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
serialized = config.model_dump(mode="json", exclude_none=True)
|
||||
|
||||
# Atomic write to avoid corrupting conf.json if the process is interrupted.
|
||||
tmp_dir = str(path.parent)
|
||||
with tempfile.NamedTemporaryFile(
|
||||
@@ -59,9 +149,13 @@ def write_config(config: AppConfig) -> None:
|
||||
suffix=".tmp",
|
||||
delete=False,
|
||||
) as handle:
|
||||
json.dump(serialized, handle, indent=2, ensure_ascii=False)
|
||||
json.dump(data, handle, indent=2, ensure_ascii=False)
|
||||
handle.write("\n")
|
||||
tmp_name = handle.name
|
||||
|
||||
os.replace(tmp_name, path)
|
||||
|
||||
|
||||
def write_config(config: AppConfig) -> None:
|
||||
write_raw_config(config.model_dump(mode="json", exclude_none=True))
|
||||
|
||||
+9
-1
@@ -6,6 +6,15 @@ from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
class AppSettings(BaseSettings):
|
||||
config_dir: Path = Path("./config")
|
||||
database_url: str | None = None
|
||||
films_dir: Path = Path("./films")
|
||||
# Racine de la bibliotheque telle que rapportee par Radarr, si elle
|
||||
# differe du point de montage dans le conteneur (films_dir). Les chemins
|
||||
# ISO stockes sont traduits grace a ce couple.
|
||||
radarr_films_dir: Path | None = None
|
||||
downloads_dir: Path = Path("./downloads")
|
||||
# Simulation (dev/tests): produit un faux MKV au lieu d'appeler MakeMKV.
|
||||
simulate_conversion: bool = True
|
||||
worker_interval: float = 10.0
|
||||
|
||||
model_config = SettingsConfigDict(env_prefix="MKVTOOL_", env_file=".env")
|
||||
|
||||
@@ -17,4 +26,3 @@ class AppSettings(BaseSettings):
|
||||
|
||||
|
||||
settings = AppSettings()
|
||||
|
||||
+60
-9
@@ -40,13 +40,31 @@ class ConversionPaths:
|
||||
destination_folder: Path
|
||||
|
||||
|
||||
def container_iso_path(movie: IsoMovie) -> Path:
|
||||
"""Chemin de l'ISO tel que vu dans le conteneur.
|
||||
|
||||
Radarr rapporte ses chemins dans son propre referentiel
|
||||
(radarr_films_dir); si celui-ci differe du point de montage du conteneur
|
||||
(films_dir), on traduit. Sans radarr_films_dir, les chemins sont pris
|
||||
tels quels (montage "meme chemin").
|
||||
"""
|
||||
iso = Path(movie.path)
|
||||
radarr_root = settings.radarr_films_dir
|
||||
if radarr_root is not None:
|
||||
try:
|
||||
return settings.films_dir / iso.relative_to(radarr_root)
|
||||
except ValueError:
|
||||
pass
|
||||
return iso
|
||||
|
||||
|
||||
def conversion_paths(movie: IsoMovie) -> ConversionPaths:
|
||||
title = sanitize_component(movie.title)
|
||||
movie_name = f"{title} {movie.year}" if movie.year else title
|
||||
mkv_name = f"{title} ({movie.year}).mkv" if movie.year else f"{title}.mkv"
|
||||
downloads_folder = settings.downloads_dir / movie_name
|
||||
|
||||
iso_folder = Path(movie.path).parent
|
||||
iso_folder = container_iso_path(movie).parent
|
||||
films_root = settings.films_dir.resolve()
|
||||
if iso_folder.resolve().is_relative_to(films_root):
|
||||
destination_folder = iso_folder
|
||||
@@ -70,12 +88,20 @@ def extract_mkv(movie: IsoMovie, mkv_path: Path) -> None:
|
||||
if shutil.which("makemkvcon") is None:
|
||||
raise RuntimeError("MakeMKV (makemkvcon) n'est pas installe sur le serveur")
|
||||
result = subprocess.run(
|
||||
["makemkvcon", "mkv", f"iso:{movie.path}", "0", str(mkv_path.parent)],
|
||||
["makemkvcon", "mkv", f"iso:{container_iso_path(movie)}", "0", str(mkv_path.parent)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
detail = result.stderr.strip() or result.stdout.strip()
|
||||
if "purchase an activation key" in detail or "evaluation period" in detail:
|
||||
raise RuntimeError(
|
||||
"MakeMKV n'est pas activé: une clé est requise pour la conversion. "
|
||||
"Utilisez la clé bêta gratuite du forum officiel MakeMKV ou une clé "
|
||||
"achetée, puis `docker exec mkvtool makemkvcon reg <clé>` "
|
||||
"(ou renseignez app_MakeMKV_key dans /config/.MakeMKV/settings.conf). "
|
||||
"Voir IMAGE.md."
|
||||
)
|
||||
raise RuntimeError(f"MakeMKV a echoue: {detail}")
|
||||
produced = sorted(mkv_path.parent.glob("*.mkv"))
|
||||
if not produced:
|
||||
@@ -83,15 +109,38 @@ def extract_mkv(movie: IsoMovie, mkv_path: Path) -> None:
|
||||
produced[0].replace(mkv_path)
|
||||
|
||||
|
||||
def import_mkv(mkv_path: Path, destination_folder: Path) -> Path:
|
||||
"""Crée le lien du MKV dans le dossier du film, sans toucher au reste.
|
||||
def clear_folder(destination_folder: Path, keep: list[Path]) -> None:
|
||||
"""Vide le dossier du film, sauf les chemins listés dans keep (l'ISO...)."""
|
||||
resolved = guarded_folder(destination_folder)
|
||||
if not resolved.exists():
|
||||
return
|
||||
keep_resolved = {path.resolve() for path in keep}
|
||||
for entry in resolved.iterdir():
|
||||
if entry.resolve() in keep_resolved:
|
||||
continue
|
||||
if entry.is_dir() and not entry.is_symlink():
|
||||
shutil.rmtree(entry)
|
||||
else:
|
||||
entry.unlink()
|
||||
|
||||
L'ISO et les autres fichiers du dossier ne sont supprimés qu'à la
|
||||
validation manuelle (finalize_validation).
|
||||
|
||||
def import_mkv(
|
||||
mkv_path: Path,
|
||||
destination_folder: Path,
|
||||
target_name: str | None = None,
|
||||
keep: list[Path] | None = None,
|
||||
) -> Path:
|
||||
"""Nettoie le dossier du film puis crée le lien du MKV.
|
||||
|
||||
Ordre voulu: (1) suppression de tout ce qui traîne dans le dossier du
|
||||
film — sauf les chemins de `keep` (l'ISO reste en sécurité jusqu'à la
|
||||
validation manuelle) — puis (2) création du lien dur, nommé selon la
|
||||
configuration Media Management de Radarr (`target_name`).
|
||||
"""
|
||||
resolved = guarded_folder(destination_folder)
|
||||
resolved.mkdir(parents=True, exist_ok=True)
|
||||
target = resolved / mkv_path.name
|
||||
clear_folder(resolved, keep or [])
|
||||
target = resolved / (target_name or mkv_path.name)
|
||||
if target.exists() or target.is_symlink():
|
||||
target.unlink()
|
||||
try:
|
||||
@@ -116,13 +165,15 @@ def finalize_validation(destination_folder: Path, keep_name: str) -> None:
|
||||
entry.unlink()
|
||||
|
||||
|
||||
def cancel_conversion(mkv_path: Path, destination_folder: Path) -> None:
|
||||
def cancel_conversion(
|
||||
mkv_path: Path, destination_folder: Path, target_name: str | None = None
|
||||
) -> None:
|
||||
"""Annule une conversion en attente de validation.
|
||||
|
||||
Supprime le MKV converti et son lien dans le dossier du film (s'ils
|
||||
existent); l'ISO et le reste du dossier ne sont pas touches.
|
||||
"""
|
||||
target = destination_folder / mkv_path.name
|
||||
target = destination_folder / (target_name or mkv_path.name)
|
||||
for path in (target, mkv_path):
|
||||
if path.is_symlink() or path.exists():
|
||||
path.unlink()
|
||||
|
||||
+456
-31
@@ -1,49 +1,74 @@
|
||||
import asyncio
|
||||
import os
|
||||
import shutil
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Annotated
|
||||
|
||||
import httpx
|
||||
from fastapi import Depends, FastAPI, HTTPException
|
||||
from fastapi import Cookie, Depends, FastAPI, HTTPException, Response
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from sqlalchemy import inspect, select, text
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy import select, update
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.conf_store import read_config, write_config
|
||||
from app import auth
|
||||
from app.conf_store import (
|
||||
ApiServiceConfig,
|
||||
QbittorrentConfig,
|
||||
build_base_url,
|
||||
read_config,
|
||||
record_test,
|
||||
reset_test,
|
||||
service_configured,
|
||||
service_status,
|
||||
write_config,
|
||||
)
|
||||
from app.converter import cancel_conversion, conversion_paths, finalize_validation
|
||||
from app.database import Base, engine, get_db
|
||||
from app.migrations import migrate_conf_file, run_db_migrations
|
||||
from app.models import IsoMovie
|
||||
from app.qbittorrent import QbittorrentClient, match_torrent
|
||||
from app.radarr import RadarrClient, movie_file_path
|
||||
from app.schemas import (
|
||||
ApiServiceSettingsRead,
|
||||
AuthCredentialsWrite,
|
||||
AuthSetupWrite,
|
||||
AuthUserRead,
|
||||
ConnectionResult,
|
||||
HealthRead,
|
||||
IsoMovieRead,
|
||||
QbittorrentSettingsRead,
|
||||
QbittorrentSettingsWrite,
|
||||
RadarrSettingsRead,
|
||||
RadarrSettingsWrite,
|
||||
ScanResult,
|
||||
SettingsRead,
|
||||
SettingsWrite,
|
||||
)
|
||||
from app.worker import conversion_worker
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_: FastAPI):
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
# Very small "migration" helper for dev: add new columns if the SQLite DB already exists.
|
||||
# (SQLAlchemy create_all doesn't alter existing tables.)
|
||||
# Migrations versionnees (base + conf.json), tracees au demarrage.
|
||||
db_applied = run_db_migrations(engine)
|
||||
if db_applied:
|
||||
print(f"migrations de base appliquees: {', '.join(db_applied)}", flush=True)
|
||||
conf_applied = migrate_conf_file()
|
||||
if conf_applied:
|
||||
print(f"migrations conf.json: {', '.join(conf_applied)}", flush=True)
|
||||
|
||||
auth.bootstrap_setup()
|
||||
_log_config_summary()
|
||||
worker_task = asyncio.create_task(conversion_worker())
|
||||
try:
|
||||
inspector = inspect(engine)
|
||||
columns = {col["name"] for col in inspector.get_columns("iso_movies")}
|
||||
if "processed_at" not in columns:
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("ALTER TABLE iso_movies ADD COLUMN processed_at DATETIME"))
|
||||
except Exception:
|
||||
# Don't fail app startup for a best-effort migration.
|
||||
pass
|
||||
yield
|
||||
yield
|
||||
finally:
|
||||
worker_task.cancel()
|
||||
|
||||
|
||||
app = FastAPI(title="MKVTool", version="0.1.0", lifespan=lifespan)
|
||||
@@ -57,29 +82,47 @@ app.add_middleware(
|
||||
DbSession = Annotated[Session, Depends(get_db)]
|
||||
|
||||
|
||||
def _api_service_read(url: str | None, api_key: str | None) -> ApiServiceSettingsRead:
|
||||
return ApiServiceSettingsRead(url=url, api_key_configured=api_key is not None)
|
||||
def _api_service_read(service: ApiServiceConfig) -> ApiServiceSettingsRead:
|
||||
return ApiServiceSettingsRead(
|
||||
url=service.url,
|
||||
port=service.port,
|
||||
api_key_configured=service.api_key is not None,
|
||||
status=service_status(service),
|
||||
tested_version=service.test.version,
|
||||
tested_at=service.test.at,
|
||||
test_error=service.test.error,
|
||||
)
|
||||
|
||||
|
||||
def _qbittorrent_read(qb: QbittorrentConfig) -> QbittorrentSettingsRead:
|
||||
return QbittorrentSettingsRead(
|
||||
url=qb.url,
|
||||
port=qb.port,
|
||||
username=qb.username,
|
||||
password_configured=qb.password is not None,
|
||||
api_key_configured=qb.api_key is not None,
|
||||
status=service_status(qb),
|
||||
tested_version=qb.test.version,
|
||||
tested_at=qb.test.at,
|
||||
test_error=qb.test.error,
|
||||
)
|
||||
|
||||
|
||||
def _settings_read() -> SettingsRead:
|
||||
cfg = read_config()
|
||||
return SettingsRead(
|
||||
radarr=_api_service_read(cfg.radarr.url, cfg.radarr.api_key),
|
||||
sonarr=_api_service_read(cfg.sonarr.url, cfg.sonarr.api_key),
|
||||
prowlarr=_api_service_read(cfg.prowlarr.url, cfg.prowlarr.api_key),
|
||||
jellyfin=_api_service_read(cfg.jellyfin.url, cfg.jellyfin.api_key),
|
||||
seerr=_api_service_read(cfg.seerr.url, cfg.seerr.api_key),
|
||||
qbittorrent=QbittorrentSettingsRead(
|
||||
url=cfg.qbittorrent.url,
|
||||
username=cfg.qbittorrent.username,
|
||||
password_configured=cfg.qbittorrent.password is not None,
|
||||
),
|
||||
radarr=_api_service_read(cfg.radarr),
|
||||
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),
|
||||
)
|
||||
|
||||
|
||||
def client_from_config() -> RadarrClient:
|
||||
cfg = read_config()
|
||||
url = (cfg.radarr.url or "").rstrip("/")
|
||||
url = build_base_url(cfg.radarr.url, cfg.radarr.port)
|
||||
api_key = cfg.radarr.api_key
|
||||
if not url or not api_key:
|
||||
raise HTTPException(status_code=409, detail="La connexion Radarr n'est pas configurée")
|
||||
@@ -99,8 +142,7 @@ def health() -> HealthRead:
|
||||
|
||||
@app.get("/api/settings/radarr", response_model=RadarrSettingsRead)
|
||||
def get_radarr_settings() -> RadarrSettingsRead:
|
||||
cfg = read_config()
|
||||
return RadarrSettingsRead(url=cfg.radarr.url, api_key_configured=cfg.radarr.api_key is not None)
|
||||
return _api_service_read(read_config().radarr)
|
||||
|
||||
|
||||
@app.put("/api/settings/radarr", response_model=RadarrSettingsRead)
|
||||
@@ -108,12 +150,20 @@ def put_radarr_settings(
|
||||
payload: RadarrSettingsWrite,
|
||||
) -> RadarrSettingsRead:
|
||||
cfg = read_config()
|
||||
url = str(payload.url).rstrip("/")
|
||||
url = str(payload.url).strip().rstrip("/")
|
||||
# Toute modification de la connexion invalide le dernier test.
|
||||
if (
|
||||
url != (cfg.radarr.url or "")
|
||||
or payload.port != cfg.radarr.port
|
||||
or (payload.api_key and payload.api_key != cfg.radarr.api_key)
|
||||
):
|
||||
reset_test(cfg.radarr)
|
||||
cfg.radarr.url = url
|
||||
cfg.radarr.port = payload.port
|
||||
if payload.api_key:
|
||||
cfg.radarr.api_key = payload.api_key
|
||||
write_config(cfg)
|
||||
return RadarrSettingsRead(url=url, api_key_configured=cfg.radarr.api_key is not None)
|
||||
return _api_service_read(cfg.radarr)
|
||||
|
||||
|
||||
@app.get("/api/settings", response_model=SettingsRead)
|
||||
@@ -128,6 +178,13 @@ def put_settings(payload: SettingsWrite) -> SettingsRead:
|
||||
def apply_service(target, patch):
|
||||
if patch is None:
|
||||
return
|
||||
changed = False
|
||||
if patch.url is not None and str(patch.url).rstrip("/") != (target.url or ""):
|
||||
changed = True
|
||||
if patch.api_key and patch.api_key != target.api_key:
|
||||
changed = True
|
||||
if changed:
|
||||
reset_test(target)
|
||||
if patch.url is not None:
|
||||
target.url = str(patch.url).rstrip("/")
|
||||
if patch.api_key:
|
||||
@@ -141,12 +198,20 @@ def put_settings(payload: SettingsWrite) -> SettingsRead:
|
||||
|
||||
if payload.qbittorrent is not None:
|
||||
qb = payload.qbittorrent
|
||||
qb_changed = bool(qb.url) and str(qb.url).rstrip("/") != (cfg.qbittorrent.url or "")
|
||||
qb_changed = qb_changed or bool(qb.username and qb.username != cfg.qbittorrent.username)
|
||||
qb_changed = qb_changed or bool(qb.password)
|
||||
qb_changed = qb_changed or bool(qb.api_key)
|
||||
if qb_changed:
|
||||
reset_test(cfg.qbittorrent)
|
||||
if qb.url is not None:
|
||||
cfg.qbittorrent.url = str(qb.url).rstrip("/")
|
||||
if qb.username:
|
||||
cfg.qbittorrent.username = qb.username
|
||||
if qb.password:
|
||||
cfg.qbittorrent.password = qb.password
|
||||
if qb.api_key:
|
||||
cfg.qbittorrent.api_key = qb.api_key
|
||||
|
||||
write_config(cfg)
|
||||
return _settings_read()
|
||||
@@ -158,13 +223,144 @@ async def test_radarr() -> ConnectionResult:
|
||||
try:
|
||||
status = await client.system_status()
|
||||
except (httpx.HTTPError, ValueError) as error:
|
||||
record_test("radarr", ok=False, error=str(error))
|
||||
raise HTTPException(
|
||||
status_code=502, detail=f"Connexion Radarr impossible: {error}"
|
||||
) from error
|
||||
version = str(status.get("version", "inconnue"))
|
||||
record_test("radarr", ok=True, version=version)
|
||||
return ConnectionResult(success=True, version=version, message=f"Radarr {version} accessible")
|
||||
|
||||
|
||||
# --- 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:
|
||||
qb = read_config().qbittorrent
|
||||
url = build_base_url(qb.url, qb.port)
|
||||
if not url:
|
||||
raise HTTPException(status_code=409, detail="La connexion qBittorrent n'est pas configurée")
|
||||
return QbittorrentClient(url, qb.username, qb.password, qb.api_key)
|
||||
|
||||
|
||||
@app.get("/api/settings/qbittorrent", response_model=QbittorrentSettingsRead)
|
||||
def get_qbittorrent_settings() -> QbittorrentSettingsRead:
|
||||
return _qbittorrent_read(read_config().qbittorrent)
|
||||
|
||||
|
||||
@app.put("/api/settings/qbittorrent", response_model=QbittorrentSettingsRead)
|
||||
def put_qbittorrent_settings(payload: QbittorrentSettingsWrite) -> QbittorrentSettingsRead:
|
||||
cfg = read_config()
|
||||
qb = cfg.qbittorrent
|
||||
qb_changed = payload.url is not None and str(payload.url).strip().rstrip("/") != (
|
||||
qb.url or ""
|
||||
)
|
||||
qb_changed = qb_changed or bool(payload.username and payload.username != qb.username)
|
||||
qb_changed = qb_changed or bool(payload.password)
|
||||
qb_changed = qb_changed or bool(payload.api_key)
|
||||
if qb_changed:
|
||||
reset_test(qb)
|
||||
if payload.url is not None:
|
||||
qb.url = str(payload.url).strip().rstrip("/")
|
||||
qb.port = payload.port
|
||||
if payload.username:
|
||||
qb.username = payload.username
|
||||
if payload.password:
|
||||
qb.password = payload.password
|
||||
elif payload.password:
|
||||
# Mot de passe seul: on conserve l'utilisateur existant.
|
||||
qb.password = payload.password
|
||||
else:
|
||||
# Champs vides: mode bypass d'authentification qBittorrent, sans identifiants.
|
||||
qb.username = None
|
||||
qb.password = None
|
||||
if payload.api_key:
|
||||
qb.api_key = payload.api_key
|
||||
write_config(cfg)
|
||||
return _qbittorrent_read(qb)
|
||||
|
||||
|
||||
@app.post("/api/settings/qbittorrent/test", response_model=ConnectionResult)
|
||||
async def test_qbittorrent() -> ConnectionResult:
|
||||
client = qbittorrent_from_config()
|
||||
try:
|
||||
version = await client.version()
|
||||
except (httpx.HTTPError, ValueError) as error:
|
||||
record_test("qbittorrent", ok=False, error=str(error))
|
||||
raise HTTPException(
|
||||
status_code=502, detail=f"Connexion qBittorrent impossible: {error}"
|
||||
) from error
|
||||
record_test("qbittorrent", ok=True, version=version)
|
||||
return ConnectionResult(
|
||||
success=True, version=version, message=f"qBittorrent {version} accessible"
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/movies", response_model=list[IsoMovieRead])
|
||||
def list_movies(db: DbSession) -> list[IsoMovie]:
|
||||
return list(db.scalars(select(IsoMovie).order_by(IsoMovie.title)).all())
|
||||
@@ -183,6 +379,38 @@ def get_file(file_id: int, db: DbSession) -> IsoMovie:
|
||||
return item
|
||||
|
||||
|
||||
def _log_config_summary() -> None:
|
||||
"""Rend visible au lancement le chargement de conf.json."""
|
||||
cfg = read_config()
|
||||
configured = [
|
||||
name
|
||||
for name in ("radarr", "sonarr", "prowlarr", "jellyfin", "seerr")
|
||||
if getattr(cfg, name).url
|
||||
]
|
||||
if cfg.qbittorrent.url:
|
||||
if cfg.qbittorrent.api_key:
|
||||
mode = "cle API"
|
||||
elif cfg.qbittorrent.username:
|
||||
mode = "identifiants"
|
||||
else:
|
||||
mode = "bypass d'authentification"
|
||||
configured.append(f"qbittorrent ({mode})")
|
||||
if configured:
|
||||
print(f"conf.json charge: {', '.join(configured)}", flush=True)
|
||||
else:
|
||||
print(
|
||||
"conf.json: aucune connexion configuree — a renseigner dans la page Configuration.",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
def _poster_url(movie: dict) -> str | None:
|
||||
for image in movie.get("images") or []:
|
||||
if image.get("coverType") == "poster":
|
||||
return str(image.get("remoteUrl") or image.get("url") or "") or None
|
||||
return None
|
||||
|
||||
|
||||
@app.post("/api/scans", response_model=ScanResult)
|
||||
async def scan_radarr(db: DbSession) -> ScanResult:
|
||||
client = client_from_config()
|
||||
@@ -193,6 +421,10 @@ async def scan_radarr(db: DbSession) -> ScanResult:
|
||||
|
||||
iso_files = created = updated = 0
|
||||
now = datetime.now(UTC)
|
||||
# Pastille "Radarr lie": on repart de zero, la boucle marque les films
|
||||
# toujours presents cote Radarr; les fichiers supprimes ou remplaces
|
||||
# passent donc a False.
|
||||
db.execute(update(IsoMovie).values(radarr_linked=False))
|
||||
for movie in movies:
|
||||
movie_file = movie.get("movieFile") or {}
|
||||
path = movie_file_path(movie)
|
||||
@@ -217,6 +449,8 @@ async def scan_radarr(db: DbSession) -> ScanResult:
|
||||
year=movie.get("year"),
|
||||
path=path,
|
||||
size=movie_file.get("size"),
|
||||
poster_url=_poster_url(movie),
|
||||
radarr_linked=True,
|
||||
last_seen_at=now,
|
||||
)
|
||||
db.add(item)
|
||||
@@ -226,9 +460,200 @@ async def scan_radarr(db: DbSession) -> ScanResult:
|
||||
item.year = movie.get("year")
|
||||
item.path = path
|
||||
item.size = movie_file.get("size")
|
||||
item.poster_url = _poster_url(movie)
|
||||
item.radarr_linked = True
|
||||
item.last_seen_at = now
|
||||
updated += 1
|
||||
db.commit()
|
||||
return ScanResult(
|
||||
scanned_movies=len(movies), iso_files=iso_files, created=created, updated=updated
|
||||
)
|
||||
|
||||
|
||||
# --- Conversion (file traitee par le worker, une tache a la fois) ---
|
||||
def _linked_mkv(movie: IsoMovie) -> Path | None:
|
||||
"""Retrouve le MKV lie dans le dossier du film (meme inode que la source)."""
|
||||
paths = conversion_paths(movie)
|
||||
if not paths.destination_folder.is_dir():
|
||||
return None
|
||||
candidates = sorted(
|
||||
entry
|
||||
for entry in paths.destination_folder.iterdir()
|
||||
if entry.is_file() and entry.suffix.lower() == ".mkv"
|
||||
)
|
||||
if not candidates:
|
||||
return None
|
||||
if paths.mkv_path.exists():
|
||||
source_inode = paths.mkv_path.stat().st_ino
|
||||
for candidate in candidates:
|
||||
if candidate.stat().st_ino == source_inode:
|
||||
return candidate
|
||||
return candidates[0]
|
||||
|
||||
|
||||
async def _delete_iso_torrent(iso_path: str) -> None:
|
||||
"""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
|
||||
url = build_base_url(qb.url, qb.port)
|
||||
if not url:
|
||||
return
|
||||
try:
|
||||
client = QbittorrentClient(url, qb.username, qb.password, qb.api_key)
|
||||
torrents = await client.torrents()
|
||||
match = match_torrent(torrents, iso_path)
|
||||
if match is not None and match.get("hash"):
|
||||
await client.delete([str(match["hash"])], delete_files=True)
|
||||
except Exception: # noqa: BLE001 - qBittorrent ne doit pas bloquer la validation
|
||||
pass
|
||||
|
||||
|
||||
@app.post("/api/movies/{movie_id}/convert", response_model=IsoMovieRead)
|
||||
def convert_movie(movie_id: int, db: DbSession) -> IsoMovie:
|
||||
movie = db.get(IsoMovie, movie_id)
|
||||
if movie is None:
|
||||
raise HTTPException(status_code=404, detail="Film introuvable")
|
||||
if movie.status not in {"detected", "ready", "failed"}:
|
||||
raise HTTPException(
|
||||
status_code=409, detail="Ce film n'est pas convertible dans son état actuel"
|
||||
)
|
||||
movie.status = "queued"
|
||||
movie.failed_step = None
|
||||
movie.last_error = None
|
||||
db.commit()
|
||||
return movie
|
||||
|
||||
|
||||
@app.post("/api/movies/{movie_id}/cancel", response_model=IsoMovieRead)
|
||||
def cancel_movie(movie_id: int, db: DbSession) -> IsoMovie:
|
||||
movie = db.get(IsoMovie, movie_id)
|
||||
if movie is None:
|
||||
raise HTTPException(status_code=404, detail="Film introuvable")
|
||||
if movie.status not in {"queued", "validating"}:
|
||||
raise HTTPException(status_code=409, detail="Aucune conversion à annuler")
|
||||
if movie.status == "validating":
|
||||
paths = conversion_paths(movie)
|
||||
linked = _linked_mkv(movie)
|
||||
cancel_conversion(paths.mkv_path, paths.destination_folder, linked.name if linked else None)
|
||||
movie.status = "detected"
|
||||
db.commit()
|
||||
return movie
|
||||
|
||||
|
||||
@app.post("/api/movies/{movie_id}/validate", response_model=IsoMovieRead)
|
||||
async def validate_movie(movie_id: int, db: DbSession) -> IsoMovie:
|
||||
"""Validation manuelle: supprime l'ISO, le torrent et le dossier de travail.
|
||||
|
||||
Le MKV lie dans le dossier du film reste en place (le lien dur etant sur
|
||||
le meme inode, les donnees restent intactes).
|
||||
"""
|
||||
movie = db.get(IsoMovie, movie_id)
|
||||
if movie is None:
|
||||
raise HTTPException(status_code=404, detail="Film introuvable")
|
||||
if movie.status != "validating":
|
||||
raise HTTPException(status_code=409, detail="Ce film n'est pas en attente de validation")
|
||||
|
||||
paths = conversion_paths(movie)
|
||||
linked = _linked_mkv(movie)
|
||||
if linked is None:
|
||||
raise HTTPException(status_code=409, detail="Aucun MKV lié à valider")
|
||||
|
||||
# Supprime l'ISO et le reste du dossier du film, puis le torrent qBittorrent.
|
||||
finalize_validation(paths.destination_folder, linked.name)
|
||||
await _delete_iso_torrent(movie.path)
|
||||
|
||||
# Nettoyage du dossier de travail (le lien dur garde les donnees).
|
||||
if linked.exists() and paths.mkv_path.exists():
|
||||
paths.mkv_path.unlink()
|
||||
if paths.mkv_path.parent.is_dir() and not any(paths.mkv_path.parent.iterdir()):
|
||||
paths.mkv_path.parent.rmdir()
|
||||
|
||||
movie.status = "completed"
|
||||
now = datetime.now(UTC)
|
||||
movie.processed_at = now
|
||||
movie.completed_at = now
|
||||
db.commit()
|
||||
return movie
|
||||
|
||||
|
||||
@app.delete("/api/movies/{movie_id}", response_model=IsoMovieRead)
|
||||
def delete_movie(movie_id: int, db: DbSession) -> IsoMovie:
|
||||
movie = db.get(IsoMovie, movie_id)
|
||||
if movie is None:
|
||||
raise HTTPException(status_code=404, detail="Film introuvable")
|
||||
if movie.status in {"queued", "converting", "importing", "validating"}:
|
||||
raise HTTPException(
|
||||
status_code=409, detail="Une conversion est en cours: impossible de retirer ce film"
|
||||
)
|
||||
snapshot = IsoMovieRead.model_validate(movie)
|
||||
db.delete(movie)
|
||||
db.commit()
|
||||
return snapshot
|
||||
|
||||
|
||||
# --- Authentification locale ---
|
||||
# Premier lancement: le lien affiche dans les logs par bootstrap_setup() porte
|
||||
# un jeton a usage unique; il disparait des qu'un compte existe.
|
||||
@app.post("/api/auth/setup", response_model=AuthUserRead)
|
||||
def auth_setup(payload: AuthSetupWrite, response: Response) -> AuthUserRead:
|
||||
if auth.setup_token is None or payload.token != auth.setup_token:
|
||||
raise HTTPException(status_code=403, detail="Lien de création invalide ou expiré")
|
||||
if auth.user_count() > 0:
|
||||
raise HTTPException(status_code=403, detail="Un compte existe déjà")
|
||||
user_id = auth.create_user(payload.username, payload.password)
|
||||
auth.setup_token = None
|
||||
response.set_cookie(
|
||||
auth.SESSION_COOKIE, auth.create_session(user_id), httponly=True, samesite="lax"
|
||||
)
|
||||
return AuthUserRead(username=payload.username)
|
||||
|
||||
|
||||
@app.post("/api/auth/login", response_model=AuthUserRead)
|
||||
def auth_login(payload: AuthCredentialsWrite, response: Response) -> AuthUserRead:
|
||||
user_id = auth.check_credentials(payload.username, payload.password)
|
||||
if user_id is None:
|
||||
raise HTTPException(status_code=401, detail="Identifiants incorrects")
|
||||
response.set_cookie(
|
||||
auth.SESSION_COOKIE, auth.create_session(user_id), httponly=True, samesite="lax"
|
||||
)
|
||||
return AuthUserRead(username=payload.username)
|
||||
|
||||
|
||||
@app.get("/api/auth/me", response_model=AuthUserRead)
|
||||
def auth_me(user_id: int = Depends(auth.current_user)) -> AuthUserRead:
|
||||
username = auth.get_username(user_id)
|
||||
if username is None:
|
||||
raise HTTPException(status_code=401, detail="Non authentifié")
|
||||
return AuthUserRead(username=username)
|
||||
|
||||
|
||||
@app.post("/api/auth/logout")
|
||||
def auth_logout(
|
||||
response: Response,
|
||||
mkvtool_session: str | None = Cookie(default=None, alias=auth.SESSION_COOKIE),
|
||||
) -> dict[str, bool]:
|
||||
auth.end_session(mkvtool_session)
|
||||
response.delete_cookie(auth.SESSION_COOKIE)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# Service du front : sert web/dist (fourni par l'image via MKVTOOL_WEB_DIR).
|
||||
# Le catch-all est declare en dernier, donc les routes /api ci-dessus gardent la
|
||||
# priorite; les chemins inconnus (ex: /setup?token=...) renvoient le SPA pour
|
||||
# son routage cote client. En dev (vite sur :5173), la variable est absente.
|
||||
web_dir = os.environ.get("MKVTOOL_WEB_DIR")
|
||||
if web_dir and os.path.isdir(web_dir):
|
||||
|
||||
@app.get("/{full_path:path}", include_in_schema=False)
|
||||
async def serve_web(full_path: str) -> FileResponse:
|
||||
if full_path.startswith("api/"):
|
||||
raise HTTPException(status_code=404, detail="Route inconnue")
|
||||
root = Path(web_dir).resolve()
|
||||
candidate = (root / full_path).resolve()
|
||||
if full_path and candidate.is_file() and candidate.is_relative_to(root):
|
||||
return FileResponse(candidate)
|
||||
return FileResponse(root / "index.html")
|
||||
@@ -0,0 +1,156 @@
|
||||
"""Migrations versionnees de la base de donnees et de conf.json.
|
||||
|
||||
Chaque evolution de structure est une migration identifiee par un numero de
|
||||
version. Au demarrage, les migrations non appliquees sont jouees une seule
|
||||
fois et tracees :
|
||||
|
||||
- base de donnees : table ``schema_migrations`` (une ligne par version) ;
|
||||
- conf.json : cle ``version`` en tete du fichier.
|
||||
|
||||
Conventions importantes :
|
||||
|
||||
- ``Base.metadata.create_all`` cree deja le schema le plus recent sur une
|
||||
base vierge. Les migrations de base doivent donc etre inoffensives sur un
|
||||
schema deja a jour (verifier l'existence des tables/colonnes avant d'agir).
|
||||
- Les migrations sont appliquees dans l'ordre, chacune dans sa transaction,
|
||||
et enregistrees dans la meme transaction : une migration echouee laisse la
|
||||
base dans l'etat de la version precedente.
|
||||
|
||||
Pour ajouter une migration :
|
||||
|
||||
- base de donnees : ajouter un ``DbMigration`` en fin de ``DB_MIGRATIONS``
|
||||
avec le numero de version suivant ;
|
||||
- conf.json : ajouter une fonction ``(dict) -> dict`` en fin de
|
||||
``CONF_MIGRATIONS`` (elle transforme la version N vers N+1), puis mettre a
|
||||
jour la valeur par défaut de ``AppConfig.version`` dans conf_store.py.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import Connection, inspect, text
|
||||
from sqlalchemy.engine import Engine
|
||||
|
||||
from app.conf_store import read_raw_config, write_raw_config
|
||||
|
||||
|
||||
# --- Migrations de la base de donnees ---
|
||||
@dataclass(frozen=True)
|
||||
class DbMigration:
|
||||
"""Une migration de base : version cible, description, corps."""
|
||||
|
||||
version: int
|
||||
description: str
|
||||
upgrade: Callable[[Connection], None]
|
||||
|
||||
|
||||
def _upgrade_v1(conn: Connection) -> None:
|
||||
"""Colonnes de suivi des conversions (bases creees avant le systeme)."""
|
||||
inspector = inspect(conn)
|
||||
if not inspector.has_table("iso_movies"):
|
||||
return
|
||||
columns = {col["name"] for col in inspector.get_columns("iso_movies")}
|
||||
new_columns = {
|
||||
"processed_at": "DATETIME",
|
||||
"completed_at": "DATETIME",
|
||||
"failed_step": "TEXT",
|
||||
"last_error": "TEXT",
|
||||
"poster_url": "TEXT",
|
||||
"radarr_linked": "BOOLEAN DEFAULT 1",
|
||||
}
|
||||
for column, ddl in new_columns.items():
|
||||
if column not in columns:
|
||||
conn.execute(text(f"ALTER TABLE iso_movies ADD COLUMN {column} {ddl}"))
|
||||
|
||||
|
||||
DB_MIGRATIONS: list[DbMigration] = [
|
||||
DbMigration(
|
||||
version=1,
|
||||
description="iso_movies: colonnes de suivi des conversions",
|
||||
upgrade=_upgrade_v1,
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def run_db_migrations(engine: Engine) -> list[str]:
|
||||
"""Applique les migrations non jouees; renvoie leurs descriptions."""
|
||||
with engine.begin() as conn:
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version INTEGER PRIMARY KEY,
|
||||
description TEXT NOT NULL,
|
||||
applied_at TEXT NOT NULL
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
with engine.connect() as conn:
|
||||
applied = {
|
||||
row[0] for row in conn.execute(text("SELECT version FROM schema_migrations"))
|
||||
}
|
||||
|
||||
done: list[str] = []
|
||||
for migration in DB_MIGRATIONS:
|
||||
if migration.version in applied:
|
||||
continue
|
||||
with engine.begin() as conn:
|
||||
migration.upgrade(conn)
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO schema_migrations (version, description, applied_at)
|
||||
VALUES (:version, :description, :applied_at)
|
||||
"""
|
||||
),
|
||||
{
|
||||
"version": migration.version,
|
||||
"description": migration.description,
|
||||
"applied_at": datetime.now(UTC).isoformat(),
|
||||
},
|
||||
)
|
||||
done.append(migration.description)
|
||||
return done
|
||||
|
||||
|
||||
# --- Migrations de conf.json ---
|
||||
# CONF_MIGRATIONS[i] transforme le contenu brut du fichier de la version
|
||||
# i+1 vers i+2. La version courante de la structure suit la longueur de
|
||||
# cette liste; elle doit rester synchrone avec AppConfig.version par defaut.
|
||||
CONF_MIGRATIONS: list[Callable[[dict], dict]] = []
|
||||
|
||||
|
||||
def current_conf_version() -> int:
|
||||
return 1 + len(CONF_MIGRATIONS)
|
||||
|
||||
|
||||
def migrate_conf_file() -> list[str]:
|
||||
"""Migre conf.json vers la version courante de la structure.
|
||||
|
||||
Un fichier sans cle ``version`` est considere comme v1 (structure
|
||||
d'avant la mise en place du systeme). Renvoie la liste des migrations
|
||||
appliquees, pour trace au demarrage.
|
||||
"""
|
||||
raw = read_raw_config()
|
||||
if raw is None:
|
||||
return []
|
||||
|
||||
version = raw.get("version")
|
||||
if not isinstance(version, int):
|
||||
version = 1
|
||||
|
||||
applied: list[str] = []
|
||||
for step, migrate in enumerate(CONF_MIGRATIONS, start=1):
|
||||
if version > step:
|
||||
continue
|
||||
raw = migrate(raw)
|
||||
applied.append(f"conf.json v{step} -> v{step + 1}")
|
||||
|
||||
target = current_conf_version()
|
||||
if raw.get("version") != target:
|
||||
raw["version"] = target
|
||||
write_raw_config(raw)
|
||||
return applied
|
||||
+16
-1
@@ -1,6 +1,6 @@
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import BigInteger, DateTime, String, Text, UniqueConstraint, func
|
||||
from sqlalchemy import BigInteger, Boolean, DateTime, String, Text, UniqueConstraint, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.database import Base
|
||||
@@ -25,8 +25,23 @@ class IsoMovie(Base):
|
||||
path: Mapped[str] = mapped_column(Text)
|
||||
size: Mapped[int | None] = mapped_column(BigInteger)
|
||||
status: Mapped[str] = mapped_column(String(30), default="detected")
|
||||
# Le fichier ISO existe toujours tel quel cote Radarr (mis a jour au scan).
|
||||
radarr_linked: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
poster_url: Mapped[str | None] = mapped_column(Text)
|
||||
last_seen_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now()
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
processed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
completed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
failed_step: Mapped[str | None] = mapped_column(String(30))
|
||||
last_error: Mapped[str | None] = mapped_column(Text)
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
username: Mapped[str] = mapped_column(String(100), unique=True)
|
||||
password_hash: Mapped[str] = mapped_column(String(255))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
+36
-10
@@ -6,25 +6,51 @@ import httpx
|
||||
|
||||
|
||||
class QbittorrentClient:
|
||||
def __init__(self, url: str, username: str, password: str) -> None:
|
||||
"""Client WebUI (API v2).
|
||||
|
||||
Modes d'authentification, dans l'ordre de priorite:
|
||||
|
||||
1. Cle API (qBittorrent >= 5.2): envoyee en en-tete ``Authorization:
|
||||
Bearer <cle>`` sur chaque appel, sans login ni session.
|
||||
2. Identifiants (login ``POST /api/v2/auth/login`` + cookie de session).
|
||||
qBittorrent >= 5.2 repond 204 sans corps; les versions anterieures
|
||||
renvoient 200 avec le corps "Ok.".
|
||||
3. Sans rien: bypass d'authentification qBittorrent (la plage IP du
|
||||
conteneur doit etre autorisee dans la WebUI), aucune API key native
|
||||
n'existait avant la 5.2.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
url: str,
|
||||
username: str | None = None,
|
||||
password: str | None = None,
|
||||
api_key: str | None = None,
|
||||
) -> None:
|
||||
self._url = url.rstrip("/")
|
||||
self._username = username
|
||||
self._password = password
|
||||
self._api_key = api_key
|
||||
|
||||
async def _request(self, method: str, endpoint: str, **kwargs) -> httpx.Response:
|
||||
headers = {"Referer": self._url}
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
login = await client.post(
|
||||
f"{self._url}/api/v2/auth/login",
|
||||
data={"username": self._username, "password": self._password},
|
||||
headers={"Referer": self._url},
|
||||
)
|
||||
login.raise_for_status()
|
||||
if login.text.strip() != "Ok.":
|
||||
raise ValueError("Authentification qBittorrent refusée")
|
||||
if self._api_key:
|
||||
headers["Authorization"] = f"Bearer {self._api_key}"
|
||||
elif self._username and self._password:
|
||||
login = await client.post(
|
||||
f"{self._url}/api/v2/auth/login",
|
||||
data={"username": self._username, "password": self._password},
|
||||
headers={"Referer": self._url},
|
||||
)
|
||||
login.raise_for_status()
|
||||
# qBittorrent >= 5.2 renvoie 204 sans corps.
|
||||
if login.status_code != 204 and login.text.strip() != "Ok.":
|
||||
raise ValueError("Authentification qBittorrent refusée")
|
||||
response = await client.request(
|
||||
method,
|
||||
f"{self._url}{endpoint}",
|
||||
headers={"Referer": self._url},
|
||||
headers=headers,
|
||||
**kwargs,
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
+47
-5
@@ -1,38 +1,60 @@
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, HttpUrl
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class RadarrSettingsRead(BaseModel):
|
||||
url: str | None
|
||||
port: int | None = None
|
||||
api_key_configured: bool
|
||||
status: str
|
||||
tested_version: str | None = None
|
||||
tested_at: str | None = None
|
||||
test_error: str | None = None
|
||||
|
||||
|
||||
class RadarrSettingsWrite(BaseModel):
|
||||
url: HttpUrl
|
||||
url: str
|
||||
port: int | None = Field(default=None, ge=1, le=65535)
|
||||
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: HttpUrl | None = None
|
||||
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):
|
||||
url: str | None
|
||||
port: int | None = None
|
||||
username: str | None
|
||||
password_configured: bool
|
||||
api_key_configured: bool
|
||||
status: str
|
||||
tested_version: str | None = None
|
||||
tested_at: str | None = None
|
||||
test_error: str | None = None
|
||||
|
||||
|
||||
class QbittorrentSettingsWrite(BaseModel):
|
||||
url: HttpUrl | None = None
|
||||
username: str | None = Field(default=None, min_length=1)
|
||||
url: str | None = None
|
||||
port: int | None = Field(default=None, ge=1, le=65535)
|
||||
# Utilisateur vide = bypass d'authentification qBittorrent.
|
||||
username: str | None = None
|
||||
password: str | None = Field(default=None, min_length=1)
|
||||
# Cle API native qBittorrent >= 5.2, prioritaire sur le login.
|
||||
api_key: str | None = Field(default=None, min_length=1)
|
||||
|
||||
|
||||
class SettingsRead(BaseModel):
|
||||
@@ -70,9 +92,14 @@ class IsoMovieRead(BaseModel):
|
||||
path: str
|
||||
size: int | None
|
||||
status: str
|
||||
radarr_linked: bool = True
|
||||
poster_url: str | None = None
|
||||
last_seen_at: datetime
|
||||
created_at: datetime | None = None
|
||||
processed_at: datetime | None = None
|
||||
completed_at: datetime | None = None
|
||||
failed_step: str | None = None
|
||||
last_error: str | None = None
|
||||
|
||||
|
||||
class ScanResult(BaseModel):
|
||||
@@ -87,3 +114,18 @@ class HealthRead(BaseModel):
|
||||
database: str
|
||||
makemkv_available: bool
|
||||
makemkv_version: str | None
|
||||
|
||||
|
||||
class AuthSetupWrite(BaseModel):
|
||||
token: str
|
||||
username: str
|
||||
password: str
|
||||
|
||||
|
||||
class AuthCredentialsWrite(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
|
||||
|
||||
class AuthUserRead(BaseModel):
|
||||
username: str
|
||||
@@ -6,11 +6,12 @@ The project now externalises its configuration into ./config/conf.json.
|
||||
This module is kept temporarily because some imports may still reference it.
|
||||
"""
|
||||
|
||||
from app.conf_store import read_config
|
||||
from app.conf_store import build_base_url, read_config
|
||||
|
||||
|
||||
def radarr_credentials(_: object | None = None) -> tuple[str, str]:
|
||||
cfg = read_config()
|
||||
if not cfg.radarr.url or not cfg.radarr.api_key:
|
||||
url = build_base_url(cfg.radarr.url, cfg.radarr.port)
|
||||
if not url or not cfg.radarr.api_key:
|
||||
raise ValueError("La connexion Radarr n'est pas configurée")
|
||||
return cfg.radarr.url.rstrip("/"), cfg.radarr.api_key
|
||||
return url, cfg.radarr.api_key
|
||||
+12
-2
@@ -2,11 +2,12 @@
|
||||
|
||||
import asyncio
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.config import settings
|
||||
from app.converter import conversion_paths, extract_mkv, import_mkv
|
||||
from app.converter import container_iso_path, conversion_paths, extract_mkv, import_mkv
|
||||
from app.database import SessionLocal
|
||||
from app.models import IsoMovie
|
||||
|
||||
@@ -29,7 +30,16 @@ async def _process(movie_id: int) -> None:
|
||||
step = "importing"
|
||||
movie.status = "importing"
|
||||
db.commit()
|
||||
await asyncio.to_thread(import_mkv, paths.mkv_path, paths.destination_folder)
|
||||
# Le MKV lié reprend le nom du fichier Radarr (l'ISO), seule
|
||||
# l'extension change.
|
||||
target_name = f"{Path(movie.path).stem}.mkv"
|
||||
await asyncio.to_thread(
|
||||
import_mkv,
|
||||
paths.mkv_path,
|
||||
paths.destination_folder,
|
||||
target_name,
|
||||
[container_iso_path(movie)],
|
||||
)
|
||||
# Le passage en "completed" (ISO supprimee) se fait manuellement
|
||||
# via l'endpoint de validation apres verification par l'utilisateur.
|
||||
movie.status = "validating"
|
||||
|
||||
+8
-3
@@ -22,9 +22,14 @@ services:
|
||||
TZ: "Europe/Paris"
|
||||
# Sur le NAS: desactiver la simulation MakeMKV.
|
||||
MKVTOOL_SIMULATE_CONVERSION: "false"
|
||||
# Dossiers vus par l'API: la bibliotheque est montee en /films.
|
||||
MKVTOOL_FILMS_DIR: /films
|
||||
# Chemin de la bibliotheque tel que Radarr le rapporte (traduction ISO).
|
||||
MKVTOOL_RADARR_FILMS_DIR: /nas_storage/jellyfin/films
|
||||
MKVTOOL_DOWNLOADS_DIR: /qbittorrentdownloads
|
||||
volumes:
|
||||
# Montages aux MEMES chemins que Radarr/qBittorrent: les chemins ISO
|
||||
# enregistres par le scan restent valides tels quels.
|
||||
# La bibliotheque Jellyfin est montee en /films dans le conteneur; les
|
||||
# chemins Radarr (MKVTOOL_RADARR_FILMS_DIR) sont traduits par l'API.
|
||||
- /volume1/docker/mkvtool:/config
|
||||
- /qbittorrentdownloads:/qbittorrentdownloads
|
||||
- /nas_storage/jellyfin/films:/nas_storage/jellyfin/films
|
||||
- /nas_storage/jellyfin/films:/films
|
||||
+5
-1
@@ -4,4 +4,8 @@ from pathlib import Path
|
||||
|
||||
_test_config = Path(tempfile.mkdtemp(prefix="mkvtool-tests-"))
|
||||
os.environ["MKVTOOL_CONFIG_DIR"] = str(_test_config)
|
||||
|
||||
os.environ["MKVTOOL_FILMS_DIR"] = str(_test_config / "films")
|
||||
os.environ["MKVTOOL_RADARR_FILMS_DIR"] = str(_test_config / "radarr")
|
||||
os.environ["MKVTOOL_DOWNLOADS_DIR"] = str(_test_config / "downloads")
|
||||
os.environ["MKVTOOL_SIMULATE_CONVERSION"] = "true"
|
||||
os.environ["MKVTOOL_WORKER_INTERVAL"] = "0.05"
|
||||
@@ -1,8 +1,14 @@
|
||||
import json
|
||||
|
||||
import respx
|
||||
from fastapi.testclient import TestClient
|
||||
from httpx import Response
|
||||
|
||||
from app import auth as auth_module
|
||||
from app.conf_store import config_path
|
||||
from app.database import SessionLocal
|
||||
from app.main import app
|
||||
from app.models import User
|
||||
|
||||
|
||||
def configure_radarr(client: TestClient) -> None:
|
||||
@@ -32,6 +38,109 @@ def test_radarr_connection() -> None:
|
||||
assert response.json()["version"] == "5.27.0"
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_service_status_lifecycle() -> None:
|
||||
"""Statut par service: configured -> tested apres un test reussi, puis
|
||||
retour a configured quand la configuration change.
|
||||
|
||||
Utilise une URL distincte des autres tests: conf.json etant partage entre
|
||||
les tests, il faut garantir un reset du statut herite.
|
||||
"""
|
||||
respx.get("http://radarr-lifecycle:7878/api/v3/system/status").mock(
|
||||
return_value=Response(200, json={"version": "5.27.0"})
|
||||
)
|
||||
with TestClient(app) as client:
|
||||
response = client.put(
|
||||
"/api/settings/radarr",
|
||||
json={"url": "http://radarr-lifecycle:7878", "api_key": "test-key"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
# Configure mais pas encore teste.
|
||||
settings = client.get("/api/settings").json()
|
||||
assert settings["radarr"]["status"] == "configured"
|
||||
assert settings["qbittorrent"]["status"] in {"configured", "unconfigured"}
|
||||
|
||||
client.post("/api/settings/radarr/test")
|
||||
settings = client.get("/api/settings").json()
|
||||
assert settings["radarr"]["status"] == "tested"
|
||||
assert settings["radarr"]["tested_version"] == "5.27.0"
|
||||
assert settings["radarr"]["tested_at"] is not None
|
||||
|
||||
# Le resultat du test est persiste dans conf.json.
|
||||
raw = json.loads(config_path().read_text(encoding="utf-8"))
|
||||
assert raw["radarr"]["test"]["ok"] is True
|
||||
assert raw["radarr"]["test"]["version"] == "5.27.0"
|
||||
|
||||
# Modifier l'URL invalide le statut de test.
|
||||
client.put(
|
||||
"/api/settings/radarr",
|
||||
json={"url": "http://radarr-alt:7878", "api_key": None},
|
||||
)
|
||||
settings = client.get("/api/settings").json()
|
||||
assert settings["radarr"]["status"] == "configured"
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_failed_test_marks_service_as_error() -> None:
|
||||
respx.get("http://radarr-fail:7878/api/v3/system/status").mock(
|
||||
return_value=Response(500, text="boom")
|
||||
)
|
||||
with TestClient(app) as client:
|
||||
client.put(
|
||||
"/api/settings/radarr",
|
||||
json={"url": "http://radarr-fail:7878", "api_key": "test-key"},
|
||||
)
|
||||
response = client.post("/api/settings/radarr/test")
|
||||
assert response.status_code == 502
|
||||
settings = client.get("/api/settings").json()
|
||||
assert settings["radarr"]["status"] == "error"
|
||||
assert settings["radarr"]["test_error"] is not None
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_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
|
||||
def test_qbittorrent_status_lifecycle() -> None:
|
||||
respx.get("http://qbit-lifecycle:8080/api/v2/app/version").mock(
|
||||
return_value=Response(200, text="v5.0.2")
|
||||
)
|
||||
with TestClient(app) as client:
|
||||
client.put(
|
||||
"/api/settings/qbittorrent",
|
||||
json={"url": "http://qbit-lifecycle:8080", "port": 8080},
|
||||
)
|
||||
assert client.post("/api/settings/qbittorrent/test").status_code == 200
|
||||
settings = client.get("/api/settings").json()
|
||||
assert settings["qbittorrent"]["status"] == "tested"
|
||||
assert settings["qbittorrent"]["tested_version"] == "v5.0.2"
|
||||
|
||||
# Un nouvel enregistrement (URL differente) reinitialise le statut de test.
|
||||
client.put(
|
||||
"/api/settings/qbittorrent",
|
||||
json={"url": "http://qbit-alt:8080", "port": 8080},
|
||||
)
|
||||
settings = client.get("/api/settings").json()
|
||||
assert settings["qbittorrent"]["status"] == "configured"
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_scan_only_imports_iso_files() -> None:
|
||||
respx.get("http://radarr:7878/api/v3/movie?includeMovieFile=true").mock(
|
||||
@@ -70,3 +179,182 @@ def test_scan_only_imports_iso_files() -> None:
|
||||
assert scan.status_code == 200
|
||||
assert scan.json()["iso_files"] == 1
|
||||
assert [movie["title"] for movie in movies.json()] == ["ISO Movie"]
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_qbittorrent_connection_local_address_with_port() -> None:
|
||||
# Adresse locale sans schema + port separe: l'URL de base doit etre
|
||||
# reconstruite en http://192.168.1.50:8080.
|
||||
respx.post("http://192.168.1.50:8080/api/v2/auth/login").mock(
|
||||
return_value=Response(200, text="Ok.")
|
||||
)
|
||||
respx.get("http://192.168.1.50:8080/api/v2/app/version").mock(
|
||||
return_value=Response(200, text="v5.0.2")
|
||||
)
|
||||
with TestClient(app) as client:
|
||||
response = client.put(
|
||||
"/api/settings/qbittorrent",
|
||||
json={
|
||||
"url": "192.168.1.50",
|
||||
"port": 8080,
|
||||
"username": "admin",
|
||||
"password": "pass",
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["port"] == 8080
|
||||
test = client.post("/api/settings/qbittorrent/test")
|
||||
assert test.status_code == 200
|
||||
assert test.json()["version"] == "v5.0.2"
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_qbittorrent_connection_without_credentials() -> None:
|
||||
"""Sans identifiants (bypass d'authentification qBittorrent): aucun login,
|
||||
l'API est appelee directement."""
|
||||
respx.post("http://192.168.1.50:8555/api/v2/auth/login").mock(
|
||||
return_value=Response(404)
|
||||
)
|
||||
respx.get("http://192.168.1.50:8555/api/v2/app/version").mock(
|
||||
return_value=Response(200, text="v5.0.2")
|
||||
)
|
||||
with TestClient(app) as client:
|
||||
put = client.put(
|
||||
"/api/settings/qbittorrent",
|
||||
json={"url": "192.168.1.50", "port": 8555, "username": "", "password": None},
|
||||
)
|
||||
assert put.status_code == 200
|
||||
assert put.json()["password_configured"] is False
|
||||
test = client.post("/api/settings/qbittorrent/test")
|
||||
assert test.status_code == 200
|
||||
assert test.json()["version"] == "v5.0.2"
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_qbittorrent_login_204_modern() -> None:
|
||||
"""qBittorrent >= 5.2: le login repond 204 sans corps (plus "200 Ok.")."""
|
||||
respx.post("http://192.168.1.50:8080/api/v2/auth/login").mock(
|
||||
return_value=Response(204)
|
||||
)
|
||||
respx.get("http://192.168.1.50:8080/api/v2/app/version").mock(
|
||||
return_value=Response(200, text="v5.2.0")
|
||||
)
|
||||
with TestClient(app) as client:
|
||||
client.put(
|
||||
"/api/settings/qbittorrent",
|
||||
json={
|
||||
"url": "192.168.1.50",
|
||||
"port": 8080,
|
||||
"username": "admin",
|
||||
"password": "pass",
|
||||
},
|
||||
)
|
||||
test = client.post("/api/settings/qbittorrent/test")
|
||||
assert test.status_code == 200
|
||||
assert test.json()["version"] == "v5.2.0"
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_qbittorrent_api_key_mode() -> None:
|
||||
"""Cle API native (qBittorrent >= 5.2): en-tete Authorization: Bearer sur
|
||||
chaque appel, aucun login."""
|
||||
login_route = respx.post("http://192.168.1.50:8080/api/v2/auth/login").mock(
|
||||
return_value=Response(404)
|
||||
)
|
||||
version_route = respx.get("http://192.168.1.50:8080/api/v2/app/version").mock(
|
||||
return_value=Response(200, text="v5.2.0")
|
||||
)
|
||||
with TestClient(app) as client:
|
||||
put = client.put(
|
||||
"/api/settings/qbittorrent",
|
||||
json={"url": "192.168.1.50", "port": 8080, "api_key": "qbt_test_key"},
|
||||
)
|
||||
assert put.json()["api_key_configured"] is True
|
||||
test = client.post("/api/settings/qbittorrent/test")
|
||||
raw = json.loads(config_path().read_text(encoding="utf-8"))
|
||||
assert test.status_code == 200
|
||||
assert test.json()["version"] == "v5.2.0"
|
||||
assert not login_route.called
|
||||
assert version_route.called
|
||||
assert (
|
||||
version_route.calls.last.request.headers["authorization"] == "Bearer qbt_test_key"
|
||||
)
|
||||
assert raw["qbittorrent"]["api_key"] == "qbt_test_key"
|
||||
|
||||
|
||||
def test_settings_persist_to_conf_json() -> None:
|
||||
with TestClient(app) as client:
|
||||
put = client.put(
|
||||
"/api/settings/qbittorrent",
|
||||
json={
|
||||
"url": "http://qbit:8080/",
|
||||
"port": 8080,
|
||||
"username": "admin",
|
||||
"password": "pass",
|
||||
},
|
||||
)
|
||||
got = client.get("/api/settings/qbittorrent")
|
||||
assert put.status_code == 200
|
||||
assert put.json()["password_configured"] is True
|
||||
assert got.json()["url"] == "http://qbit:8080"
|
||||
assert got.json()["port"] == 8080
|
||||
raw = json.loads(config_path().read_text(encoding="utf-8"))
|
||||
assert raw["qbittorrent"]["url"] == "http://qbit:8080"
|
||||
assert raw["qbittorrent"]["port"] == 8080
|
||||
assert raw["qbittorrent"]["username"] == "admin"
|
||||
assert raw["qbittorrent"]["password"] == "pass"
|
||||
|
||||
|
||||
def test_setup_link_only_without_existing_account() -> None:
|
||||
"""Le lien de premier lancement ne doit pas apparaitre si un compte existe.
|
||||
|
||||
Verifie aussi que l'endpoint de setup refuse tout second compte, meme avec
|
||||
un jeton valide.
|
||||
"""
|
||||
with TestClient(app) as client:
|
||||
client.post("/api/auth/setup", json={"token": "invalide", "username": "x", "password": "y"})
|
||||
# Nettoyage: la base de test est partagee entre les tests.
|
||||
with SessionLocal() as db:
|
||||
db.query(User).delete()
|
||||
db.commit()
|
||||
# Simule un redemarrage: le lifespan relance bootstrap_setup.
|
||||
with TestClient(app):
|
||||
assert auth_module.setup_token is not None
|
||||
with TestClient(app) as client:
|
||||
response = client.post(
|
||||
"/api/auth/setup",
|
||||
json={
|
||||
"token": auth_module.setup_token,
|
||||
"username": "admin",
|
||||
"password": "pass",
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
# Le jeton est consomme apres creation du compte.
|
||||
assert auth_module.setup_token is None
|
||||
# Nouveau demarrage: un compte existe -> plus aucun jeton genere,
|
||||
# et la creation d'un second compte est refusee.
|
||||
with TestClient(app) as client:
|
||||
assert auth_module.setup_token is None
|
||||
response = client.post(
|
||||
"/api/auth/setup",
|
||||
json={"token": "peu-importe", "username": "autre", "password": "z"},
|
||||
)
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
def test_startup_logs_conf_json_summary(capsys) -> None:
|
||||
"""Au lancement, le log indique si conf.json est charge et ce qu'il contient."""
|
||||
from app.conf_store import AppConfig, write_config
|
||||
|
||||
with TestClient(app) as client:
|
||||
# Repart d'une conf vierge: les tests precedents remplissent conf.json.
|
||||
write_config(AppConfig())
|
||||
client.put(
|
||||
"/api/settings/qbittorrent",
|
||||
json={"url": "192.168.1.50", "port": 8555},
|
||||
)
|
||||
with TestClient(app):
|
||||
captured = capsys.readouterr()
|
||||
assert "conf.json charge" in captured.out
|
||||
assert "qbittorrent (bypass d'authentification)" in captured.out
|
||||
@@ -0,0 +1,197 @@
|
||||
import shutil
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import respx
|
||||
from fastapi.testclient import TestClient
|
||||
from httpx import Response
|
||||
|
||||
from app.config import settings
|
||||
from app.converter import extract_mkv
|
||||
from app.database import SessionLocal
|
||||
from app.main import app
|
||||
from app.models import IsoMovie
|
||||
from tests.test_api import configure_radarr
|
||||
|
||||
FILM_FOLDER = "ISO Movie (2025)"
|
||||
ISO_NAME = "ISO Movie (2025).iso"
|
||||
MKV_NAME = "ISO Movie (2025).mkv"
|
||||
|
||||
|
||||
def reset_state() -> None:
|
||||
"""Isole chaque test: vide la base et les dossiers films/telechargements."""
|
||||
with SessionLocal() as db:
|
||||
db.query(IsoMovie).delete()
|
||||
db.commit()
|
||||
for folder in (settings.films_dir, settings.downloads_dir):
|
||||
shutil.rmtree(folder, ignore_errors=True)
|
||||
|
||||
|
||||
def film_dir() -> Path:
|
||||
return settings.films_dir / FILM_FOLDER
|
||||
|
||||
|
||||
def radarr_movie(path: str) -> dict:
|
||||
return {
|
||||
"id": 10,
|
||||
"title": "ISO Movie",
|
||||
"year": 2025,
|
||||
"path": path,
|
||||
"images": [{"coverType": "poster", "remoteUrl": "https://img/poster.jpg"}],
|
||||
"movieFile": {
|
||||
"id": 20,
|
||||
"relativePath": ISO_NAME,
|
||||
"size": 42_000_000_000,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def mock_radarr(path: str) -> None:
|
||||
respx.get("http://radarr:7878/api/v3/movie?includeMovieFile=true").mock(
|
||||
return_value=Response(200, json=[radarr_movie(path)])
|
||||
)
|
||||
|
||||
|
||||
def create_film_folder() -> Path:
|
||||
folder = film_dir()
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
(folder / ISO_NAME).write_bytes(b"fake iso")
|
||||
(folder / "poster.jpg").write_bytes(b"junk")
|
||||
extra = folder / "extras"
|
||||
extra.mkdir(exist_ok=True)
|
||||
(extra / "trailer.mkv").write_bytes(b"junk")
|
||||
return folder
|
||||
|
||||
|
||||
def wait_for_status(client: TestClient, expected: str, timeout: float = 10.0) -> dict:
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
movie = client.get("/api/movies").json()[0]
|
||||
if movie["status"] == expected:
|
||||
return movie
|
||||
time.sleep(0.05)
|
||||
raise AssertionError(f"Statut {expected} jamais atteint (dernier: {movie['status']})")
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_conversion_order_and_radarr_file_name() -> None:
|
||||
reset_state()
|
||||
folder = create_film_folder()
|
||||
# Radarr rapporte les chemins dans son referentiel; les fichiers physiques
|
||||
# vivent sous films_dir (montage /films dans le conteneur).
|
||||
mock_radarr(str(settings.radarr_films_dir / FILM_FOLDER))
|
||||
with TestClient(app) as client:
|
||||
configure_radarr(client)
|
||||
scan = client.post("/api/scans")
|
||||
assert scan.status_code == 200
|
||||
movie_id = client.get("/api/movies").json()[0]["id"]
|
||||
|
||||
convert = client.post(f"/api/movies/{movie_id}/convert")
|
||||
assert convert.status_code == 200
|
||||
|
||||
movie = wait_for_status(client, "validating")
|
||||
assert movie["poster_url"] == "https://img/poster.jpg"
|
||||
assert movie["radarr_linked"] is True
|
||||
|
||||
# Ordre voulu: le dossier du film a ete nettoye (poster, extras)
|
||||
# sauf l'ISO, gardee jusqu'a la validation manuelle. Le MKV lie
|
||||
# reprend le nom du fichier Radarr (seule l'extension change).
|
||||
entries = sorted(entry.name for entry in folder.iterdir())
|
||||
assert entries == [ISO_NAME, MKV_NAME]
|
||||
|
||||
validate = client.post(f"/api/movies/{movie_id}/validate")
|
||||
assert validate.status_code == 200
|
||||
assert validate.json()["status"] == "completed"
|
||||
|
||||
# Validation: l'ISO est supprimee, seul le MKV reste.
|
||||
entries = sorted(entry.name for entry in folder.iterdir())
|
||||
assert entries == [MKV_NAME]
|
||||
# Le dossier de travail dans les telechargements est nettoye.
|
||||
assert not list(settings.downloads_dir.iterdir())
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_cancel_conversion_restores_detected() -> None:
|
||||
reset_state()
|
||||
folder = 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")
|
||||
|
||||
cancel = client.post(f"/api/movies/{movie_id}/cancel")
|
||||
assert cancel.status_code == 200
|
||||
assert cancel.json()["status"] == "detected"
|
||||
|
||||
# Annulation: lien et MKV de travail supprimes, l'ISO est intacte.
|
||||
entries = sorted(entry.name for entry in folder.iterdir())
|
||||
assert entries == [ISO_NAME]
|
||||
assert not list(settings.downloads_dir.iterdir())
|
||||
|
||||
# Le film reste supprimable quand il n'est pas en conversion.
|
||||
delete = client.delete(f"/api/movies/{movie_id}")
|
||||
assert delete.status_code == 200
|
||||
assert client.get("/api/movies").json() == []
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_scan_marks_missing_radarr_files_as_unlinked() -> None:
|
||||
"""La pastille "Radarr lie" suit la presence du fichier cote Radarr."""
|
||||
reset_state()
|
||||
create_film_folder()
|
||||
radarr_path = str(settings.radarr_films_dir / FILM_FOLDER)
|
||||
respx.get("http://radarr:7878/api/v3/movie?includeMovieFile=true").mock(
|
||||
return_value=Response(200, json=[radarr_movie(radarr_path)])
|
||||
)
|
||||
with TestClient(app) as client:
|
||||
configure_radarr(client)
|
||||
client.post("/api/scans")
|
||||
movie = client.get("/api/movies").json()[0]
|
||||
assert movie["radarr_linked"] is True
|
||||
|
||||
# Le film disparait de Radarr (fichier supprime): il reste en base
|
||||
# mais passe a non lie.
|
||||
respx.get("http://radarr:7878/api/v3/movie?includeMovieFile=true").mock(
|
||||
return_value=Response(200, json=[])
|
||||
)
|
||||
client.post("/api/scans")
|
||||
movie = client.get("/api/movies").json()[0]
|
||||
assert movie["radarr_linked"] is False
|
||||
assert movie["status"] == "detected"
|
||||
|
||||
|
||||
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."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
monkeypatch.setattr(settings, "simulate_conversion", False)
|
||||
monkeypatch.setattr("app.converter.shutil.which", lambda _: "/usr/bin/makemkvcon")
|
||||
monkeypatch.setattr(
|
||||
"app.converter.subprocess.run",
|
||||
lambda *args, **kwargs: SimpleNamespace(
|
||||
returncode=10,
|
||||
stdout=(
|
||||
"This functionality is shareware. You may evaluate it for 30 days "
|
||||
"after what you would need to purchase an activation key.\n"
|
||||
"Do you want to start evaluation period now?\n"
|
||||
"Evaluation version, 30 day(s) out of 30 remaining"
|
||||
),
|
||||
stderr="",
|
||||
),
|
||||
)
|
||||
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 "makemkvcon reg" in str(error)
|
||||
else:
|
||||
raise AssertionError("RuntimeError attendue")
|
||||
@@ -0,0 +1,126 @@
|
||||
import json
|
||||
|
||||
from sqlalchemy import create_engine, inspect, text
|
||||
|
||||
from app import models # noqa: F401 - enregistre les modeles SQLAlchemy
|
||||
from app.conf_store import AppConfig, config_path, write_raw_config
|
||||
from app.database import Base
|
||||
from app.migrations import (
|
||||
CONF_MIGRATIONS,
|
||||
current_conf_version,
|
||||
migrate_conf_file,
|
||||
run_db_migrations,
|
||||
)
|
||||
|
||||
|
||||
def test_db_migration_from_legacy_schema(tmp_path) -> None:
|
||||
"""Une base 'legacy' (colonnes v1 absentes) est migree, sans perdre les
|
||||
donnees, et la migration n'est jouee qu'une seule fois."""
|
||||
engine = create_engine(f"sqlite:///{tmp_path / 'legacy.db'}")
|
||||
with engine.begin() as conn:
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE iso_movies (
|
||||
id INTEGER PRIMARY KEY,
|
||||
radarr_movie_id INTEGER,
|
||||
radarr_movie_file_id INTEGER,
|
||||
title TEXT,
|
||||
path TEXT,
|
||||
status TEXT,
|
||||
last_seen_at DATETIME
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
conn.execute(
|
||||
text(
|
||||
"INSERT INTO iso_movies (radarr_movie_id, radarr_movie_file_id,"
|
||||
" title, path, status) VALUES (10, 20, 'ISO Movie', '/x.iso', 'detected')"
|
||||
)
|
||||
)
|
||||
|
||||
applied = run_db_migrations(engine)
|
||||
|
||||
assert applied == ["iso_movies: colonnes de suivi des conversions"]
|
||||
columns = {col["name"] for col in inspect(engine).get_columns("iso_movies")}
|
||||
assert {
|
||||
"processed_at",
|
||||
"completed_at",
|
||||
"failed_step",
|
||||
"last_error",
|
||||
"poster_url",
|
||||
"radarr_linked",
|
||||
} <= columns
|
||||
|
||||
# Les donnees existantes sont conservees.
|
||||
with engine.connect() as conn:
|
||||
rows = list(conn.execute(text("SELECT title, radarr_linked FROM iso_movies")))
|
||||
assert rows == [("ISO Movie", 1)]
|
||||
|
||||
# La version est tracee et la migration n'est pas rejouee.
|
||||
with engine.connect() as conn:
|
||||
recorded = list(conn.execute(text("SELECT version FROM schema_migrations")))
|
||||
assert [row[0] for row in recorded] == [1]
|
||||
assert run_db_migrations(engine) == []
|
||||
|
||||
|
||||
def test_db_migration_fresh_database(tmp_path) -> None:
|
||||
"""Sur une base vierge, create_all cree deja le schema complet: la
|
||||
migration v1 est inoffensive mais reste tracee."""
|
||||
engine = create_engine(f"sqlite:///{tmp_path / 'fresh.db'}")
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
applied = run_db_migrations(engine)
|
||||
|
||||
assert applied == ["iso_movies: colonnes de suivi des conversions"]
|
||||
assert run_db_migrations(engine) == []
|
||||
|
||||
|
||||
def test_conf_file_stamped_with_version() -> None:
|
||||
"""Un conf.json d'avant le systeme (sans cle version) est charge tel quel
|
||||
et estampille avec la version courante."""
|
||||
write_raw_config({"radarr": {"url": "http://radarr:7878", "api_key": "k"}})
|
||||
|
||||
applied = migrate_conf_file()
|
||||
|
||||
assert applied == []
|
||||
raw = json.loads(config_path().read_text(encoding="utf-8"))
|
||||
assert raw["version"] == current_conf_version()
|
||||
assert raw["radarr"]["url"] == "http://radarr:7878"
|
||||
assert raw["radarr"]["api_key"] == "k"
|
||||
|
||||
|
||||
def test_conf_migration_transforms_content(monkeypatch) -> None:
|
||||
"""Une migration conf.json transforme le contenu et incremente la version,
|
||||
en chaine jusqu'a la version courante."""
|
||||
def v1_to_v2(data: dict) -> dict:
|
||||
data["jellyfin"] = data.pop("jellyfin_old", {})
|
||||
return data
|
||||
|
||||
def v2_to_v3(data: dict) -> dict:
|
||||
data["prowlarr"] = {"url": None}
|
||||
return data
|
||||
|
||||
monkeypatch.setattr("app.migrations.CONF_MIGRATIONS", [v1_to_v2, v2_to_v3])
|
||||
assert current_conf_version() == 3
|
||||
write_raw_config({"version": 1, "jellyfin_old": {"url": "http://jf:8096"}})
|
||||
|
||||
applied = migrate_conf_file()
|
||||
|
||||
assert applied == ["conf.json v1 -> v2", "conf.json v2 -> v3"]
|
||||
raw = json.loads(config_path().read_text(encoding="utf-8"))
|
||||
assert raw["version"] == 3
|
||||
assert raw["jellyfin"] == {"url": "http://jf:8096"}
|
||||
assert "jellyfin_old" not in raw
|
||||
assert raw["prowlarr"] == {"url": None}
|
||||
|
||||
# Deja a jour: plus aucune migration a appliquer.
|
||||
assert migrate_conf_file() == []
|
||||
|
||||
|
||||
def test_appconfig_version_matches_registry(monkeypatch) -> None:
|
||||
"""Invariant: la version par defaut d'AppConfig suit le registre de
|
||||
migrations conf.json."""
|
||||
monkeypatch.setattr("app.migrations.CONF_MIGRATIONS", CONF_MIGRATIONS)
|
||||
assert AppConfig().version == current_conf_version()
|
||||
+74
-15
@@ -10,20 +10,27 @@ type Movie = {
|
||||
size: number | null;
|
||||
poster_url: string | null;
|
||||
status: string;
|
||||
radarr_linked: boolean;
|
||||
completed_at: string | null;
|
||||
last_error: string | null;
|
||||
failed_step: string | null;
|
||||
last_seen_at: string;
|
||||
};
|
||||
|
||||
type RadarrSettings = { url: string | null; api_key_configured: boolean };
|
||||
type RadarrSettings = {
|
||||
url: string | null;
|
||||
port: number | null;
|
||||
api_key_configured: boolean;
|
||||
};
|
||||
|
||||
type NotificationKind = "info" | "error" | "warning";
|
||||
type Notification = { id: number; text: string; kind: NotificationKind };
|
||||
type QbittorrentSettings = {
|
||||
url: string | null;
|
||||
port: number | null;
|
||||
username: string | null;
|
||||
password_configured: boolean;
|
||||
api_key_configured: boolean;
|
||||
};
|
||||
|
||||
const jsonHeaders = { "Content-Type": "application/json" };
|
||||
@@ -104,12 +111,16 @@ export default function App() {
|
||||
const [page, setPage] = useState<Page>("dashboard");
|
||||
const [movies, setMovies] = useState<Movie[]>([]);
|
||||
const [tab, setTab] = useState<Tab>("pending");
|
||||
const [linkedOnly, setLinkedOnly] = useState(false);
|
||||
const [url, setUrl] = useState("");
|
||||
const [radarrPort, setRadarrPort] = useState("");
|
||||
const [apiKey, setApiKey] = useState("");
|
||||
const [keyConfigured, setKeyConfigured] = useState(false);
|
||||
const [qbitUrl, setQbitUrl] = useState("");
|
||||
const [qbitPort, setQbitPort] = useState("");
|
||||
const [qbitUsername, setQbitUsername] = useState("");
|
||||
const [qbitPassword, setQbitPassword] = useState("");
|
||||
const [qbitApiKey, setQbitApiKey] = useState("");
|
||||
const [qbitConfigured, setQbitConfigured] = useState(false);
|
||||
const [selected, setSelected] = useState<Movie | null>(null);
|
||||
const [posterUrl, setPosterUrl] = useState<string | null>(null);
|
||||
@@ -197,10 +208,12 @@ export default function App() {
|
||||
])
|
||||
.then(([radarr, qbittorrent]) => {
|
||||
setUrl(radarr.url ?? "");
|
||||
setRadarrPort(radarr.port?.toString() ?? "");
|
||||
setKeyConfigured(radarr.api_key_configured);
|
||||
setQbitUrl(qbittorrent.url ?? "");
|
||||
setQbitPort(qbittorrent.port?.toString() ?? "");
|
||||
setQbitUsername(qbittorrent.username ?? "");
|
||||
setQbitConfigured(qbittorrent.password_configured);
|
||||
setQbitConfigured(qbittorrent.password_configured || qbittorrent.api_key_configured);
|
||||
if (!radarr.api_key_configured || !qbittorrent.password_configured) {
|
||||
notify(
|
||||
"Configuration incomplète — renseignez les connexions Radarr et qBittorrent dans la page Configuration.",
|
||||
@@ -294,7 +307,7 @@ export default function App() {
|
||||
const settings = await api<RadarrSettings>("/api/settings/radarr", {
|
||||
method: "PUT",
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({ url, api_key: apiKey || null }),
|
||||
body: JSON.stringify({ url, port: radarrPort ? Number(radarrPort) : null, api_key: apiKey || null }),
|
||||
});
|
||||
setKeyConfigured(settings.api_key_configured);
|
||||
setApiKey("");
|
||||
@@ -318,12 +331,15 @@ export default function App() {
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({
|
||||
url: qbitUrl,
|
||||
port: qbitPort ? Number(qbitPort) : null,
|
||||
username: qbitUsername,
|
||||
password: qbitPassword || null,
|
||||
api_key: qbitApiKey || null,
|
||||
}),
|
||||
});
|
||||
setQbitConfigured(settings.password_configured);
|
||||
setQbitConfigured(settings.password_configured || settings.api_key_configured);
|
||||
setQbitPassword("");
|
||||
setQbitApiKey("");
|
||||
const result = await api<{ message: string }>("/api/settings/qbittorrent/test", {
|
||||
method: "POST",
|
||||
});
|
||||
@@ -362,7 +378,9 @@ export default function App() {
|
||||
};
|
||||
}, [movies]);
|
||||
|
||||
const visible = movies.filter((movie) => inGroup(movie.status, tab));
|
||||
const visible = movies.filter(
|
||||
(movie) => inGroup(movie.status, tab) && (!linkedOnly || movie.radarr_linked),
|
||||
);
|
||||
const lastDone = [...groups.done].sort(
|
||||
(a, b) => Date.parse(b.last_seen_at) - Date.parse(a.last_seen_at),
|
||||
);
|
||||
@@ -813,6 +831,13 @@ export default function App() {
|
||||
<span className="count">{groups[id].length}</span>
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
className={linkedOnly ? "tab active" : "tab"}
|
||||
onClick={() => setLinkedOnly((value) => !value)}
|
||||
title="N’afficher que les films dont le fichier est toujours présent tel quel côté Radarr"
|
||||
>
|
||||
Radarr lié
|
||||
</button>
|
||||
</nav>
|
||||
{visible.length === 0 ? (
|
||||
<div className="empty">Aucun film dans cette catégorie.</div>
|
||||
@@ -877,6 +902,7 @@ export default function App() {
|
||||
Supprimer
|
||||
</button>
|
||||
)}
|
||||
{movie.radarr_linked && <span className="status linked">Radarr lié</span>}
|
||||
<span className={BROKEN.includes(movie.status) ? "status error" : "status"}>
|
||||
{statusLabel(movie.status)}
|
||||
</span>
|
||||
@@ -900,13 +926,24 @@ export default function App() {
|
||||
<label>
|
||||
URL Radarr
|
||||
<input
|
||||
type="url"
|
||||
type="text"
|
||||
required
|
||||
placeholder="http://radarr:7878"
|
||||
placeholder="http://radarr:7878 ou 192.168.1.50"
|
||||
value={url}
|
||||
onChange={(event) => setUrl(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Port (optionnel)
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
max={65535}
|
||||
placeholder="7878"
|
||||
value={radarrPort}
|
||||
onChange={(event) => setRadarrPort(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Clé API
|
||||
<input
|
||||
@@ -935,33 +972,55 @@ export default function App() {
|
||||
<label>
|
||||
URL qBittorrent
|
||||
<input
|
||||
type="url"
|
||||
type="text"
|
||||
required
|
||||
placeholder="http://qbittorrent:8080"
|
||||
placeholder="http://qbittorrent:8080 ou 192.168.1.50"
|
||||
value={qbitUrl}
|
||||
onChange={(event) => setQbitUrl(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Utilisateur
|
||||
Port (optionnel)
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
max={65535}
|
||||
placeholder="8080"
|
||||
value={qbitPort}
|
||||
onChange={(event) => setQbitPort(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Utilisateur (optionnel)
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
placeholder="admin"
|
||||
placeholder="admin — vide = bypass qBittorrent"
|
||||
value={qbitUsername}
|
||||
onChange={(event) => setQbitUsername(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Mot de passe
|
||||
Mot de passe (optionnel)
|
||||
<input
|
||||
type="password"
|
||||
required={!qbitConfigured}
|
||||
placeholder={qbitConfigured ? "Configuré — laisser vide pour conserver" : "Mot de passe WebUI"}
|
||||
placeholder={
|
||||
qbitConfigured
|
||||
? "Configuré — laisser vide pour conserver, tout vider = bypass"
|
||||
: "Vide = bypass d'authentification qBittorrent"
|
||||
}
|
||||
value={qbitPassword}
|
||||
onChange={(event) => setQbitPassword(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Clé API (optionnel — qBittorrent ≥ 5.2)
|
||||
<input
|
||||
type="password"
|
||||
placeholder="qbt_... — prioritaire sur les identifiants"
|
||||
value={qbitApiKey}
|
||||
onChange={(event) => setQbitApiKey(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button disabled={busy}>Enregistrer et tester</button>
|
||||
</form>
|
||||
{qbitConfigured && (
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
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>;
|
||||
}
|
||||
+76
-20
@@ -3,6 +3,7 @@ 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("");
|
||||
@@ -29,9 +30,12 @@ export default function Settings() {
|
||||
const [qbitUsername, setQbitUsername] = useState("");
|
||||
const [qbitPassword, setQbitPassword] = useState("");
|
||||
const [qbitPasswordConfigured, setQbitPasswordConfigured] = useState(false);
|
||||
const [qbitApiKey, setQbitApiKey] = useState("");
|
||||
const [qbitApiKeyConfigured, setQbitApiKeyConfigured] = 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.", []);
|
||||
|
||||
@@ -54,16 +58,30 @@ export default function Settings() {
|
||||
setQbitUrl(settings.qbittorrent.url ?? "");
|
||||
setQbitUsername(settings.qbittorrent.username ?? "");
|
||||
setQbitPasswordConfigured(settings.qbittorrent.password_configured);
|
||||
setQbitApiKeyConfigured(settings.qbittorrent.api_key_configured);
|
||||
}, []);
|
||||
|
||||
const refreshSettings = useCallback(async () => {
|
||||
hydrateSettings(await api<SettingsRead>("/api/settings"));
|
||||
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);
|
||||
@@ -81,8 +99,7 @@ export default function Settings() {
|
||||
});
|
||||
setRadarrApiKey("");
|
||||
await refreshSettings();
|
||||
const result = await api<{ message: string }>("/api/settings/radarr/test", {method: "POST"});
|
||||
setMessage(result.message);
|
||||
await testService("radarr");
|
||||
} catch (error) {
|
||||
setMessage((error as Error).message);
|
||||
} finally {
|
||||
@@ -117,8 +134,12 @@ export default function Settings() {
|
||||
if (name === "jellyfin") setJellyfinApiKey("");
|
||||
if (name === "seerr") setSeerrApiKey("");
|
||||
|
||||
await refreshSettings();
|
||||
setMessage("Configuration enregistrée");
|
||||
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 {
|
||||
@@ -139,13 +160,19 @@ export default function Settings() {
|
||||
url: qbitUrl || null,
|
||||
username: qbitUsername || null,
|
||||
password: qbitPassword || null,
|
||||
api_key: qbitApiKey || null,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
setQbitPassword("");
|
||||
await refreshSettings();
|
||||
setMessage("Configuration enregistrée");
|
||||
setQbitApiKey("");
|
||||
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 {
|
||||
@@ -168,7 +195,10 @@ export default function Settings() {
|
||||
|
||||
<section className="card grid-2">
|
||||
<div>
|
||||
<h3>Radarr</h3>
|
||||
<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">
|
||||
@@ -198,7 +228,10 @@ export default function Settings() {
|
||||
|
||||
<section className="card grid-2">
|
||||
<div>
|
||||
<h3>Sonarr</h3>
|
||||
<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">
|
||||
@@ -220,13 +253,16 @@ export default function Settings() {
|
||||
onChange={(event) => setSonarrApiKey(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button disabled={busy}>Enregistrer</button>
|
||||
<button disabled={busy}>Enregistrer et tester</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section className="card grid-2">
|
||||
<div>
|
||||
<h3>Prowlarr</h3>
|
||||
<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">
|
||||
@@ -248,13 +284,16 @@ export default function Settings() {
|
||||
onChange={(event) => setProwlarrApiKey(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button disabled={busy}>Enregistrer</button>
|
||||
<button disabled={busy}>Enregistrer et tester</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section className="card grid-2">
|
||||
<div>
|
||||
<h3>Jellyfin</h3>
|
||||
<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">
|
||||
@@ -276,13 +315,16 @@ export default function Settings() {
|
||||
onChange={(event) => setJellyfinApiKey(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button disabled={busy}>Enregistrer</button>
|
||||
<button disabled={busy}>Enregistrer et tester</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section className="card grid-2">
|
||||
<div>
|
||||
<h3>Overseerr</h3>
|
||||
<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">
|
||||
@@ -304,16 +346,19 @@ export default function Settings() {
|
||||
onChange={(event) => setSeerrApiKey(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button disabled={busy}>Enregistrer</button>
|
||||
<button disabled={busy}>Enregistrer et tester</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section className="card grid-2">
|
||||
<div>
|
||||
<h3>qBittorrent</h3>
|
||||
<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">
|
||||
<form onSubmit={saveQbittorrent} className="form-4">
|
||||
<label>
|
||||
URL WebUI
|
||||
<input
|
||||
@@ -341,7 +386,18 @@ export default function Settings() {
|
||||
onChange={(event) => setQbitPassword(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button disabled={busy}>Enregistrer</button>
|
||||
<label>
|
||||
Clé API {qbitApiKeyConfigured && <span>· configurée</span>}
|
||||
<input
|
||||
type="password"
|
||||
placeholder={
|
||||
qbitApiKeyConfigured ? "Laisser vide pour conserver" : "qbt_... (qBittorrent ≥ 5.2)"
|
||||
}
|
||||
value={qbitApiKey}
|
||||
onChange={(event) => setQbitApiKey(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button disabled={busy}>Enregistrer et tester</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
|
||||
@@ -127,6 +127,7 @@ h1 {
|
||||
background: var(--surface);
|
||||
}
|
||||
.settings { display: grid; grid-template-columns: 1fr 2fr; gap: 2.5rem; }
|
||||
.service-head { display: flex; align-items: center; gap: 0.75rem; }
|
||||
.panel-head h2 { font-size: 1.15rem; font-weight: 650; margin-bottom: 0.4rem; }
|
||||
.settings p, article p { color: var(--text-muted); }
|
||||
form { display: grid; grid-template-columns: 1fr 1fr auto; align-items: end; gap: 0.75rem; }
|
||||
@@ -197,6 +198,14 @@ code { color: var(--text-muted); font-size: 0.8rem; overflow-wrap: anywhere; }
|
||||
}
|
||||
|
||||
.status.error { color: var(--danger); border-color: rgba(248, 113, 113, 0.4); }
|
||||
.status.linked {
|
||||
color: #4ade80;
|
||||
border-color: rgba(74, 222, 128, 0.4);
|
||||
}
|
||||
.status.warn {
|
||||
color: #fbbf24;
|
||||
border-color: rgba(251, 191, 36, 0.4);
|
||||
}
|
||||
|
||||
.row-actions { display: flex; align-items: center; gap: 0.75rem; flex-shrink: 0; }
|
||||
button.small { padding: 0.45rem 0.9rem; font-size: 0.85rem; border-radius: 8px; }
|
||||
|
||||
+10
-2
@@ -10,11 +10,19 @@ export type Movie = {
|
||||
processed_at?: string | null;
|
||||
};
|
||||
|
||||
export type ApiServiceSettingsRead = { url: string | null; api_key_configured: boolean };
|
||||
export type QbittorrentSettingsRead = {
|
||||
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;
|
||||
api_key_configured: boolean;
|
||||
};
|
||||
|
||||
export type SettingsRead = {
|
||||
|
||||
Reference in new issue
Block a user