import json import os import tempfile from datetime import UTC, datetime from pathlib import Path from urllib.parse import urlparse 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): url: str | None = None 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: """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): # Version de la structure du fichier, migree au demarrage # (voir app/migrations.py). Doit rester synchrone avec # current_conf_version(): un test verifie cet invariant. version: int = 1 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" 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_raw_config() -> dict | None: """Contenu brut de conf.json (dict), ou None s'il est absent. Sert aux migrations, qui transforment le fichier avant validation pydantic. Un contenu invalide (non-dict) est traite comme absent. """ path = config_path() if not path.exists(): return None raw = json.loads(path.read_text(encoding="utf-8")) return raw if isinstance(raw, dict) else None def read_config() -> AppConfig: raw = read_raw_config() if raw is None: return AppConfig() return AppConfig.model_validate(raw) def write_raw_config(data: dict) -> None: """Ecriture atomique du contenu brut de conf.json.""" path = config_path() path.parent.mkdir(parents=True, exist_ok=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(data, handle, indent=2, ensure_ascii=False) handle.write("\n") tmp_name = handle.name os.replace(tmp_name, path) def write_config(config: AppConfig) -> None: write_raw_config(config.model_dump(mode="json", exclude_none=True))