Files
mkvtool/app/main.py
T

660 lines
23 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.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)
# 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) -> 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),
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 = 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)
apply_service(cfg.sonarr, payload.sonarr)
apply_service(cfg.prowlarr, payload.prowlarr)
apply_service(cfg.jellyfin, payload.jellyfin)
apply_service(cfg.seerr, payload.seerr)
if payload.qbittorrent is not None:
qb = payload.qbittorrent
qb_changed = bool(qb.url) and str(qb.url).rstrip("/") != (cfg.qbittorrent.url or "")
qb_changed = qb_changed or bool(qb.username and qb.username != cfg.qbittorrent.username)
qb_changed = qb_changed or bool(qb.password)
qb_changed = qb_changed or bool(qb.api_key)
if qb_changed:
reset_test(cfg.qbittorrent)
if qb.url is not None:
cfg.qbittorrent.url = str(qb.url).rstrip("/")
if qb.username:
cfg.qbittorrent.username = qb.username
if qb.password:
cfg.qbittorrent.password = qb.password
if qb.api_key:
cfg.qbittorrent.api_key = qb.api_key
write_config(cfg)
return _settings_read()
@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")
# --- 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())
@app.get("/api/files", response_model=list[IsoMovieRead])
def list_files(db: DbSession) -> list[IsoMovie]:
return list_movies(db)
@app.get("/api/files/{file_id}", response_model=IsoMovieRead)
def get_file(file_id: int, db: DbSession) -> IsoMovie:
item = db.get(IsoMovie, file_id)
if item is None:
raise HTTPException(status_code=404, detail="Fichier introuvable")
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()
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)
if not path or not path.lower().endswith(".iso"):
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) -> 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")