douyinWEB/backend/app/youtube_client.py
eric 47d17aee3c Document YouTube groups and Shorts side-path; sync dual-platform pipeline.
Add isolated Shorts OAuth/clip/upload worker (default off), youtube-svc + group poller, Beijing time UX, and SHORTS.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-10 00:04:06 -05:00

81 lines
2.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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:
return await _request("GET", "/health", timeout=12.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)