astrbot_plugin_jmdowloads/services/komga.py

80 行
2.4 KiB
Python

2026-07-07 00:01:44 +08:00
from __future__ import annotations
from dataclasses import dataclass
2026-07-07 00:19:34 +08:00
from urllib.parse import quote
2026-07-07 00:01:44 +08:00
import httpx
from .settings import KomgaSettings
@dataclass(frozen=True)
class KomgaScanResult:
attempted: bool
success: bool
message: str
2026-07-07 00:19:34 +08:00
status_code: int | None = None
endpoint: str = ""
2026-07-07 00:01:44 +08:00
class KomgaClient:
def __init__(self, settings: KomgaSettings) -> None:
self.settings = settings
async def scan_library(self) -> KomgaScanResult:
if not self.settings.enabled:
2026-07-07 00:19:34 +08:00
return KomgaScanResult(False, False, "Komga 自动扫描未启用")
2026-07-07 00:01:44 +08:00
if not self.settings.can_scan:
return KomgaScanResult(
False,
False,
2026-07-07 00:19:34 +08:00
"Komga 扫描配置不完整,请填写 base_url、library_id 和认证信息",
2026-07-07 00:01:44 +08:00
)
2026-07-07 00:19:34 +08:00
url = self._scan_url()
2026-07-07 00:01:44 +08:00
try:
2026-07-07 00:19:34 +08:00
async with httpx.AsyncClient(
timeout=self.settings.scan_timeout_seconds,
) as client:
response = await client.post(
url,
headers=self._headers(),
auth=self._auth(),
)
if response.status_code in {200, 202, 204}:
return KomgaScanResult(
True,
True,
"Komga 已接受扫描请求",
status_code=response.status_code,
endpoint=url,
)
2026-07-07 00:01:44 +08:00
return KomgaScanResult(
True,
False,
2026-07-07 00:19:34 +08:00
f"Komga 扫描触发失败:HTTP {response.status_code} {response.text[:200]}",
status_code=response.status_code,
endpoint=url,
2026-07-07 00:01:44 +08:00
)
except Exception as exc:
2026-07-07 00:19:34 +08:00
return KomgaScanResult(
True,
False,
f"Komga 扫描触发异常:{exc}",
endpoint=url,
)
def _scan_url(self) -> str:
library_id = quote(self.settings.library_id, safe="")
return f"{self.settings.base_url}/api/v1/libraries/{library_id}/scan"
def _headers(self) -> dict[str, str]:
if not self.settings.api_key:
return {}
return {"X-API-Key": self.settings.api_key}
def _auth(self) -> tuple[str, str] | None:
if self.settings.api_key:
return None
return (self.settings.username, self.settings.password)