douyinWEB/backend/app/shorts_upload.py
eric ba946d5a9a Fix dy.live API hang and sticky OAuth false failures.
Keep Shorts/yt_long/tiktok/x_clips SQLite off the asyncio thread, fall back past proxy Bad Request on token refresh, and avoid marking oauth_ok=0 for transient egress errors.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-02 06:01:19 -05:00

275 lines
9.6 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 _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 [""]
_HARD_OAUTH_ERRORS = frozenset(
{
"invalid_grant",
"unauthorized_client",
"invalid_client",
"access_denied",
"invalid_request",
}
)
def is_hard_oauth_refresh_failure(
*,
status_code: int = 0,
data: dict[str, Any] | None = None,
body_text: str = "",
) -> bool:
"""True only for Google auth/config rejects — not proxy HTML / transient 400s.
Residential egress often returns plain ``Bad Request``; treating that as
hard auth failure skipped direct fallback and stuck oauth_ok=0 forever.
"""
payload = data if isinstance(data, dict) else {}
err = str(payload.get("error") or "").strip().lower()
desc = str(payload.get("error_description") or "").strip().lower()
text = str(body_text or "").strip().lower()
if err in _HARD_OAUTH_ERRORS:
# Google's invalid_request is sometimes egress junk; require a real hint.
if err == "invalid_request" and not desc:
return False
return True
if any(k in desc for k in ("revoked", "expired or revoked", "invalid_grant", "deleted")):
return True
if any(k in text for k in ("invalid_grant", "unauthorized_client", "invalid_client")):
return True
# Opaque 4xx / HTML / bare "Bad Request" → soft (try next egress).
if status_code >= 500 or status_code in (0, 408, 425, 429):
return False
if not err and ("bad request" in text or "<html" in text or not payload):
return False
return False
def is_transient_oauth_error_message(msg: str) -> bool:
"""UI/probe: do not treat egress noise as permanent reauth-needed."""
raw = str(msg or "")
low = raw.lower()
if not low.strip():
return True
if "出口不可用" in raw or "出口不稳定" in raw:
return True
if "timeout" in low or "timed out" in low or "connect" in low:
return True
if "bad request" in low and "invalid_grant" not in low and "revoked" not in low:
return True
if "proxy" in low or "tunnel" in low:
return True
return False
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 = ""
last_hard = ""
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",
},
)
raw_text = resp.text if resp.content else ""
try:
data = resp.json() if resp.content else {}
except Exception:
data = {}
if not isinstance(data, dict):
data = {}
if resp.status_code < 400 and data.get("access_token"):
return str(data["access_token"])
detail = str(data.get("error_description") or data.get("error") or raw_text or resp.status_code)[
:240
]
if is_hard_oauth_refresh_failure(
status_code=int(resp.status_code or 0),
data=data,
body_text=raw_text,
):
last_hard = detail
raise ValueError(f"OAuth 刷新失败: {detail}")
# Soft/transient: try next egress (often direct after residential).
last_transport = f"http_{resp.status_code}:{detail}"[:240]
continue
except ValueError:
raise
except Exception as exc:
last_transport = f"{type(exc).__name__}: {exc}"[:240]
continue
if last_hard:
raise ValueError(f"OAuth 刷新失败: {last_hard}")
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,
}