douyinWEB/backend/app/shorts_upload.py
eric 01c6bf4507 Shorts: SOCKS 代理、OAuth Client 分桶配额、频道级联清理;更新 README
取消本地上传拦截,按 A/B/C/D Client 独立展示配额;新增 SOCKS5 上传代理与删频道级联清理;同步文档与部署脚本。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-14 09:58:04 -05:00

151 lines
5.3 KiB
Python
Raw 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.

# -*- 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 _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 proxy:
kw["proxy"] = proxy
return kw
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")
async with httpx.AsyncClient(**_client_kwargs(timeout=30.0, proxy_url=proxy_url)) 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 = "",
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": (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(**_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,
}