Files
mkvtool/app/main.py
T

689 lines
25 KiB
Python

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 Cookie, Depends, FastAPI, HTTPException, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from sqlalchemy import select, update
from sqlalchemy.orm import Session
from app import auth
from app import worker as conversion_queue
from app.conf_store import (
ApiServiceConfig,
QbittorrentConfig,
build_base_url,
read_config,
record_test,
reset_test,
service_status,
write_config,
)
from app.converter import (
cancel_conversion,
clear_workspace,
conversion_paths,
finalize_validation,
looks_like_iso,
rmdir_if_empty,
unlink_if_exists,
workspace_files,
)
from app.database import Base, engine, get_db
from app.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 (
AuthCredentialsWrite,
AuthSetupWrite,
AuthUserRead,
ConnectionResult,
ConversionLogRead,
HealthRead,
IsoMovieDetailRead,
IsoMovieRead,
QbittorrentSettingsRead,
QbittorrentSettingsWrite,
RadarrSettingsRead,
RadarrSettingsWrite,
ScanResult,
SettingsRead,
SettingsWrite,
ValidationRead,
)
from app.worker import conversion_worker
@asynccontextmanager
async def lifespan(_: FastAPI):
Base.metadata.create_all(bind=engine)
# Migrations versionnees (base + conf.json), tracees au demarrage.
db_applied = run_db_migrations(engine)
if db_applied:
print(f"migrations de base appliquees: {', '.join(db_applied)}", flush=True)
conf_applied = migrate_conf_file()
if conf_applied:
print(f"migrations conf.json: {', '.join(conf_applied)}", flush=True)
auth.bootstrap_setup()
_log_config_summary()
worker_task = asyncio.create_task(conversion_worker())
try:
yield
finally:
worker_task.cancel()
app = FastAPI(title="MKVTool", version="0.1.0", lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:5173", "http://127.0.0.1:5173"],
allow_methods=["*"],
allow_headers=["*"],
)
DbSession = Annotated[Session, Depends(get_db)]
def _api_service_read(service: ApiServiceConfig) -> RadarrSettingsRead:
return RadarrSettingsRead(
url=service.url,
port=service.port,
api_key_configured=service.api_key is not None,
status=service_status(service),
tested_version=service.test.version,
tested_at=service.test.at,
test_error=service.test.error,
)
def _qbittorrent_read(qb: QbittorrentConfig) -> QbittorrentSettingsRead:
return QbittorrentSettingsRead(
url=qb.url,
port=qb.port,
username=qb.username,
password_configured=qb.password is not None,
api_key_configured=qb.api_key is not None,
status=service_status(qb),
tested_version=qb.test.version,
tested_at=qb.test.at,
test_error=qb.test.error,
)
def _settings_read() -> SettingsRead:
cfg = read_config()
return SettingsRead(
radarr=_api_service_read(cfg.radarr),
qbittorrent=_qbittorrent_read(cfg.qbittorrent),
)
def client_from_config() -> RadarrClient:
cfg = read_config()
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")
return RadarrClient(url, api_key)
@app.get("/api/health", response_model=HealthRead)
def health() -> HealthRead:
executable = shutil.which("makemkvcon")
return HealthRead(
status="ok",
database="ok",
makemkv_available=executable is not None,
makemkv_version=os.getenv("MAKEMKV_VERSION") if executable else None,
)
@app.get("/api/settings/radarr", response_model=RadarrSettingsRead)
def get_radarr_settings() -> RadarrSettingsRead:
return _api_service_read(read_config().radarr)
@app.put("/api/settings/radarr", response_model=RadarrSettingsRead)
def put_radarr_settings(
payload: RadarrSettingsWrite,
) -> RadarrSettingsRead:
cfg = read_config()
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 _api_service_read(cfg.radarr)
@app.get("/api/settings", response_model=SettingsRead)
def get_settings() -> SettingsRead:
return _settings_read()
@app.put("/api/settings", response_model=SettingsRead)
def put_settings(payload: SettingsWrite) -> SettingsRead:
cfg = read_config()
def apply_service(target, patch):
if patch is None:
return
changed = False
if patch.url is not None and str(patch.url).rstrip("/") != (target.url or ""):
changed = True
if patch.api_key and patch.api_key != target.api_key:
changed = True
if changed:
reset_test(target)
if patch.url is not None:
target.url = str(patch.url).rstrip("/")
if patch.api_key:
target.api_key = patch.api_key
apply_service(cfg.radarr, payload.radarr)
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()
@app.post("/api/settings/radarr/test", response_model=ConnectionResult)
async def test_radarr() -> ConnectionResult:
client = client_from_config()
try:
status = await client.system_status()
except (httpx.HTTPError, ValueError) as error:
record_test("radarr", ok=False, error=str(error))
raise HTTPException(
status_code=502, detail=f"Connexion Radarr impossible: {error}"
) from error
version = str(status.get("version", "inconnue"))
record_test("radarr", ok=True, version=version)
return ConnectionResult(success=True, version=version, message=f"Radarr {version} accessible")
def qbittorrent_from_config() -> QbittorrentClient:
qb = read_config().qbittorrent
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())
@app.get("/api/files", response_model=list[IsoMovieRead])
def list_files(db: DbSession) -> list[IsoMovie]:
return list_movies(db)
def _movie_detail(movie: IsoMovie) -> IsoMovieDetailRead:
"""Fiche detaillee: chemins du MKV brut et du MKV lie, etat du dossier."""
paths = conversion_paths(movie)
linked = _linked_mkv(movie)
detail = IsoMovieDetailRead.model_validate(movie)
detail.work_mkv_path = str(paths.mkv_path) if paths.mkv_path.is_file() else None
detail.linked_mkv_path = str(linked) if linked is not None else None
detail.workspace_folder = str(paths.downloads_folder)
detail.workspace_files = workspace_files(paths.downloads_folder)
return detail
@app.get("/api/files/{file_id}", response_model=IsoMovieDetailRead)
def get_file(file_id: int, db: DbSession) -> IsoMovieDetailRead:
item = db.get(IsoMovie, file_id)
if item is None:
raise HTTPException(status_code=404, detail="Fichier introuvable")
return _movie_detail(item)
@app.get("/api/movies/{movie_id}/log", response_model=ConversionLogRead)
def get_conversion_log(movie_id: int, db: DbSession) -> ConversionLogRead:
"""Journal de la conversion (terminal de suivi), conserve apres echec."""
movie = db.get(IsoMovie, movie_id)
if movie is None:
raise HTTPException(status_code=404, detail="Film introuvable")
return ConversionLogRead(
lines=conversion_queue.conversion_log(movie_id),
running=conversion_queue.is_converting(movie_id),
)
def _log_config_summary() -> None:
"""Rend visible au lancement le chargement de conf.json."""
cfg = read_config()
configured = ["radarr"] if cfg.radarr.url else []
if cfg.qbittorrent.url:
if cfg.qbittorrent.api_key:
mode = "cle API"
elif cfg.qbittorrent.username:
mode = "identifiants"
else:
mode = "bypass d'authentification"
configured.append(f"qbittorrent ({mode})")
if configured:
print(f"conf.json charge: {', '.join(configured)}", flush=True)
else:
print(
"conf.json: aucune connexion configuree — a renseigner dans la page Configuration.",
flush=True,
)
def _poster_url(movie: dict) -> str | None:
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()
try:
movies = await client.movies()
except (httpx.HTTPError, ValueError) as error:
raise HTTPException(status_code=502, detail=f"Scan Radarr impossible: {error}") from error
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)
# L'extension preslectionne, mais des MKV circulent parfois sous un
# nom en .iso: on verifie l'en-tete du contenu.
if not path or not looks_like_iso(path):
continue
movie_id = movie.get("id")
movie_file_id = movie_file.get("id")
if not isinstance(movie_id, int) or not isinstance(movie_file_id, int):
continue
iso_files += 1
item = db.scalar(
select(IsoMovie).where(
IsoMovie.radarr_movie_id == movie_id,
IsoMovie.radarr_movie_file_id == movie_file_id,
)
)
if item is None:
item = IsoMovie(
radarr_movie_id=movie_id,
radarr_movie_file_id=movie_file_id,
title=str(movie.get("title", "Film sans titre")),
year=movie.get("year"),
path=path,
size=movie_file.get("size"),
poster_url=_poster_url(movie),
radarr_linked=True,
last_seen_at=now,
)
db.add(item)
created += 1
else:
item.title = str(movie.get("title", item.title))
item.year = movie.get("year")
item.path = path
item.size = movie_file.get("size")
item.poster_url = _poster_url(movie)
item.radarr_linked = True
item.last_seen_at = now
updated += 1
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, force: bool = False) -> IsoMovie:
"""Met la conversion en file.
Refuse (409, code ``workspace_not_empty``) si le dossier de travail
contient des restes d'anciennes conversions, sauf si ``force`` est vrai:
le contenu est alors supprime pour qu'un seul MKV soit produit a la fin.
Une reprise apres echec d'import (MKV deja extrait) n'est pas bloquee.
"""
movie = db.get(IsoMovie, movie_id)
if movie is None:
raise HTTPException(status_code=404, detail="Film introuvable")
if movie.status not in {"detected", "ready", "failed"}:
raise HTTPException(
status_code=409, detail="Ce film n'est pas convertible dans son état actuel"
)
paths = conversion_paths(movie)
resumable = movie.failed_step == "importing" and paths.mkv_path.is_file()
leftovers = [
name
for name in workspace_files(paths.downloads_folder)
if not (resumable and (paths.downloads_folder / name) == paths.mkv_path)
]
if leftovers and not force:
raise HTTPException(
status_code=409,
detail={
"code": "workspace_not_empty",
"message": (
"Le dossier de travail contient des fichiers issus d'une ancienne "
"conversion. Supprimez-les pour ne garder qu'un seul MKV en fin "
"de conversion."
),
"folder": str(paths.downloads_folder),
"files": leftovers,
},
)
if leftovers:
clear_workspace(paths.downloads_folder)
paths.downloads_folder.mkdir(parents=True, exist_ok=True)
movie.status = "queued"
movie.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:
"""Annule une conversion en attente de validation et supprime le MKV.
Reserve a l'etat ``validating``: avant cette etape le MKV converti
n'existe pas. Les fichiers deja disparus sont toleres; seule une erreur
de droits interrompt, remontee en erreur explicite.
"""
movie = db.get(IsoMovie, movie_id)
if movie is None:
raise HTTPException(status_code=404, detail="Film introuvable")
if movie.status != "validating":
raise HTTPException(status_code=409, detail="Aucune conversion à annuler")
paths = conversion_paths(movie)
linked = _linked_mkv(movie)
try:
cancel_conversion(
paths.mkv_path, paths.destination_folder, linked.name if linked else None
)
except Exception as error: # noqa: BLE001 - message explicite pour l'UI
raise HTTPException(
status_code=409, detail=f"Annulation impossible: {error}"
) from error
movie.status = "detected"
movie.failed_step = None
movie.last_error = None
db.commit()
return movie
@app.post("/api/movies/{movie_id}/validate", response_model=ValidationRead)
async def validate_movie(movie_id: int, db: DbSession) -> ValidationRead:
"""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.
try:
finalize_validation(paths.destination_folder, linked.name)
except Exception as error: # noqa: BLE001 - message explicite pour l'UI
raise HTTPException(
status_code=409, detail=f"Validation impossible (dossier du film): {error}"
) from error
await _delete_iso_torrent(movie.path)
# Nettoyage du dossier de travail (le lien dur garde les donnees).
try:
unlink_if_exists(paths.mkv_path)
rmdir_if_empty(paths.mkv_path.parent)
except Exception as error: # noqa: BLE001 - message explicite pour l'UI
raise HTTPException(
status_code=409, detail=f"Validation impossible (dossier de travail): {error}"
) from error
movie.status = "completed"
now = datetime.now(UTC)
movie.processed_at = now
movie.completed_at = now
db.commit()
snapshot = ValidationRead.model_validate(movie)
# Rescan puis renommage Radarr: le dossier ne contient plus que le MKV
# lie; Radarr l'adopte comme fichier du film puis le renomme selon sa
# config Media Management (l'ancien nom de l'ISO ne correspond pas au
# format attendu). Les commandes Radarr sont executees dans l'ordre
# d'envoi. Best effort: un echec n'invalide pas la validation (l'ISO est
# deja supprimee), il remonte en avertissement.
rescan_warning: str | None = None
try:
radarr_client = client_from_config()
await radarr_client.rescan_movie(movie.radarr_movie_id)
await radarr_client.rename_movie(movie.radarr_movie_id)
except Exception as error: # noqa: BLE001 - la validation reste acquise
rescan_warning = (
f"ISO supprimée, mais mise à jour Radarr impossible: {error}. "
"Lancez un rescan puis un renommage du film dans Radarr pour "
"qu'il détecte et renomme le MKV selon sa config."
)
snapshot.rescan_warning = rescan_warning
return snapshot
@app.delete("/api/movies/{movie_id}", response_model=IsoMovieRead)
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")