245 lines
8.1 KiB
Python
245 lines
8.1 KiB
Python
import os
|
|
import shutil
|
|
from contextlib import asynccontextmanager
|
|
from datetime import UTC, datetime
|
|
from typing import Annotated
|
|
|
|
import httpx
|
|
from fastapi import Depends, FastAPI, HTTPException
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from fastapi.staticfiles import StaticFiles
|
|
from sqlalchemy import inspect, select, text
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.conf_store import read_config, write_config
|
|
from app.database import Base, engine, get_db
|
|
from app.models import IsoMovie
|
|
from app.radarr import RadarrClient, movie_file_path
|
|
from app.schemas import (
|
|
ApiServiceSettingsRead,
|
|
ConnectionResult,
|
|
HealthRead,
|
|
IsoMovieRead,
|
|
QbittorrentSettingsRead,
|
|
RadarrSettingsRead,
|
|
RadarrSettingsWrite,
|
|
ScanResult,
|
|
SettingsRead,
|
|
SettingsWrite,
|
|
)
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(_: FastAPI):
|
|
Base.metadata.create_all(bind=engine)
|
|
|
|
# Very small "migration" helper for dev: add new columns if the SQLite DB already exists.
|
|
# (SQLAlchemy create_all doesn't alter existing tables.)
|
|
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"))
|
|
except Exception:
|
|
# Don't fail app startup for a best-effort migration.
|
|
pass
|
|
yield
|
|
|
|
|
|
app = FastAPI(title="MKVTool", version="0.1.0", lifespan=lifespan)
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["http://localhost:5173", "http://127.0.0.1:5173"],
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
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 _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),
|
|
qbittorrent=QbittorrentSettingsRead(
|
|
url=cfg.qbittorrent.url,
|
|
username=cfg.qbittorrent.username,
|
|
password_configured=cfg.qbittorrent.password is not None,
|
|
),
|
|
)
|
|
|
|
|
|
def client_from_config() -> RadarrClient:
|
|
cfg = read_config()
|
|
url = (cfg.radarr.url or "").rstrip("/")
|
|
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")
|
|
return RadarrClient(url, api_key)
|
|
|
|
|
|
@app.get("/api/health", response_model=HealthRead)
|
|
def health() -> HealthRead:
|
|
executable = shutil.which("makemkvcon")
|
|
return HealthRead(
|
|
status="ok",
|
|
database="ok",
|
|
makemkv_available=executable is not None,
|
|
makemkv_version=os.getenv("MAKEMKV_VERSION") if executable else None,
|
|
)
|
|
|
|
|
|
@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)
|
|
|
|
|
|
@app.put("/api/settings/radarr", response_model=RadarrSettingsRead)
|
|
def put_radarr_settings(
|
|
payload: RadarrSettingsWrite,
|
|
) -> RadarrSettingsRead:
|
|
cfg = read_config()
|
|
url = str(payload.url).rstrip("/")
|
|
cfg.radarr.url = url
|
|
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)
|
|
|
|
|
|
@app.get("/api/settings", response_model=SettingsRead)
|
|
def get_settings() -> SettingsRead:
|
|
return _settings_read()
|
|
|
|
|
|
@app.put("/api/settings", response_model=SettingsRead)
|
|
def put_settings(payload: SettingsWrite) -> SettingsRead:
|
|
cfg = read_config()
|
|
|
|
def apply_service(target, patch):
|
|
if patch is None:
|
|
return
|
|
if patch.url is not None:
|
|
target.url = str(patch.url).rstrip("/")
|
|
if patch.api_key:
|
|
target.api_key = patch.api_key
|
|
|
|
apply_service(cfg.radarr, payload.radarr)
|
|
apply_service(cfg.sonarr, payload.sonarr)
|
|
apply_service(cfg.prowlarr, payload.prowlarr)
|
|
apply_service(cfg.jellyfin, payload.jellyfin)
|
|
apply_service(cfg.seerr, payload.seerr)
|
|
|
|
if payload.qbittorrent is not None:
|
|
qb = payload.qbittorrent
|
|
if qb.url is not None:
|
|
cfg.qbittorrent.url = str(qb.url).rstrip("/")
|
|
if qb.username:
|
|
cfg.qbittorrent.username = qb.username
|
|
if qb.password:
|
|
cfg.qbittorrent.password = qb.password
|
|
|
|
write_config(cfg)
|
|
return _settings_read()
|
|
|
|
|
|
@app.post("/api/settings/radarr/test", response_model=ConnectionResult)
|
|
async def test_radarr() -> ConnectionResult:
|
|
client = client_from_config()
|
|
try:
|
|
status = await client.system_status()
|
|
except (httpx.HTTPError, ValueError) as error:
|
|
raise HTTPException(
|
|
status_code=502, detail=f"Connexion Radarr impossible: {error}"
|
|
) from error
|
|
version = str(status.get("version", "inconnue"))
|
|
return ConnectionResult(success=True, version=version, message=f"Radarr {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())
|
|
|
|
|
|
@app.get("/api/files", response_model=list[IsoMovieRead])
|
|
def list_files(db: DbSession) -> list[IsoMovie]:
|
|
return list_movies(db)
|
|
|
|
|
|
@app.get("/api/files/{file_id}", response_model=IsoMovieRead)
|
|
def get_file(file_id: int, db: DbSession) -> IsoMovie:
|
|
item = db.get(IsoMovie, file_id)
|
|
if item is None:
|
|
raise HTTPException(status_code=404, detail="Fichier introuvable")
|
|
return item
|
|
|
|
|
|
@app.post("/api/scans", response_model=ScanResult)
|
|
async def scan_radarr(db: DbSession) -> ScanResult:
|
|
client = client_from_config()
|
|
try:
|
|
movies = await client.movies()
|
|
except (httpx.HTTPError, ValueError) as error:
|
|
raise HTTPException(status_code=502, detail=f"Scan Radarr impossible: {error}") from error
|
|
|
|
iso_files = created = updated = 0
|
|
now = datetime.now(UTC)
|
|
for movie in movies:
|
|
movie_file = movie.get("movieFile") or {}
|
|
path = movie_file_path(movie)
|
|
if not path or not path.lower().endswith(".iso"):
|
|
continue
|
|
movie_id = movie.get("id")
|
|
movie_file_id = movie_file.get("id")
|
|
if not isinstance(movie_id, int) or not isinstance(movie_file_id, int):
|
|
continue
|
|
iso_files += 1
|
|
item = db.scalar(
|
|
select(IsoMovie).where(
|
|
IsoMovie.radarr_movie_id == movie_id,
|
|
IsoMovie.radarr_movie_file_id == movie_file_id,
|
|
)
|
|
)
|
|
if item is None:
|
|
item = IsoMovie(
|
|
radarr_movie_id=movie_id,
|
|
radarr_movie_file_id=movie_file_id,
|
|
title=str(movie.get("title", "Film sans titre")),
|
|
year=movie.get("year"),
|
|
path=path,
|
|
size=movie_file.get("size"),
|
|
last_seen_at=now,
|
|
)
|
|
db.add(item)
|
|
created += 1
|
|
else:
|
|
item.title = str(movie.get("title", item.title))
|
|
item.year = movie.get("year")
|
|
item.path = path
|
|
item.size = movie_file.get("size")
|
|
item.last_seen_at = now
|
|
updated += 1
|
|
db.commit()
|
|
return ScanResult(
|
|
scanned_movies=len(movies), iso_files=iso_files, created=created, updated=updated
|
|
)
|
|
|
|
|
|
# Service du front : monte web/dist en racine quand l'image le fournit
|
|
# (MKVTOOL_WEB_DIR). Le montage est declare en dernier, donc les routes /api
|
|
# ci-dessus gardent la priorite; en dev (vite sur :5173), la variable est
|
|
# absente et le montage est saute.
|
|
web_dir = os.environ.get("MKVTOOL_WEB_DIR")
|
|
if web_dir and os.path.isdir(web_dir):
|
|
app.mount("/", StaticFiles(directory=web_dir, html=True), name="web")
|