# -*- 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() -> str: return ( "YouTube 每日 Video Uploads 配额已用尽(429)。" "上传已自动暂停,待太平洋时间 0 点配额重置后会继续。" ) async def refresh_access_token(*, client_id: str, client_secret: str, refresh_token: str) -> str: if not (client_id and client_secret and refresh_token): raise ValueError("缺少 OAuth client_id / client_secret / refresh_token") async with httpx.AsyncClient(timeout=30.0, trust_env=False) 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"): raise ValueError(f"OAuth 刷新失败: {data.get('error_description') or data or resp.text}") return str(data["access_token"]) async def upload_shorts_mp4( *, file_path: str, title: str, description: str = "", privacy: str = "public", client_id: str = "", client_secret: str = "", refresh_token: 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 ) try: size = path.stat().st_size raw = path.read_bytes() except FileNotFoundError as exc: raise ValueError("成片文件不存在,已重新排队录制") from exc meta = { "snippet": { "title": (title or "Shorts")[:100], "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(timeout=180.0, trust_env=False) 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, }