douyinWEB/backend/app/shorts_upload.py
eric 47d17aee3c Document YouTube groups and Shorts side-path; sync dual-platform pipeline.
Add isolated Shorts OAuth/clip/upload worker (default off), youtube-svc + group poller, Beijing time UX, and SHORTS.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-10 00:04:06 -05:00

96 lines
3.3 KiB
Python

# -*- 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
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
)
size = path.stat().st_size
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=120.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:
raise ValueError(f"初始化上传失败: {init.text[:400]}")
raw = path.read_bytes()
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"):
raise ValueError(f"上传失败: {data.get('error') or put.text[:400]}")
vid = str(data["id"])
return {
"ok": True,
"video_id": vid,
"url": f"https://www.youtube.com/shorts/{vid}",
"raw": data,
}