89 lines
2.5 KiB
Python
89 lines
2.5 KiB
Python
import json
|
|
import os
|
|
import tempfile
|
|
from pathlib import Path
|
|
from urllib.parse import urlparse
|
|
|
|
from pydantic import BaseModel, Field
|
|
|
|
from app.config import settings
|
|
|
|
|
|
class ApiServiceConfig(BaseModel):
|
|
url: str | None = None
|
|
port: int | None = None
|
|
api_key: str | None = None
|
|
|
|
|
|
class QbittorrentConfig(BaseModel):
|
|
url: str | None = None
|
|
port: int | None = None
|
|
username: str | None = None
|
|
password: str | None = None
|
|
|
|
|
|
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):
|
|
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)
|
|
|