Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
78e6b0bb22 | ||
|
|
2d2ebde4f6 | ||
|
|
198a014967 |
No files matched your search
@@ -58,6 +58,10 @@ COPY docker/entrypoint.py /entrypoint.py
|
||||
|
||||
ENV MKVTOOL_CONFIG_DIR=/config \
|
||||
MKVTOOL_WEB_DIR=/app/web/dist \
|
||||
MKVTOOL_FILMS_DIR=/films \
|
||||
MKVTOOL_RADARR_FILMS_DIR=/nas_storage/jellyfin/films \
|
||||
MKVTOOL_DOWNLOADS_DIR=/qbittorrentdownloads \
|
||||
MKVTOOL_SIMULATE_CONVERSION=false \
|
||||
MAKEMKV_VERSION=${MAKEMKV_VERSION}
|
||||
RUN mkdir -p /config
|
||||
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
# Image Docker MKVTool
|
||||
|
||||
Image de l'application complète : API FastAPI, interface web, worker de
|
||||
conversion ISO vers MKV, MakeMKV et ffmpeg. Une image est publiée dans le
|
||||
Container Registry GitLab a chaque release.
|
||||
|
||||
## Recuperer l'image
|
||||
|
||||
```bash
|
||||
docker login registry-gitlab.orionis-home.fr
|
||||
docker pull registry-gitlab.orionis-home.fr/deposit/mkvtool:v1.0.7
|
||||
```
|
||||
|
||||
Les tags disponibles : `vX.Y.Z` (une version par release GitLab) et `latest`.
|
||||
L'authentification se fait avec un compte GitLab (ou un Personal Access Token
|
||||
scopes `read_registry`).
|
||||
|
||||
## Construction de l'image
|
||||
|
||||
L'image est construite par la CI (job `container:image`, Kaniko) a chaque tag
|
||||
`vX.Y.Z`. Le `Dockerfile` est multi-etapes :
|
||||
|
||||
| Etape | Base | Role |
|
||||
|---|---|---|
|
||||
| `web` | `node:22-slim` | `npm ci` + `vite build` → `web/dist` |
|
||||
| `api` | `python:3.13-slim` | ffmpeg, MakeMKV compile depuis les sources, dependances `uv sync --no-dev` |
|
||||
|
||||
MakeMKV (`makemkvcon`) est compile dans l'image a partir de la version definie
|
||||
par l'argument de build `MAKEMKV_VERSION` (par defaut `2.0.0`). Le build local
|
||||
reste possible : `docker build -t mkvtool .`.
|
||||
|
||||
## Variables d'environnement
|
||||
|
||||
| Variable | Defaut image | Role |
|
||||
|---|---|---|
|
||||
| `PUID` / `PGID` | `0` / `0` | UID/GID sous lesquels le service tourne (modele LinuxServer.io) |
|
||||
| `TZ` | `UTC` | Fuseau horaire |
|
||||
| `MKVTOOL_CONFIG_DIR` | `/config` | Dossier de conf et base SQLite (`mkvtool.db`, `conf.json`) |
|
||||
| `MKVTOOL_WEB_DIR` | `/app/web/dist` | Emplacement du front servi par l'API |
|
||||
| `MKVTOOL_FILMS_DIR` | `/films` | Racine de la bibliotheque Jellyfin dans le conteneur |
|
||||
| `MKVTOOL_RADARR_FILMS_DIR` | `/nas_storage/jellyfin/films` | Racine telle que Radarr la rapporte ; les chemins ISO sont traduits vers `MKVTOOL_FILMS_DIR` |
|
||||
| `MKVTOOL_DOWNLOADS_DIR` | `/qbittorrentdownloads` | Racine des telechargements qBittorrent |
|
||||
| `MKVTOOL_SIMULATE_CONVERSION` | `false` | `true` = produit un faux MKV sans appeler MakeMKV (dev/tests) |
|
||||
| `MKVTOOL_WORKER_INTERVAL` | `10` | Secondes entre deux tours de la file de conversion |
|
||||
| `MAKEMKV_VERSION` | `2.0.0` | Version MakeMKV embarquee (visible dans `/api/health`) |
|
||||
|
||||
## Volumes
|
||||
|
||||
| Chemin conteneur | Contenu |
|
||||
|---|---|
|
||||
| `/config` | `conf.json` (connexions Radarr/qBittorrent, mis a jour par l'interface), `mkvtool.db` (inventaire + sessions) |
|
||||
| `/films` | Bibliotheque Jellyfin : dossiers des films, ISO sources et MKV finaux |
|
||||
| `/qbittorrentdownloads` | Telechargements qBittorrent : dossier de travail ou le MKV est extrait avant le lien dur |
|
||||
|
||||
La bibliotheque est montee en `/films` dans le conteneur. Radarr rapporte ses
|
||||
propres chemins (`MKVTOOL_RADARR_FILMS_DIR`, par defaut
|
||||
`/nas_storage/jellyfin/films`) : l'API traduit automatiquement les chemins ISO
|
||||
vers `/films` au moment de la conversion. Si Radarr utilise un autre chemin
|
||||
d'installation, ajustez `MKVTOOL_RADARR_FILMS_DIR`. Les telechargements
|
||||
qBittorrent restent montes au meme chemin pour que le lien dur soit possible.
|
||||
|
||||
## Ports
|
||||
|
||||
| Port | Service |
|
||||
|---|---|
|
||||
| `8000` | API + interface web (uvicorn) |
|
||||
|
||||
## Fonctionnement au demarrage
|
||||
|
||||
1. Le conteneur demarre en root, attribue `/config` a `PUID:PGID`, puis baisse
|
||||
les privileges et lance uvicorn sous cette identite.
|
||||
2. Premier lancement : une banniere dans les logs affiche un lien
|
||||
`/setup?token=...` a usage unique pour creer le compte (jeton regenere a
|
||||
chaque redemarrage tant qu'aucun compte n'existe).
|
||||
3. Le worker de conversion demarre et traite la file (une conversion a la
|
||||
fois) toutes les `MKVTOOL_WORKER_INTERVAL` secondes.
|
||||
|
||||
## Cycle de conversion d'un film
|
||||
|
||||
1. **Conversion** : MakeMKV extrait le MKV vers
|
||||
`$MKVTOOL_DOWNLOADS_DIR/<Film>/`.
|
||||
2. **Nettoyage** : le dossier du film dans Jellyfin (`/films/...` dans le
|
||||
conteneur) est vide (tout sauf l'ISO, gardee jusqu'a la validation).
|
||||
3. **Lien** : le MKV est lie par `ln` dans le dossier du film, nomme selon le
|
||||
Media Management de Radarr (`{Movie Title} ({Release Year})...`). Si
|
||||
Radarr ne renomme pas ou est injoignable, le nom MakeMKV est conserve.
|
||||
L'ISO et le torrent sont conserves tant que la conversion n'est pas validee.
|
||||
4. **Validation manuelle** (bouton dans l'interface) : supprime l'ISO, le
|
||||
torrent qBittorrent correspondant et le dossier de travail. Le MKV lie
|
||||
reste (lien dur, meme inode : aucune donnee n'est recopiee).
|
||||
|
||||
## Exemple docker run
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
--name mkvtool \
|
||||
--restart unless-stopped \
|
||||
-p 8000:8000 \
|
||||
-e PUID=1020 -e PGID=100 -e TZ=Europe/Paris \
|
||||
-e MKVTOOL_SIMULATE_CONVERSION=false \
|
||||
-v /volume1/docker/mkvtool:/config \
|
||||
-v /qbittorrentdownloads:/qbittorrentdownloads \
|
||||
-v /nas_storage/jellyfin/films:/films \
|
||||
registry-gitlab.orionis-home.fr/deposit/mkvtool:latest
|
||||
```
|
||||
|
||||
## Mise a jour
|
||||
|
||||
```bash
|
||||
docker pull registry-gitlab.orionis-home.fr/deposit/mkvtool:latest
|
||||
docker rm -f mkvtool
|
||||
# puis relancer la commande ci-dessus
|
||||
```
|
||||
|
||||
La base SQLite est migree automatiquement au demarrage (ajout de colonnes
|
||||
manquantes) ; `/config` doit donc etre un volume persistant.
|
||||
|
||||
## Sante
|
||||
|
||||
`GET /api/health` renvoie l'etat de la base et la disponibilite de
|
||||
`makemkvcon` — utile pour verifier que l'image est fonctionnelle :
|
||||
|
||||
```bash
|
||||
curl http://localhost:8000/api/health
|
||||
```
|
||||
+9
-1
@@ -6,6 +6,15 @@ from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
class AppSettings(BaseSettings):
|
||||
config_dir: Path = Path("./config")
|
||||
database_url: str | None = None
|
||||
films_dir: Path = Path("./films")
|
||||
# Racine de la bibliotheque telle que rapportee par Radarr, si elle
|
||||
# differe du point de montage dans le conteneur (films_dir). Les chemins
|
||||
# ISO stockes sont traduits grace a ce couple.
|
||||
radarr_films_dir: Path | None = None
|
||||
downloads_dir: Path = Path("./downloads")
|
||||
# Simulation (dev/tests): produit un faux MKV au lieu d'appeler MakeMKV.
|
||||
simulate_conversion: bool = True
|
||||
worker_interval: float = 10.0
|
||||
|
||||
model_config = SettingsConfigDict(env_prefix="MKVTOOL_", env_file=".env")
|
||||
|
||||
@@ -17,4 +26,3 @@ class AppSettings(BaseSettings):
|
||||
|
||||
|
||||
settings = AppSettings()
|
||||
|
||||
+52
-9
@@ -40,13 +40,31 @@ class ConversionPaths:
|
||||
destination_folder: Path
|
||||
|
||||
|
||||
def container_iso_path(movie: IsoMovie) -> Path:
|
||||
"""Chemin de l'ISO tel que vu 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)
|
||||
radarr_root = settings.radarr_films_dir
|
||||
if radarr_root is not None:
|
||||
try:
|
||||
return settings.films_dir / iso.relative_to(radarr_root)
|
||||
except ValueError:
|
||||
pass
|
||||
return iso
|
||||
|
||||
|
||||
def conversion_paths(movie: IsoMovie) -> ConversionPaths:
|
||||
title = sanitize_component(movie.title)
|
||||
movie_name = f"{title} {movie.year}" if movie.year else title
|
||||
mkv_name = f"{title} ({movie.year}).mkv" if movie.year else f"{title}.mkv"
|
||||
downloads_folder = settings.downloads_dir / movie_name
|
||||
|
||||
iso_folder = Path(movie.path).parent
|
||||
iso_folder = container_iso_path(movie).parent
|
||||
films_root = settings.films_dir.resolve()
|
||||
if iso_folder.resolve().is_relative_to(films_root):
|
||||
destination_folder = iso_folder
|
||||
@@ -70,7 +88,7 @@ def extract_mkv(movie: IsoMovie, mkv_path: Path) -> None:
|
||||
if shutil.which("makemkvcon") is None:
|
||||
raise RuntimeError("MakeMKV (makemkvcon) n'est pas installe sur le serveur")
|
||||
result = subprocess.run(
|
||||
["makemkvcon", "mkv", f"iso:{movie.path}", "0", str(mkv_path.parent)],
|
||||
["makemkvcon", "mkv", f"iso:{container_iso_path(movie)}", "0", str(mkv_path.parent)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
@@ -83,15 +101,38 @@ def extract_mkv(movie: IsoMovie, mkv_path: Path) -> None:
|
||||
produced[0].replace(mkv_path)
|
||||
|
||||
|
||||
def import_mkv(mkv_path: Path, destination_folder: Path) -> Path:
|
||||
"""Crée le lien du MKV dans le dossier du film, sans toucher au reste.
|
||||
def clear_folder(destination_folder: Path, keep: list[Path]) -> None:
|
||||
"""Vide le dossier du film, sauf les chemins listés dans keep (l'ISO...)."""
|
||||
resolved = guarded_folder(destination_folder)
|
||||
if not resolved.exists():
|
||||
return
|
||||
keep_resolved = {path.resolve() for path in keep}
|
||||
for entry in resolved.iterdir():
|
||||
if entry.resolve() in keep_resolved:
|
||||
continue
|
||||
if entry.is_dir() and not entry.is_symlink():
|
||||
shutil.rmtree(entry)
|
||||
else:
|
||||
entry.unlink()
|
||||
|
||||
L'ISO et les autres fichiers du dossier ne sont supprimés qu'à la
|
||||
validation manuelle (finalize_validation).
|
||||
|
||||
def import_mkv(
|
||||
mkv_path: Path,
|
||||
destination_folder: Path,
|
||||
target_name: str | None = None,
|
||||
keep: list[Path] | None = None,
|
||||
) -> Path:
|
||||
"""Nettoie le dossier du film puis crée le lien du MKV.
|
||||
|
||||
Ordre voulu: (1) suppression de tout ce qui traîne dans le dossier du
|
||||
film — sauf les chemins de `keep` (l'ISO reste en sécurité jusqu'à la
|
||||
validation manuelle) — puis (2) création du lien dur, nommé selon la
|
||||
configuration Media Management de Radarr (`target_name`).
|
||||
"""
|
||||
resolved = guarded_folder(destination_folder)
|
||||
resolved.mkdir(parents=True, exist_ok=True)
|
||||
target = resolved / mkv_path.name
|
||||
clear_folder(resolved, keep or [])
|
||||
target = resolved / (target_name or mkv_path.name)
|
||||
if target.exists() or target.is_symlink():
|
||||
target.unlink()
|
||||
try:
|
||||
@@ -116,13 +157,15 @@ def finalize_validation(destination_folder: Path, keep_name: str) -> None:
|
||||
entry.unlink()
|
||||
|
||||
|
||||
def cancel_conversion(mkv_path: Path, destination_folder: Path) -> None:
|
||||
def cancel_conversion(
|
||||
mkv_path: Path, destination_folder: Path, target_name: str | None = None
|
||||
) -> None:
|
||||
"""Annule une conversion en attente de validation.
|
||||
|
||||
Supprime le MKV converti et son lien dans le dossier du film (s'ils
|
||||
existent); l'ISO et le reste du dossier ne sont pas touches.
|
||||
"""
|
||||
target = destination_folder / mkv_path.name
|
||||
target = destination_folder / (target_name or mkv_path.name)
|
||||
for path in (target, mkv_path):
|
||||
if path.is_symlink() or path.exists():
|
||||
path.unlink()
|
||||
|
||||
+148
-5
@@ -1,3 +1,4 @@
|
||||
import asyncio
|
||||
import os
|
||||
import shutil
|
||||
from contextlib import asynccontextmanager
|
||||
@@ -14,9 +15,10 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from app import auth
|
||||
from app.conf_store import read_config, write_config
|
||||
from app.converter import cancel_conversion, conversion_paths, finalize_validation
|
||||
from app.database import Base, engine, get_db
|
||||
from app.models import IsoMovie
|
||||
from app.qbittorrent import QbittorrentClient
|
||||
from app.qbittorrent import QbittorrentClient, match_torrent
|
||||
from app.radarr import RadarrClient, movie_file_path
|
||||
from app.schemas import (
|
||||
ApiServiceSettingsRead,
|
||||
@@ -34,6 +36,7 @@ from app.schemas import (
|
||||
SettingsRead,
|
||||
SettingsWrite,
|
||||
)
|
||||
from app.worker import conversion_worker
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
@@ -45,14 +48,26 @@ async def lifespan(_: FastAPI):
|
||||
try:
|
||||
inspector = inspect(engine)
|
||||
columns = {col["name"] for col in inspector.get_columns("iso_movies")}
|
||||
if "processed_at" not in columns:
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("ALTER TABLE iso_movies ADD COLUMN processed_at DATETIME"))
|
||||
migrations = {
|
||||
"processed_at": "DATETIME",
|
||||
"completed_at": "DATETIME",
|
||||
"failed_step": "TEXT",
|
||||
"last_error": "TEXT",
|
||||
"poster_url": "TEXT",
|
||||
}
|
||||
with engine.begin() as conn:
|
||||
for column, ddl in migrations.items():
|
||||
if column not in columns:
|
||||
conn.execute(text(f"ALTER TABLE iso_movies ADD COLUMN {column} {ddl}"))
|
||||
except Exception:
|
||||
# Don't fail app startup for a best-effort migration.
|
||||
pass
|
||||
auth.bootstrap_setup()
|
||||
yield
|
||||
worker_task = asyncio.create_task(conversion_worker())
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
worker_task.cancel()
|
||||
|
||||
|
||||
app = FastAPI(title="MKVTool", version="0.1.0", lifespan=lifespan)
|
||||
@@ -238,6 +253,13 @@ def get_file(file_id: int, db: DbSession) -> IsoMovie:
|
||||
return item
|
||||
|
||||
|
||||
def _poster_url(movie: dict) -> str | None:
|
||||
for image in movie.get("images") or []:
|
||||
if image.get("coverType") == "poster":
|
||||
return str(image.get("remoteUrl") or image.get("url") or "") or None
|
||||
return None
|
||||
|
||||
|
||||
@app.post("/api/scans", response_model=ScanResult)
|
||||
async def scan_radarr(db: DbSession) -> ScanResult:
|
||||
client = client_from_config()
|
||||
@@ -272,6 +294,7 @@ async def scan_radarr(db: DbSession) -> ScanResult:
|
||||
year=movie.get("year"),
|
||||
path=path,
|
||||
size=movie_file.get("size"),
|
||||
poster_url=_poster_url(movie),
|
||||
last_seen_at=now,
|
||||
)
|
||||
db.add(item)
|
||||
@@ -281,6 +304,7 @@ async def scan_radarr(db: DbSession) -> ScanResult:
|
||||
item.year = movie.get("year")
|
||||
item.path = path
|
||||
item.size = movie_file.get("size")
|
||||
item.poster_url = _poster_url(movie)
|
||||
item.last_seen_at = now
|
||||
updated += 1
|
||||
db.commit()
|
||||
@@ -289,6 +313,125 @@ async def scan_radarr(db: DbSession) -> ScanResult:
|
||||
)
|
||||
|
||||
|
||||
# --- Conversion (file traitee par le worker, une tache a la fois) ---
|
||||
def _linked_mkv(movie: IsoMovie) -> Path | None:
|
||||
"""Retrouve le MKV lie dans le dossier du film (meme inode que la source)."""
|
||||
paths = conversion_paths(movie)
|
||||
if not paths.destination_folder.is_dir():
|
||||
return None
|
||||
candidates = sorted(
|
||||
entry
|
||||
for entry in paths.destination_folder.iterdir()
|
||||
if entry.is_file() and entry.suffix.lower() == ".mkv"
|
||||
)
|
||||
if not candidates:
|
||||
return None
|
||||
if paths.mkv_path.exists():
|
||||
source_inode = paths.mkv_path.stat().st_ino
|
||||
for candidate in candidates:
|
||||
if candidate.stat().st_ino == source_inode:
|
||||
return candidate
|
||||
return candidates[0]
|
||||
|
||||
|
||||
async def _delete_iso_torrent(iso_path: str) -> None:
|
||||
"""Supprime le torrent qBittorrent de l'ISO (best effort, sans bloquer)."""
|
||||
qb = read_config().qbittorrent
|
||||
if not qb.url or not qb.username or not qb.password:
|
||||
return
|
||||
try:
|
||||
client = QbittorrentClient(qb.url, qb.username, qb.password)
|
||||
torrents = await client.torrents()
|
||||
match = match_torrent(torrents, iso_path)
|
||||
if match is not None and match.get("hash"):
|
||||
await client.delete([str(match["hash"])], delete_files=True)
|
||||
except Exception: # noqa: BLE001 - qBittorrent ne doit pas bloquer la validation
|
||||
pass
|
||||
|
||||
|
||||
@app.post("/api/movies/{movie_id}/convert", response_model=IsoMovieRead)
|
||||
def convert_movie(movie_id: int, db: DbSession) -> IsoMovie:
|
||||
movie = db.get(IsoMovie, movie_id)
|
||||
if movie is None:
|
||||
raise HTTPException(status_code=404, detail="Film introuvable")
|
||||
if movie.status not in {"detected", "ready", "failed"}:
|
||||
raise HTTPException(
|
||||
status_code=409, detail="Ce film n'est pas convertible dans son état actuel"
|
||||
)
|
||||
movie.status = "queued"
|
||||
movie.failed_step = None
|
||||
movie.last_error = None
|
||||
db.commit()
|
||||
return movie
|
||||
|
||||
|
||||
@app.post("/api/movies/{movie_id}/cancel", response_model=IsoMovieRead)
|
||||
def cancel_movie(movie_id: int, db: DbSession) -> IsoMovie:
|
||||
movie = db.get(IsoMovie, movie_id)
|
||||
if movie is None:
|
||||
raise HTTPException(status_code=404, detail="Film introuvable")
|
||||
if movie.status not in {"queued", "validating"}:
|
||||
raise HTTPException(status_code=409, detail="Aucune conversion à annuler")
|
||||
if movie.status == "validating":
|
||||
paths = conversion_paths(movie)
|
||||
linked = _linked_mkv(movie)
|
||||
cancel_conversion(paths.mkv_path, paths.destination_folder, linked.name if linked else None)
|
||||
movie.status = "detected"
|
||||
db.commit()
|
||||
return movie
|
||||
|
||||
|
||||
@app.post("/api/movies/{movie_id}/validate", response_model=IsoMovieRead)
|
||||
async def validate_movie(movie_id: int, db: DbSession) -> IsoMovie:
|
||||
"""Validation manuelle: supprime l'ISO, le torrent et le dossier de travail.
|
||||
|
||||
Le MKV lie dans le dossier du film reste en place (le lien dur etant sur
|
||||
le meme inode, les donnees restent intactes).
|
||||
"""
|
||||
movie = db.get(IsoMovie, movie_id)
|
||||
if movie is None:
|
||||
raise HTTPException(status_code=404, detail="Film introuvable")
|
||||
if movie.status != "validating":
|
||||
raise HTTPException(status_code=409, detail="Ce film n'est pas en attente de validation")
|
||||
|
||||
paths = conversion_paths(movie)
|
||||
linked = _linked_mkv(movie)
|
||||
if linked is None:
|
||||
raise HTTPException(status_code=409, detail="Aucun MKV lié à valider")
|
||||
|
||||
# Supprime l'ISO et le reste du dossier du film, puis le torrent qBittorrent.
|
||||
finalize_validation(paths.destination_folder, linked.name)
|
||||
await _delete_iso_torrent(movie.path)
|
||||
|
||||
# Nettoyage du dossier de travail (le lien dur garde les donnees).
|
||||
if linked.exists() and paths.mkv_path.exists():
|
||||
paths.mkv_path.unlink()
|
||||
if paths.mkv_path.parent.is_dir() and not any(paths.mkv_path.parent.iterdir()):
|
||||
paths.mkv_path.parent.rmdir()
|
||||
|
||||
movie.status = "completed"
|
||||
now = datetime.now(UTC)
|
||||
movie.processed_at = now
|
||||
movie.completed_at = now
|
||||
db.commit()
|
||||
return movie
|
||||
|
||||
|
||||
@app.delete("/api/movies/{movie_id}", response_model=IsoMovieRead)
|
||||
def delete_movie(movie_id: int, db: DbSession) -> IsoMovie:
|
||||
movie = db.get(IsoMovie, movie_id)
|
||||
if movie is None:
|
||||
raise HTTPException(status_code=404, detail="Film introuvable")
|
||||
if movie.status in {"queued", "converting", "importing", "validating"}:
|
||||
raise HTTPException(
|
||||
status_code=409, detail="Une conversion est en cours: impossible de retirer ce film"
|
||||
)
|
||||
snapshot = IsoMovieRead.model_validate(movie)
|
||||
db.delete(movie)
|
||||
db.commit()
|
||||
return snapshot
|
||||
|
||||
|
||||
# --- Authentification locale ---
|
||||
# Premier lancement: le lien affiche dans les logs par bootstrap_setup() porte
|
||||
# un jeton a usage unique; il disparait des qu'un compte existe.
|
||||
|
||||
@@ -25,11 +25,15 @@ 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")
|
||||
poster_url: Mapped[str | None] = mapped_column(Text)
|
||||
last_seen_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now()
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
processed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
completed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
failed_step: Mapped[str | None] = mapped_column(String(30))
|
||||
last_error: Mapped[str | None] = mapped_column(Text)
|
||||
|
||||
|
||||
class User(Base):
|
||||
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
"""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,6 +28,19 @@ 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,9 +70,13 @@ class IsoMovieRead(BaseModel):
|
||||
path: str
|
||||
size: int | None
|
||||
status: str
|
||||
poster_url: str | None = None
|
||||
last_seen_at: datetime
|
||||
created_at: datetime | None = None
|
||||
processed_at: datetime | None = None
|
||||
completed_at: datetime | None = None
|
||||
failed_step: str | None = None
|
||||
last_error: str | None = None
|
||||
|
||||
|
||||
class ScanResult(BaseModel):
|
||||
|
||||
+36
-2
@@ -2,13 +2,17 @@
|
||||
|
||||
import asyncio
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.conf_store import read_config
|
||||
from app.config import settings
|
||||
from app.converter import conversion_paths, extract_mkv, import_mkv
|
||||
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:
|
||||
@@ -29,7 +33,14 @@ async def _process(movie_id: int) -> None:
|
||||
step = "importing"
|
||||
movie.status = "importing"
|
||||
db.commit()
|
||||
await asyncio.to_thread(import_mkv, paths.mkv_path, paths.destination_folder)
|
||||
target_name = await _target_name(movie)
|
||||
await asyncio.to_thread(
|
||||
import_mkv,
|
||||
paths.mkv_path,
|
||||
paths.destination_folder,
|
||||
target_name,
|
||||
[container_iso_path(movie)],
|
||||
)
|
||||
# Le passage en "completed" (ISO supprimee) se fait manuellement
|
||||
# via l'endpoint de validation apres verification par l'utilisateur.
|
||||
movie.status = "validating"
|
||||
@@ -42,6 +53,29 @@ 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(
|
||||
|
||||
+8
-3
@@ -22,9 +22,14 @@ services:
|
||||
TZ: "Europe/Paris"
|
||||
# Sur le NAS: desactiver la simulation MakeMKV.
|
||||
MKVTOOL_SIMULATE_CONVERSION: "false"
|
||||
# Dossiers vus par l'API: la bibliotheque est montee en /films.
|
||||
MKVTOOL_FILMS_DIR: /films
|
||||
# Chemin de la bibliotheque tel que Radarr le rapporte (traduction ISO).
|
||||
MKVTOOL_RADARR_FILMS_DIR: /nas_storage/jellyfin/films
|
||||
MKVTOOL_DOWNLOADS_DIR: /qbittorrentdownloads
|
||||
volumes:
|
||||
# Montages aux MEMES chemins que Radarr/qBittorrent: les chemins ISO
|
||||
# enregistres par le scan restent valides tels quels.
|
||||
# La bibliotheque Jellyfin est montee en /films dans le conteneur; les
|
||||
# chemins Radarr (MKVTOOL_RADARR_FILMS_DIR) sont traduits par l'API.
|
||||
- /volume1/docker/mkvtool:/config
|
||||
- /qbittorrentdownloads:/qbittorrentdownloads
|
||||
- /nas_storage/jellyfin/films:/nas_storage/jellyfin/films
|
||||
- /nas_storage/jellyfin/films:/films
|
||||
+5
-1
@@ -4,4 +4,8 @@ from pathlib import Path
|
||||
|
||||
_test_config = Path(tempfile.mkdtemp(prefix="mkvtool-tests-"))
|
||||
os.environ["MKVTOOL_CONFIG_DIR"] = str(_test_config)
|
||||
|
||||
os.environ["MKVTOOL_FILMS_DIR"] = str(_test_config / "films")
|
||||
os.environ["MKVTOOL_RADARR_FILMS_DIR"] = str(_test_config / "radarr")
|
||||
os.environ["MKVTOOL_DOWNLOADS_DIR"] = str(_test_config / "downloads")
|
||||
os.environ["MKVTOOL_SIMULATE_CONVERSION"] = "true"
|
||||
os.environ["MKVTOOL_WORKER_INTERVAL"] = "0.05"
|
||||
@@ -0,0 +1,173 @@
|
||||
import shutil
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import respx
|
||||
from fastapi.testclient import TestClient
|
||||
from httpx import Response
|
||||
|
||||
from app.config import settings
|
||||
from app.database import SessionLocal
|
||||
from app.main import app
|
||||
from app.models import IsoMovie
|
||||
from app.naming import movie_file_name
|
||||
from tests.test_api import configure_radarr
|
||||
|
||||
|
||||
def reset_state() -> None:
|
||||
"""Isole chaque test: vide la base et les dossiers films/telechargements."""
|
||||
with SessionLocal() as db:
|
||||
db.query(IsoMovie).delete()
|
||||
db.commit()
|
||||
for folder in (settings.films_dir, settings.downloads_dir):
|
||||
shutil.rmtree(folder, ignore_errors=True)
|
||||
|
||||
FILM_FOLDER = "ISO Movie (2025)"
|
||||
ISO_NAME = "ISO Movie (2025).iso"
|
||||
# Format Media Management de Radarr utilise dans les mocks.
|
||||
NAMING = {
|
||||
"renameMovies": True,
|
||||
"standardMovieFormat": "{Movie Title} ({Release Year}) {Quality Full}",
|
||||
}
|
||||
|
||||
|
||||
def film_dir() -> Path:
|
||||
return settings.films_dir / FILM_FOLDER
|
||||
|
||||
|
||||
def radarr_movie(path: str) -> dict:
|
||||
return {
|
||||
"id": 10,
|
||||
"title": "ISO Movie",
|
||||
"year": 2025,
|
||||
"path": path,
|
||||
"images": [{"coverType": "poster", "remoteUrl": "https://img/poster.jpg"}],
|
||||
"movieFile": {
|
||||
"id": 20,
|
||||
"relativePath": ISO_NAME,
|
||||
"size": 42_000_000_000,
|
||||
"quality": {"quality": {"name": "WEBDL-1080p"}, "revision": {"version": 2, "real": 0}},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def mock_radarr(path: str) -> None:
|
||||
respx.get("http://radarr:7878/api/v3/movie?includeMovieFile=true").mock(
|
||||
return_value=Response(200, json=[radarr_movie(path)])
|
||||
)
|
||||
respx.get("http://radarr:7878/api/v3/movie/10?includeMovieFile=true").mock(
|
||||
return_value=Response(200, json=radarr_movie(path))
|
||||
)
|
||||
respx.get("http://radarr:7878/api/v3/config/naming").mock(
|
||||
return_value=Response(200, json=NAMING)
|
||||
)
|
||||
|
||||
|
||||
def create_film_folder() -> Path:
|
||||
folder = film_dir()
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
(folder / ISO_NAME).write_bytes(b"fake iso")
|
||||
(folder / "poster.jpg").write_bytes(b"junk")
|
||||
extra = folder / "extras"
|
||||
extra.mkdir(exist_ok=True)
|
||||
(extra / "trailer.mkv").write_bytes(b"junk")
|
||||
return folder
|
||||
|
||||
|
||||
def wait_for_status(client: TestClient, expected: str, timeout: float = 10.0) -> dict:
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
movie = client.get("/api/movies").json()[0]
|
||||
if movie["status"] == expected:
|
||||
return movie
|
||||
time.sleep(0.05)
|
||||
raise AssertionError(f"Statut {expected} jamais atteint (dernier: {movie['status']})")
|
||||
|
||||
|
||||
def test_movie_file_name_tokens() -> None:
|
||||
movie_file = {
|
||||
"quality": {"quality": {"name": "WEBDL-1080p"}, "revision": {"version": 2, "real": 0}},
|
||||
"mediaInfo": {"videoCodec": "h264", "audioCodec": "dts", "audioChannels": "5.1"},
|
||||
"releaseGroup": "TEAM",
|
||||
}
|
||||
name = movie_file_name(
|
||||
{
|
||||
"renameMovies": True,
|
||||
"standardMovieFormat": "{Movie Title} {Quality Title} {MediaInfo Simple}",
|
||||
},
|
||||
{"title": "ISO Movie", "year": 2025},
|
||||
movie_file,
|
||||
"fallback.mkv",
|
||||
)
|
||||
assert name == "ISO Movie WEBDL-1080p x264-5.1"
|
||||
|
||||
|
||||
def test_movie_file_name_respects_rename_disabled() -> None:
|
||||
name = movie_file_name(
|
||||
{"renameMovies": False, "standardMovieFormat": "{Movie Title}"},
|
||||
{"title": "ISO Movie"},
|
||||
{},
|
||||
"Fallback Name (2025).mkv",
|
||||
)
|
||||
assert name == "Fallback Name (2025).mkv"
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_conversion_order_and_radarr_naming() -> None:
|
||||
reset_state()
|
||||
folder = create_film_folder()
|
||||
mock_radarr(str(settings.radarr_films_dir / FILM_FOLDER))
|
||||
with TestClient(app) as client:
|
||||
configure_radarr(client)
|
||||
scan = client.post("/api/scans")
|
||||
assert scan.status_code == 200
|
||||
movie_id = client.get("/api/movies").json()[0]["id"]
|
||||
|
||||
convert = client.post(f"/api/movies/{movie_id}/convert")
|
||||
assert convert.status_code == 200
|
||||
|
||||
movie = wait_for_status(client, "validating")
|
||||
assert movie["poster_url"] == "https://img/poster.jpg"
|
||||
|
||||
# Ordre voulu: le dossier du film a ete nettoye (poster, extras)
|
||||
# sauf l'ISO, gardee jusqu'a la validation manuelle.
|
||||
entries = sorted(entry.name for entry in folder.iterdir())
|
||||
assert entries == ["ISO Movie (2025) WEBDL-1080p Proper.mkv", ISO_NAME]
|
||||
|
||||
validate = client.post(f"/api/movies/{movie_id}/validate")
|
||||
assert validate.status_code == 200
|
||||
assert validate.json()["status"] == "completed"
|
||||
|
||||
# Validation: l'ISO est supprimee, seul le MKV (nomme par Radarr) reste.
|
||||
entries = sorted(entry.name for entry in folder.iterdir())
|
||||
assert entries == ["ISO Movie (2025) WEBDL-1080p Proper.mkv"]
|
||||
# Le dossier de travail dans les telechargements est nettoye.
|
||||
assert not list(settings.downloads_dir.iterdir())
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_cancel_conversion_restores_detected() -> None:
|
||||
reset_state()
|
||||
folder = 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"]
|
||||
|
||||
client.post(f"/api/movies/{movie_id}/convert")
|
||||
wait_for_status(client, "validating")
|
||||
|
||||
cancel = client.post(f"/api/movies/{movie_id}/cancel")
|
||||
assert cancel.status_code == 200
|
||||
assert cancel.json()["status"] == "detected"
|
||||
|
||||
# Annulation: lien et MKV de travail supprimes, l'ISO est intacte.
|
||||
entries = sorted(entry.name for entry in folder.iterdir())
|
||||
assert entries == [ISO_NAME]
|
||||
assert not list(settings.downloads_dir.iterdir())
|
||||
|
||||
# Le film reste supprimable quand il n'est pas en conversion.
|
||||
delete = client.delete(f"/api/movies/{movie_id}")
|
||||
assert delete.status_code == 200
|
||||
assert client.get("/api/movies").json() == []
|
||||
Reference in new issue
Block a user