✨ Selection du titre le plus long (robot TINFO) + code de sortie/signal dans l'erreur MakeMKV

This commit is contained in:
Orionis312050 committed 2026-10-13 16:26:52 +00:00
1 parent 39319b7caa
commit 078905e944
2 files changed
+100 -4

No files matched your search

+46 -4
View File
@@ -9,6 +9,7 @@ import errno
import os import os
import re import re
import shutil import shutil
import signal
import subprocess import subprocess
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
@@ -17,6 +18,9 @@ from app.config import settings
from app.models import IsoMovie from app.models import IsoMovie
INVALID_CHARACTERS = re.compile(r'[/\\:*?"<>|]') 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})"')
def guarded_folder(folder: Path) -> Path: def guarded_folder(folder: Path) -> Path:
@@ -77,6 +81,30 @@ def conversion_paths(movie: IsoMovie) -> ConversionPaths:
) )
def longest_title_id(iso: Path) -> str:
"""Identifiant du titre le plus long, via ``makemkvcon --robot info``.
Les identifiants ne suivent pas la duree: le titre 0 n'est pas
forcement le film (souvent un bonus). En cas d'echec de l'analyse on
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,
)
best_title, best_seconds = "0", -1
for line in result.stdout.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
def extract_mkv(movie: IsoMovie, mkv_path: Path) -> None: def extract_mkv(movie: IsoMovie, mkv_path: Path) -> None:
mkv_path.parent.mkdir(parents=True, exist_ok=True) mkv_path.parent.mkdir(parents=True, exist_ok=True)
if settings.simulate_conversion: if settings.simulate_conversion:
@@ -87,14 +115,17 @@ def extract_mkv(movie: IsoMovie, mkv_path: Path) -> None:
return return
if shutil.which("makemkvcon") is None: if shutil.which("makemkvcon") is None:
raise RuntimeError("MakeMKV (makemkvcon) n'est pas installe sur le serveur") raise RuntimeError("MakeMKV (makemkvcon) n'est pas installe sur le serveur")
iso = container_iso_path(movie)
title = longest_title_id(iso)
result = subprocess.run( result = subprocess.run(
["makemkvcon", "mkv", f"iso:{container_iso_path(movie)}", "0", str(mkv_path.parent)], ["makemkvcon", "mkv", f"iso:{iso}", title, str(mkv_path.parent)],
capture_output=True, capture_output=True,
text=True, text=True,
) )
output = result.stdout or ""
error = result.stderr or ""
if result.returncode != 0: if result.returncode != 0:
detail = result.stderr.strip() or result.stdout.strip() if "purchase an activation key" in output or "evaluation period" in output:
if "purchase an activation key" in detail or "evaluation period" in detail:
raise RuntimeError( raise RuntimeError(
"MakeMKV n'est pas activé: une clé est requise pour la conversion. " "MakeMKV n'est pas activé: une clé est requise pour la conversion. "
"Renseignez la variable d'environnement MAKEMKV_KEY (clé bêta gratuite " "Renseignez la variable d'environnement MAKEMKV_KEY (clé bêta gratuite "
@@ -102,7 +133,18 @@ def extract_mkv(movie: IsoMovie, mkv_path: Path) -> None:
"ou ajoutez app_Key = \"<clé>\" dans /config/.MakeMKV/settings.conf " "ou ajoutez app_Key = \"<clé>\" dans /config/.MakeMKV/settings.conf "
"(nom app_Key, pas app_MakeMKV_key). Voir IMAGE.md." "(nom app_Key, pas app_MakeMKV_key). Voir IMAGE.md."
) )
raise RuntimeError(f"MakeMKV a echoue: {detail}") if result.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
except ValueError:
name = f"signal {-result.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}")
produced = sorted(mkv_path.parent.glob("*.mkv")) produced = sorted(mkv_path.parent.glob("*.mkv"))
if not produced: if not produced:
raise RuntimeError("MakeMKV n'a produit aucun fichier MKV") raise RuntimeError("MakeMKV n'a produit aucun fichier MKV")
+54
View File
@@ -195,3 +195,57 @@ def test_extract_fails_with_activation_error_when_makemkv_unactivated(
assert "MAKEMKV_KEY" in str(error) assert "MAKEMKV_KEY" in str(error)
else: else:
raise AssertionError("RuntimeError attendue") raise AssertionError("RuntimeError attendue")
def test_extract_reports_signal_kill(monkeypatch, tmp_path) -> None:
"""Un processus tue par signal (ex: OOM) est identifie dans l'erreur."""
from types import SimpleNamespace
monkeypatch.setattr(settings, "simulate_conversion", False)
monkeypatch.setattr("app.converter.shutil.which", lambda _: "/usr/bin/makemkvcon")
monkeypatch.setattr(
"app.converter.subprocess.run",
lambda *args, **kwargs: SimpleNamespace(returncode=-9, stdout="", stderr=""),
)
movie = IsoMovie(
radarr_movie_id=1, radarr_movie_file_id=2, title="ISO Movie", path="/x.iso"
)
try:
extract_mkv(movie, tmp_path / "out" / "movie.mkv")
except RuntimeError as error:
assert "SIGKILL" in str(error)
else:
raise AssertionError("RuntimeError attendue")
def test_extract_picks_longest_title(monkeypatch, tmp_path) -> None:
"""Le titre extrait est le plus long, pas le numero 0."""
from types import SimpleNamespace
robot_info = "\n".join(
[
'MSG:1005,0,1,"MakeMKV started"',
'TINFO:0,9,0,"0:02:30"',
'TINFO:1,9,0,"1:57:00"',
'TINFO:2,9,0,"0:24:13"',
]
)
def fake_run(args, **kwargs):
if "--robot" in args:
return SimpleNamespace(returncode=0, stdout=robot_info, stderr="")
# Commande mkv: on verifie le titre choisi et on simule la sortie.
assert args[3] == "1", f"titre attendu: 1, commande: {args}"
out = tmp_path / "out"
out.mkdir(parents=True, exist_ok=True)
(out / "movie.mkv").write_text("mkv")
return SimpleNamespace(returncode=0, stdout="", stderr="")
monkeypatch.setattr(settings, "simulate_conversion", False)
monkeypatch.setattr("app.converter.shutil.which", lambda _: "/usr/bin/makemkvcon")
monkeypatch.setattr("app.converter.subprocess.run", fake_run)
movie = IsoMovie(
radarr_movie_id=1, radarr_movie_file_id=2, title="ISO Movie", path="/x.iso"
)
extract_mkv(movie, tmp_path / "out" / "movie.mkv")
assert (tmp_path / "out" / "movie.mkv").exists()