Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
23132c6219 | ||
|
|
514f417c15 | ||
|
|
e8bbbc7d1e | ||
|
|
95e5ead67a | ||
|
|
76dbd7e425 | ||
|
|
f0b5f2b21e | ||
|
|
78e6b0bb22 | ||
|
|
2d2ebde4f6 | ||
|
|
198a014967 | ||
|
|
cfc0c54181 |
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
|
||||
```
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 59 KiB |
@@ -2,6 +2,7 @@ import json
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
@@ -10,15 +11,35 @@ from app.config import settings
|
||||
|
||||
class ApiServiceConfig(BaseModel):
|
||||
url: str | None = None
|
||||
port: int | None = None
|
||||
api_key: str | None = None
|
||||
|
||||
|
||||
class QbittorrentConfig(BaseModel):
|
||||
url: str | None = None
|
||||
port: int | None = None
|
||||
username: str | None = None
|
||||
password: str | None = None
|
||||
|
||||
|
||||
def build_base_url(url: str | None, port: int | None = None) -> str | None:
|
||||
"""Normalise une adresse de service en URL de base.
|
||||
|
||||
Accepte une adresse locale sans schema ("http://" est deduit) et un port
|
||||
optionnel separe, applique seulement si l'URL n'en porte pas deja un.
|
||||
"""
|
||||
if not url:
|
||||
return None
|
||||
base = str(url).strip().rstrip("/")
|
||||
if "://" not in base:
|
||||
base = f"http://{base}"
|
||||
if port:
|
||||
parsed = urlparse(base)
|
||||
if parsed.port is None:
|
||||
base = f"{parsed.scheme}://{parsed.netloc}:{port}"
|
||||
return base
|
||||
|
||||
|
||||
class AppConfig(BaseModel):
|
||||
radarr: ApiServiceConfig = Field(default_factory=ApiServiceConfig)
|
||||
sonarr: ApiServiceConfig = Field(default_factory=ApiServiceConfig)
|
||||
|
||||
+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()
|
||||
|
||||
+261
-18
@@ -1,3 +1,4 @@
|
||||
import asyncio
|
||||
import os
|
||||
import shutil
|
||||
from contextlib import asynccontextmanager
|
||||
@@ -9,13 +10,15 @@ 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
|
||||
from app.conf_store import read_config, write_config
|
||||
from app.conf_store import ApiServiceConfig, build_base_url, 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, match_torrent
|
||||
from app.radarr import RadarrClient, movie_file_path
|
||||
from app.schemas import (
|
||||
ApiServiceSettingsRead,
|
||||
@@ -26,12 +29,14 @@ from app.schemas import (
|
||||
HealthRead,
|
||||
IsoMovieRead,
|
||||
QbittorrentSettingsRead,
|
||||
QbittorrentSettingsWrite,
|
||||
RadarrSettingsRead,
|
||||
RadarrSettingsWrite,
|
||||
ScanResult,
|
||||
SettingsRead,
|
||||
SettingsWrite,
|
||||
)
|
||||
from app.worker import conversion_worker
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
@@ -43,14 +48,28 @@ 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",
|
||||
"radarr_linked": "BOOLEAN DEFAULT 1",
|
||||
}
|
||||
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
|
||||
_log_config_summary()
|
||||
worker_task = asyncio.create_task(conversion_worker())
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
worker_task.cancel()
|
||||
|
||||
|
||||
app = FastAPI(title="MKVTool", version="0.1.0", lifespan=lifespan)
|
||||
@@ -64,18 +83,20 @@ app.add_middleware(
|
||||
DbSession = Annotated[Session, Depends(get_db)]
|
||||
|
||||
|
||||
def _api_service_read(url: str | None, api_key: str | None) -> ApiServiceSettingsRead:
|
||||
return ApiServiceSettingsRead(url=url, api_key_configured=api_key is not None)
|
||||
def _api_service_read(service: ApiServiceConfig) -> ApiServiceSettingsRead:
|
||||
return ApiServiceSettingsRead(
|
||||
url=service.url, port=service.port, api_key_configured=service.api_key is not None
|
||||
)
|
||||
|
||||
|
||||
def _settings_read() -> SettingsRead:
|
||||
cfg = read_config()
|
||||
return SettingsRead(
|
||||
radarr=_api_service_read(cfg.radarr.url, cfg.radarr.api_key),
|
||||
sonarr=_api_service_read(cfg.sonarr.url, cfg.sonarr.api_key),
|
||||
prowlarr=_api_service_read(cfg.prowlarr.url, cfg.prowlarr.api_key),
|
||||
jellyfin=_api_service_read(cfg.jellyfin.url, cfg.jellyfin.api_key),
|
||||
seerr=_api_service_read(cfg.seerr.url, cfg.seerr.api_key),
|
||||
radarr=_api_service_read(cfg.radarr),
|
||||
sonarr=_api_service_read(cfg.sonarr),
|
||||
prowlarr=_api_service_read(cfg.prowlarr),
|
||||
jellyfin=_api_service_read(cfg.jellyfin),
|
||||
seerr=_api_service_read(cfg.seerr),
|
||||
qbittorrent=QbittorrentSettingsRead(
|
||||
url=cfg.qbittorrent.url,
|
||||
username=cfg.qbittorrent.username,
|
||||
@@ -86,7 +107,7 @@ def _settings_read() -> SettingsRead:
|
||||
|
||||
def client_from_config() -> RadarrClient:
|
||||
cfg = read_config()
|
||||
url = (cfg.radarr.url or "").rstrip("/")
|
||||
url = build_base_url(cfg.radarr.url, cfg.radarr.port)
|
||||
api_key = cfg.radarr.api_key
|
||||
if not url or not api_key:
|
||||
raise HTTPException(status_code=409, detail="La connexion Radarr n'est pas configurée")
|
||||
@@ -106,8 +127,12 @@ def health() -> HealthRead:
|
||||
|
||||
@app.get("/api/settings/radarr", response_model=RadarrSettingsRead)
|
||||
def get_radarr_settings() -> RadarrSettingsRead:
|
||||
cfg = read_config()
|
||||
return RadarrSettingsRead(url=cfg.radarr.url, api_key_configured=cfg.radarr.api_key is not None)
|
||||
radarr = read_config().radarr
|
||||
return RadarrSettingsRead(
|
||||
url=radarr.url,
|
||||
port=radarr.port,
|
||||
api_key_configured=radarr.api_key is not None,
|
||||
)
|
||||
|
||||
|
||||
@app.put("/api/settings/radarr", response_model=RadarrSettingsRead)
|
||||
@@ -115,12 +140,17 @@ def put_radarr_settings(
|
||||
payload: RadarrSettingsWrite,
|
||||
) -> RadarrSettingsRead:
|
||||
cfg = read_config()
|
||||
url = str(payload.url).rstrip("/")
|
||||
url = str(payload.url).strip().rstrip("/")
|
||||
cfg.radarr.url = url
|
||||
cfg.radarr.port = payload.port
|
||||
if payload.api_key:
|
||||
cfg.radarr.api_key = payload.api_key
|
||||
write_config(cfg)
|
||||
return RadarrSettingsRead(url=url, api_key_configured=cfg.radarr.api_key is not None)
|
||||
return RadarrSettingsRead(
|
||||
url=url,
|
||||
port=cfg.radarr.port,
|
||||
api_key_configured=cfg.radarr.api_key is not None,
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/settings", response_model=SettingsRead)
|
||||
@@ -172,6 +202,65 @@ async def test_radarr() -> ConnectionResult:
|
||||
return ConnectionResult(success=True, version=version, message=f"Radarr {version} accessible")
|
||||
|
||||
|
||||
def qbittorrent_from_config() -> QbittorrentClient:
|
||||
qb = read_config().qbittorrent
|
||||
url = build_base_url(qb.url, qb.port)
|
||||
if not url:
|
||||
raise HTTPException(status_code=409, detail="La connexion qBittorrent n'est pas configurée")
|
||||
return QbittorrentClient(url, qb.username, qb.password)
|
||||
|
||||
|
||||
@app.get("/api/settings/qbittorrent", response_model=QbittorrentSettingsRead)
|
||||
def get_qbittorrent_settings() -> QbittorrentSettingsRead:
|
||||
qb = read_config().qbittorrent
|
||||
return QbittorrentSettingsRead(
|
||||
url=qb.url,
|
||||
port=qb.port,
|
||||
username=qb.username,
|
||||
password_configured=qb.password is not None,
|
||||
)
|
||||
|
||||
|
||||
@app.put("/api/settings/qbittorrent", response_model=QbittorrentSettingsRead)
|
||||
def put_qbittorrent_settings(payload: QbittorrentSettingsWrite) -> QbittorrentSettingsRead:
|
||||
cfg = read_config()
|
||||
if payload.url is not None:
|
||||
cfg.qbittorrent.url = str(payload.url).strip().rstrip("/")
|
||||
cfg.qbittorrent.port = payload.port
|
||||
if payload.username:
|
||||
cfg.qbittorrent.username = payload.username
|
||||
if payload.password:
|
||||
cfg.qbittorrent.password = payload.password
|
||||
elif payload.password:
|
||||
# Mot de passe seul: on conserve l'utilisateur existant.
|
||||
cfg.qbittorrent.password = payload.password
|
||||
else:
|
||||
# Champs vides: mode bypass d'authentification qBittorrent, sans identifiants.
|
||||
cfg.qbittorrent.username = None
|
||||
cfg.qbittorrent.password = None
|
||||
write_config(cfg)
|
||||
return QbittorrentSettingsRead(
|
||||
url=cfg.qbittorrent.url,
|
||||
port=cfg.qbittorrent.port,
|
||||
username=cfg.qbittorrent.username,
|
||||
password_configured=cfg.qbittorrent.password is not None,
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/settings/qbittorrent/test", response_model=ConnectionResult)
|
||||
async def test_qbittorrent() -> ConnectionResult:
|
||||
client = qbittorrent_from_config()
|
||||
try:
|
||||
version = await client.version()
|
||||
except (httpx.HTTPError, ValueError) as error:
|
||||
raise HTTPException(
|
||||
status_code=502, detail=f"Connexion qBittorrent impossible: {error}"
|
||||
) from error
|
||||
return ConnectionResult(
|
||||
success=True, version=version, message=f"qBittorrent {version} accessible"
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/movies", response_model=list[IsoMovieRead])
|
||||
def list_movies(db: DbSession) -> list[IsoMovie]:
|
||||
return list(db.scalars(select(IsoMovie).order_by(IsoMovie.title)).all())
|
||||
@@ -190,6 +279,33 @@ def get_file(file_id: int, db: DbSession) -> IsoMovie:
|
||||
return item
|
||||
|
||||
|
||||
def _log_config_summary() -> None:
|
||||
"""Rend visible au lancement le chargement de conf.json."""
|
||||
cfg = read_config()
|
||||
configured = [
|
||||
name
|
||||
for name in ("radarr", "sonarr", "prowlarr", "jellyfin", "seerr")
|
||||
if getattr(cfg, name).url
|
||||
]
|
||||
if cfg.qbittorrent.url:
|
||||
mode = "identifiants" if cfg.qbittorrent.username else "bypass d'authentification"
|
||||
configured.append(f"qbittorrent ({mode})")
|
||||
if configured:
|
||||
print(f"conf.json charge: {', '.join(configured)}", flush=True)
|
||||
else:
|
||||
print(
|
||||
"conf.json: aucune connexion configuree — a renseigner dans la page Configuration.",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
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()
|
||||
@@ -200,6 +316,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)
|
||||
@@ -224,6 +344,8 @@ async def scan_radarr(db: DbSession) -> ScanResult:
|
||||
year=movie.get("year"),
|
||||
path=path,
|
||||
size=movie_file.get("size"),
|
||||
poster_url=_poster_url(movie),
|
||||
radarr_linked=True,
|
||||
last_seen_at=now,
|
||||
)
|
||||
db.add(item)
|
||||
@@ -233,6 +355,8 @@ 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.radarr_linked = True
|
||||
item.last_seen_at = now
|
||||
updated += 1
|
||||
db.commit()
|
||||
@@ -241,6 +365,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.
|
||||
|
||||
+7
-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,11 +25,17 @@ 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()
|
||||
)
|
||||
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):
|
||||
|
||||
+16
-9
@@ -6,21 +6,28 @@ import httpx
|
||||
|
||||
|
||||
class QbittorrentClient:
|
||||
def __init__(self, url: str, username: str, password: str) -> None:
|
||||
"""Client WebUI (API v2). Identifiants optionnels: sans eux, aucun login
|
||||
n'est effectue — qBittorrent doit alors autoriser la plage IP (bypass
|
||||
d'authentification), car il n'existe pas d'API key cote qBittorrent."""
|
||||
|
||||
def __init__(
|
||||
self, url: str, username: str | None = None, password: str | None = None
|
||||
) -> None:
|
||||
self._url = url.rstrip("/")
|
||||
self._username = username
|
||||
self._password = password
|
||||
|
||||
async def _request(self, method: str, endpoint: str, **kwargs) -> httpx.Response:
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
login = await client.post(
|
||||
f"{self._url}/api/v2/auth/login",
|
||||
data={"username": self._username, "password": self._password},
|
||||
headers={"Referer": self._url},
|
||||
)
|
||||
login.raise_for_status()
|
||||
if login.text.strip() != "Ok.":
|
||||
raise ValueError("Authentification qBittorrent refusée")
|
||||
if self._username and self._password:
|
||||
login = await client.post(
|
||||
f"{self._url}/api/v2/auth/login",
|
||||
data={"username": self._username, "password": self._password},
|
||||
headers={"Referer": self._url},
|
||||
)
|
||||
login.raise_for_status()
|
||||
if login.text.strip() != "Ok.":
|
||||
raise ValueError("Authentification qBittorrent refusée")
|
||||
response = await client.request(
|
||||
method,
|
||||
f"{self._url}{endpoint}",
|
||||
|
||||
+17
-5
@@ -1,37 +1,44 @@
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, HttpUrl
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class RadarrSettingsRead(BaseModel):
|
||||
url: str | None
|
||||
port: int | None = None
|
||||
api_key_configured: bool
|
||||
|
||||
|
||||
class RadarrSettingsWrite(BaseModel):
|
||||
url: HttpUrl
|
||||
url: str
|
||||
port: int | None = Field(default=None, ge=1, le=65535)
|
||||
api_key: str | None = Field(default=None, min_length=1)
|
||||
|
||||
|
||||
class ApiServiceSettingsRead(BaseModel):
|
||||
url: str | None
|
||||
port: int | None = None
|
||||
api_key_configured: bool
|
||||
|
||||
|
||||
class ApiServiceSettingsWrite(BaseModel):
|
||||
url: HttpUrl | None = None
|
||||
url: str | None = None
|
||||
port: int | None = Field(default=None, ge=1, le=65535)
|
||||
api_key: str | None = Field(default=None, min_length=1)
|
||||
|
||||
|
||||
class QbittorrentSettingsRead(BaseModel):
|
||||
url: str | None
|
||||
port: int | None = None
|
||||
username: str | None
|
||||
password_configured: bool
|
||||
|
||||
|
||||
class QbittorrentSettingsWrite(BaseModel):
|
||||
url: HttpUrl | None = None
|
||||
username: str | None = Field(default=None, min_length=1)
|
||||
url: str | None = None
|
||||
port: int | None = Field(default=None, ge=1, le=65535)
|
||||
# Utilisateur vide = bypass d'authentification qBittorrent.
|
||||
username: str | None = None
|
||||
password: str | None = Field(default=None, min_length=1)
|
||||
|
||||
|
||||
@@ -70,9 +77,14 @@ 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
|
||||
processed_at: datetime | None = None
|
||||
completed_at: datetime | None = None
|
||||
failed_step: str | None = None
|
||||
last_error: str | None = None
|
||||
|
||||
|
||||
class ScanResult(BaseModel):
|
||||
|
||||
@@ -6,11 +6,12 @@ The project now externalises its configuration into ./config/conf.json.
|
||||
This module is kept temporarily because some imports may still reference it.
|
||||
"""
|
||||
|
||||
from app.conf_store import read_config
|
||||
from app.conf_store import build_base_url, read_config
|
||||
|
||||
|
||||
def radarr_credentials(_: object | None = None) -> tuple[str, str]:
|
||||
cfg = read_config()
|
||||
if not cfg.radarr.url or not cfg.radarr.api_key:
|
||||
url = build_base_url(cfg.radarr.url, cfg.radarr.port)
|
||||
if not url or not cfg.radarr.api_key:
|
||||
raise ValueError("La connexion Radarr n'est pas configurée")
|
||||
return cfg.radarr.url.rstrip("/"), cfg.radarr.api_key
|
||||
return url, cfg.radarr.api_key
|
||||
+12
-2
@@ -2,11 +2,12 @@
|
||||
|
||||
import asyncio
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
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
|
||||
|
||||
@@ -29,7 +30,16 @@ 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)
|
||||
# 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,
|
||||
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"
|
||||
|
||||
+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"
|
||||
@@ -1,8 +1,14 @@
|
||||
import json
|
||||
|
||||
import respx
|
||||
from fastapi.testclient import TestClient
|
||||
from httpx import Response
|
||||
|
||||
from app import auth as auth_module
|
||||
from app.conf_store import config_path
|
||||
from app.database import SessionLocal
|
||||
from app.main import app
|
||||
from app.models import User
|
||||
|
||||
|
||||
def configure_radarr(client: TestClient) -> None:
|
||||
@@ -70,3 +76,126 @@ def test_scan_only_imports_iso_files() -> None:
|
||||
assert scan.status_code == 200
|
||||
assert scan.json()["iso_files"] == 1
|
||||
assert [movie["title"] for movie in movies.json()] == ["ISO Movie"]
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_qbittorrent_connection_local_address_with_port() -> None:
|
||||
# Adresse locale sans schema + port separe: l'URL de base doit etre
|
||||
# reconstruite en http://192.168.1.50:8080.
|
||||
respx.post("http://192.168.1.50:8080/api/v2/auth/login").mock(
|
||||
return_value=Response(200, text="Ok.")
|
||||
)
|
||||
respx.get("http://192.168.1.50:8080/api/v2/app/version").mock(
|
||||
return_value=Response(200, text="v5.0.2")
|
||||
)
|
||||
with TestClient(app) as client:
|
||||
response = client.put(
|
||||
"/api/settings/qbittorrent",
|
||||
json={
|
||||
"url": "192.168.1.50",
|
||||
"port": 8080,
|
||||
"username": "admin",
|
||||
"password": "pass",
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["port"] == 8080
|
||||
test = client.post("/api/settings/qbittorrent/test")
|
||||
assert test.status_code == 200
|
||||
assert test.json()["version"] == "v5.0.2"
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_qbittorrent_connection_without_credentials() -> None:
|
||||
"""Sans identifiants (bypass d'authentification qBittorrent): aucun login,
|
||||
l'API est appelee directement."""
|
||||
respx.post("http://192.168.1.50:8555/api/v2/auth/login").mock(
|
||||
return_value=Response(404)
|
||||
)
|
||||
respx.get("http://192.168.1.50:8555/api/v2/app/version").mock(
|
||||
return_value=Response(200, text="v5.0.2")
|
||||
)
|
||||
with TestClient(app) as client:
|
||||
put = client.put(
|
||||
"/api/settings/qbittorrent",
|
||||
json={"url": "192.168.1.50", "port": 8555, "username": "", "password": None},
|
||||
)
|
||||
assert put.status_code == 200
|
||||
assert put.json()["password_configured"] is False
|
||||
test = client.post("/api/settings/qbittorrent/test")
|
||||
assert test.status_code == 200
|
||||
assert test.json()["version"] == "v5.0.2"
|
||||
|
||||
|
||||
def test_settings_persist_to_conf_json() -> None:
|
||||
with TestClient(app) as client:
|
||||
put = client.put(
|
||||
"/api/settings/qbittorrent",
|
||||
json={
|
||||
"url": "http://qbit:8080/",
|
||||
"port": 8080,
|
||||
"username": "admin",
|
||||
"password": "pass",
|
||||
},
|
||||
)
|
||||
got = client.get("/api/settings/qbittorrent")
|
||||
assert put.status_code == 200
|
||||
assert put.json()["password_configured"] is True
|
||||
assert got.json()["url"] == "http://qbit:8080"
|
||||
assert got.json()["port"] == 8080
|
||||
raw = json.loads(config_path().read_text(encoding="utf-8"))
|
||||
assert raw["qbittorrent"]["url"] == "http://qbit:8080"
|
||||
assert raw["qbittorrent"]["port"] == 8080
|
||||
assert raw["qbittorrent"]["username"] == "admin"
|
||||
assert raw["qbittorrent"]["password"] == "pass"
|
||||
|
||||
|
||||
def test_setup_link_only_without_existing_account() -> None:
|
||||
"""Le lien de premier lancement ne doit pas apparaitre si un compte existe.
|
||||
|
||||
Verifie aussi que l'endpoint de setup refuse tout second compte, meme avec
|
||||
un jeton valide.
|
||||
"""
|
||||
with TestClient(app) as client:
|
||||
client.post("/api/auth/setup", json={"token": "invalide", "username": "x", "password": "y"})
|
||||
# Nettoyage: la base de test est partagee entre les tests.
|
||||
with SessionLocal() as db:
|
||||
db.query(User).delete()
|
||||
db.commit()
|
||||
# Simule un redemarrage: le lifespan relance bootstrap_setup.
|
||||
with TestClient(app):
|
||||
assert auth_module.setup_token is not None
|
||||
with TestClient(app) as client:
|
||||
response = client.post(
|
||||
"/api/auth/setup",
|
||||
json={
|
||||
"token": auth_module.setup_token,
|
||||
"username": "admin",
|
||||
"password": "pass",
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
# Le jeton est consomme apres creation du compte.
|
||||
assert auth_module.setup_token is None
|
||||
# Nouveau demarrage: un compte existe -> plus aucun jeton genere,
|
||||
# et la creation d'un second compte est refusee.
|
||||
with TestClient(app) as client:
|
||||
assert auth_module.setup_token is None
|
||||
response = client.post(
|
||||
"/api/auth/setup",
|
||||
json={"token": "peu-importe", "username": "autre", "password": "z"},
|
||||
)
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
def test_startup_logs_conf_json_summary(capsys) -> None:
|
||||
"""Au lancement, le log indique si conf.json est charge et ce qu'il contient."""
|
||||
with TestClient(app) as client:
|
||||
client.put(
|
||||
"/api/settings/qbittorrent",
|
||||
json={"url": "192.168.1.50", "port": 8555},
|
||||
)
|
||||
with TestClient(app):
|
||||
captured = capsys.readouterr()
|
||||
assert "conf.json charge" in captured.out
|
||||
assert "qbittorrent (bypass d'authentification)" in captured.out
|
||||
@@ -0,0 +1,163 @@
|
||||
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 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:
|
||||
"""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)
|
||||
|
||||
|
||||
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,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
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)])
|
||||
)
|
||||
|
||||
|
||||
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']})")
|
||||
|
||||
|
||||
@respx.mock
|
||||
def test_conversion_order_and_radarr_file_name() -> None:
|
||||
reset_state()
|
||||
folder = create_film_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:
|
||||
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"
|
||||
assert movie["radarr_linked"] is True
|
||||
|
||||
# Ordre voulu: le dossier du film a ete nettoye (poster, extras)
|
||||
# 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())
|
||||
assert entries == [ISO_NAME, MKV_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 reste.
|
||||
entries = sorted(entry.name for entry in folder.iterdir())
|
||||
assert entries == [MKV_NAME]
|
||||
# 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() == []
|
||||
|
||||
|
||||
@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"
|
||||
+59
-13
@@ -10,18 +10,24 @@ type Movie = {
|
||||
size: number | null;
|
||||
poster_url: string | null;
|
||||
status: string;
|
||||
radarr_linked: boolean;
|
||||
completed_at: string | null;
|
||||
last_error: string | null;
|
||||
failed_step: string | null;
|
||||
last_seen_at: string;
|
||||
};
|
||||
|
||||
type RadarrSettings = { url: string | null; api_key_configured: boolean };
|
||||
type RadarrSettings = {
|
||||
url: string | null;
|
||||
port: number | null;
|
||||
api_key_configured: boolean;
|
||||
};
|
||||
|
||||
type NotificationKind = "info" | "error" | "warning";
|
||||
type Notification = { id: number; text: string; kind: NotificationKind };
|
||||
type QbittorrentSettings = {
|
||||
url: string | null;
|
||||
port: number | null;
|
||||
username: string | null;
|
||||
password_configured: boolean;
|
||||
};
|
||||
@@ -104,10 +110,13 @@ export default function App() {
|
||||
const [page, setPage] = useState<Page>("dashboard");
|
||||
const [movies, setMovies] = useState<Movie[]>([]);
|
||||
const [tab, setTab] = useState<Tab>("pending");
|
||||
const [linkedOnly, setLinkedOnly] = useState(false);
|
||||
const [url, setUrl] = useState("");
|
||||
const [radarrPort, setRadarrPort] = useState("");
|
||||
const [apiKey, setApiKey] = useState("");
|
||||
const [keyConfigured, setKeyConfigured] = useState(false);
|
||||
const [qbitUrl, setQbitUrl] = useState("");
|
||||
const [qbitPort, setQbitPort] = useState("");
|
||||
const [qbitUsername, setQbitUsername] = useState("");
|
||||
const [qbitPassword, setQbitPassword] = useState("");
|
||||
const [qbitConfigured, setQbitConfigured] = useState(false);
|
||||
@@ -197,8 +206,10 @@ export default function App() {
|
||||
])
|
||||
.then(([radarr, qbittorrent]) => {
|
||||
setUrl(radarr.url ?? "");
|
||||
setRadarrPort(radarr.port?.toString() ?? "");
|
||||
setKeyConfigured(radarr.api_key_configured);
|
||||
setQbitUrl(qbittorrent.url ?? "");
|
||||
setQbitPort(qbittorrent.port?.toString() ?? "");
|
||||
setQbitUsername(qbittorrent.username ?? "");
|
||||
setQbitConfigured(qbittorrent.password_configured);
|
||||
if (!radarr.api_key_configured || !qbittorrent.password_configured) {
|
||||
@@ -294,7 +305,7 @@ export default function App() {
|
||||
const settings = await api<RadarrSettings>("/api/settings/radarr", {
|
||||
method: "PUT",
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({ url, api_key: apiKey || null }),
|
||||
body: JSON.stringify({ url, port: radarrPort ? Number(radarrPort) : null, api_key: apiKey || null }),
|
||||
});
|
||||
setKeyConfigured(settings.api_key_configured);
|
||||
setApiKey("");
|
||||
@@ -318,6 +329,7 @@ export default function App() {
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({
|
||||
url: qbitUrl,
|
||||
port: qbitPort ? Number(qbitPort) : null,
|
||||
username: qbitUsername,
|
||||
password: qbitPassword || null,
|
||||
}),
|
||||
@@ -362,7 +374,9 @@ export default function App() {
|
||||
};
|
||||
}, [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(
|
||||
(a, b) => Date.parse(b.last_seen_at) - Date.parse(a.last_seen_at),
|
||||
);
|
||||
@@ -813,6 +827,13 @@ export default function App() {
|
||||
<span className="count">{groups[id].length}</span>
|
||||
</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>
|
||||
{visible.length === 0 ? (
|
||||
<div className="empty">Aucun film dans cette catégorie.</div>
|
||||
@@ -877,6 +898,7 @@ export default function App() {
|
||||
Supprimer
|
||||
</button>
|
||||
)}
|
||||
{movie.radarr_linked && <span className="status linked">Radarr lié</span>}
|
||||
<span className={BROKEN.includes(movie.status) ? "status error" : "status"}>
|
||||
{statusLabel(movie.status)}
|
||||
</span>
|
||||
@@ -900,13 +922,24 @@ export default function App() {
|
||||
<label>
|
||||
URL Radarr
|
||||
<input
|
||||
type="url"
|
||||
type="text"
|
||||
required
|
||||
placeholder="http://radarr:7878"
|
||||
placeholder="http://radarr:7878 ou 192.168.1.50"
|
||||
value={url}
|
||||
onChange={(event) => setUrl(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Port (optionnel)
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
max={65535}
|
||||
placeholder="7878"
|
||||
value={radarrPort}
|
||||
onChange={(event) => setRadarrPort(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Clé API
|
||||
<input
|
||||
@@ -935,29 +968,42 @@ export default function App() {
|
||||
<label>
|
||||
URL qBittorrent
|
||||
<input
|
||||
type="url"
|
||||
type="text"
|
||||
required
|
||||
placeholder="http://qbittorrent:8080"
|
||||
placeholder="http://qbittorrent:8080 ou 192.168.1.50"
|
||||
value={qbitUrl}
|
||||
onChange={(event) => setQbitUrl(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Utilisateur
|
||||
Port (optionnel)
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
max={65535}
|
||||
placeholder="8080"
|
||||
value={qbitPort}
|
||||
onChange={(event) => setQbitPort(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Utilisateur (optionnel)
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
placeholder="admin"
|
||||
placeholder="admin — vide = bypass qBittorrent"
|
||||
value={qbitUsername}
|
||||
onChange={(event) => setQbitUsername(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Mot de passe
|
||||
Mot de passe (optionnel)
|
||||
<input
|
||||
type="password"
|
||||
required={!qbitConfigured}
|
||||
placeholder={qbitConfigured ? "Configuré — laisser vide pour conserver" : "Mot de passe WebUI"}
|
||||
placeholder={
|
||||
qbitConfigured
|
||||
? "Configuré — laisser vide pour conserver, tout vider = bypass"
|
||||
: "Vide = bypass d'authentification qBittorrent"
|
||||
}
|
||||
value={qbitPassword}
|
||||
onChange={(event) => setQbitPassword(event.target.value)}
|
||||
/>
|
||||
|
||||
@@ -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.linked {
|
||||
color: #4ade80;
|
||||
border-color: rgba(74, 222, 128, 0.4);
|
||||
}
|
||||
|
||||
.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; }
|
||||
|
||||
Reference in new issue
Block a user