douyinWEB/backend/app/shorts_oauth.py
eric 11394a2a80 Document Pro relay/time-slot ops and harden relay worker stability.
README covers YouTube RTMPS relay, time-slot mode, ops/Netdata, and global SOCKS plan. Relay pipeline keeps FFmpeg alive across probe flicker, stabilizes time-slot source selection, and fixes misleading start-button copy in the UI.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 10:53:29 -05:00

597 lines
24 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 OAuth for Shorts — click-to-authorize, stores refresh_token on channel.
OAuth Client resolution order:
1. Named profile A/B/C/D from settings.shorts_oauth_profiles (channel.oauth_profile_id)
2. Legacy per-channel client_id/client_secret on the row
3. Global shorts_oauth_client_id / shorts_oauth_client_secret
"""
from __future__ import annotations
import secrets
import time
from typing import Any
from urllib.parse import urlencode
import httpx
from . import db
# Required for upload / YPP — used by missing_required_scopes / oauth_ok.
YOUTUBE_SCOPES = " ".join(
[
# Upload + Studio monetize (force-ssl).
# Avoid youtubepartner / yt-analytics — they often break
# unverified OAuth consent (Google 500 / access_denied).
"https://www.googleapis.com/auth/youtube.upload",
"https://www.googleapis.com/auth/youtube.readonly",
"https://www.googleapis.com/auth/youtube.force-ssl",
]
)
# Requested on authorize so we can show Gmail on A/B/C/D; not required for oauth_ok.
IDENTITY_SCOPES = "openid email profile"
DEFAULT_OAUTH_PROFILES: list[dict[str, str]] = [
{"id": "A", "label": "谷歌账号 A", "client_id": "", "client_secret": "", "email": ""},
{"id": "B", "label": "谷歌账号 B", "client_id": "", "client_secret": "", "email": ""},
{"id": "C", "label": "谷歌账号 C", "client_id": "", "client_secret": "", "email": ""},
{"id": "D", "label": "谷歌账号 D", "client_id": "", "client_secret": "", "email": ""},
]
# state -> (channel_pk, expires_at, client_id, client_secret, return_to?)
_oauth_states: dict[str, tuple[str, float, str, str] | tuple[str, float, str, str, str]] = {}
def _cfg() -> dict[str, Any]:
return db.get_settings_map()
def _mask_secret(secret: str) -> str:
s = str(secret or "")
if not s:
return ""
return ("***" + s[-4:]) if len(s) > 4 else "***"
def normalize_oauth_profiles(raw: Any) -> list[dict[str, str]]:
"""Return A/B/C/D profiles; fill missing slots from defaults."""
by_id: dict[str, dict[str, str]] = {}
if isinstance(raw, list):
for item in raw:
if not isinstance(item, dict):
continue
pid = str(item.get("id") or "").strip().upper()
if not pid:
continue
by_id[pid] = {
"id": pid,
"label": str(item.get("label") or f"谷歌账号 {pid}").strip() or f"谷歌账号 {pid}",
"client_id": str(item.get("client_id") or "").strip(),
"client_secret": str(item.get("client_secret") or "").strip(),
"email": str(item.get("email") or "").strip(),
}
out: list[dict[str, str]] = []
for d in DEFAULT_OAUTH_PROFILES:
pid = d["id"]
if pid in by_id:
out.append(by_id[pid])
else:
out.append(dict(d))
for pid, row in by_id.items():
if pid not in {"A", "B", "C", "D"}:
out.append(row)
return out
def list_oauth_profiles(cfg: dict[str, Any] | None = None, *, public: bool = False) -> list[dict[str, Any]]:
settings = cfg or _cfg()
rows = normalize_oauth_profiles(settings.get("shorts_oauth_profiles"))
# Legacy: if profile A empty, mirror global client into A for display/resolve convenience
g_id = str(settings.get("shorts_oauth_client_id") or "").strip()
g_secret = str(settings.get("shorts_oauth_client_secret") or "").strip()
if g_id and g_secret:
for i, row in enumerate(rows):
if row["id"] == "A" and not (row["client_id"] and row["client_secret"]):
mirrored = dict(row)
mirrored["client_id"] = g_id
mirrored["client_secret"] = g_secret
rows[i] = mirrored
break
if not public:
return rows
pub: list[dict[str, Any]] = []
for row in rows:
secret = row.get("client_secret") or ""
pub.append(
{
"id": row["id"],
"label": row["label"],
"email": str(row.get("email") or "").strip(),
"client_id": row.get("client_id") or "",
"has_client_secret": bool(str(secret).strip()),
"client_secret": _mask_secret(str(secret)),
"configured": bool(str(row.get("client_id") or "").strip() and str(secret).strip()),
}
)
return pub
def get_oauth_profile(profile_id: str, cfg: dict[str, Any] | None = None) -> dict[str, str] | None:
pid = str(profile_id or "").strip().upper()
if not pid:
return None
for row in list_oauth_profiles(cfg, public=False):
if row["id"] == pid:
return row # type: ignore[return-value]
return None
def merge_oauth_profiles_patch(incoming: Any, existing_cfg: dict[str, Any] | None = None) -> list[dict[str, str]]:
"""Merge UI patch into stored profiles; empty/*** secrets keep previous."""
settings = existing_cfg or _cfg()
prev = {r["id"]: r for r in normalize_oauth_profiles(settings.get("shorts_oauth_profiles"))}
g_id = str(settings.get("shorts_oauth_client_id") or "").strip()
g_secret = str(settings.get("shorts_oauth_client_secret") or "").strip()
merged = normalize_oauth_profiles(incoming if isinstance(incoming, list) else [])
out: list[dict[str, str]] = []
for row in merged:
pid = row["id"]
old = prev.get(pid) or {}
secret = str(row.get("client_secret") or "").strip()
if (not secret) or secret.startswith("***"):
secret = str(old.get("client_secret") or "").strip()
if not secret and pid == "A":
secret = g_secret
client_id = str(row.get("client_id") or "").strip()
if not client_id:
client_id = str(old.get("client_id") or "").strip()
if not client_id and pid == "A":
client_id = g_id
email = str(row.get("email") or "").strip() or str(old.get("email") or "").strip()
out.append(
{
"id": pid,
"label": str(row.get("label") or old.get("label") or f"谷歌账号 {pid}").strip(),
"client_id": client_id,
"client_secret": secret,
"email": email,
}
)
return out
def set_oauth_profile_email(profile_id: str, email: str) -> None:
"""Persist Gmail onto shorts_oauth_profiles[profile_id]."""
pid = str(profile_id or "").strip().upper()
mail = str(email or "").strip()
if not pid or not mail:
return
cfg = _cfg()
rows = normalize_oauth_profiles(cfg.get("shorts_oauth_profiles"))
changed = False
out: list[dict[str, str]] = []
for row in rows:
r = dict(row)
if r.get("id") == pid:
if str(r.get("email") or "").strip() != mail:
r["email"] = mail
changed = True
out.append(r)
if changed:
db.update_settings_map({"shorts_oauth_profiles": out})
async def fetch_google_account_email(access_token: str) -> str:
"""Best-effort Gmail from OpenID userinfo (needs email scope)."""
token = str(access_token or "").strip()
if not token:
return ""
try:
async with httpx.AsyncClient(timeout=20.0, trust_env=False) as client:
resp = await client.get(
"https://openidconnect.googleapis.com/v1/userinfo",
headers={"Authorization": f"Bearer {token}"},
)
if resp.status_code >= 400:
resp = await client.get(
"https://www.googleapis.com/oauth2/v2/userinfo",
headers={"Authorization": f"Bearer {token}"},
)
data = resp.json() if resp.content else {}
if resp.status_code >= 400:
return ""
return str(data.get("email") or "").strip()
except Exception:
return ""
def oauth_client_configured() -> bool:
cfg = _cfg()
if str(cfg.get("shorts_oauth_client_id") or "").strip() and str(cfg.get("shorts_oauth_client_secret") or "").strip():
return True
for row in list_oauth_profiles(cfg, public=False):
if row.get("client_id") and row.get("client_secret"):
return True
return False
def resolve_redirect_uri(request_base: str = "") -> str:
"""OAuth callback must match the origin that started the flow.
Priority: request Host (dy.nomadro.live / …) → DY_PUBLIC_BASE_URL → settings fallback.
Never pin a stale hardcoded domain.
"""
from .config import settings as app_settings
req = str(request_base or "").strip().rstrip("/")
pub = str(getattr(app_settings, "public_base_url", "") or "").strip().rstrip("/")
base = req or pub
if base:
return f"{base}/api/shorts/oauth/callback"
custom = str(_cfg().get("shorts_oauth_redirect_uri") or "").strip().rstrip("/")
if custom:
return custom
raise ValueError("无法推导 OAuth 回调地址:请用站点域名打开,或设置 DY_PUBLIC_BASE_URL")
def resolve_oauth_client(
channel: dict[str, Any] | None = None,
cfg: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Resolve Client for authorize/upload.
Returns:
client_id, client_secret, source ("profile"|"channel"|"global"|"none"), profile_id
"""
settings = cfg or _cfg()
ch = channel or {}
profile_id = str(ch.get("oauth_profile_id") or "").strip().upper()
if profile_id:
prof = get_oauth_profile(profile_id, settings)
if prof and prof.get("client_id") and prof.get("client_secret"):
return {
"client_id": prof["client_id"],
"client_secret": prof["client_secret"],
"source": "profile",
"profile_id": profile_id,
}
ch_id = str(ch.get("client_id") or "").strip()
ch_secret = str(ch.get("client_secret") or "").strip()
if ch_id and ch_secret:
return {
"client_id": ch_id,
"client_secret": ch_secret,
"source": "channel",
"profile_id": profile_id,
}
g_id = str(settings.get("shorts_oauth_client_id") or "").strip()
g_secret = str(settings.get("shorts_oauth_client_secret") or "").strip()
if g_id and g_secret:
return {"client_id": g_id, "client_secret": g_secret, "source": "global", "profile_id": profile_id}
return {"client_id": "", "client_secret": "", "source": "none", "profile_id": profile_id}
def channel_can_authorize(channel: dict[str, Any] | None, cfg: dict[str, Any] | None = None) -> bool:
return resolve_oauth_client(channel, cfg).get("source") != "none"
def build_authorize_url(*, channel_pk: str, request_base: str = "", return_to: str = "") -> str:
cfg = _cfg()
channel = db.get_shorts_channel(channel_pk)
if not channel:
raise ValueError("频道不存在")
client = resolve_oauth_client(channel, cfg)
client_id = str(client.get("client_id") or "")
client_secret = str(client.get("client_secret") or "")
if not client_id or not client_secret:
raise ValueError(
"请先在「设置 → OAuth 配置档」填写对应 A/B/C/D 的 Client,并在频道选择该配置档"
)
ret = str(return_to or "").strip()
if ret and (not ret.startswith("/") or ret.startswith("//")):
ret = ""
now = time.time()
for k, packed in list(_oauth_states.items()):
if len(packed) < 2 or packed[1] < now:
_oauth_states.pop(k, None)
state = secrets.token_urlsafe(24)
if ret:
_oauth_states[state] = (channel_pk, now + 600, client_id, client_secret, ret)
else:
_oauth_states[state] = (channel_pk, now + 600, client_id, client_secret)
params = {
"client_id": client_id,
"redirect_uri": resolve_redirect_uri(request_base),
"response_type": "code",
"scope": authorize_scopes(),
"access_type": "offline",
"prompt": "consent select_account",
"include_granted_scopes": "true",
"state": state,
}
return "https://accounts.google.com/o/oauth2/v2/auth?" + urlencode(params)
def requested_scopes() -> list[str]:
"""YouTube scopes required for oauth_ok (identity scopes are optional extras)."""
return [s for s in YOUTUBE_SCOPES.split() if s]
def authorize_scopes() -> str:
"""Scopes for Google consent. YouTube only — brand accounts break with openid/email."""
return " ".join(s for s in YOUTUBE_SCOPES.split() if s)
FORCE_SSL_SCOPE = "https://www.googleapis.com/auth/youtube.force-ssl"
async def token_scopes(access_token: str) -> set[str]:
"""Granted scopes on an access token (tokeninfo)."""
if not access_token:
return set()
try:
async with httpx.AsyncClient(timeout=20.0, trust_env=False) as client:
resp = await client.get(
"https://oauth2.googleapis.com/tokeninfo",
params={"access_token": access_token},
)
data = resp.json() if resp.content else {}
raw = str(data.get("scope") or "")
return {s for s in raw.split() if s.strip()}
except Exception:
return set()
def missing_required_scopes(granted: set[str]) -> list[str]:
need = set(requested_scopes())
return sorted(s for s in need if s not in granted)
async def revoke_refresh_token(*, refresh_token: str, client_id: str = "", client_secret: str = "") -> bool:
"""Revoke old refresh token so re-auth must issue a new one with full scopes."""
rt = str(refresh_token or "").strip()
if not rt:
return False
try:
async with httpx.AsyncClient(timeout=20.0, trust_env=False) as client:
resp = await client.post(
"https://oauth2.googleapis.com/revoke",
data={"token": rt},
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
return resp.status_code in (200, 400)
except Exception:
return False
async def prepare_reauthorize(channel_pk: str) -> None:
"""Soft-mark OAuth start on the clicked card — never revoke sibling brands."""
ch = db.get_shorts_channel(channel_pk) or {}
if not ch:
return
db.update_shorts_channel(
channel_pk,
oauth_checked_at=time.time(),
oauth_error="授权中:完成 Google 后凭证写入本卡片",
)
async def exchange_code(*, code: str, state: str, request_base: str = "") -> dict[str, Any]:
packed = _oauth_states.pop(state, None)
if not packed:
raise ValueError("授权 state 无效或已过期,请重新点击授权")
# Always bind OAuth result to the card the operator clicked.
channel_pk = packed[0]
exp = packed[1]
return_to = str(packed[4]).strip() if len(packed) >= 5 else ""
if return_to and (not return_to.startswith("/") or return_to.startswith("//")):
return_to = ""
if exp < time.time():
raise ValueError("授权已过期,请重新点击授权")
cfg = _cfg()
channel = db.get_shorts_channel(channel_pk) or {}
if len(packed) >= 4 and packed[2] and packed[3]:
client_id, client_secret = packed[2], packed[3]
else:
client = resolve_oauth_client(channel, cfg)
client_id = str(client.get("client_id") or "")
client_secret = str(client.get("client_secret") or "")
source_meta = resolve_oauth_client(channel, cfg)
source = str(source_meta.get("source") or "none")
profile_id = str(source_meta.get("profile_id") or channel.get("oauth_profile_id") or "").strip().upper()
if not client_id or not client_secret:
raise ValueError("缺少 OAuth Client 配置")
redirect_uri = resolve_redirect_uri(request_base)
async with httpx.AsyncClient(timeout=30.0, trust_env=False) as client:
token_resp = await client.post(
"https://oauth2.googleapis.com/token",
data={
"code": code,
"client_id": client_id,
"client_secret": client_secret,
"redirect_uri": redirect_uri,
"grant_type": "authorization_code",
},
)
token = token_resp.json() if token_resp.content else {}
if token_resp.status_code >= 400 or not token.get("access_token"):
raise ValueError(f"换取 token 失败: {token.get('error_description') or token or token_resp.text}")
access = str(token["access_token"])
refresh = str(token.get("refresh_token") or "").strip()
granted = await token_scopes(access)
missing = missing_required_scopes(granted)
if missing:
scope_hint = "、".join(s.rsplit("/", 1)[-1] for s in missing)
raise ValueError(
f"授权权限不完整(缺 {scope_hint})。"
f"请再点「重授权」;若仍失败,到 Google 账号 → 第三方应用访问权限,移除本应用后再授权。"
)
ch_resp = await client.get(
"https://www.googleapis.com/youtube/v3/channels",
params={"part": "snippet,contentDetails", "mine": "true"},
headers={"Authorization": f"Bearer {access}"},
)
ch_data = ch_resp.json() if ch_resp.content else {}
if ch_resp.status_code >= 400:
err = (ch_data.get("error") or {}).get("message") or ch_resp.text
if "has not been used in project" in str(err) or "youtube.googleapis.com" in str(err):
raise ValueError(
f"OAuth 配置档 {profile_id or '?'} 的 Google 项目未启用 YouTube Data API v3。"
"请到 Google Cloud Console → API 和服务 → 启用「YouTube Data API v3」后,再点「重授权」。"
)
raise ValueError(f"读取 YouTube 频道失败: {err}")
items = ch_data.get("items") or []
yt_id = ""
yt_title = ""
yt_handle = ""
if items:
sn = items[0].get("snippet") or {}
yt_id = str(items[0].get("id") or "")
yt_title = str(sn.get("title") or "")
yt_handle = str(sn.get("customUrl") or "").strip()
google_email = await fetch_google_account_email(access)
# Clicked card wins: accept whatever brand Google returned; never reject / never rewrite siblings.
had_old = bool(str(channel.get("refresh_token") or "").strip())
if not refresh:
if had_old:
refresh = str(channel.get("refresh_token") or "").strip()
else:
raise ValueError("未拿到 refresh_token,请在 Google 账号权限里撤销本应用后重试")
patch: dict[str, Any] = {
"client_id": client_id,
"client_secret": client_secret,
"refresh_token": refresh,
}
if yt_id:
patch["youtube_channel_id"] = yt_id
if google_email:
patch["oauth_email"] = google_email
# Refresh display name/handle from Google — brand label may differ from old card title.
if yt_title:
patch["name"] = yt_title
if profile_id and not str(channel.get("oauth_profile_id") or "").strip():
patch["oauth_profile_id"] = profile_id
updated = db.update_shorts_channel(
channel_pk,
**patch,
oauth_ok=1,
oauth_checked_at=time.time(),
oauth_error="",
)
if google_email and profile_id:
try:
set_oauth_profile_email(profile_id, google_email)
except Exception:
pass
try:
from . import yt_long_db
yt_long_db.sync_channels_from_shorts()
except Exception:
pass
try:
from . import youtube_manage as ytm
from .yt_long_monetize import refresh_ypp_for_shorts_channel
await ytm.fetch_channel_profile(channel_pk)
await refresh_ypp_for_shorts_channel(channel_pk)
except Exception as exc:
err = str(exc).strip() or "拉取频道资料失败"
db.update_shorts_channel(channel_pk, oauth_error=err)
return {
"ok": True,
"channel": updated,
"youtube_channel_id": yt_id,
"youtube_title": yt_title or str((updated or {}).get("name") or ""),
"youtube_handle": yt_handle,
"oauth_email": google_email,
"oauth_scopes_ok": True,
"oauth_client_source": source,
"oauth_profile_id": profile_id,
"return_to": return_to,
}
def channel_oauth_creds(channel: dict[str, Any], cfg: dict[str, Any] | None = None) -> dict[str, str]:
"""Resolve upload credentials: profile/channel/global client + channel refresh_token."""
client = resolve_oauth_client(channel, cfg)
return {
"client_id": str(client.get("client_id") or ""),
"client_secret": str(client.get("client_secret") or ""),
"refresh_token": str(channel.get("refresh_token") or "").strip(),
}
async def probe_channel_oauth(channel: dict[str, Any], cfg: dict[str, Any] | None = None) -> dict[str, Any]:
"""Try refresh_token once; persist oauth_ok / oauth_error on the channel."""
from .shorts_upload import refresh_access_token
creds = channel_oauth_creds(channel, cfg)
cid = str(channel.get("id") or "")
now = time.time()
if not cid:
return {"ok": False, "error": "频道 ID 缺失"}
if not (creds["refresh_token"] and creds["client_id"] and creds["client_secret"]):
db.update_shorts_channel(
cid,
oauth_ok=0,
oauth_checked_at=now,
oauth_error="未授权或缺少 OAuth 凭证",
)
return {"ok": False, "error": "未授权或缺少 OAuth 凭证", "channel_id": cid}
try:
access = await refresh_access_token(
client_id=creds["client_id"],
client_secret=creds["client_secret"],
refresh_token=creds["refresh_token"],
)
missing = missing_required_scopes(await token_scopes(str(access)))
if missing:
err = "OAuth 权限不足(缺 force-ssl),请点「重授权」升级 YPP 获利权限"
db.update_shorts_channel(cid, oauth_ok=0, oauth_checked_at=now, oauth_error=err)
return {"ok": False, "error": err, "channel_id": cid, "missing_scopes": missing}
google_email = await fetch_google_account_email(str(access))
patch: dict[str, Any] = {"oauth_ok": 1, "oauth_checked_at": now, "oauth_error": ""}
if google_email:
patch["oauth_email"] = google_email
pid = str(channel.get("oauth_profile_id") or "").strip().upper()
if pid:
try:
set_oauth_profile_email(pid, google_email)
except Exception:
pass
db.update_shorts_channel(cid, **patch)
return {"ok": True, "channel_id": cid, "oauth_email": google_email}
except Exception as exc:
err = str(exc)[:240]
db.update_shorts_channel(cid, oauth_ok=0, oauth_checked_at=now, oauth_error=err)
return {"ok": False, "error": err, "channel_id": cid}
async def probe_all_enabled_channels(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
settings = cfg or _cfg()
rows = db.list_shorts_channels(enabled=True)
results = []
bad = 0
for ch in rows:
if not str(ch.get("refresh_token") or "").strip():
r = await probe_channel_oauth(ch, settings)
results.append(r)
if not r.get("ok"):
bad += 1
continue
checked = float(ch.get("oauth_checked_at") or 0)
ok_flag = int(ch.get("oauth_ok") if ch.get("oauth_ok") is not None else -1)
if ok_flag == 1 and checked and (time.time() - checked) < 1800:
results.append({"ok": True, "channel_id": ch.get("id"), "skipped": True})
continue
r = await probe_channel_oauth(ch, settings)
results.append(r)
if not r.get("ok"):
bad += 1
return {"checked": len(results), "failed": bad, "results": results}