Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d2ebde4f6 | ||
|
|
198a014967 | ||
|
|
cfc0c54181 | ||
|
|
de4a9b212f |
No files matched your search
@@ -58,6 +58,9 @@ COPY docker/entrypoint.py /entrypoint.py
|
||||
|
||||
ENV MKVTOOL_CONFIG_DIR=/config \
|
||||
MKVTOOL_WEB_DIR=/app/web/dist \
|
||||
MKVTOOL_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,121 @@
|
||||
# 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 .`.
|
||||
|
||||
## 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` | `/nas_storage/jellyfin/films` | Racine de la bibliotheque Jellyfin |
|
||||
| `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) |
|
||||
| `/nas_storage/jellyfin/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 |
|
||||
|
||||
Les chemins des films et telechargements doivent etre les MEMES que ceux vus
|
||||
par Radarr et qBittorrent (meme montage cote hote) pour que le lien dur reste
|
||||
possible et que les chemins ISO enregistres restent valides.
|
||||
|
||||
## 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 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:/nas_storage/jellyfin/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
|
||||
```
|
||||
@@ -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
|
||||
+5
-1
@@ -6,6 +6,11 @@ from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
class AppSettings(BaseSettings):
|
||||
config_dir: Path = Path("./config")
|
||||
database_url: str | None = None
|
||||
films_dir: Path = Path("./films")
|
||||
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 +22,3 @@ class AppSettings(BaseSettings):
|
||||
|
||||
|
||||
settings = AppSettings()
|
||||
|
||||
+32
-7
@@ -83,15 +83,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 +139,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()
|
||||
|
||||
+263
-11
@@ -1,32 +1,42 @@
|
||||
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 fastapi.staticfiles import StaticFiles
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy import inspect, select, text
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import auth
|
||||
from app.conf_store import read_config, write_config
|
||||
from app.converter import cancel_conversion, conversion_paths, finalize_validation
|
||||
from app.database import Base, engine, get_db
|
||||
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
|
||||
@@ -38,13 +48,26 @@ async def lifespan(_: FastAPI):
|
||||
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"))
|
||||
migrations = {
|
||||
"processed_at": "DATETIME",
|
||||
"completed_at": "DATETIME",
|
||||
"failed_step": "TEXT",
|
||||
"last_error": "TEXT",
|
||||
"poster_url": "TEXT",
|
||||
}
|
||||
with engine.begin() as conn:
|
||||
for column, ddl in migrations.items():
|
||||
if column not in columns:
|
||||
conn.execute(text(f"ALTER TABLE iso_movies ADD COLUMN {column} {ddl}"))
|
||||
except Exception:
|
||||
# Don't fail app startup for a best-effort migration.
|
||||
pass
|
||||
yield
|
||||
auth.bootstrap_setup()
|
||||
worker_task = asyncio.create_task(conversion_worker())
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
worker_task.cancel()
|
||||
|
||||
|
||||
app = FastAPI(title="MKVTool", version="0.1.0", lifespan=lifespan)
|
||||
@@ -166,6 +189,52 @@ async def test_radarr() -> ConnectionResult:
|
||||
return ConnectionResult(success=True, version=version, message=f"Radarr {version} accessible")
|
||||
|
||||
|
||||
def qbittorrent_from_config() -> QbittorrentClient:
|
||||
qb = read_config().qbittorrent
|
||||
if not qb.url or not qb.username or not qb.password:
|
||||
raise HTTPException(status_code=409, detail="La connexion qBittorrent n'est pas configurée")
|
||||
return QbittorrentClient(qb.url, qb.username, qb.password)
|
||||
|
||||
|
||||
@app.get("/api/settings/qbittorrent", response_model=QbittorrentSettingsRead)
|
||||
def get_qbittorrent_settings() -> QbittorrentSettingsRead:
|
||||
qb = read_config().qbittorrent
|
||||
return QbittorrentSettingsRead(
|
||||
url=qb.url, username=qb.username, password_configured=qb.password is not None
|
||||
)
|
||||
|
||||
|
||||
@app.put("/api/settings/qbittorrent", response_model=QbittorrentSettingsRead)
|
||||
def put_qbittorrent_settings(payload: QbittorrentSettingsWrite) -> QbittorrentSettingsRead:
|
||||
cfg = read_config()
|
||||
if payload.url is not None:
|
||||
cfg.qbittorrent.url = str(payload.url).rstrip("/")
|
||||
if payload.username:
|
||||
cfg.qbittorrent.username = payload.username
|
||||
if payload.password:
|
||||
cfg.qbittorrent.password = payload.password
|
||||
write_config(cfg)
|
||||
return QbittorrentSettingsRead(
|
||||
url=cfg.qbittorrent.url,
|
||||
username=cfg.qbittorrent.username,
|
||||
password_configured=cfg.qbittorrent.password is not None,
|
||||
)
|
||||
|
||||
|
||||
@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:
|
||||
raise HTTPException(
|
||||
status_code=502, detail=f"Connexion qBittorrent impossible: {error}"
|
||||
) from error
|
||||
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())
|
||||
@@ -184,6 +253,13 @@ def get_file(file_id: int, db: DbSession) -> IsoMovie:
|
||||
return item
|
||||
|
||||
|
||||
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()
|
||||
@@ -218,6 +294,7 @@ async def scan_radarr(db: DbSession) -> ScanResult:
|
||||
year=movie.get("year"),
|
||||
path=path,
|
||||
size=movie_file.get("size"),
|
||||
poster_url=_poster_url(movie),
|
||||
last_seen_at=now,
|
||||
)
|
||||
db.add(item)
|
||||
@@ -227,6 +304,7 @@ 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.last_seen_at = now
|
||||
updated += 1
|
||||
db.commit()
|
||||
@@ -235,10 +313,184 @@ async def scan_radarr(db: DbSession) -> ScanResult:
|
||||
)
|
||||
|
||||
|
||||
# Service du front : monte web/dist en racine quand l'image le fournit
|
||||
# (MKVTOOL_WEB_DIR). Le montage est declare en dernier, donc les routes /api
|
||||
# ci-dessus gardent la priorite; en dev (vite sur :5173), la variable est
|
||||
# absente et le montage est saute.
|
||||
# --- 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)."""
|
||||
qb = read_config().qbittorrent
|
||||
if not qb.url or not qb.username or not qb.password:
|
||||
return
|
||||
try:
|
||||
client = QbittorrentClient(qb.url, qb.username, qb.password)
|
||||
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.mount("/", StaticFiles(directory=web_dir, html=True), name="web")
|
||||
|
||||
@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")
|
||||
@@ -25,8 +25,21 @@ 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")
|
||||
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())
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
"""Nom du fichier MKV selon la configuration Media Management de Radarr.
|
||||
|
||||
Applique le "Standard Movie Format" de Radarr (/api/v3/config/naming) au
|
||||
fichier converti : les tokens usuels ({Movie Title}, {Release Year},
|
||||
{Quality Title}...) sont remplacés à partir des données du film et du
|
||||
movieFile. Si Radarr n'est pas configuré pour renommer (renameMovies=false),
|
||||
le nom d'origine du MKV est conservé.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
from app.converter import sanitize_component
|
||||
|
||||
_VIDEO_CODECS = {
|
||||
"h264": "x264",
|
||||
"x264": "x264",
|
||||
"h265": "x265",
|
||||
"hevc": "x265",
|
||||
"x265": "x265",
|
||||
"av1": "AV1",
|
||||
"mpeg2video": "MPEG2",
|
||||
"mpeg-2": "MPEG2",
|
||||
"vc1": "VC1",
|
||||
"vp9": "VP9",
|
||||
"xvid": "Xvid",
|
||||
"divx": "DivX",
|
||||
}
|
||||
|
||||
_AUDIO_CODECS = {
|
||||
"ac3": "AC3",
|
||||
"eac3": "EAC3",
|
||||
"dts": "DTS",
|
||||
"truehd": "TrueHD",
|
||||
"flac": "FLAC",
|
||||
"aac": "AAC",
|
||||
"mp3": "MP3",
|
||||
"opus": "Opus",
|
||||
"vorbis": "Vorbis",
|
||||
"pcm": "PCM",
|
||||
"lpcm": "PCM",
|
||||
}
|
||||
|
||||
_INVALID_TOKEN = re.compile(r"\{[^{}]*\}")
|
||||
|
||||
|
||||
def _media_info_tokens(movie_file: dict) -> dict[str, str]:
|
||||
media = movie_file.get("mediaInfo") or {}
|
||||
video = str(media.get("videoCodec", "") or "").lower()
|
||||
audio = str(media.get("audioCodec", "") or "").lower()
|
||||
channels = str(media.get("audioChannels", "") or "")
|
||||
simple = "-".join(part for part in (_VIDEO_CODECS.get(video, video.upper()), channels) if part)
|
||||
full = " ".join(
|
||||
part
|
||||
for part in (
|
||||
_VIDEO_CODECS.get(video, video.upper()),
|
||||
_AUDIO_CODECS.get(audio, audio.upper()),
|
||||
channels,
|
||||
)
|
||||
if part
|
||||
)
|
||||
return {"MediaInfo Simple": simple, "MediaInfo Full": full}
|
||||
|
||||
|
||||
def _quality_tokens(movie_file: dict) -> dict[str, str]:
|
||||
quality = (movie_file.get("quality") or {}).get("quality") or {}
|
||||
revision = (movie_file.get("quality") or {}).get("revision") or {}
|
||||
title = str(quality.get("name", "") or "")
|
||||
version = int(revision.get("version", 1) or 1)
|
||||
is_real = int(revision.get("real", 0) or 0)
|
||||
return {
|
||||
"Quality Title": title,
|
||||
"Quality Full": " ".join(
|
||||
part
|
||||
for part in (title, "Proper" if version > 1 else "", "Real" if is_real else "")
|
||||
if part
|
||||
),
|
||||
"Quality Proper": "Proper" if version > 1 else "",
|
||||
"Quality Real": "Real" if is_real else "",
|
||||
}
|
||||
|
||||
|
||||
def movie_file_name(naming: dict, movie: dict, movie_file: dict, fallback: str) -> str:
|
||||
"""Construit le nom de fichier (sans extension) attendu par Radarr."""
|
||||
if not naming.get("renameMovies"):
|
||||
return fallback
|
||||
|
||||
pattern = str(naming.get("standardMovieFormat", "") or "")
|
||||
if not pattern:
|
||||
return fallback
|
||||
|
||||
tokens = {
|
||||
"Movie Title": sanitize_component(str(movie.get("title", "") or "")),
|
||||
"Movie CleanTitle": sanitize_component(str(movie.get("title", "") or "")),
|
||||
"Movie OriginalTitle": sanitize_component(str(movie.get("originalTitle", "") or "")),
|
||||
"Release Year": str(movie.get("year", "") or ""),
|
||||
"Year": str(movie.get("year", "") or ""),
|
||||
"Tmdb Id": str(movie.get("tmdbId", "") or ""),
|
||||
"Imdb Id": str(movie.get("imdbId", "") or ""),
|
||||
"Edition": sanitize_component(str(movie_file.get("edition", "") or "")),
|
||||
"Release Group": sanitize_component(str(movie_file.get("releaseGroup", "") or "")),
|
||||
}
|
||||
tokens.update(_quality_tokens(movie_file))
|
||||
tokens.update(_media_info_tokens(movie_file))
|
||||
|
||||
result = pattern
|
||||
for token, value in tokens.items():
|
||||
result = result.replace("{" + token + "}", value)
|
||||
result = result.replace("{" + token.lower() + "}", value)
|
||||
# Tokens inconnus: retires pour ne pas laisser d'accolades dans le nom.
|
||||
result = _INVALID_TOKEN.sub("", result)
|
||||
result = sanitize_component(result)
|
||||
return result or fallback
|
||||
@@ -28,6 +28,19 @@ class RadarrClient:
|
||||
raise ValueError("Réponse Radarr inattendue")
|
||||
return result
|
||||
|
||||
async def movie(self, movie_id: int) -> dict:
|
||||
result = await self._get(f"movie/{movie_id}?includeMovieFile=true")
|
||||
if not isinstance(result, dict):
|
||||
raise ValueError("Réponse Radarr inattendue")
|
||||
return result
|
||||
|
||||
async def naming(self) -> dict:
|
||||
"""Configuration Media Management: formats de renommage."""
|
||||
result = await self._get("config/naming")
|
||||
if not isinstance(result, dict):
|
||||
raise ValueError("Réponse Radarr inattendue")
|
||||
return result
|
||||
|
||||
|
||||
def movie_file_path(movie: dict) -> str | None:
|
||||
movie_file = movie.get("movieFile") or {}
|
||||
|
||||
@@ -70,9 +70,13 @@ class IsoMovieRead(BaseModel):
|
||||
path: str
|
||||
size: int | None
|
||||
status: str
|
||||
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 +91,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
|
||||
+35
-1
@@ -2,13 +2,17 @@
|
||||
|
||||
import asyncio
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.conf_store import read_config
|
||||
from app.config import settings
|
||||
from app.converter import conversion_paths, extract_mkv, import_mkv
|
||||
from app.database import SessionLocal
|
||||
from app.models import IsoMovie
|
||||
from app.naming import movie_file_name
|
||||
from app.radarr import RadarrClient
|
||||
|
||||
|
||||
async def _process(movie_id: int) -> None:
|
||||
@@ -29,7 +33,14 @@ 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)
|
||||
target_name = await _target_name(movie)
|
||||
await asyncio.to_thread(
|
||||
import_mkv,
|
||||
paths.mkv_path,
|
||||
paths.destination_folder,
|
||||
target_name,
|
||||
[Path(movie.path)],
|
||||
)
|
||||
# Le passage en "completed" (ISO supprimee) se fait manuellement
|
||||
# via l'endpoint de validation apres verification par l'utilisateur.
|
||||
movie.status = "validating"
|
||||
@@ -42,6 +53,29 @@ async def _process(movie_id: int) -> None:
|
||||
db.commit()
|
||||
|
||||
|
||||
async def _target_name(movie: IsoMovie) -> str:
|
||||
"""Nom du lien selon la configuration Media Management de Radarr.
|
||||
|
||||
En cas d'erreur (Radarr non configuré, API injoignable), on retombe sur le
|
||||
nom du MKV produit par MakeMKV plutôt que de faire échouer la conversion.
|
||||
"""
|
||||
fallback = Path(conversion_paths(movie).mkv_path).name
|
||||
cfg = read_config()
|
||||
if not cfg.radarr.url or not cfg.radarr.api_key:
|
||||
return fallback
|
||||
try:
|
||||
client = RadarrClient(cfg.radarr.url, cfg.radarr.api_key)
|
||||
radarr_movie = await client.movie(movie.radarr_movie_id)
|
||||
naming = await client.naming()
|
||||
name = movie_file_name(
|
||||
naming, radarr_movie, radarr_movie.get("movieFile") or {}, fallback
|
||||
)
|
||||
return name if name.lower().endswith(".mkv") else f"{name}.mkv"
|
||||
except Exception: # noqa: BLE001 - le nommage ne doit pas bloquer la conversion
|
||||
traceback.print_exc()
|
||||
return fallback
|
||||
|
||||
|
||||
async def _process_next() -> bool:
|
||||
with SessionLocal() as db:
|
||||
movie_id = db.scalar(
|
||||
|
||||
@@ -22,6 +22,9 @@ services:
|
||||
TZ: "Europe/Paris"
|
||||
# Sur le NAS: desactiver la simulation MakeMKV.
|
||||
MKVTOOL_SIMULATE_CONVERSION: "false"
|
||||
# Dossiers vus par l'API: memes chemins que les volumes montes.
|
||||
MKVTOOL_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.
|
||||
|
||||
+4
-1
@@ -4,4 +4,7 @@ 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_DOWNLOADS_DIR"] = str(_test_config / "downloads")
|
||||
os.environ["MKVTOOL_SIMULATE_CONVERSION"] = "true"
|
||||
os.environ["MKVTOOL_WORKER_INTERVAL"] = "0.05"
|
||||
@@ -1,7 +1,10 @@
|
||||
import json
|
||||
|
||||
import respx
|
||||
from fastapi.testclient import TestClient
|
||||
from httpx import Response
|
||||
|
||||
from app.conf_store import config_path
|
||||
from app.main import app
|
||||
|
||||
|
||||
@@ -70,3 +73,38 @@ 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() -> None:
|
||||
respx.post("http://qbit:8080/api/v2/auth/login").mock(
|
||||
return_value=Response(200, text="Ok.")
|
||||
)
|
||||
respx.get("http://qbit:8080/api/v2/app/version").mock(
|
||||
return_value=Response(200, text="v5.0.2")
|
||||
)
|
||||
with TestClient(app) as client:
|
||||
response = client.put(
|
||||
"/api/settings/qbittorrent",
|
||||
json={"url": "http://qbit:8080", "username": "admin", "password": "pass"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
test = client.post("/api/settings/qbittorrent/test")
|
||||
assert test.status_code == 200
|
||||
assert test.json()["version"] == "v5.0.2"
|
||||
|
||||
|
||||
def test_settings_persist_to_conf_json() -> None:
|
||||
with TestClient(app) as client:
|
||||
put = client.put(
|
||||
"/api/settings/qbittorrent",
|
||||
json={"url": "http://qbit:8080/", "username": "admin", "password": "pass"},
|
||||
)
|
||||
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"
|
||||
raw = json.loads(config_path().read_text(encoding="utf-8"))
|
||||
assert raw["qbittorrent"]["url"] == "http://qbit:8080"
|
||||
assert raw["qbittorrent"]["username"] == "admin"
|
||||
assert raw["qbittorrent"]["password"] == "pass"
|
||||
@@ -0,0 +1,173 @@
|
||||
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.database import SessionLocal
|
||||
from app.main import app
|
||||
from app.models import IsoMovie
|
||||
from app.naming import movie_file_name
|
||||
from tests.test_api import configure_radarr
|
||||
|
||||
|
||||
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)
|
||||
|
||||
FILM_FOLDER = "ISO Movie (2025)"
|
||||
ISO_NAME = "ISO Movie (2025).iso"
|
||||
# Format Media Management de Radarr utilise dans les mocks.
|
||||
NAMING = {
|
||||
"renameMovies": True,
|
||||
"standardMovieFormat": "{Movie Title} ({Release Year}) {Quality Full}",
|
||||
}
|
||||
|
||||
|
||||
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,
|
||||
"quality": {"quality": {"name": "WEBDL-1080p"}, "revision": {"version": 2, "real": 0}},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
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)])
|
||||
)
|
||||
respx.get("http://radarr:7878/api/v3/movie/10?includeMovieFile=true").mock(
|
||||
return_value=Response(200, json=radarr_movie(path))
|
||||
)
|
||||
respx.get("http://radarr:7878/api/v3/config/naming").mock(
|
||||
return_value=Response(200, json=NAMING)
|
||||
)
|
||||
|
||||
|
||||
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']})")
|
||||
|
||||
|
||||
def test_movie_file_name_tokens() -> None:
|
||||
movie_file = {
|
||||
"quality": {"quality": {"name": "WEBDL-1080p"}, "revision": {"version": 2, "real": 0}},
|
||||
"mediaInfo": {"videoCodec": "h264", "audioCodec": "dts", "audioChannels": "5.1"},
|
||||
"releaseGroup": "TEAM",
|
||||
}
|
||||
name = movie_file_name(
|
||||
{
|
||||
"renameMovies": True,
|
||||
"standardMovieFormat": "{Movie Title} {Quality Title} {MediaInfo Simple}",
|
||||
},
|
||||
{"title": "ISO Movie", "year": 2025},
|
||||
movie_file,
|
||||
"fallback.mkv",
|
||||
)
|
||||
assert name == "ISO Movie WEBDL-1080p x264-5.1"
|
||||
|
||||
|
||||
def test_movie_file_name_respects_rename_disabled() -> None:
|
||||
name = movie_file_name(
|
||||
{"renameMovies": False, "standardMovieFormat": "{Movie Title}"},
|
||||
{"title": "ISO Movie"},
|
||||
{},
|
||||
"Fallback Name (2025).mkv",
|
||||
)
|
||||
assert name == "Fallback Name (2025).mkv"
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_conversion_order_and_radarr_naming() -> None:
|
||||
reset_state()
|
||||
folder = create_film_folder()
|
||||
mock_radarr(str(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"
|
||||
|
||||
# Ordre voulu: le dossier du film a ete nettoye (poster, extras)
|
||||
# sauf l'ISO, gardee jusqu'a la validation manuelle.
|
||||
entries = sorted(entry.name for entry in folder.iterdir())
|
||||
assert entries == ["ISO Movie (2025) WEBDL-1080p Proper.mkv", ISO_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 (nomme par Radarr) reste.
|
||||
entries = sorted(entry.name for entry in folder.iterdir())
|
||||
assert entries == ["ISO Movie (2025) WEBDL-1080p Proper.mkv"]
|
||||
# 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(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() == []
|
||||
Reference in new issue
Block a user