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)