# -*- coding: utf-8 -*- """YouTube Shorts upload via OAuth refresh token (httpx, no heavy google SDK).""" from __future__ import annotations from pathlib import Path from typing import Any import httpx def is_upload_quota_error(msg: str) -> bool: """Detect YouTube Data API daily Video Uploads quota (HTTP 429).""" raw = msg or "" low = raw.lower() if not low.strip(): return False if "quota_exceeded" in low or "配额已用尽" in raw: return True if "quota exceeded" in low and ("video upload" in low or "uploads per day" in low): return True if "429" in low and ("video upload" in low or "uploads per day" in low): return True if '"code": 429' in low or 'code": 429' in low: if "upload" in low or "video" in low: return True return False def quota_error_message(profile_id: str = "") -> str: pid = str(profile_id or "").strip().upper() tag = f"【Client {pid}】" if pid else "" return ( f"{tag}YouTube 接口返回:每日 Video Uploads 配额已用尽(429)。" "其他 Client(A/B/C/D)配额互不影响;" "太平洋时间 0 点后 YouTube 侧配额重置。本系统不拦截手动上传。" ) def _sanitize_yt_title(title: str) -> str: """YouTube rejects empty titles and angle brackets (invalidTitle).""" import re t = re.sub(r"[<>]+", " ", str(title or "")) t = re.sub(r"\s+", " ", t).strip() return (t or "Shorts")[:100] def _client_kwargs(*, timeout: float, proxy_url: str = "") -> dict[str, Any]: kw: dict[str, Any] = {"timeout": timeout, "trust_env": False} proxy = str(proxy_url or "").strip() if not proxy: try: from . import egress_hub proxy = egress_hub.google_http_proxy() except Exception: proxy = "" if proxy: kw["proxy"] = proxy return kw def _proxy_candidates(proxy_url: str = "") -> list[str]: try: from . import egress_hub return egress_hub.google_http_proxy_candidates(prefer=str(proxy_url or "").strip()) except Exception: p = str(proxy_url or "").strip() return [p] if p else [""] async def refresh_access_token( *, client_id: str, client_secret: str, refresh_token: str, proxy_url: str = "", ) -> str: if not (client_id and client_secret and refresh_token): raise ValueError("缺少 OAuth client_id / client_secret / refresh_token") last_transport = "" for proxy in _proxy_candidates(proxy_url): # Flaky residential: fail fast then fall back to VPS direct. attempt_timeout = 12.0 if proxy else 30.0 try: from . import egress_hub kw = egress_hub.httpx_kwargs_for_proxy(proxy, timeout=attempt_timeout) except Exception: kw = _client_kwargs(timeout=attempt_timeout, proxy_url=proxy) try: async with httpx.AsyncClient(**kw) as client: resp = await client.post( "https://oauth2.googleapis.com/token", data={ "client_id": client_id, "client_secret": client_secret, "refresh_token": refresh_token, "grant_type": "refresh_token", }, ) data = resp.json() if resp.content else {} if resp.status_code >= 400 or not data.get("access_token"): # Auth/config errors: do not fall through to another egress. raise ValueError( f"OAuth 刷新失败: {data.get('error_description') or data or resp.text}" ) return str(data["access_token"]) except ValueError: raise except Exception as exc: last_transport = f"{type(exc).__name__}: {exc}"[:240] continue raise ValueError(f"OAuth 刷新失败(出口不可用): {last_transport or 'unknown'}") async def upload_shorts_mp4( *, file_path: str, title: str, description: str = "", privacy: str = "public", client_id: str = "", client_secret: str = "", refresh_token: str = "", proxy_url: str = "", ) -> dict[str, Any]: path = Path(file_path) if not path.is_file(): raise ValueError("成片文件不存在,已重新排队录制") access = await refresh_access_token( client_id=client_id, client_secret=client_secret, refresh_token=refresh_token, proxy_url=proxy_url, ) try: size = path.stat().st_size raw = path.read_bytes() except FileNotFoundError as exc: raise ValueError("成片文件不存在,已重新排队录制") from exc meta = { "snippet": { "title": _sanitize_yt_title(title), "description": description or "", "categoryId": "22", }, "status": { "privacyStatus": privacy if privacy in {"public", "unlisted", "private"} else "public", "selfDeclaredMadeForKids": False, }, } init_url = ( "https://www.googleapis.com/upload/youtube/v3/videos" "?uploadType=resumable&part=snippet,status" ) async with httpx.AsyncClient(**_client_kwargs(timeout=180.0, proxy_url=proxy_url)) as client: init = await client.post( init_url, headers={ "Authorization": f"Bearer {access}", "Content-Type": "application/json; charset=UTF-8", "X-Upload-Content-Length": str(size), "X-Upload-Content-Type": "video/mp4", }, json=meta, ) upload_url = init.headers.get("location") or init.headers.get("Location") if init.status_code >= 400 or not upload_url: body = init.text[:800] if init.status_code == 429 or is_upload_quota_error(body): raise ValueError(f"QUOTA_EXCEEDED: {quota_error_message()} ({body[:200]})") raise ValueError(f"初始化上传失败: {body[:400]}") put = await client.put( upload_url, headers={ "Authorization": f"Bearer {access}", "Content-Type": "video/mp4", "Content-Length": str(size), }, content=raw, ) data = put.json() if put.content else {} if put.status_code >= 400 or not data.get("id"): err_text = str(data.get("error") or put.text[:800]) if put.status_code == 429 or is_upload_quota_error(err_text): raise ValueError(f"QUOTA_EXCEEDED: {quota_error_message()} ({err_text[:200]})") raise ValueError(f"上传失败: {err_text[:400]}") vid = str(data["id"]) return { "ok": True, "video_id": vid, "url": f"https://www.youtube.com/shorts/{vid}", "raw": data, }