111 lines
3.8 KiB
Python
111 lines
3.8 KiB
Python
"""Worker de conversion: traite les films en file, une conversion a la fois."""
|
|
|
|
import asyncio
|
|
import traceback
|
|
from pathlib import Path
|
|
|
|
from sqlalchemy import select
|
|
|
|
from app.config import settings
|
|
from app.converter import container_iso_path, conversion_paths, extract_mkv, import_mkv
|
|
from app.database import SessionLocal
|
|
from app.models import IsoMovie
|
|
|
|
LOG_LIMIT = 500
|
|
# Journal de la conversion en cours, par film (diffuse dans l'interface).
|
|
_run_logs: dict[int, list[str]] = {}
|
|
_current_movie_id: int | None = None
|
|
|
|
|
|
def conversion_log(movie_id: int) -> list[str]:
|
|
"""Lignes du journal de conversion du film (vide si jamais converti)."""
|
|
return list(_run_logs.get(movie_id, []))
|
|
|
|
|
|
def is_converting(movie_id: int) -> bool:
|
|
"""Vrai si ce film est celui en cours de traitement par le worker."""
|
|
return _current_movie_id == movie_id
|
|
|
|
|
|
def _log(movie_id: int, line: str) -> None:
|
|
log = _run_logs.setdefault(movie_id, [])
|
|
log.append(line)
|
|
if len(log) > LOG_LIMIT:
|
|
del log[: len(log) - LOG_LIMIT]
|
|
|
|
|
|
async def _process(movie_id: int) -> None:
|
|
global _current_movie_id
|
|
with SessionLocal() as db:
|
|
movie = db.get(IsoMovie, movie_id)
|
|
if movie is None or movie.status != "queued":
|
|
return
|
|
paths = conversion_paths(movie)
|
|
step = "converting"
|
|
_run_logs[movie_id] = []
|
|
_current_movie_id = movie_id
|
|
try:
|
|
movie.status = "converting"
|
|
movie.last_error = None
|
|
db.commit()
|
|
# Reprise: uniquement si l'echec precedent a eu lieu APRES
|
|
# l'extraction (import). Un MKV issu d'une extraction incomplete
|
|
# n'est jamais repris: la conversion repart de zero.
|
|
resumable = movie.failed_step == "importing" and paths.mkv_path.exists()
|
|
if not resumable:
|
|
_log(movie_id, "— Extraction MakeMKV en cours…")
|
|
await asyncio.to_thread(
|
|
extract_mkv, movie, paths.mkv_path, lambda line: _log(movie_id, line)
|
|
)
|
|
else:
|
|
_log(movie_id, "— MKV déjà extrait, reprise à l'import.")
|
|
step = "importing"
|
|
movie.status = "importing"
|
|
db.commit()
|
|
# Le MKV lié reprend le nom du fichier Radarr (l'ISO), seule
|
|
# l'extension change.
|
|
target_name = f"{Path(movie.path).stem}.mkv"
|
|
_log(movie_id, "— Import: lien dans le dossier du film…")
|
|
await asyncio.to_thread(
|
|
import_mkv,
|
|
paths.mkv_path,
|
|
paths.destination_folder,
|
|
target_name,
|
|
[container_iso_path(movie)],
|
|
)
|
|
# Le passage en "completed" (ISO supprimee) se fait manuellement
|
|
# via l'endpoint de validation apres verification par l'utilisateur.
|
|
movie.status = "validating"
|
|
movie.failed_step = None
|
|
_log(movie_id, "— Conversion terminée: en attente de validation.")
|
|
except Exception as error: # noqa: BLE001 - le worker doit survivre a toute erreur
|
|
movie.status = "failed"
|
|
movie.failed_step = step
|
|
movie.last_error = f"{error}"
|
|
_log(movie_id, f"— Échec ({step}): {error}")
|
|
traceback.print_exc()
|
|
finally:
|
|
_current_movie_id = None
|
|
db.commit()
|
|
|
|
|
|
async def _process_next() -> bool:
|
|
with SessionLocal() as db:
|
|
movie_id = db.scalar(
|
|
select(IsoMovie.id)
|
|
.where(IsoMovie.status == "queued")
|
|
.order_by(IsoMovie.id)
|
|
.limit(1)
|
|
)
|
|
if movie_id is None:
|
|
return False
|
|
await _process(movie_id)
|
|
return True
|
|
|
|
|
|
async def conversion_worker() -> None:
|
|
while True:
|
|
processed = await _process_next()
|
|
if not processed:
|
|
await asyncio.sleep(settings.worker_interval)
|