Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f0b5f2b21e | ||
|
|
78e6b0bb22 |
No files matched your search
+2
-1
@@ -58,7 +58,8 @@ COPY docker/entrypoint.py /entrypoint.py
|
|||||||
|
|
||||||
ENV MKVTOOL_CONFIG_DIR=/config \
|
ENV MKVTOOL_CONFIG_DIR=/config \
|
||||||
MKVTOOL_WEB_DIR=/app/web/dist \
|
MKVTOOL_WEB_DIR=/app/web/dist \
|
||||||
MKVTOOL_FILMS_DIR=/nas_storage/jellyfin/films \
|
MKVTOOL_FILMS_DIR=/films \
|
||||||
|
MKVTOOL_RADARR_FILMS_DIR=/nas_storage/jellyfin/films \
|
||||||
MKVTOOL_DOWNLOADS_DIR=/qbittorrentdownloads \
|
MKVTOOL_DOWNLOADS_DIR=/qbittorrentdownloads \
|
||||||
MKVTOOL_SIMULATE_CONVERSION=false \
|
MKVTOOL_SIMULATE_CONVERSION=false \
|
||||||
MAKEMKV_VERSION=${MAKEMKV_VERSION}
|
MAKEMKV_VERSION=${MAKEMKV_VERSION}
|
||||||
|
|||||||
@@ -37,7 +37,8 @@ reste possible : `docker build -t mkvtool .`.
|
|||||||
| `TZ` | `UTC` | Fuseau horaire |
|
| `TZ` | `UTC` | Fuseau horaire |
|
||||||
| `MKVTOOL_CONFIG_DIR` | `/config` | Dossier de conf et base SQLite (`mkvtool.db`, `conf.json`) |
|
| `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_WEB_DIR` | `/app/web/dist` | Emplacement du front servi par l'API |
|
||||||
| `MKVTOOL_FILMS_DIR` | `/nas_storage/jellyfin/films` | Racine de la bibliotheque Jellyfin |
|
| `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_DOWNLOADS_DIR` | `/qbittorrentdownloads` | Racine des telechargements qBittorrent |
|
||||||
| `MKVTOOL_SIMULATE_CONVERSION` | `false` | `true` = produit un faux MKV sans appeler MakeMKV (dev/tests) |
|
| `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 |
|
| `MKVTOOL_WORKER_INTERVAL` | `10` | Secondes entre deux tours de la file de conversion |
|
||||||
@@ -48,12 +49,15 @@ reste possible : `docker build -t mkvtool .`.
|
|||||||
| Chemin conteneur | Contenu |
|
| Chemin conteneur | Contenu |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `/config` | `conf.json` (connexions Radarr/qBittorrent, mis a jour par l'interface), `mkvtool.db` (inventaire + sessions) |
|
| `/config` | `conf.json` (connexions Radarr/qBittorrent, mis a jour par l'interface), `mkvtool.db` (inventaire + sessions) |
|
||||||
| `/nas_storage/jellyfin/films` | Bibliotheque Jellyfin : dossiers des films, ISO sources et MKV finaux |
|
| `/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 |
|
| `/qbittorrentdownloads` | Telechargements qBittorrent : dossier de travail ou le MKV est extrait avant le lien dur |
|
||||||
|
|
||||||
Les chemins des films et telechargements doivent etre les MEMES que ceux vus
|
La bibliotheque est montee en `/films` dans le conteneur. Radarr rapporte ses
|
||||||
par Radarr et qBittorrent (meme montage cote hote) pour que le lien dur reste
|
propres chemins (`MKVTOOL_RADARR_FILMS_DIR`, par defaut
|
||||||
possible et que les chemins ISO enregistres restent valides.
|
`/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
|
## Ports
|
||||||
|
|
||||||
@@ -75,8 +79,8 @@ possible et que les chemins ISO enregistres restent valides.
|
|||||||
|
|
||||||
1. **Conversion** : MakeMKV extrait le MKV vers
|
1. **Conversion** : MakeMKV extrait le MKV vers
|
||||||
`$MKVTOOL_DOWNLOADS_DIR/<Film>/`.
|
`$MKVTOOL_DOWNLOADS_DIR/<Film>/`.
|
||||||
2. **Nettoyage** : le dossier du film dans Jellyfin est vide (tout sauf l'ISO,
|
2. **Nettoyage** : le dossier du film dans Jellyfin (`/films/...` dans le
|
||||||
gardee jusqu'a la validation).
|
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
|
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
|
Media Management de Radarr (`{Movie Title} ({Release Year})...`). Si
|
||||||
Radarr ne renomme pas ou est injoignable, le nom MakeMKV est conserve.
|
Radarr ne renomme pas ou est injoignable, le nom MakeMKV est conserve.
|
||||||
@@ -96,7 +100,7 @@ docker run -d \
|
|||||||
-e MKVTOOL_SIMULATE_CONVERSION=false \
|
-e MKVTOOL_SIMULATE_CONVERSION=false \
|
||||||
-v /volume1/docker/mkvtool:/config \
|
-v /volume1/docker/mkvtool:/config \
|
||||||
-v /qbittorrentdownloads:/qbittorrentdownloads \
|
-v /qbittorrentdownloads:/qbittorrentdownloads \
|
||||||
-v /nas_storage/jellyfin/films:/nas_storage/jellyfin/films \
|
-v /nas_storage/jellyfin/films:/films \
|
||||||
registry-gitlab.orionis-home.fr/deposit/mkvtool:latest
|
registry-gitlab.orionis-home.fr/deposit/mkvtool:latest
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,10 @@ class AppSettings(BaseSettings):
|
|||||||
config_dir: Path = Path("./config")
|
config_dir: Path = Path("./config")
|
||||||
database_url: str | None = None
|
database_url: str | None = None
|
||||||
films_dir: Path = Path("./films")
|
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")
|
downloads_dir: Path = Path("./downloads")
|
||||||
# Simulation (dev/tests): produit un faux MKV au lieu d'appeler MakeMKV.
|
# Simulation (dev/tests): produit un faux MKV au lieu d'appeler MakeMKV.
|
||||||
simulate_conversion: bool = True
|
simulate_conversion: bool = True
|
||||||
|
|||||||
+20
-2
@@ -40,13 +40,31 @@ class ConversionPaths:
|
|||||||
destination_folder: Path
|
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:
|
def conversion_paths(movie: IsoMovie) -> ConversionPaths:
|
||||||
title = sanitize_component(movie.title)
|
title = sanitize_component(movie.title)
|
||||||
movie_name = f"{title} {movie.year}" if movie.year else 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"
|
mkv_name = f"{title} ({movie.year}).mkv" if movie.year else f"{title}.mkv"
|
||||||
downloads_folder = settings.downloads_dir / movie_name
|
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()
|
films_root = settings.films_dir.resolve()
|
||||||
if iso_folder.resolve().is_relative_to(films_root):
|
if iso_folder.resolve().is_relative_to(films_root):
|
||||||
destination_folder = iso_folder
|
destination_folder = iso_folder
|
||||||
@@ -70,7 +88,7 @@ def extract_mkv(movie: IsoMovie, mkv_path: Path) -> None:
|
|||||||
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")
|
||||||
result = subprocess.run(
|
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,
|
capture_output=True,
|
||||||
text=True,
|
text=True,
|
||||||
)
|
)
|
||||||
|
|||||||
+8
-1
@@ -10,7 +10,7 @@ import httpx
|
|||||||
from fastapi import Cookie, Depends, FastAPI, HTTPException, Response
|
from fastapi import Cookie, Depends, FastAPI, HTTPException, Response
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from fastapi.responses import FileResponse
|
from fastapi.responses import FileResponse
|
||||||
from sqlalchemy import inspect, select, text
|
from sqlalchemy import inspect, select, text, update
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from app import auth
|
from app import auth
|
||||||
@@ -54,6 +54,7 @@ async def lifespan(_: FastAPI):
|
|||||||
"failed_step": "TEXT",
|
"failed_step": "TEXT",
|
||||||
"last_error": "TEXT",
|
"last_error": "TEXT",
|
||||||
"poster_url": "TEXT",
|
"poster_url": "TEXT",
|
||||||
|
"radarr_linked": "BOOLEAN DEFAULT 1",
|
||||||
}
|
}
|
||||||
with engine.begin() as conn:
|
with engine.begin() as conn:
|
||||||
for column, ddl in migrations.items():
|
for column, ddl in migrations.items():
|
||||||
@@ -270,6 +271,10 @@ async def scan_radarr(db: DbSession) -> ScanResult:
|
|||||||
|
|
||||||
iso_files = created = updated = 0
|
iso_files = created = updated = 0
|
||||||
now = datetime.now(UTC)
|
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:
|
for movie in movies:
|
||||||
movie_file = movie.get("movieFile") or {}
|
movie_file = movie.get("movieFile") or {}
|
||||||
path = movie_file_path(movie)
|
path = movie_file_path(movie)
|
||||||
@@ -295,6 +300,7 @@ async def scan_radarr(db: DbSession) -> ScanResult:
|
|||||||
path=path,
|
path=path,
|
||||||
size=movie_file.get("size"),
|
size=movie_file.get("size"),
|
||||||
poster_url=_poster_url(movie),
|
poster_url=_poster_url(movie),
|
||||||
|
radarr_linked=True,
|
||||||
last_seen_at=now,
|
last_seen_at=now,
|
||||||
)
|
)
|
||||||
db.add(item)
|
db.add(item)
|
||||||
@@ -305,6 +311,7 @@ async def scan_radarr(db: DbSession) -> ScanResult:
|
|||||||
item.path = path
|
item.path = path
|
||||||
item.size = movie_file.get("size")
|
item.size = movie_file.get("size")
|
||||||
item.poster_url = _poster_url(movie)
|
item.poster_url = _poster_url(movie)
|
||||||
|
item.radarr_linked = True
|
||||||
item.last_seen_at = now
|
item.last_seen_at = now
|
||||||
updated += 1
|
updated += 1
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|||||||
+3
-1
@@ -1,6 +1,6 @@
|
|||||||
from datetime import datetime
|
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 sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
from app.database import Base
|
from app.database import Base
|
||||||
@@ -25,6 +25,8 @@ class IsoMovie(Base):
|
|||||||
path: Mapped[str] = mapped_column(Text)
|
path: Mapped[str] = mapped_column(Text)
|
||||||
size: Mapped[int | None] = mapped_column(BigInteger)
|
size: Mapped[int | None] = mapped_column(BigInteger)
|
||||||
status: Mapped[str] = mapped_column(String(30), default="detected")
|
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)
|
poster_url: Mapped[str | None] = mapped_column(Text)
|
||||||
last_seen_at: Mapped[datetime] = mapped_column(
|
last_seen_at: Mapped[datetime] = mapped_column(
|
||||||
DateTime(timezone=True), server_default=func.now()
|
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")
|
raise ValueError("Réponse Radarr inattendue")
|
||||||
return result
|
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:
|
def movie_file_path(movie: dict) -> str | None:
|
||||||
movie_file = movie.get("movieFile") or {}
|
movie_file = movie.get("movieFile") or {}
|
||||||
|
|||||||
@@ -70,6 +70,7 @@ class IsoMovieRead(BaseModel):
|
|||||||
path: str
|
path: str
|
||||||
size: int | None
|
size: int | None
|
||||||
status: str
|
status: str
|
||||||
|
radarr_linked: bool = True
|
||||||
poster_url: str | None = None
|
poster_url: str | None = None
|
||||||
last_seen_at: datetime
|
last_seen_at: datetime
|
||||||
created_at: datetime | None = None
|
created_at: datetime | None = None
|
||||||
|
|||||||
+5
-29
@@ -6,13 +6,10 @@ from pathlib import Path
|
|||||||
|
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
|
|
||||||
from app.conf_store import read_config
|
|
||||||
from app.config import settings
|
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.database import SessionLocal
|
||||||
from app.models import IsoMovie
|
from app.models import IsoMovie
|
||||||
from app.naming import movie_file_name
|
|
||||||
from app.radarr import RadarrClient
|
|
||||||
|
|
||||||
|
|
||||||
async def _process(movie_id: int) -> None:
|
async def _process(movie_id: int) -> None:
|
||||||
@@ -33,13 +30,15 @@ async def _process(movie_id: int) -> None:
|
|||||||
step = "importing"
|
step = "importing"
|
||||||
movie.status = "importing"
|
movie.status = "importing"
|
||||||
db.commit()
|
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(
|
await asyncio.to_thread(
|
||||||
import_mkv,
|
import_mkv,
|
||||||
paths.mkv_path,
|
paths.mkv_path,
|
||||||
paths.destination_folder,
|
paths.destination_folder,
|
||||||
target_name,
|
target_name,
|
||||||
[Path(movie.path)],
|
[container_iso_path(movie)],
|
||||||
)
|
)
|
||||||
# Le passage en "completed" (ISO supprimee) se fait manuellement
|
# Le passage en "completed" (ISO supprimee) se fait manuellement
|
||||||
# via l'endpoint de validation apres verification par l'utilisateur.
|
# via l'endpoint de validation apres verification par l'utilisateur.
|
||||||
@@ -53,29 +52,6 @@ async def _process(movie_id: int) -> None:
|
|||||||
db.commit()
|
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:
|
async def _process_next() -> bool:
|
||||||
with SessionLocal() as db:
|
with SessionLocal() as db:
|
||||||
movie_id = db.scalar(
|
movie_id = db.scalar(
|
||||||
|
|||||||
+7
-5
@@ -22,12 +22,14 @@ services:
|
|||||||
TZ: "Europe/Paris"
|
TZ: "Europe/Paris"
|
||||||
# Sur le NAS: desactiver la simulation MakeMKV.
|
# Sur le NAS: desactiver la simulation MakeMKV.
|
||||||
MKVTOOL_SIMULATE_CONVERSION: "false"
|
MKVTOOL_SIMULATE_CONVERSION: "false"
|
||||||
# Dossiers vus par l'API: memes chemins que les volumes montes.
|
# Dossiers vus par l'API: la bibliotheque est montee en /films.
|
||||||
MKVTOOL_FILMS_DIR: /nas_storage/jellyfin/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
|
MKVTOOL_DOWNLOADS_DIR: /qbittorrentdownloads
|
||||||
volumes:
|
volumes:
|
||||||
# Montages aux MEMES chemins que Radarr/qBittorrent: les chemins ISO
|
# La bibliotheque Jellyfin est montee en /films dans le conteneur; les
|
||||||
# enregistres par le scan restent valides tels quels.
|
# chemins Radarr (MKVTOOL_RADARR_FILMS_DIR) sont traduits par l'API.
|
||||||
- /volume1/docker/mkvtool:/config
|
- /volume1/docker/mkvtool:/config
|
||||||
- /qbittorrentdownloads:/qbittorrentdownloads
|
- /qbittorrentdownloads:/qbittorrentdownloads
|
||||||
- /nas_storage/jellyfin/films:/nas_storage/jellyfin/films
|
- /nas_storage/jellyfin/films:/films
|
||||||
@@ -5,6 +5,7 @@ from pathlib import Path
|
|||||||
_test_config = Path(tempfile.mkdtemp(prefix="mkvtool-tests-"))
|
_test_config = Path(tempfile.mkdtemp(prefix="mkvtool-tests-"))
|
||||||
os.environ["MKVTOOL_CONFIG_DIR"] = str(_test_config)
|
os.environ["MKVTOOL_CONFIG_DIR"] = str(_test_config)
|
||||||
os.environ["MKVTOOL_FILMS_DIR"] = str(_test_config / "films")
|
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_DOWNLOADS_DIR"] = str(_test_config / "downloads")
|
||||||
os.environ["MKVTOOL_SIMULATE_CONVERSION"] = "true"
|
os.environ["MKVTOOL_SIMULATE_CONVERSION"] = "true"
|
||||||
os.environ["MKVTOOL_WORKER_INTERVAL"] = "0.05"
|
os.environ["MKVTOOL_WORKER_INTERVAL"] = "0.05"
|
||||||
+41
-51
@@ -10,9 +10,12 @@ from app.config import settings
|
|||||||
from app.database import SessionLocal
|
from app.database import SessionLocal
|
||||||
from app.main import app
|
from app.main import app
|
||||||
from app.models import IsoMovie
|
from app.models import IsoMovie
|
||||||
from app.naming import movie_file_name
|
|
||||||
from tests.test_api import configure_radarr
|
from tests.test_api import configure_radarr
|
||||||
|
|
||||||
|
FILM_FOLDER = "ISO Movie (2025)"
|
||||||
|
ISO_NAME = "ISO Movie (2025).iso"
|
||||||
|
MKV_NAME = "ISO Movie (2025).mkv"
|
||||||
|
|
||||||
|
|
||||||
def reset_state() -> None:
|
def reset_state() -> None:
|
||||||
"""Isole chaque test: vide la base et les dossiers films/telechargements."""
|
"""Isole chaque test: vide la base et les dossiers films/telechargements."""
|
||||||
@@ -22,14 +25,6 @@ def reset_state() -> None:
|
|||||||
for folder in (settings.films_dir, settings.downloads_dir):
|
for folder in (settings.films_dir, settings.downloads_dir):
|
||||||
shutil.rmtree(folder, ignore_errors=True)
|
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:
|
def film_dir() -> Path:
|
||||||
return settings.films_dir / FILM_FOLDER
|
return settings.films_dir / FILM_FOLDER
|
||||||
@@ -46,7 +41,6 @@ def radarr_movie(path: str) -> dict:
|
|||||||
"id": 20,
|
"id": 20,
|
||||||
"relativePath": ISO_NAME,
|
"relativePath": ISO_NAME,
|
||||||
"size": 42_000_000_000,
|
"size": 42_000_000_000,
|
||||||
"quality": {"quality": {"name": "WEBDL-1080p"}, "revision": {"version": 2, "real": 0}},
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,12 +49,6 @@ def mock_radarr(path: str) -> None:
|
|||||||
respx.get("http://radarr:7878/api/v3/movie?includeMovieFile=true").mock(
|
respx.get("http://radarr:7878/api/v3/movie?includeMovieFile=true").mock(
|
||||||
return_value=Response(200, json=[radarr_movie(path)])
|
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:
|
def create_film_folder() -> Path:
|
||||||
@@ -84,39 +72,13 @@ def wait_for_status(client: TestClient, expected: str, timeout: float = 10.0) ->
|
|||||||
raise AssertionError(f"Statut {expected} jamais atteint (dernier: {movie['status']})")
|
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
|
@respx.mock
|
||||||
def test_conversion_order_and_radarr_naming() -> None:
|
def test_conversion_order_and_radarr_file_name() -> None:
|
||||||
reset_state()
|
reset_state()
|
||||||
folder = create_film_folder()
|
folder = create_film_folder()
|
||||||
mock_radarr(str(folder))
|
# Radarr rapporte les chemins dans son referentiel; les fichiers physiques
|
||||||
|
# vivent sous films_dir (montage /films dans le conteneur).
|
||||||
|
mock_radarr(str(settings.radarr_films_dir / FILM_FOLDER))
|
||||||
with TestClient(app) as client:
|
with TestClient(app) as client:
|
||||||
configure_radarr(client)
|
configure_radarr(client)
|
||||||
scan = client.post("/api/scans")
|
scan = client.post("/api/scans")
|
||||||
@@ -128,19 +90,21 @@ def test_conversion_order_and_radarr_naming() -> None:
|
|||||||
|
|
||||||
movie = wait_for_status(client, "validating")
|
movie = wait_for_status(client, "validating")
|
||||||
assert movie["poster_url"] == "https://img/poster.jpg"
|
assert movie["poster_url"] == "https://img/poster.jpg"
|
||||||
|
assert movie["radarr_linked"] is True
|
||||||
|
|
||||||
# Ordre voulu: le dossier du film a ete nettoye (poster, extras)
|
# Ordre voulu: le dossier du film a ete nettoye (poster, extras)
|
||||||
# sauf l'ISO, gardee jusqu'a la validation manuelle.
|
# sauf l'ISO, gardee jusqu'a la validation manuelle. Le MKV lie
|
||||||
|
# reprend le nom du fichier Radarr (seule l'extension change).
|
||||||
entries = sorted(entry.name for entry in folder.iterdir())
|
entries = sorted(entry.name for entry in folder.iterdir())
|
||||||
assert entries == ["ISO Movie (2025) WEBDL-1080p Proper.mkv", ISO_NAME]
|
assert entries == [ISO_NAME, MKV_NAME]
|
||||||
|
|
||||||
validate = client.post(f"/api/movies/{movie_id}/validate")
|
validate = client.post(f"/api/movies/{movie_id}/validate")
|
||||||
assert validate.status_code == 200
|
assert validate.status_code == 200
|
||||||
assert validate.json()["status"] == "completed"
|
assert validate.json()["status"] == "completed"
|
||||||
|
|
||||||
# Validation: l'ISO est supprimee, seul le MKV (nomme par Radarr) reste.
|
# Validation: l'ISO est supprimee, seul le MKV reste.
|
||||||
entries = sorted(entry.name for entry in folder.iterdir())
|
entries = sorted(entry.name for entry in folder.iterdir())
|
||||||
assert entries == ["ISO Movie (2025) WEBDL-1080p Proper.mkv"]
|
assert entries == [MKV_NAME]
|
||||||
# Le dossier de travail dans les telechargements est nettoye.
|
# Le dossier de travail dans les telechargements est nettoye.
|
||||||
assert not list(settings.downloads_dir.iterdir())
|
assert not list(settings.downloads_dir.iterdir())
|
||||||
|
|
||||||
@@ -149,7 +113,7 @@ def test_conversion_order_and_radarr_naming() -> None:
|
|||||||
def test_cancel_conversion_restores_detected() -> None:
|
def test_cancel_conversion_restores_detected() -> None:
|
||||||
reset_state()
|
reset_state()
|
||||||
folder = create_film_folder()
|
folder = create_film_folder()
|
||||||
mock_radarr(str(folder))
|
mock_radarr(str(settings.radarr_films_dir / FILM_FOLDER))
|
||||||
with TestClient(app) as client:
|
with TestClient(app) as client:
|
||||||
configure_radarr(client)
|
configure_radarr(client)
|
||||||
client.post("/api/scans")
|
client.post("/api/scans")
|
||||||
@@ -171,3 +135,29 @@ def test_cancel_conversion_restores_detected() -> None:
|
|||||||
delete = client.delete(f"/api/movies/{movie_id}")
|
delete = client.delete(f"/api/movies/{movie_id}")
|
||||||
assert delete.status_code == 200
|
assert delete.status_code == 200
|
||||||
assert client.get("/api/movies").json() == []
|
assert client.get("/api/movies").json() == []
|
||||||
|
|
||||||
|
|
||||||
|
@respx.mock
|
||||||
|
def test_scan_marks_missing_radarr_files_as_unlinked() -> None:
|
||||||
|
"""La pastille "Radarr lie" suit la presence du fichier cote Radarr."""
|
||||||
|
reset_state()
|
||||||
|
create_film_folder()
|
||||||
|
radarr_path = str(settings.radarr_films_dir / FILM_FOLDER)
|
||||||
|
respx.get("http://radarr:7878/api/v3/movie?includeMovieFile=true").mock(
|
||||||
|
return_value=Response(200, json=[radarr_movie(radarr_path)])
|
||||||
|
)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
configure_radarr(client)
|
||||||
|
client.post("/api/scans")
|
||||||
|
movie = client.get("/api/movies").json()[0]
|
||||||
|
assert movie["radarr_linked"] is True
|
||||||
|
|
||||||
|
# Le film disparait de Radarr (fichier supprime): il reste en base
|
||||||
|
# mais passe a non lie.
|
||||||
|
respx.get("http://radarr:7878/api/v3/movie?includeMovieFile=true").mock(
|
||||||
|
return_value=Response(200, json=[])
|
||||||
|
)
|
||||||
|
client.post("/api/scans")
|
||||||
|
movie = client.get("/api/movies").json()[0]
|
||||||
|
assert movie["radarr_linked"] is False
|
||||||
|
assert movie["status"] == "detected"
|
||||||
+13
-1
@@ -10,6 +10,7 @@ type Movie = {
|
|||||||
size: number | null;
|
size: number | null;
|
||||||
poster_url: string | null;
|
poster_url: string | null;
|
||||||
status: string;
|
status: string;
|
||||||
|
radarr_linked: boolean;
|
||||||
completed_at: string | null;
|
completed_at: string | null;
|
||||||
last_error: string | null;
|
last_error: string | null;
|
||||||
failed_step: string | null;
|
failed_step: string | null;
|
||||||
@@ -104,6 +105,7 @@ export default function App() {
|
|||||||
const [page, setPage] = useState<Page>("dashboard");
|
const [page, setPage] = useState<Page>("dashboard");
|
||||||
const [movies, setMovies] = useState<Movie[]>([]);
|
const [movies, setMovies] = useState<Movie[]>([]);
|
||||||
const [tab, setTab] = useState<Tab>("pending");
|
const [tab, setTab] = useState<Tab>("pending");
|
||||||
|
const [linkedOnly, setLinkedOnly] = useState(false);
|
||||||
const [url, setUrl] = useState("");
|
const [url, setUrl] = useState("");
|
||||||
const [apiKey, setApiKey] = useState("");
|
const [apiKey, setApiKey] = useState("");
|
||||||
const [keyConfigured, setKeyConfigured] = useState(false);
|
const [keyConfigured, setKeyConfigured] = useState(false);
|
||||||
@@ -362,7 +364,9 @@ export default function App() {
|
|||||||
};
|
};
|
||||||
}, [movies]);
|
}, [movies]);
|
||||||
|
|
||||||
const visible = movies.filter((movie) => inGroup(movie.status, tab));
|
const visible = movies.filter(
|
||||||
|
(movie) => inGroup(movie.status, tab) && (!linkedOnly || movie.radarr_linked),
|
||||||
|
);
|
||||||
const lastDone = [...groups.done].sort(
|
const lastDone = [...groups.done].sort(
|
||||||
(a, b) => Date.parse(b.last_seen_at) - Date.parse(a.last_seen_at),
|
(a, b) => Date.parse(b.last_seen_at) - Date.parse(a.last_seen_at),
|
||||||
);
|
);
|
||||||
@@ -813,6 +817,13 @@ export default function App() {
|
|||||||
<span className="count">{groups[id].length}</span>
|
<span className="count">{groups[id].length}</span>
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
|
<button
|
||||||
|
className={linkedOnly ? "tab active" : "tab"}
|
||||||
|
onClick={() => setLinkedOnly((value) => !value)}
|
||||||
|
title="N’afficher que les films dont le fichier est toujours présent tel quel côté Radarr"
|
||||||
|
>
|
||||||
|
Radarr lié
|
||||||
|
</button>
|
||||||
</nav>
|
</nav>
|
||||||
{visible.length === 0 ? (
|
{visible.length === 0 ? (
|
||||||
<div className="empty">Aucun film dans cette catégorie.</div>
|
<div className="empty">Aucun film dans cette catégorie.</div>
|
||||||
@@ -877,6 +888,7 @@ export default function App() {
|
|||||||
Supprimer
|
Supprimer
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
{movie.radarr_linked && <span className="status linked">Radarr lié</span>}
|
||||||
<span className={BROKEN.includes(movie.status) ? "status error" : "status"}>
|
<span className={BROKEN.includes(movie.status) ? "status error" : "status"}>
|
||||||
{statusLabel(movie.status)}
|
{statusLabel(movie.status)}
|
||||||
</span>
|
</span>
|
||||||
|
|||||||
@@ -197,6 +197,10 @@ code { color: var(--text-muted); font-size: 0.8rem; overflow-wrap: anywhere; }
|
|||||||
}
|
}
|
||||||
|
|
||||||
.status.error { color: var(--danger); border-color: rgba(248, 113, 113, 0.4); }
|
.status.error { color: var(--danger); border-color: rgba(248, 113, 113, 0.4); }
|
||||||
|
.status.linked {
|
||||||
|
color: #4ade80;
|
||||||
|
border-color: rgba(74, 222, 128, 0.4);
|
||||||
|
}
|
||||||
|
|
||||||
.row-actions { display: flex; align-items: center; gap: 0.75rem; flex-shrink: 0; }
|
.row-actions { display: flex; align-items: center; gap: 0.75rem; flex-shrink: 0; }
|
||||||
button.small { padding: 0.45rem 0.9rem; font-size: 0.85rem; border-radius: 8px; }
|
button.small { padding: 0.45rem 0.9rem; font-size: 0.85rem; border-radius: 8px; }
|
||||||
|
|||||||
Reference in new issue
Block a user