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 inspect, select, text, update from sqlalchemy.orm import Session from app import auth from app.conf_store import ApiServiceConfig, build_base_url, 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 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.) try: inspector = inspect(engine) columns = {col["name"] for col in inspector.get_columns("iso_movies")} migrations = { "processed_at": "DATETIME", "completed_at": "DATETIME", "failed_step": "TEXT", "last_error": "TEXT", "poster_url": "TEXT", "radarr_linked": "BOOLEAN DEFAULT 1", } 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 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 ) 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=QbittorrentSettingsRead( url=cfg.qbittorrent.url, username=cfg.qbittorrent.username, password_configured=cfg.qbittorrent.password is not None, ), ) 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: radarr = read_config().radarr return RadarrSettingsRead( url=radarr.url, port=radarr.port, api_key_configured=radarr.api_key is not None, ) @app.put("/api/settings/radarr", response_model=RadarrSettingsRead) def put_radarr_settings( payload: RadarrSettingsWrite, ) -> RadarrSettingsRead: cfg = read_config() url = str(payload.url).strip().rstrip("/") 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, port=cfg.radarr.port, api_key_configured=cfg.radarr.api_key is not None, ) @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 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 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 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: raise HTTPException( status_code=502, detail=f"Connexion Radarr impossible: {error}" ) from error version = str(status.get("version", "inconnue")) 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) @app.get("/api/settings/qbittorrent", response_model=QbittorrentSettingsRead) def get_qbittorrent_settings() -> QbittorrentSettingsRead: qb = read_config().qbittorrent return QbittorrentSettingsRead( url=qb.url, port=qb.port, 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).strip().rstrip("/") cfg.qbittorrent.port = payload.port if payload.username: cfg.qbittorrent.username = payload.username if payload.password: cfg.qbittorrent.password = payload.password elif payload.password: # Mot de passe seul: on conserve l'utilisateur existant. cfg.qbittorrent.password = payload.password else: # Champs vides: mode bypass d'authentification qBittorrent, sans identifiants. cfg.qbittorrent.username = None cfg.qbittorrent.password = None write_config(cfg) return QbittorrentSettingsRead( url=cfg.qbittorrent.url, port=cfg.qbittorrent.port, 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()) @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: mode = "identifiants" if cfg.qbittorrent.username else "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).""" 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.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")