✨ Rattrapage: renommage Radarr des films deja traites (unitaire + global, avant la v1.0.26)
This commit is contained in:
1 parent
b4cd2dc855
commit
aadf30bb07
4 files changed
+205
-9
No files matched your search
+58
-9
@@ -44,6 +44,8 @@ from app.schemas import (
|
|||||||
AuthCredentialsWrite,
|
AuthCredentialsWrite,
|
||||||
AuthSetupWrite,
|
AuthSetupWrite,
|
||||||
AuthUserRead,
|
AuthUserRead,
|
||||||
|
BulkRenameFailure,
|
||||||
|
BulkRenameResult,
|
||||||
ConnectionResult,
|
ConnectionResult,
|
||||||
ConversionLogRead,
|
ConversionLogRead,
|
||||||
HealthRead,
|
HealthRead,
|
||||||
@@ -469,6 +471,58 @@ async def _delete_iso_torrent(iso_path: str) -> None:
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
async def _sync_radarr_rename(movie: IsoMovie) -> None:
|
||||||
|
"""Rescan puis renommage Radarr d'un film.
|
||||||
|
|
||||||
|
Radarr rescanne le dossier du film puis renomme ses fichiers selon sa
|
||||||
|
config Media Management. Les commandes Radarr sont executees dans
|
||||||
|
l'ordre d'envoi; le renommage preserve l'inode, le lien dur reste intact.
|
||||||
|
"""
|
||||||
|
radarr_client = client_from_config()
|
||||||
|
await radarr_client.rescan_movie(movie.radarr_movie_id)
|
||||||
|
await radarr_client.rename_movie(movie.radarr_movie_id)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/movies/{movie_id}/radarr-rename", response_model=IsoMovieRead)
|
||||||
|
async def radarr_rename_movie(movie_id: int, db: DbSession) -> IsoMovie:
|
||||||
|
"""Rescan + renommage Radarr pour un film deja traite.
|
||||||
|
|
||||||
|
Rattrapage des conversions faites avant l'automatisme: le MKV lie
|
||||||
|
garde le nom de l'ISO, Radarr lui applique sa config Media Management.
|
||||||
|
"""
|
||||||
|
movie = db.get(IsoMovie, movie_id)
|
||||||
|
if movie is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Film introuvable")
|
||||||
|
if movie.status != "completed":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=409, detail="Seuls les films déjà traités peuvent être renommés via Radarr"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
await _sync_radarr_rename(movie)
|
||||||
|
except Exception as error: # noqa: BLE001 - message explicite pour l'UI
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=409, detail=f"Renommage Radarr impossible: {error}"
|
||||||
|
) from error
|
||||||
|
return movie
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/radarr/rename-processed", response_model=BulkRenameResult)
|
||||||
|
async def radarr_rename_processed(db: DbSession) -> BulkRenameResult:
|
||||||
|
"""Rescan + renommage Radarr de tous les films deja traites."""
|
||||||
|
movies = list(
|
||||||
|
db.scalars(select(IsoMovie).where(IsoMovie.status == "completed").order_by(IsoMovie.title))
|
||||||
|
)
|
||||||
|
renamed = 0
|
||||||
|
failures: list[BulkRenameFailure] = []
|
||||||
|
for movie in movies:
|
||||||
|
try:
|
||||||
|
await _sync_radarr_rename(movie)
|
||||||
|
renamed += 1
|
||||||
|
except Exception as error: # noqa: BLE001 - on continue avec les autres
|
||||||
|
failures.append(BulkRenameFailure(title=movie.title, error=f"{error}"))
|
||||||
|
return BulkRenameResult(renamed=renamed, failures=failures)
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/movies/{movie_id}/convert", response_model=IsoMovieRead)
|
@app.post("/api/movies/{movie_id}/convert", response_model=IsoMovieRead)
|
||||||
def convert_movie(movie_id: int, db: DbSession, force: bool = False) -> IsoMovie:
|
def convert_movie(movie_id: int, db: DbSession, force: bool = False) -> IsoMovie:
|
||||||
"""Met la conversion en file.
|
"""Met la conversion en file.
|
||||||
@@ -588,17 +642,12 @@ async def validate_movie(movie_id: int, db: DbSession) -> ValidationRead:
|
|||||||
db.commit()
|
db.commit()
|
||||||
snapshot = ValidationRead.model_validate(movie)
|
snapshot = ValidationRead.model_validate(movie)
|
||||||
|
|
||||||
# Rescan puis renommage Radarr: le dossier ne contient plus que le MKV
|
# Rescan puis renommage Radarr (voir _sync_radarr_rename). Best effort:
|
||||||
# lie; Radarr l'adopte comme fichier du film puis le renomme selon sa
|
# un echec n'invalide pas la validation (l'ISO est deja supprimee),
|
||||||
# config Media Management (l'ancien nom de l'ISO ne correspond pas au
|
# il remonte en avertissement.
|
||||||
# format attendu). Les commandes Radarr sont executees dans l'ordre
|
|
||||||
# d'envoi. Best effort: un echec n'invalide pas la validation (l'ISO est
|
|
||||||
# deja supprimee), il remonte en avertissement.
|
|
||||||
rescan_warning: str | None = None
|
rescan_warning: str | None = None
|
||||||
try:
|
try:
|
||||||
radarr_client = client_from_config()
|
await _sync_radarr_rename(movie)
|
||||||
await radarr_client.rescan_movie(movie.radarr_movie_id)
|
|
||||||
await radarr_client.rename_movie(movie.radarr_movie_id)
|
|
||||||
except Exception as error: # noqa: BLE001 - la validation reste acquise
|
except Exception as error: # noqa: BLE001 - la validation reste acquise
|
||||||
rescan_warning = (
|
rescan_warning = (
|
||||||
f"ISO supprimée, mais mise à jour Radarr impossible: {error}. "
|
f"ISO supprimée, mais mise à jour Radarr impossible: {error}. "
|
||||||
|
|||||||
@@ -97,6 +97,16 @@ class ValidationRead(IsoMovieRead):
|
|||||||
rescan_warning: str | None = None
|
rescan_warning: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class BulkRenameFailure(BaseModel):
|
||||||
|
title: str
|
||||||
|
error: str
|
||||||
|
|
||||||
|
|
||||||
|
class BulkRenameResult(BaseModel):
|
||||||
|
renamed: int
|
||||||
|
failures: list[BulkRenameFailure] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
class ConversionLogRead(BaseModel):
|
class ConversionLogRead(BaseModel):
|
||||||
lines: list[str]
|
lines: list[str]
|
||||||
running: bool
|
running: bool
|
||||||
|
|||||||
@@ -2,8 +2,10 @@ import errno
|
|||||||
import json
|
import json
|
||||||
import shutil
|
import shutil
|
||||||
import time
|
import time
|
||||||
|
from datetime import datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
import httpx
|
||||||
import respx
|
import respx
|
||||||
from fastapi.testclient import TestClient
|
from fastapi.testclient import TestClient
|
||||||
from httpx import Response
|
from httpx import Response
|
||||||
@@ -467,3 +469,87 @@ def test_validate_survives_radarr_rescan_failure() -> None:
|
|||||||
assert body["status"] == "completed"
|
assert body["status"] == "completed"
|
||||||
assert body["rescan_warning"] is not None
|
assert body["rescan_warning"] is not None
|
||||||
assert "mise à jour Radarr impossible" in body["rescan_warning"]
|
assert "mise à jour Radarr impossible" in body["rescan_warning"]
|
||||||
|
|
||||||
|
|
||||||
|
@respx.mock
|
||||||
|
def test_radarr_rename_only_for_processed_movies() -> None:
|
||||||
|
"""Le renommage Radarr unitaire n'accepte que les films termines."""
|
||||||
|
reset_state()
|
||||||
|
create_film_folder()
|
||||||
|
mock_radarr(str(settings.radarr_films_dir / FILM_FOLDER))
|
||||||
|
with TestClient(app) as client:
|
||||||
|
configure_radarr(client)
|
||||||
|
client.post("/api/scans")
|
||||||
|
movie_id = client.get("/api/movies").json()[0]["id"]
|
||||||
|
|
||||||
|
# Film non termine: refus.
|
||||||
|
refused = client.post(f"/api/movies/{movie_id}/radarr-rename")
|
||||||
|
assert refused.status_code == 409
|
||||||
|
|
||||||
|
client.post(f"/api/movies/{movie_id}/convert")
|
||||||
|
wait_for_status(client, "validating")
|
||||||
|
respx.post("http://radarr:7878/api/v3/command").mock(
|
||||||
|
return_value=Response(201, json={"id": 1})
|
||||||
|
)
|
||||||
|
client.post(f"/api/movies/{movie_id}/validate")
|
||||||
|
wait_for_status(client, "completed")
|
||||||
|
|
||||||
|
# Film termine: rescan + renommage Radarr.
|
||||||
|
command_route = respx.post("http://radarr:7878/api/v3/command")
|
||||||
|
response = client.post(f"/api/movies/{movie_id}/radarr-rename")
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json()["status"] == "completed"
|
||||||
|
commands = [json.loads(call.request.content) for call in command_route.calls]
|
||||||
|
# Deux appels de plus depuis le rattrapage: Rescan puis Rename.
|
||||||
|
assert commands[-2:] == [
|
||||||
|
{"name": "RescanMovie", "movieId": 10},
|
||||||
|
{"name": "RenameMovie", "movieId": 10},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@respx.mock
|
||||||
|
def test_radarr_rename_processed_bulk_reports_failures() -> None:
|
||||||
|
"""Le renommage global traite tous les films termines et collecte les
|
||||||
|
echecs sans interrompre la serie."""
|
||||||
|
reset_state()
|
||||||
|
create_film_folder()
|
||||||
|
with SessionLocal() as db:
|
||||||
|
db.add(
|
||||||
|
IsoMovie(
|
||||||
|
radarr_movie_id=10,
|
||||||
|
radarr_movie_file_id=20,
|
||||||
|
title="Film A",
|
||||||
|
path="/films/a.iso",
|
||||||
|
status="completed",
|
||||||
|
last_seen_at=datetime(2026, 1, 1),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
db.add(
|
||||||
|
IsoMovie(
|
||||||
|
radarr_movie_id=11,
|
||||||
|
radarr_movie_file_id=21,
|
||||||
|
title="Film B",
|
||||||
|
path="/films/b.iso",
|
||||||
|
status="completed",
|
||||||
|
last_seen_at=datetime(2026, 1, 1),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
def command_response(request: httpx.Request) -> Response:
|
||||||
|
body = json.loads(request.content)
|
||||||
|
if body["movieId"] == 11:
|
||||||
|
return Response(500, text="boom")
|
||||||
|
return Response(201, json={"id": 1})
|
||||||
|
|
||||||
|
respx.post("http://radarr:7878/api/v3/command").mock(side_effect=command_response)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
configure_radarr(client)
|
||||||
|
result = client.post("/api/radarr/rename-processed")
|
||||||
|
|
||||||
|
assert result.status_code == 200
|
||||||
|
body = result.json()
|
||||||
|
assert body["renamed"] == 1
|
||||||
|
assert len(body["failures"]) == 1
|
||||||
|
assert body["failures"][0]["title"] == "Film B"
|
||||||
|
assert "500" in body["failures"][0]["error"]
|
||||||
@@ -366,6 +366,45 @@ export default function App() {
|
|||||||
}
|
}
|
||||||
}, [logLines]);
|
}, [logLines]);
|
||||||
|
|
||||||
|
async function radarrRename(movie: MovieDetail) {
|
||||||
|
setModalBusy(true);
|
||||||
|
try {
|
||||||
|
await api<Movie>(`/api/movies/${movie.id}/radarr-rename`, { method: "POST" });
|
||||||
|
await loadMovies();
|
||||||
|
notify(
|
||||||
|
`« ${movie.title} » envoyé à Radarr — rescan puis renommage selon sa config Media Management.`,
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
notify(`Renommage de « ${movie.title} » impossible : ${(error as Error).message}`, "error");
|
||||||
|
} finally {
|
||||||
|
setModalBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function radarrRenameAll() {
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const result = await api<{
|
||||||
|
renamed: number;
|
||||||
|
failures: { title: string; error: string }[];
|
||||||
|
}>("/api/radarr/rename-processed", { method: "POST" });
|
||||||
|
if (result.failures.length === 0) {
|
||||||
|
notify(
|
||||||
|
`${result.renamed} film(s) traité(s) envoyé(s) à Radarr — renommage selon sa config.`,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
notify(
|
||||||
|
`${result.renamed} renommé(s), ${result.failures.length} en échec (ex: ${result.failures[0].title}: ${result.failures[0].error}).`,
|
||||||
|
"error",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
notify((error as Error).message, "error");
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function copyPath(path: string) {
|
function copyPath(path: string) {
|
||||||
navigator.clipboard.writeText(path).catch(() => undefined);
|
navigator.clipboard.writeText(path).catch(() => undefined);
|
||||||
notify("Chemin copié dans le presse-papiers.");
|
notify("Chemin copié dans le presse-papiers.");
|
||||||
@@ -981,6 +1020,11 @@ export default function App() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="title-actions">
|
<div className="title-actions">
|
||||||
<span>{movies.length} détecté(s)</span>
|
<span>{movies.length} détecté(s)</span>
|
||||||
|
{tab === "done" && groups.done.length > 0 && (
|
||||||
|
<button className="small" disabled={busy} onClick={radarrRenameAll}>
|
||||||
|
Renommer les traités via Radarr
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
{selectMode ? (
|
{selectMode ? (
|
||||||
<button className="small" onClick={exitSelectMode}>Quitter la sélection</button>
|
<button className="small" onClick={exitSelectMode}>Quitter la sélection</button>
|
||||||
) : (
|
) : (
|
||||||
@@ -1376,6 +1420,7 @@ export default function App() {
|
|||||||
</button>
|
</button>
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
|
<>
|
||||||
<button className="primary" disabled={modalBusy || !convertible} onClick={() => convert(selected)}>
|
<button className="primary" disabled={modalBusy || !convertible} onClick={() => convert(selected)}>
|
||||||
{modalBusy
|
{modalBusy
|
||||||
? "Envoi…"
|
? "Envoi…"
|
||||||
@@ -1383,6 +1428,12 @@ export default function App() {
|
|||||||
? "Reprendre la conversion en MKV"
|
? "Reprendre la conversion en MKV"
|
||||||
: "Convertir en MKV"}
|
: "Convertir en MKV"}
|
||||||
</button>
|
</button>
|
||||||
|
{selected.status === "completed" && (
|
||||||
|
<button disabled={modalBusy} onClick={() => radarrRename(selected)}>
|
||||||
|
{modalBusy ? "Envoi…" : "Renommer via Radarr"}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{selected.status === "validating" ? (
|
{selected.status === "validating" ? (
|
||||||
|
|||||||
Reference in new issue
Block a user