astrbot_plugin_jmdowloads/services/komga.py
2026-07-07 00:19:34 +08:00

79 行
2.4 KiB
Python

此文件含有模棱两可的 Unicode 字符

此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。

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)