✨ Pastille 'Radarr lie' (filtre + maj au scan) et ln nomme comme le fichier Radarr
This commit is contained in:
1 parent
78e6b0bb22
commit
f0b5f2b21e
9 files changed
+71
-204
No files matched your search
+8
-1
@@ -10,7 +10,7 @@ import httpx
|
||||
from fastapi import Cookie, Depends, FastAPI, HTTPException, Response
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy import inspect, select, text
|
||||
from sqlalchemy import inspect, select, text, update
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import auth
|
||||
@@ -54,6 +54,7 @@ async def lifespan(_: FastAPI):
|
||||
"failed_step": "TEXT",
|
||||
"last_error": "TEXT",
|
||||
"poster_url": "TEXT",
|
||||
"radarr_linked": "BOOLEAN DEFAULT 1",
|
||||
}
|
||||
with engine.begin() as conn:
|
||||
for column, ddl in migrations.items():
|
||||
@@ -270,6 +271,10 @@ async def scan_radarr(db: DbSession) -> ScanResult:
|
||||
|
||||
iso_files = created = updated = 0
|
||||
now = datetime.now(UTC)
|
||||
# Pastille "Radarr lie": on repart de zero, la boucle marque les films
|
||||
# toujours presents cote Radarr; les fichiers supprimes ou remplaces
|
||||
# passent donc a False.
|
||||
db.execute(update(IsoMovie).values(radarr_linked=False))
|
||||
for movie in movies:
|
||||
movie_file = movie.get("movieFile") or {}
|
||||
path = movie_file_path(movie)
|
||||
@@ -295,6 +300,7 @@ async def scan_radarr(db: DbSession) -> ScanResult:
|
||||
path=path,
|
||||
size=movie_file.get("size"),
|
||||
poster_url=_poster_url(movie),
|
||||
radarr_linked=True,
|
||||
last_seen_at=now,
|
||||
)
|
||||
db.add(item)
|
||||
@@ -305,6 +311,7 @@ async def scan_radarr(db: DbSession) -> ScanResult:
|
||||
item.path = path
|
||||
item.size = movie_file.get("size")
|
||||
item.poster_url = _poster_url(movie)
|
||||
item.radarr_linked = True
|
||||
item.last_seen_at = now
|
||||
updated += 1
|
||||
db.commit()
|
||||
|
||||
+3
-1
@@ -1,6 +1,6 @@
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import BigInteger, DateTime, String, Text, UniqueConstraint, func
|
||||
from sqlalchemy import BigInteger, Boolean, DateTime, String, Text, UniqueConstraint, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.database import Base
|
||||
@@ -25,6 +25,8 @@ class IsoMovie(Base):
|
||||
path: Mapped[str] = mapped_column(Text)
|
||||
size: Mapped[int | None] = mapped_column(BigInteger)
|
||||
status: Mapped[str] = mapped_column(String(30), default="detected")
|
||||
# Le fichier ISO existe toujours tel quel cote Radarr (mis a jour au scan).
|
||||
radarr_linked: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
poster_url: Mapped[str | None] = mapped_column(Text)
|
||||
last_seen_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now()
|
||||
|
||||
-112
@@ -1,112 +0,0 @@
|
||||
"""Nom du fichier MKV selon la configuration Media Management de Radarr.
|
||||
|
||||
Applique le "Standard Movie Format" de Radarr (/api/v3/config/naming) au
|
||||
fichier converti : les tokens usuels ({Movie Title}, {Release Year},
|
||||
{Quality Title}...) sont remplacés à partir des données du film et du
|
||||
movieFile. Si Radarr n'est pas configuré pour renommer (renameMovies=false),
|
||||
le nom d'origine du MKV est conservé.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
from app.converter import sanitize_component
|
||||
|
||||
_VIDEO_CODECS = {
|
||||
"h264": "x264",
|
||||
"x264": "x264",
|
||||
"h265": "x265",
|
||||
"hevc": "x265",
|
||||
"x265": "x265",
|
||||
"av1": "AV1",
|
||||
"mpeg2video": "MPEG2",
|
||||
"mpeg-2": "MPEG2",
|
||||
"vc1": "VC1",
|
||||
"vp9": "VP9",
|
||||
"xvid": "Xvid",
|
||||
"divx": "DivX",
|
||||
}
|
||||
|
||||
_AUDIO_CODECS = {
|
||||
"ac3": "AC3",
|
||||
"eac3": "EAC3",
|
||||
"dts": "DTS",
|
||||
"truehd": "TrueHD",
|
||||
"flac": "FLAC",
|
||||
"aac": "AAC",
|
||||
"mp3": "MP3",
|
||||
"opus": "Opus",
|
||||
"vorbis": "Vorbis",
|
||||
"pcm": "PCM",
|
||||
"lpcm": "PCM",
|
||||
}
|
||||
|
||||
_INVALID_TOKEN = re.compile(r"\{[^{}]*\}")
|
||||
|
||||
|
||||
def _media_info_tokens(movie_file: dict) -> dict[str, str]:
|
||||
media = movie_file.get("mediaInfo") or {}
|
||||
video = str(media.get("videoCodec", "") or "").lower()
|
||||
audio = str(media.get("audioCodec", "") or "").lower()
|
||||
channels = str(media.get("audioChannels", "") or "")
|
||||
simple = "-".join(part for part in (_VIDEO_CODECS.get(video, video.upper()), channels) if part)
|
||||
full = " ".join(
|
||||
part
|
||||
for part in (
|
||||
_VIDEO_CODECS.get(video, video.upper()),
|
||||
_AUDIO_CODECS.get(audio, audio.upper()),
|
||||
channels,
|
||||
)
|
||||
if part
|
||||
)
|
||||
return {"MediaInfo Simple": simple, "MediaInfo Full": full}
|
||||
|
||||
|
||||
def _quality_tokens(movie_file: dict) -> dict[str, str]:
|
||||
quality = (movie_file.get("quality") or {}).get("quality") or {}
|
||||
revision = (movie_file.get("quality") or {}).get("revision") or {}
|
||||
title = str(quality.get("name", "") or "")
|
||||
version = int(revision.get("version", 1) or 1)
|
||||
is_real = int(revision.get("real", 0) or 0)
|
||||
return {
|
||||
"Quality Title": title,
|
||||
"Quality Full": " ".join(
|
||||
part
|
||||
for part in (title, "Proper" if version > 1 else "", "Real" if is_real else "")
|
||||
if part
|
||||
),
|
||||
"Quality Proper": "Proper" if version > 1 else "",
|
||||
"Quality Real": "Real" if is_real else "",
|
||||
}
|
||||
|
||||
|
||||
def movie_file_name(naming: dict, movie: dict, movie_file: dict, fallback: str) -> str:
|
||||
"""Construit le nom de fichier (sans extension) attendu par Radarr."""
|
||||
if not naming.get("renameMovies"):
|
||||
return fallback
|
||||
|
||||
pattern = str(naming.get("standardMovieFormat", "") or "")
|
||||
if not pattern:
|
||||
return fallback
|
||||
|
||||
tokens = {
|
||||
"Movie Title": sanitize_component(str(movie.get("title", "") or "")),
|
||||
"Movie CleanTitle": sanitize_component(str(movie.get("title", "") or "")),
|
||||
"Movie OriginalTitle": sanitize_component(str(movie.get("originalTitle", "") or "")),
|
||||
"Release Year": str(movie.get("year", "") or ""),
|
||||
"Year": str(movie.get("year", "") or ""),
|
||||
"Tmdb Id": str(movie.get("tmdbId", "") or ""),
|
||||
"Imdb Id": str(movie.get("imdbId", "") or ""),
|
||||
"Edition": sanitize_component(str(movie_file.get("edition", "") or "")),
|
||||
"Release Group": sanitize_component(str(movie_file.get("releaseGroup", "") or "")),
|
||||
}
|
||||
tokens.update(_quality_tokens(movie_file))
|
||||
tokens.update(_media_info_tokens(movie_file))
|
||||
|
||||
result = pattern
|
||||
for token, value in tokens.items():
|
||||
result = result.replace("{" + token + "}", value)
|
||||
result = result.replace("{" + token.lower() + "}", value)
|
||||
# Tokens inconnus: retires pour ne pas laisser d'accolades dans le nom.
|
||||
result = _INVALID_TOKEN.sub("", result)
|
||||
result = sanitize_component(result)
|
||||
return result or fallback
|
||||
@@ -28,19 +28,6 @@ class RadarrClient:
|
||||
raise ValueError("Réponse Radarr inattendue")
|
||||
return result
|
||||
|
||||
async def movie(self, movie_id: int) -> dict:
|
||||
result = await self._get(f"movie/{movie_id}?includeMovieFile=true")
|
||||
if not isinstance(result, dict):
|
||||
raise ValueError("Réponse Radarr inattendue")
|
||||
return result
|
||||
|
||||
async def naming(self) -> dict:
|
||||
"""Configuration Media Management: formats de renommage."""
|
||||
result = await self._get("config/naming")
|
||||
if not isinstance(result, dict):
|
||||
raise ValueError("Réponse Radarr inattendue")
|
||||
return result
|
||||
|
||||
|
||||
def movie_file_path(movie: dict) -> str | None:
|
||||
movie_file = movie.get("movieFile") or {}
|
||||
|
||||
@@ -70,6 +70,7 @@ class IsoMovieRead(BaseModel):
|
||||
path: str
|
||||
size: int | None
|
||||
status: str
|
||||
radarr_linked: bool = True
|
||||
poster_url: str | None = None
|
||||
last_seen_at: datetime
|
||||
created_at: datetime | None = None
|
||||
|
||||
+3
-27
@@ -6,13 +6,10 @@ from pathlib import Path
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.conf_store import read_config
|
||||
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
|
||||
from app.naming import movie_file_name
|
||||
from app.radarr import RadarrClient
|
||||
|
||||
|
||||
async def _process(movie_id: int) -> None:
|
||||
@@ -33,7 +30,9 @@ async def _process(movie_id: int) -> None:
|
||||
step = "importing"
|
||||
movie.status = "importing"
|
||||
db.commit()
|
||||
target_name = await _target_name(movie)
|
||||
# Le MKV lié reprend le nom du fichier Radarr (l'ISO), seule
|
||||
# l'extension change.
|
||||
target_name = f"{Path(movie.path).stem}.mkv"
|
||||
await asyncio.to_thread(
|
||||
import_mkv,
|
||||
paths.mkv_path,
|
||||
@@ -53,29 +52,6 @@ async def _process(movie_id: int) -> None:
|
||||
db.commit()
|
||||
|
||||
|
||||
async def _target_name(movie: IsoMovie) -> str:
|
||||
"""Nom du lien selon la configuration Media Management de Radarr.
|
||||
|
||||
En cas d'erreur (Radarr non configuré, API injoignable), on retombe sur le
|
||||
nom du MKV produit par MakeMKV plutôt que de faire échouer la conversion.
|
||||
"""
|
||||
fallback = Path(conversion_paths(movie).mkv_path).name
|
||||
cfg = read_config()
|
||||
if not cfg.radarr.url or not cfg.radarr.api_key:
|
||||
return fallback
|
||||
try:
|
||||
client = RadarrClient(cfg.radarr.url, cfg.radarr.api_key)
|
||||
radarr_movie = await client.movie(movie.radarr_movie_id)
|
||||
naming = await client.naming()
|
||||
name = movie_file_name(
|
||||
naming, radarr_movie, radarr_movie.get("movieFile") or {}, fallback
|
||||
)
|
||||
return name if name.lower().endswith(".mkv") else f"{name}.mkv"
|
||||
except Exception: # noqa: BLE001 - le nommage ne doit pas bloquer la conversion
|
||||
traceback.print_exc()
|
||||
return fallback
|
||||
|
||||
|
||||
async def _process_next() -> bool:
|
||||
with SessionLocal() as db:
|
||||
movie_id = db.scalar(
|
||||
|
||||
Reference in new issue
Block a user