:feature: Mise en place de l'interface et de la configuration
This commit is contained in:
1 parent
6278d19618
commit
311ec74668
21 files changed
+1920
-231
No files matched your search
@@ -0,0 +1,67 @@
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.config import settings
|
||||
|
||||
|
||||
class ApiServiceConfig(BaseModel):
|
||||
url: str | None = None
|
||||
api_key: str | None = None
|
||||
|
||||
|
||||
class QbittorrentConfig(BaseModel):
|
||||
url: str | None = None
|
||||
username: str | None = None
|
||||
password: str | None = None
|
||||
|
||||
|
||||
class AppConfig(BaseModel):
|
||||
radarr: ApiServiceConfig = Field(default_factory=ApiServiceConfig)
|
||||
sonarr: ApiServiceConfig = Field(default_factory=ApiServiceConfig)
|
||||
prowlarr: ApiServiceConfig = Field(default_factory=ApiServiceConfig)
|
||||
jellyfin: ApiServiceConfig = Field(default_factory=ApiServiceConfig)
|
||||
seerr: ApiServiceConfig = Field(default_factory=ApiServiceConfig)
|
||||
qbittorrent: QbittorrentConfig = Field(default_factory=QbittorrentConfig)
|
||||
|
||||
|
||||
def config_path() -> Path:
|
||||
# Keep the name requested by the user: conf.json
|
||||
return settings.config_dir / "conf.json"
|
||||
|
||||
|
||||
def read_config() -> AppConfig:
|
||||
path = config_path()
|
||||
if not path.exists():
|
||||
return AppConfig()
|
||||
raw = json.loads(path.read_text(encoding="utf-8"))
|
||||
if not isinstance(raw, dict):
|
||||
return AppConfig()
|
||||
return AppConfig.model_validate(raw)
|
||||
|
||||
|
||||
def write_config(config: AppConfig) -> None:
|
||||
path = config_path()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
serialized = config.model_dump(mode="json", exclude_none=True)
|
||||
|
||||
# Atomic write to avoid corrupting conf.json if the process is interrupted.
|
||||
tmp_dir = str(path.parent)
|
||||
with tempfile.NamedTemporaryFile(
|
||||
mode="w",
|
||||
encoding="utf-8",
|
||||
dir=tmp_dir,
|
||||
prefix=path.name + ".",
|
||||
suffix=".tmp",
|
||||
delete=False,
|
||||
) as handle:
|
||||
json.dump(serialized, handle, indent=2, ensure_ascii=False)
|
||||
handle.write("\n")
|
||||
tmp_name = handle.name
|
||||
|
||||
os.replace(tmp_name, path)
|
||||
|
||||
+106
-22
@@ -7,26 +7,43 @@ from typing import Annotated
|
||||
import httpx
|
||||
from fastapi import Depends, FastAPI, HTTPException
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from sqlalchemy import select
|
||||
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,
|
||||
QbittorrentSettingsRead,
|
||||
ConnectionResult,
|
||||
HealthRead,
|
||||
IsoMovieRead,
|
||||
RadarrSettingsRead,
|
||||
RadarrSettingsWrite,
|
||||
ScanResult,
|
||||
SettingsRead,
|
||||
SettingsWrite,
|
||||
)
|
||||
from app.settings_store import radarr_credentials, read_setting, write_setting
|
||||
from app.settings_store import radarr_credentials
|
||||
|
||||
|
||||
@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
|
||||
|
||||
|
||||
@@ -41,11 +58,32 @@ app.add_middleware(
|
||||
DbSession = Annotated[Session, Depends(get_db)]
|
||||
|
||||
|
||||
def client_from_db(db: Session) -> RadarrClient:
|
||||
try:
|
||||
url, api_key = radarr_credentials(db)
|
||||
except ValueError as error:
|
||||
raise HTTPException(status_code=409, detail=str(error)) from error
|
||||
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)
|
||||
|
||||
|
||||
@@ -61,30 +99,63 @@ def health() -> HealthRead:
|
||||
|
||||
|
||||
@app.get("/api/settings/radarr", response_model=RadarrSettingsRead)
|
||||
def get_radarr_settings(db: DbSession) -> RadarrSettingsRead:
|
||||
return RadarrSettingsRead(
|
||||
url=read_setting(db, "radarr_url"),
|
||||
api_key_configured=read_setting(db, "radarr_api_key") is not None,
|
||||
)
|
||||
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, db: DbSession
|
||||
payload: RadarrSettingsWrite,
|
||||
) -> RadarrSettingsRead:
|
||||
cfg = read_config()
|
||||
url = str(payload.url).rstrip("/")
|
||||
write_setting(db, "radarr_url", url)
|
||||
cfg.radarr.url = url
|
||||
if payload.api_key:
|
||||
write_setting(db, "radarr_api_key", payload.api_key)
|
||||
db.commit()
|
||||
return RadarrSettingsRead(
|
||||
url=url, api_key_configured=read_setting(db, "radarr_api_key") is not None
|
||||
)
|
||||
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(db: DbSession) -> ConnectionResult:
|
||||
client = client_from_db(db)
|
||||
async def test_radarr() -> ConnectionResult:
|
||||
client = client_from_config()
|
||||
try:
|
||||
status = await client.system_status()
|
||||
except (httpx.HTTPError, ValueError) as error:
|
||||
@@ -100,9 +171,22 @@ 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_db(db)
|
||||
client = client_from_config()
|
||||
try:
|
||||
movies = await client.movies()
|
||||
except (httpx.HTTPError, ValueError) as error:
|
||||
|
||||
@@ -29,3 +29,4 @@ class IsoMovie(Base):
|
||||
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)
|
||||
+3
-2
@@ -21,7 +21,9 @@ class RadarrClient:
|
||||
return result
|
||||
|
||||
async def movies(self) -> list[dict]:
|
||||
result = await self._get("movie")
|
||||
# Radarr does not always embed movieFile by default depending on client version.
|
||||
# The documented way is to request it explicitly.
|
||||
result = await self._get("movie?includeMovieFile=true")
|
||||
if not isinstance(result, list):
|
||||
raise ValueError("Réponse Radarr inattendue")
|
||||
return result
|
||||
@@ -37,4 +39,3 @@ def movie_file_path(movie: dict) -> str | None:
|
||||
if relative_path and movie_path:
|
||||
return str(PurePath(str(movie_path)) / str(relative_path))
|
||||
return None
|
||||
|
||||
+42
-1
@@ -13,6 +13,46 @@ class RadarrSettingsWrite(BaseModel):
|
||||
api_key: str | None = Field(default=None, min_length=1)
|
||||
|
||||
|
||||
class ApiServiceSettingsRead(BaseModel):
|
||||
url: str | None
|
||||
api_key_configured: bool
|
||||
|
||||
|
||||
class ApiServiceSettingsWrite(BaseModel):
|
||||
url: HttpUrl | None = None
|
||||
api_key: str | None = Field(default=None, min_length=1)
|
||||
|
||||
|
||||
class QbittorrentSettingsRead(BaseModel):
|
||||
url: str | None
|
||||
username: str | None
|
||||
password_configured: bool
|
||||
|
||||
|
||||
class QbittorrentSettingsWrite(BaseModel):
|
||||
url: HttpUrl | None = None
|
||||
username: str | None = Field(default=None, min_length=1)
|
||||
password: str | None = Field(default=None, min_length=1)
|
||||
|
||||
|
||||
class SettingsRead(BaseModel):
|
||||
radarr: ApiServiceSettingsRead
|
||||
sonarr: ApiServiceSettingsRead
|
||||
prowlarr: ApiServiceSettingsRead
|
||||
jellyfin: ApiServiceSettingsRead
|
||||
seerr: ApiServiceSettingsRead
|
||||
qbittorrent: QbittorrentSettingsRead
|
||||
|
||||
|
||||
class SettingsWrite(BaseModel):
|
||||
radarr: ApiServiceSettingsWrite | None = None
|
||||
sonarr: ApiServiceSettingsWrite | None = None
|
||||
prowlarr: ApiServiceSettingsWrite | None = None
|
||||
jellyfin: ApiServiceSettingsWrite | None = None
|
||||
seerr: ApiServiceSettingsWrite | None = None
|
||||
qbittorrent: QbittorrentSettingsWrite | None = None
|
||||
|
||||
|
||||
class ConnectionResult(BaseModel):
|
||||
success: bool
|
||||
version: str | None = None
|
||||
@@ -31,6 +71,8 @@ class IsoMovieRead(BaseModel):
|
||||
size: int | None
|
||||
status: str
|
||||
last_seen_at: datetime
|
||||
created_at: datetime | None = None
|
||||
processed_at: datetime | None = None
|
||||
|
||||
|
||||
class ScanResult(BaseModel):
|
||||
@@ -45,4 +87,3 @@ class HealthRead(BaseModel):
|
||||
database: str
|
||||
makemkv_available: bool
|
||||
makemkv_version: str | None
|
||||
|
||||
+12
-21
@@ -1,25 +1,16 @@
|
||||
from sqlalchemy.orm import Session
|
||||
"""Legacy module.
|
||||
|
||||
from app.models import ApplicationSetting
|
||||
Historically, MKVTool stored connection settings inside SQLite.
|
||||
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
|
||||
|
||||
|
||||
def read_setting(db: Session, key: str) -> str | None:
|
||||
item = db.get(ApplicationSetting, key)
|
||||
return item.value if item else None
|
||||
|
||||
|
||||
def write_setting(db: Session, key: str, value: str) -> None:
|
||||
item = db.get(ApplicationSetting, key)
|
||||
if item:
|
||||
item.value = value
|
||||
else:
|
||||
db.add(ApplicationSetting(key=key, value=value))
|
||||
|
||||
|
||||
def radarr_credentials(db: Session) -> tuple[str, str]:
|
||||
url = read_setting(db, "radarr_url")
|
||||
api_key = read_setting(db, "radarr_api_key")
|
||||
if not url or not api_key:
|
||||
def radarr_credentials(_: object | None = None) -> tuple[str, str]:
|
||||
cfg = read_config()
|
||||
if not cfg.radarr.url or not cfg.radarr.api_key:
|
||||
raise ValueError("La connexion Radarr n'est pas configurée")
|
||||
return url.rstrip("/"), api_key
|
||||
|
||||
return cfg.radarr.url.rstrip("/"), cfg.radarr.api_key
|
||||
Reference in new issue
Block a user