✨ UI dynamique (couleurs par etat, spinner, terminal de conversion live, restes de conversion, liens MKV), responsive, scan ISO par contenu, retrait Sonarr/Prowlarr/Jellyfin/Seerr
This commit is contained in:
1 parent
078905e944
commit
70ce0b95a8
20 files changed
+793
-1143
No files matched your search
+89
-25
@@ -11,6 +11,7 @@ import re
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
@@ -21,6 +22,9 @@ INVALID_CHARACTERS = re.compile(r'[/\\:*?"<>|]')
|
||||
# Mode robot de makemkvcon: TINFO:<titre>,9,<code>,"H:MM:SS" par titre
|
||||
# (code 9 = duree, voir makemkv.com/developers/usage.txt).
|
||||
TITLE_DURATION = re.compile(r'TINFO:(\d+),9,\d+,"(\d+):(\d{2}):(\d{2})"')
|
||||
# En-tete EBML (Matroska): un fichier .iso qui commence par ces octets est
|
||||
# en realite un MKV renomme.
|
||||
EBML_MAGIC = b"\x1aE\xdf\xa3"
|
||||
|
||||
|
||||
def guarded_folder(folder: Path) -> Path:
|
||||
@@ -44,15 +48,15 @@ class ConversionPaths:
|
||||
destination_folder: Path
|
||||
|
||||
|
||||
def container_iso_path(movie: IsoMovie) -> Path:
|
||||
"""Chemin de l'ISO tel que vu dans le conteneur.
|
||||
def radarr_to_container_path(path: str) -> Path:
|
||||
"""Traduit un chemin Radarr vers son equivalent dans le conteneur.
|
||||
|
||||
Radarr rapporte ses chemins dans son propre referentiel
|
||||
(radarr_films_dir); si celui-ci differe du point de montage du conteneur
|
||||
(films_dir), on traduit. Sans radarr_films_dir, les chemins sont pris
|
||||
tels quels (montage "meme chemin").
|
||||
"""
|
||||
iso = Path(movie.path)
|
||||
iso = Path(path)
|
||||
radarr_root = settings.radarr_films_dir
|
||||
if radarr_root is not None:
|
||||
try:
|
||||
@@ -62,6 +66,27 @@ def container_iso_path(movie: IsoMovie) -> Path:
|
||||
return iso
|
||||
|
||||
|
||||
def container_iso_path(movie: IsoMovie) -> Path:
|
||||
"""Chemin de l'ISO tel que vu dans le conteneur."""
|
||||
return radarr_to_container_path(movie.path)
|
||||
|
||||
|
||||
def looks_like_iso(radarr_path: str) -> bool:
|
||||
"""Verifie qu'un fichier .iso est bien une image disque, pas un MKV renomme.
|
||||
|
||||
L'extension suffit a preslectionner, mais des MKV circulent parfois avec
|
||||
un nom en .iso: on ecarte tout fichier dont l'en-tete est EBML (Matroska).
|
||||
Si le contenu est illisible, on fait confiance a l'extension.
|
||||
"""
|
||||
if not radarr_path.lower().endswith(".iso"):
|
||||
return False
|
||||
try:
|
||||
with radarr_to_container_path(radarr_path).open("rb") as handle:
|
||||
return handle.read(4) != EBML_MAGIC
|
||||
except OSError:
|
||||
return True
|
||||
|
||||
|
||||
def conversion_paths(movie: IsoMovie) -> ConversionPaths:
|
||||
title = sanitize_component(movie.title)
|
||||
movie_name = f"{title} {movie.year}" if movie.year else title
|
||||
@@ -81,7 +106,47 @@ def conversion_paths(movie: IsoMovie) -> ConversionPaths:
|
||||
)
|
||||
|
||||
|
||||
def longest_title_id(iso: Path) -> str:
|
||||
def workspace_files(folder: Path) -> list[str]:
|
||||
"""Contenu du dossier de travail (restes d'anciennes conversions)."""
|
||||
if not folder.is_dir():
|
||||
return []
|
||||
return sorted(entry.name for entry in folder.iterdir())
|
||||
|
||||
|
||||
def clear_workspace(folder: Path) -> int:
|
||||
"""Vide le dossier de travail; renvoie le nombre d'entrees supprimees."""
|
||||
removed = 0
|
||||
if not folder.is_dir():
|
||||
return removed
|
||||
for entry in folder.iterdir():
|
||||
if entry.is_dir() and not entry.is_symlink():
|
||||
shutil.rmtree(entry)
|
||||
else:
|
||||
entry.unlink()
|
||||
removed += 1
|
||||
return removed
|
||||
|
||||
|
||||
def _run_makemkv(args: list[str], on_line: Callable[[str], None] | None = None) -> tuple[int, str]:
|
||||
"""Execute makemkvcon et diffuse sa sortie ligne par ligne.
|
||||
|
||||
stderr est fusionne dans stdout (la sortie de MakeMKV n'est pas
|
||||
structuree). Renvoie (code de sortie, sortie complete).
|
||||
"""
|
||||
with subprocess.Popen( # noqa: S603 - arguments construits en interne
|
||||
args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1
|
||||
) as process:
|
||||
chunks: list[str] = []
|
||||
assert process.stdout is not None
|
||||
for line in process.stdout:
|
||||
chunks.append(line)
|
||||
if on_line is not None:
|
||||
on_line(line.rstrip("\n"))
|
||||
returncode = process.wait()
|
||||
return returncode, "".join(chunks)
|
||||
|
||||
|
||||
def longest_title_id(iso: Path, on_line: Callable[[str], None] | None = None) -> str:
|
||||
"""Identifiant du titre le plus long, via ``makemkvcon --robot info``.
|
||||
|
||||
Les identifiants ne suivent pas la duree: le titre 0 n'est pas
|
||||
@@ -89,42 +154,42 @@ def longest_title_id(iso: Path) -> str:
|
||||
retombe sur le titre 0. Le seuil minlength est laisse par defaut (120 s)
|
||||
pour que la numerotation concorde avec la commande ``mkv``.
|
||||
"""
|
||||
result = subprocess.run(
|
||||
["makemkvcon", "--robot", "info", f"iso:{iso}"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
returncode, output = _run_makemkv(
|
||||
["makemkvcon", "--robot", "info", f"iso:{iso}"], on_line
|
||||
)
|
||||
best_title, best_seconds = "0", -1
|
||||
for line in result.stdout.splitlines():
|
||||
for line in output.splitlines():
|
||||
match = TITLE_DURATION.search(line)
|
||||
if not match:
|
||||
continue
|
||||
seconds = int(match[2]) * 3600 + int(match[3]) * 60 + int(match[4])
|
||||
if seconds > best_seconds:
|
||||
best_title, best_seconds = match[1], seconds
|
||||
return best_title
|
||||
return best_title if returncode == 0 or best_seconds >= 0 else "0"
|
||||
|
||||
|
||||
def extract_mkv(movie: IsoMovie, mkv_path: Path) -> None:
|
||||
def extract_mkv(
|
||||
movie: IsoMovie,
|
||||
mkv_path: Path,
|
||||
on_line: Callable[[str], None] | None = None,
|
||||
) -> None:
|
||||
mkv_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if settings.simulate_conversion:
|
||||
# Simulation en attendant MakeMKV sur le NAS : fichier MKV de substitution.
|
||||
mkv_path.write_text(
|
||||
"MKV simule par MKVTool — MakeMKV n'est pas installe dans cet environnement.\n"
|
||||
)
|
||||
if on_line is not None:
|
||||
on_line("MKV simule par MKVTool (mode simulation).")
|
||||
return
|
||||
if shutil.which("makemkvcon") is None:
|
||||
raise RuntimeError("MakeMKV (makemkvcon) n'est pas installe sur le serveur")
|
||||
iso = container_iso_path(movie)
|
||||
title = longest_title_id(iso)
|
||||
result = subprocess.run(
|
||||
["makemkvcon", "mkv", f"iso:{iso}", title, str(mkv_path.parent)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
title = longest_title_id(iso, on_line)
|
||||
returncode, output = _run_makemkv(
|
||||
["makemkvcon", "mkv", f"iso:{iso}", title, str(mkv_path.parent)], on_line
|
||||
)
|
||||
output = result.stdout or ""
|
||||
error = result.stderr or ""
|
||||
if result.returncode != 0:
|
||||
if returncode != 0:
|
||||
if "purchase an activation key" in output or "evaluation period" in output:
|
||||
raise RuntimeError(
|
||||
"MakeMKV n'est pas activé: une clé est requise pour la conversion. "
|
||||
@@ -133,18 +198,17 @@ def extract_mkv(movie: IsoMovie, mkv_path: Path) -> None:
|
||||
"ou ajoutez app_Key = \"<clé>\" dans /config/.MakeMKV/settings.conf "
|
||||
"(nom app_Key, pas app_MakeMKV_key). Voir IMAGE.md."
|
||||
)
|
||||
if result.returncode < 0:
|
||||
if returncode < 0:
|
||||
# Un code negatif signale un processus tue par un signal:
|
||||
# SIGKILL = en general le tueur OOM (manque de memoire).
|
||||
try:
|
||||
name = signal.Signals(-result.returncode).name
|
||||
name = signal.Signals(-returncode).name
|
||||
except ValueError:
|
||||
name = f"signal {-result.returncode}"
|
||||
name = f"signal {-returncode}"
|
||||
reason = f"processus tué par {name} — souvent un manque de mémoire"
|
||||
else:
|
||||
reason = f"code {result.returncode}"
|
||||
detail = "\n".join(part.strip() for part in (error, output) if part.strip())
|
||||
raise RuntimeError(f"MakeMKV a échoué ({reason}): {detail}")
|
||||
reason = f"code {returncode}"
|
||||
raise RuntimeError(f"MakeMKV a échoué ({reason}): {output.strip()}")
|
||||
produced = sorted(mkv_path.parent.glob("*.mkv"))
|
||||
if not produced:
|
||||
raise RuntimeError("MakeMKV n'a produit aucun fichier MKV")
|
||||
|
||||
Reference in new issue
Block a user