✨ Statut par service dans la Configuration: configure / teste / echec + endpoints de test pour tous les services

This commit is contained in:
Orionis312050 committed 2026-10-12 18:03:49 +00:00
1 parent 23132c6219
commit 3a75527135
9 files changed
+409 -59

No files matched your search

+54
View File
@@ -1,6 +1,7 @@
import json
import os
import tempfile
from datetime import UTC, datetime
from pathlib import Path
from urllib.parse import urlparse
@@ -9,10 +10,20 @@ from pydantic import BaseModel, Field
from app.config import settings
class TestState(BaseModel):
"""Resultat du dernier test de connexion (None = jamais teste)."""
at: str | None = None
ok: bool | None = None
version: str | None = None
error: str | None = None
class ApiServiceConfig(BaseModel):
url: str | None = None
port: int | None = None
api_key: str | None = None
test: TestState = Field(default_factory=TestState)
class QbittorrentConfig(BaseModel):
@@ -20,6 +31,7 @@ class QbittorrentConfig(BaseModel):
port: int | None = None
username: str | None = None
password: str | None = None
test: TestState = Field(default_factory=TestState)
def build_base_url(url: str | None, port: int | None = None) -> str | None:
@@ -54,6 +66,48 @@ def config_path() -> Path:
return settings.config_dir / "conf.json"
SERVICE_NAMES = ("radarr", "sonarr", "prowlarr", "jellyfin", "seerr", "qbittorrent")
def service_configured(service: ApiServiceConfig | QbittorrentConfig) -> bool:
"""Un service est completement configure quand son URL (et sa cle API,
quand il en faut une) est renseignee."""
if isinstance(service, QbittorrentConfig):
return bool(service.url)
return bool(service.url and service.api_key)
def service_status(service: ApiServiceConfig | QbittorrentConfig) -> str:
"""Statut expose a l'UI: unconfigured | configured | tested | error."""
if not service_configured(service):
return "unconfigured"
if service.test.ok is None:
return "configured"
return "tested" if service.test.ok else "error"
def record_test(
service_name: str, ok: bool, version: str | None = None, error: str | None = None
) -> None:
"""Persiste dans conf.json le resultat du dernier test de connexion."""
if service_name not in SERVICE_NAMES:
raise ValueError(f"Service inconnu: {service_name}")
cfg = read_config()
service = getattr(cfg, service_name)
service.test = TestState(
at=datetime.now(UTC).isoformat(),
ok=ok,
version=version if ok else None,
error=None if ok else error,
)
write_config(cfg)
def reset_test(service: ApiServiceConfig | QbittorrentConfig) -> None:
"""Reinitialise le statut de test quand la configuration change."""
service.test = TestState()
def read_config() -> AppConfig:
path = config_path()
if not path.exists():
+142 -38
View File
@@ -14,7 +14,17 @@ from sqlalchemy import inspect, select, text, update
from sqlalchemy.orm import Session
from app import auth
from app.conf_store import ApiServiceConfig, build_base_url, read_config, write_config
from app.conf_store import (
ApiServiceConfig,
QbittorrentConfig,
build_base_url,
read_config,
record_test,
reset_test,
service_configured,
service_status,
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
@@ -85,7 +95,26 @@ DbSession = Annotated[Session, Depends(get_db)]
def _api_service_read(service: ApiServiceConfig) -> ApiServiceSettingsRead:
return ApiServiceSettingsRead(
url=service.url, port=service.port, api_key_configured=service.api_key is not None
url=service.url,
port=service.port,
api_key_configured=service.api_key is not None,
status=service_status(service),
tested_version=service.test.version,
tested_at=service.test.at,
test_error=service.test.error,
)
def _qbittorrent_read(qb: QbittorrentConfig) -> QbittorrentSettingsRead:
return QbittorrentSettingsRead(
url=qb.url,
port=qb.port,
username=qb.username,
password_configured=qb.password is not None,
status=service_status(qb),
tested_version=qb.test.version,
tested_at=qb.test.at,
test_error=qb.test.error,
)
@@ -97,11 +126,7 @@ def _settings_read() -> SettingsRead:
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,
password_configured=cfg.qbittorrent.password is not None,
),
qbittorrent=_qbittorrent_read(cfg.qbittorrent),
)
@@ -127,12 +152,7 @@ def health() -> HealthRead:
@app.get("/api/settings/radarr", response_model=RadarrSettingsRead)
def get_radarr_settings() -> RadarrSettingsRead:
radarr = read_config().radarr
return RadarrSettingsRead(
url=radarr.url,
port=radarr.port,
api_key_configured=radarr.api_key is not None,
)
return _api_service_read(read_config().radarr)
@app.put("/api/settings/radarr", response_model=RadarrSettingsRead)
@@ -141,16 +161,19 @@ def put_radarr_settings(
) -> RadarrSettingsRead:
cfg = read_config()
url = str(payload.url).strip().rstrip("/")
# Toute modification de la connexion invalide le dernier test.
if (
url != (cfg.radarr.url or "")
or payload.port != cfg.radarr.port
or (payload.api_key and payload.api_key != cfg.radarr.api_key)
):
reset_test(cfg.radarr)
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,
port=cfg.radarr.port,
api_key_configured=cfg.radarr.api_key is not None,
)
return _api_service_read(cfg.radarr)
@app.get("/api/settings", response_model=SettingsRead)
@@ -165,6 +188,13 @@ def put_settings(payload: SettingsWrite) -> SettingsRead:
def apply_service(target, patch):
if patch is None:
return
changed = False
if patch.url is not None and str(patch.url).rstrip("/") != (target.url or ""):
changed = True
if patch.api_key and patch.api_key != target.api_key:
changed = True
if changed:
reset_test(target)
if patch.url is not None:
target.url = str(patch.url).rstrip("/")
if patch.api_key:
@@ -178,6 +208,11 @@ def put_settings(payload: SettingsWrite) -> SettingsRead:
if payload.qbittorrent is not None:
qb = payload.qbittorrent
qb_changed = bool(qb.url) and str(qb.url).rstrip("/") != (cfg.qbittorrent.url or "")
qb_changed = qb_changed or bool(qb.username and qb.username != cfg.qbittorrent.username)
qb_changed = qb_changed or bool(qb.password)
if qb_changed:
reset_test(cfg.qbittorrent)
if qb.url is not None:
cfg.qbittorrent.url = str(qb.url).rstrip("/")
if qb.username:
@@ -195,13 +230,83 @@ async def test_radarr() -> ConnectionResult:
try:
status = await client.system_status()
except (httpx.HTTPError, ValueError) as error:
record_test("radarr", ok=False, error=str(error))
raise HTTPException(
status_code=502, detail=f"Connexion Radarr impossible: {error}"
) from error
version = str(status.get("version", "inconnue"))
record_test("radarr", ok=True, version=version)
return ConnectionResult(success=True, version=version, message=f"Radarr {version} accessible")
# --- Tests de connexion des autres services API (Sonarr, Prowlarr, Jellyfin,
# Overseerr). Chacun expose un endpoint systeme et une version. ---
API_SERVICE_TESTS: dict[str, tuple[str, str, str]] = {
# service: (endpoint, nom de l'en-tete d'authentification, cle de version)
"sonarr": ("api/v3/system/status", "X-Api-Key", "version"),
"prowlarr": ("api/v1/system/status", "X-Api-Key", "version"),
"jellyfin": ("System/Info", "X-Emby-Token", "Version"),
"seerr": ("api/v1/status", "X-Api-Key", "version"),
}
SERVICE_LABELS = {
"sonarr": "Sonarr",
"prowlarr": "Prowlarr",
"jellyfin": "Jellyfin",
"seerr": "Overseerr",
}
async def _test_api_service(name: str) -> ConnectionResult:
service = getattr(read_config(), name)
label = SERVICE_LABELS[name]
url = build_base_url(service.url, service.port)
if not service_configured(service):
raise HTTPException(
status_code=409, detail=f"La connexion {label} n'est pas configurée"
)
endpoint, auth_header, version_key = API_SERVICE_TESTS[name]
try:
async with httpx.AsyncClient(timeout=30) as client:
response = await client.get(
f"{url}/{endpoint}", headers={auth_header: service.api_key}
)
response.raise_for_status()
data = response.json()
except (httpx.HTTPError, ValueError) as error:
record_test(name, ok=False, error=str(error))
raise HTTPException(
status_code=502, detail=f"Connexion {label} impossible: {error}"
) from error
if not isinstance(data, dict):
error = "Réponse inattendue du service"
record_test(name, ok=False, error=error)
raise HTTPException(status_code=502, detail=f"Connexion {label} impossible: {error}")
version = str(data.get(version_key, "inconnue"))
record_test(name, ok=True, version=version)
return ConnectionResult(success=True, version=version, message=f"{label} {version} accessible")
@app.post("/api/settings/sonarr/test", response_model=ConnectionResult)
async def test_sonarr() -> ConnectionResult:
return await _test_api_service("sonarr")
@app.post("/api/settings/prowlarr/test", response_model=ConnectionResult)
async def test_prowlarr() -> ConnectionResult:
return await _test_api_service("prowlarr")
@app.post("/api/settings/jellyfin/test", response_model=ConnectionResult)
async def test_jellyfin() -> ConnectionResult:
return await _test_api_service("jellyfin")
@app.post("/api/settings/seerr/test", response_model=ConnectionResult)
async def test_seerr() -> ConnectionResult:
return await _test_api_service("seerr")
def qbittorrent_from_config() -> QbittorrentClient:
qb = read_config().qbittorrent
url = build_base_url(qb.url, qb.port)
@@ -212,39 +317,36 @@ def qbittorrent_from_config() -> QbittorrentClient:
@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,
)
return _qbittorrent_read(read_config().qbittorrent)
@app.put("/api/settings/qbittorrent", response_model=QbittorrentSettingsRead)
def put_qbittorrent_settings(payload: QbittorrentSettingsWrite) -> QbittorrentSettingsRead:
cfg = read_config()
qb = cfg.qbittorrent
qb_changed = payload.url is not None and str(payload.url).strip().rstrip("/") != (
qb.url or ""
)
qb_changed = qb_changed or bool(payload.username and payload.username != qb.username)
qb_changed = qb_changed or bool(payload.password)
if qb_changed:
reset_test(qb)
if payload.url is not None:
cfg.qbittorrent.url = str(payload.url).strip().rstrip("/")
cfg.qbittorrent.port = payload.port
qb.url = str(payload.url).strip().rstrip("/")
qb.port = payload.port
if payload.username:
cfg.qbittorrent.username = payload.username
qb.username = payload.username
if payload.password:
cfg.qbittorrent.password = payload.password
qb.password = payload.password
elif payload.password:
# Mot de passe seul: on conserve l'utilisateur existant.
cfg.qbittorrent.password = payload.password
qb.password = payload.password
else:
# Champs vides: mode bypass d'authentification qBittorrent, sans identifiants.
cfg.qbittorrent.username = None
cfg.qbittorrent.password = None
qb.username = None
qb.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,
)
return _qbittorrent_read(qb)
@app.post("/api/settings/qbittorrent/test", response_model=ConnectionResult)
@@ -253,9 +355,11 @@ async def test_qbittorrent() -> ConnectionResult:
try:
version = await client.version()
except (httpx.HTTPError, ValueError) as error:
record_test("qbittorrent", ok=False, error=str(error))
raise HTTPException(
status_code=502, detail=f"Connexion qBittorrent impossible: {error}"
) from error
record_test("qbittorrent", ok=True, version=version)
return ConnectionResult(
success=True, version=version, message=f"qBittorrent {version} accessible"
)
+12
View File
@@ -7,6 +7,10 @@ class RadarrSettingsRead(BaseModel):
url: str | None
port: int | None = None
api_key_configured: bool
status: str
tested_version: str | None = None
tested_at: str | None = None
test_error: str | None = None
class RadarrSettingsWrite(BaseModel):
@@ -19,6 +23,10 @@ class ApiServiceSettingsRead(BaseModel):
url: str | None
port: int | None = None
api_key_configured: bool
status: str
tested_version: str | None = None
tested_at: str | None = None
test_error: str | None = None
class ApiServiceSettingsWrite(BaseModel):
@@ -32,6 +40,10 @@ class QbittorrentSettingsRead(BaseModel):
port: int | None = None
username: str | None
password_configured: bool
status: str
tested_version: str | None = None
tested_at: str | None = None
test_error: str | None = None
class QbittorrentSettingsWrite(BaseModel):