# -*- coding: utf-8 -*- """YouTube long-form (16:9) upload — same OAuth transport as Shorts, watch URL not /shorts/.""" from __future__ import annotations 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, ) 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 raw = path.read_bytes() except FileNotFoundError as exc: raise ValueError("成片文件不存在") from exc # No #Shorts — this is a normal YouTube video (16:9). clean_title = (title or "Live clip").replace("#Shorts", "").replace("#shorts", "").strip()[:100] meta = { "snippet": { "title": clean_title or "Live clip", "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=600.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/watch?v={vid}", "raw": data, }