✨ Conversion: worker + endpoints convert/cancel/validate, ordre dossier->ln, nommage selon le Media Management Radarr

This commit is contained in:
Orionis312050 committed 2026-10-11 18:26:08 +00:00
1 parent cfc0c54181
commit 198a014967
12 files changed
+536 -15

No files matched your search

+148 -5
View File
@@ -1,3 +1,4 @@
import asyncio
import os
import shutil
from contextlib import asynccontextmanager
@@ -14,9 +15,10 @@ 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
from app.qbittorrent import QbittorrentClient, match_torrent
from app.radarr import RadarrClient, movie_file_path
from app.schemas import (
ApiServiceSettingsRead,
@@ -34,6 +36,7 @@ from app.schemas import (
SettingsRead,
SettingsWrite,
)
from app.worker import conversion_worker
@asynccontextmanager
@@ -45,14 +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
auth.bootstrap_setup()
yield
worker_task = asyncio.create_task(conversion_worker())
try:
yield
finally:
worker_task.cancel()
app = FastAPI(title="MKVTool", version="0.1.0", lifespan=lifespan)
@@ -238,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()
@@ -272,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)
@@ -281,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()
@@ -289,6 +313,125 @@ async def scan_radarr(db: DbSession) -> ScanResult:
)
# --- 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.