79 行
2.4 KiB
Python
79 行
2.4 KiB
Python
from __future__ import annotations
|
||
|
||
from dataclasses import dataclass
|
||
from urllib.parse import quote
|
||
|
||
import httpx
|
||
|
||
from .settings import KomgaSettings
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class KomgaScanResult:
|
||
attempted: bool
|
||
success: bool
|
||
message: str
|
||
status_code: int | None = None
|
||
endpoint: str = ""
|
||
|
||
|
||
class KomgaClient:
|
||
def __init__(self, settings: KomgaSettings) -> None:
|
||
self.settings = settings
|
||
|
||
async def scan_library(self) -> KomgaScanResult:
|
||
if not self.settings.enabled:
|
||
return KomgaScanResult(False, False, "Komga 自动扫描未启用")
|
||
if not self.settings.can_scan:
|
||
return KomgaScanResult(
|
||
False,
|
||
False,
|
||
"Komga 扫描配置不完整,请填写 base_url、library_id 和认证信息",
|
||
)
|
||
|
||
url = self._scan_url()
|
||
try:
|
||
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,
|
||
)
|
||
return KomgaScanResult(
|
||
True,
|
||
False,
|
||
f"Komga 扫描触发失败:HTTP {response.status_code} {response.text[:200]}",
|
||
status_code=response.status_code,
|
||
endpoint=url,
|
||
)
|
||
except Exception as exc:
|
||
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)
|