# -*- coding: utf-8 -*- """YouTube long-form upload — same OAuth transport as Shorts, watch URL not /shorts/. Streams the mp4 via an *async* byte iterator (no full-file RAM load, compatible with httpx.AsyncClient). Size-aware timeout so 8–15 min masters do not hang. """ from __future__ import annotations import asyncio import re from collections.abc import AsyncIterator from pathlib import Path from typing import Any import httpx from .shorts_upload import ( _client_kwargs, is_upload_quota_error, quota_error_message, refresh_access_token, ) _CHUNK = 1024 * 1024 # 1 MiB def _sanitize_yt_text(text: str, *, limit: int) -> str: """YouTube rejects angle brackets in title/description (invalid metadata).""" t = re.sub(r"[<>]+", " ", str(text or "")) t = re.sub(r"\s+", " ", t).strip() return t[:limit] def _upload_timeout_sec(size_bytes: int) -> float: """Scale HTTP timeout with file size (min 10m, ~8s/MB, cap 45m).""" mb = max(1.0, float(size_bytes) / (1024.0 * 1024.0)) return float(min(2700.0, max(600.0, mb * 8.0 + 120.0))) async def _aiter_file_chunks(path: Path, *, chunk_size: int = _CHUNK) -> AsyncIterator[bytes]: """Yield file bytes without blocking the event loop (AsyncClient-safe).""" loop = asyncio.get_running_loop() fh = await loop.run_in_executor(None, path.open, "rb") try: while True: chunk = await loop.run_in_executor(None, fh.read, chunk_size) if not chunk: break yield chunk finally: await loop.run_in_executor(None, fh.close) async def upload_youtube_long_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 except FileNotFoundError as exc: raise ValueError("成片文件不存在") from exc if size <= 0: raise ValueError("成片文件为空") # No #Shorts — this is a normal YouTube watch video (9:16 vertical by default). clean_title = (title or "Live clip").replace("#Shorts", "").replace("#shorts", "").strip() clean_title = _sanitize_yt_text(clean_title, limit=100) or "Live clip" clean_desc = _sanitize_yt_text(description or "", limit=4900) meta = { "snippet": { "title": clean_title, "description": clean_desc, "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" ) timeout = _upload_timeout_sec(size) async with httpx.AsyncClient(**_client_kwargs(timeout=timeout, 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]})") if init.status_code in (401, 403): raise ValueError(f"OAUTH_INVALID: 初始化上传失败: {body[:400]}") raise ValueError(f"初始化上传失败: {body[:400]}") # AsyncClient rejects sync file objects ("Attempted to send an sync request…"). # Stream via async chunk iterator instead of path.open() / read_bytes(). put = await client.put( upload_url, headers={ "Authorization": f"Bearer {access}", "Content-Type": "video/mp4", "Content-Length": str(size), }, content=_aiter_file_chunks(path), ) 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]})") if put.status_code in (401, 403): raise ValueError(f"OAUTH_INVALID: 上传失败: {err_text[:400]}") raise ValueError(f"上传失败: {err_text[:400]}") vid = str(data["id"]) return { "ok": True, "video_id": vid, "url": f"https://www.youtube.com/watch?v={vid}", "raw": data, "bytes": size, "timeout_sec": timeout, }