from __future__ import annotations from typing import Any, Optional import httpx from .config import settings class YouTubeSvcError(RuntimeError): def __init__(self, message: str, status_code: int = 400): super().__init__(message) self.status_code = status_code async def _request( method: str, path: str, *, params: Optional[dict[str, Any]] = None, json: Any = None, timeout: float = 45.0, ) -> dict[str, Any]: base = str(settings.youtube_svc_url or "").rstrip("/") if not base: raise YouTubeSvcError("YouTube 服务未配置 (DY_YOUTUBE_SVC_URL)", 503) url = f"{base}{path}" try: async with httpx.AsyncClient(timeout=timeout) as client: resp = await client.request(method, url, params=params, json=json) except httpx.HTTPError as exc: raise YouTubeSvcError(f"YouTube 服务不可用:{exc}", 503) from exc try: data = resp.json() except Exception as exc: raise YouTubeSvcError(f"YouTube 服务返回非 JSON(HTTP {resp.status_code})", 502) from exc if resp.status_code >= 400 or (isinstance(data, dict) and data.get("ok") is False): msg = "" if isinstance(data, dict): msg = str(data.get("error") or data.get("detail") or "") raise YouTubeSvcError(msg or f"YouTube 服务错误 HTTP {resp.status_code}", min(resp.status_code, 599) or 400) return data if isinstance(data, dict) else {"ok": True, "data": data} async def health() -> dict[str, Any]: try: # Callers wrap with ~0.6s; keep internal timeout short to avoid half-open churn. return await _request("GET", "/health", timeout=1.0) except YouTubeSvcError as exc: return {"ok": False, "error": str(exc), "service": "youtube-svc"} async def resolve(url: str) -> dict[str, Any]: return await _request("GET", "/resolve", params={"url": url}) async def channel(url: str, *, videos: bool = False, limit: int = 8) -> dict[str, Any]: return await _request( "GET", "/channel", params={"url": url, "videos": "1" if videos else "0", "limit": str(limit)}, timeout=60.0, ) async def channel_live(url: str) -> dict[str, Any]: return await _request("GET", "/channel/live", params={"url": url}, timeout=60.0) async def video(url: str) -> dict[str, Any]: return await _request("GET", "/video", params={"url": url}, timeout=45.0) async def search(q: str, *, limit: int = 12) -> dict[str, Any]: return await _request("GET", "/search", params={"q": q, "limit": str(limit)}, timeout=45.0) async def batch_live(items: list[str]) -> dict[str, Any]: return await _request("POST", "/batch/live", json={"items": items}, timeout=120.0)