Files
mkvtool/app/radarr.py
T

86 lines
3.3 KiB
Python

from pathlib import PurePath
import httpx
class RadarrClient:
def __init__(self, url: str, api_key: str) -> None:
self._url = url.rstrip("/")
self._headers = {"X-Api-Key": api_key}
async def _get(self, endpoint: str) -> object:
async with httpx.AsyncClient(timeout=30) as client:
response = await client.get(f"{self._url}/api/v3/{endpoint}", headers=self._headers)
response.raise_for_status()
return response.json()
async def system_status(self) -> dict:
result = await self._get("system/status")
if not isinstance(result, dict):
raise ValueError("Réponse Radarr inattendue")
return result
async def movies(self) -> list[dict]:
# Radarr does not always embed movieFile by default depending on client version.
# The documented way is to request it explicitly.
result = await self._get("movie?includeMovieFile=true")
if not isinstance(result, list):
raise ValueError("Réponse Radarr inattendue")
return result
async def _command(self, payload: dict) -> None:
"""Enfile une commande Radarr (traitees sequentiellement par Radarr)."""
async with httpx.AsyncClient(timeout=30) as client:
response = await client.post(
f"{self._url}/api/v3/command",
headers=self._headers,
json=payload,
)
response.raise_for_status()
async def movie(self, movie_id: int) -> dict:
"""Fiche Radarr d'un film (avec son movieFile): donne le chemin
attendu du fichier, notamment apres renommage Media Management."""
result = await self._get(f"movie/{movie_id}")
if not isinstance(result, dict):
raise ValueError("Réponse Radarr inattendue")
return result
async def rescan_movie(self, movie_id: int) -> None:
"""Demande a Radarr de rescanner le dossier du film.
Apres validation d'une conversion, le dossier ne contient plus que
le MKV lie (lien dur): Radarr l'adopte comme fichier du film a la
place de l'ISO supprimee.
"""
await self._command({"name": "RescanMovie", "movieId": movie_id})
async def rename_movie(self, movie_id: int) -> None:
"""Demande a Radarr de renommer les fichiers du film selon sa config
Media Management.
Enchaine apres le rescan: le MKV lie prend le nom standard Radarr
(l'ancien nom de l'ISO ne correspond pas au format attendu). Le
renommage preserve l'inode, le lien dur reste intact.
"""
await self._command({"name": "RenameMovie", "movieId": movie_id})
def movie_file_path(movie: dict) -> str | None:
"""Chemin du fichier courant rapporte par Radarr.
Les espaces parasites (tete surtout — une racine Radarr configuree avec
une espace de trop) sont ecartees: elles casseraient silencieusement la
traduction de chemin (relative_to echoue) et MakeMKV chercherait un
fichier « inexistant ».
"""
movie_file = movie.get("movieFile") or {}
path = movie_file.get("path")
if path:
return str(path).strip()
relative_path = movie_file.get("relativePath")
movie_path = movie.get("path")
if relative_path and movie_path:
return str(PurePath(str(movie_path).strip()) / str(relative_path).strip())
return None