douyinWEB/backend/app/shorts_oauth.py
hackrobot 1e8eb0130a Sync dylive production working tree to test3.
Include latest server fixes for yt-long/disk/ops and related frontend.
Exclude .bak scratch files.
2026-10-14 07:04:18 +00:00

1065 lines
42 KiB
Python
Raw Permalink 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",
]
)
# Opt-in only (收益 tab / reauth). Not required for oauth_ok.
YT_MONETARY_SCOPES = " ".join(
[
"https://www.googleapis.com/auth/yt-analytics.readonly",
"https://www.googleapis.com/auth/yt-analytics-monetary.readonly",
]
)
# 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]] = {}
_OAUTH_STATE_KEY = "shorts_oauth_pending_states"
_OAUTH_STATE_TTL_SEC = 1800.0 # 30min — Google consent + brand pick can be slow
def _persist_oauth_states() -> None:
"""Survive API restarts between Google consent and callback."""
now = time.time()
# Merge with DB so another worker's pending states are not wiped.
try:
db._invalidate_settings_cache()
except Exception:
pass
try:
raw = (_cfg() or {}).get(_OAUTH_STATE_KEY) or {}
except Exception:
raw = {}
merged: dict[str, list[Any]] = {}
if isinstance(raw, dict):
for k, packed in raw.items():
if not isinstance(packed, (list, tuple)) or len(packed) < 4:
continue
try:
exp = float(packed[1])
except Exception:
continue
if exp < now:
continue
merged[str(k)] = list(packed)
for k, packed in list(_oauth_states.items()):
if len(packed) < 2 or float(packed[1]) < now:
_oauth_states.pop(k, None)
continue
merged[str(k)] = list(packed)
_oauth_states[str(k)] = packed
try:
db.update_settings_map({_OAUTH_STATE_KEY: merged})
except Exception:
pass
def _hydrate_oauth_states(*, force: bool = False) -> None:
"""Load pending states from DB. Always merge — never skip when memory is non-empty."""
try:
if force:
db._invalidate_settings_cache()
except Exception:
pass
try:
raw = (_cfg() or {}).get(_OAUTH_STATE_KEY) or {}
except Exception:
raw = {}
if not isinstance(raw, dict):
return
now = time.time()
for k, packed in raw.items():
if not isinstance(packed, (list, tuple)) or len(packed) < 4:
continue
try:
exp = float(packed[1])
except Exception:
continue
if exp < now:
continue
key = str(k)
if (not force) and key in _oauth_states:
continue
if len(packed) >= 5:
_oauth_states[key] = (
str(packed[0]),
exp,
str(packed[2]),
str(packed[3]),
str(packed[4] or ""),
)
else:
_oauth_states[key] = (str(packed[0]), exp, str(packed[2]), str(packed[3]))
def _pop_oauth_state(state: str) -> tuple | None:
"""Pop state from memory+DB (force hydrate first — fixes multi-worker / restart)."""
st = str(state or "").strip()
if not st:
return None
_hydrate_oauth_states(force=True)
packed = _oauth_states.pop(st, None)
if packed is None:
# One more direct DB peek in case cache raced
try:
db._invalidate_settings_cache()
raw = (_cfg() or {}).get(_OAUTH_STATE_KEY) or {}
if isinstance(raw, dict) and st in raw:
row = raw.get(st)
if isinstance(row, (list, tuple)) and len(row) >= 4:
packed = tuple(row[:5] if len(row) >= 5 else row[:4]) # type: ignore[assignment]
except Exception:
packed = None
_persist_oauth_states()
return packed # type: ignore[return-value]
def _stamp_oauth_error(channel_pk: str, err: str) -> None:
pk = str(channel_pk or "").strip()
if not pk:
return
try:
db.update_shorts_channel(
pk,
oauth_ok=0,
oauth_checked_at=time.time(),
oauth_error=str(err or "授权失败")[:500],
)
except Exception:
pass
def _oauth_log(msg: str) -> None:
try:
with open("/tmp/shorts_oauth.log", "a", encoding="utf-8") as f:
f.write(f"{time.strftime('%F %T')} {msg}\n")
except Exception:
pass
def _google_http_proxy() -> str:
"""Google API egress proxy.
- Prefer egress_hub (China physical / ShellCrash).
- Else use local clash :7890 only if it accepts connections.
- Else direct (overseas VPS / ytshort). Never force a dead 7890.
"""
try:
from . import egress_hub
p = str(egress_hub.google_http_proxy() or "").strip()
if p:
return p
except Exception:
pass
try:
import socket
s = socket.create_connection(("127.0.0.1", 7890), timeout=0.2)
s.close()
return "http://127.0.0.1:7890"
except Exception:
return ""
def _google_client_kwargs(*, timeout: float = 45.0) -> dict[str, Any]:
try:
from . import egress_hub
return egress_hub.google_httpx_kwargs(timeout=timeout)
except Exception:
proxy = _google_http_proxy()
kw: dict[str, Any] = {"timeout": timeout, "trust_env": False}
if proxy:
kw["proxy"] = proxy
return kw
def _find_shorts_by_youtube_id(yt_id: str) -> dict[str, Any] | None:
yt = str(yt_id or "").strip()
if not yt:
return None
for ch in db.list_shorts_channels(enabled=None) or []:
if str(ch.get("youtube_channel_id") or "").strip() == yt:
return ch
return None
def _dedupe_shorts_channel_by_youtube_id(prefer_pk: str, yt_id: str) -> str:
"""Warn-only: never delete cards during/after OAuth (operator data loss)."""
yt_id = str(yt_id or "").strip()
prefer_pk = str(prefer_pk or "").strip()
if not yt_id:
return ""
rows = [
ch
for ch in (db.list_shorts_channels(enabled=None) or [])
if str(ch.get("youtube_channel_id") or "").strip() == yt_id
]
if len(rows) < 2:
return ""
others = [str(r.get("name") or r.get("id") or "") for r in rows if str(r.get("id") or "") != prefer_pk]
if not others:
return ""
return (
f"注意:YouTube 频道 {yt_id} 仍挂在多张卡上({', '.join(others[:3])})。"
"未自动删除任何卡片,请手动删掉重复卡。"
)
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(**_google_client_kwargs(timeout=20.0)) 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 = "",
include_monetary: bool = False,
) -> str:
_hydrate_oauth_states()
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()
# Drop expired + older pending states for this same card (double-click / React remount).
for k, packed in list(_oauth_states.items()):
if len(packed) < 2 or packed[1] < now:
_oauth_states.pop(k, None)
continue
if str(packed[0]) == str(channel_pk):
_oauth_states.pop(k, None)
state = secrets.token_urlsafe(24)
exp = now + _OAUTH_STATE_TTL_SEC
if ret:
_oauth_states[state] = (channel_pk, exp, client_id, client_secret, ret)
else:
_oauth_states[state] = (channel_pk, exp, client_id, client_secret)
_persist_oauth_states()
_oauth_log(f"authorize_start pk={channel_pk} state={state[:10]} exp={int(exp)}")
scope = authorize_scopes(include_monetary=bool(include_monetary))
params = {
"client_id": client_id,
"redirect_uri": resolve_redirect_uri(request_base),
"response_type": "code",
"scope": scope,
"access_type": "offline",
# Must force consent to obtain refresh_token. Do NOT set include_granted_scopes —
# Google often omits refresh_token when the app "already has some access".
"prompt": "consent select_account",
"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 monetary_scopes() -> list[str]:
return [s for s in YT_MONETARY_SCOPES.split() if s]
def authorize_scopes(*, include_monetary: bool = False) -> str:
"""Scopes for Google consent. YouTube only — brand accounts break with openid/email."""
scopes = [s for s in YOUTUBE_SCOPES.split() if s]
if include_monetary:
for s in monetary_scopes():
if s not in scopes:
scopes.append(s)
return " ".join(scopes)
FORCE_SSL_SCOPE = "https://www.googleapis.com/auth/youtube.force-ssl"
async def token_scopes(access_token: str) -> set[str] | None:
"""Granted scopes on an access token (tokeninfo).
Returns None when egress/network failed — callers must NOT treat that as
「缺 force-ssl」(empty set used to false-flag OAuth 异常).
"""
if not access_token:
return set()
last_err = ""
try:
from . import egress_hub
proxies = egress_hub.google_http_proxy_candidates()
except Exception:
proxies = [str((_google_http_proxy() or "")).strip()]
if "" not in proxies:
proxies.append("")
for proxy in proxies:
try:
try:
from . import egress_hub
kw = egress_hub.httpx_kwargs_for_proxy(proxy, timeout=10.0 if proxy else 20.0)
except Exception:
kw = _google_client_kwargs(timeout=10.0 if proxy else 20.0)
if proxy:
kw = {**kw, "proxy": proxy}
elif "proxy" in kw:
kw = {k: v for k, v in kw.items() if k != "proxy"}
async with httpx.AsyncClient(**kw) 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 as exc:
last_err = f"{type(exc).__name__}: {exc}"[:160]
continue
_oauth_log(f"token_scopes_fail {last_err}")
return None
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(**_google_client_kwargs(timeout=20.0)) 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:
"""Mark OAuth start time only — do not stamp oauth_error (that looks like a failure)."""
ch = db.get_shorts_channel(channel_pk) or {}
if not ch:
return
# Keep existing oauth_ok / oauth_error so the board does not flash「OAuth 异常」
# while the operator is mid-consent on Google.
db.update_shorts_channel(channel_pk, oauth_checked_at=time.time())
async def exchange_code(*, code: str, state: str, request_base: str = "") -> dict[str, Any]:
packed = _pop_oauth_state(state)
if not packed:
_oauth_log(f"state_miss state={state[:12]} mem={len(_oauth_states)}")
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 float(exp) < time.time():
_stamp_oauth_error(channel_pk, "授权已过期,请重新点击授权")
raise ValueError("授权已过期,请重新点击授权")
cfg = _cfg()
channel = db.get_shorts_channel(channel_pk) or {}
if not channel:
raise ValueError("授权对应的频道已被删除,请新建频道后再授权")
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:
err = "缺少 OAuth Client 配置"
_stamp_oauth_error(channel_pk, err)
raise ValueError(err)
redirect_uri = resolve_redirect_uri(request_base)
proxy = _google_http_proxy()
_oauth_log(
f"exchange pk={channel_pk} redirect={redirect_uri} "
f"secret_tail={client_secret[-4:]} proxy={proxy or 'direct'}"
)
yt_id = ""
yt_title = ""
yt_handle = ""
google_email = ""
access = ""
refresh = ""
expected_uc = str(channel.get("youtube_channel_id") or "").strip()
expected_name = str(channel.get("name") or "").strip()
mismatch_warn = ""
dup_warn = ""
try:
async with httpx.AsyncClient(**_google_client_kwargs(timeout=60.0)) 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"):
err = f"换取 token 失败: {token.get('error_description') or token.get('error') or token or token_resp.text}"
_oauth_log(err)
_stamp_oauth_error(channel_pk, err)
raise ValueError(err)
access = str(token["access_token"])
refresh = str(token.get("refresh_token") or "").strip()
_oauth_log(
f"token_ok has_refresh={bool(refresh)} keys={sorted(token.keys())} "
f"scope={token.get('scope') or ''}"
)
granted = await token_scopes(access)
missing = missing_required_scopes(granted)
if missing:
scope_hint = "、".join(s.rsplit("/", 1)[-1] for s in missing)
err = (
f"授权权限不完整(缺 {scope_hint})。"
f"请到 https://myaccount.google.com/connections 移除 dylive 后再授权。"
)
_stamp_oauth_error(channel_pk, err)
raise ValueError(err)
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_msg = (ch_data.get("error") or {}).get("message") or ch_resp.text
if "has not been used in project" in str(err_msg) or "youtube.googleapis.com" in str(err_msg):
err = (
f"OAuth 配置档 {profile_id or '?'} 的 Google 项目未启用 YouTube Data API v3。"
"请到 Google Cloud Console → API 和服务 → 启用「YouTube Data API v3」后,再点「重授权」。"
)
else:
err = f"读取 YouTube 频道失败: {err_msg}"
_stamp_oauth_error(channel_pk, err)
raise ValueError(err)
items = ch_data.get("items") or []
# Card name ≠ brand title. Prefer UC match in token list; else authorized brand (items[0]).
expected_uc = str(channel.get("youtube_channel_id") or "").strip()
expected_name = str(channel.get("name") or "").strip()
chosen: dict[str, Any] | None = None
if expected_uc and isinstance(items, list):
for it in items:
if not isinstance(it, dict):
continue
if str(it.get("id") or "").strip() == expected_uc:
chosen = it
break
if chosen is None and items and isinstance(items[0], dict):
chosen = items[0]
yt_id = ""
yt_title = ""
yt_handle = ""
if chosen:
sn = chosen.get("snippet") or {}
yt_id = str(chosen.get("id") or "")
yt_title = str(sn.get("title") or "")
yt_handle = str(sn.get("customUrl") or "").strip()
if not items or not yt_id:
err = (
"Google 账号下没有可用的 YouTube 频道(mine=true 为空)。"
"请确认授权时选的是有频道的品牌账号,不是空的 Google 登录号。"
)
_stamp_oauth_error(channel_pk, err)
raise ValueError(err)
google_email = await fetch_google_account_email(access)
# Resolve target card by authorized brand UC:
# exist → update that card; missing → create new card.
# Never delete the clicked card. Never wipe unrelated cards.
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:
try:
async with httpx.AsyncClient(**_google_client_kwargs(timeout=20.0)) as client:
await client.post(
"https://oauth2.googleapis.com/revoke",
data={"token": access},
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
except Exception:
pass
err = (
"未拿到 refresh_token(Google 未下发长期凭证)。"
"已尝试撤销本次临时授权。请打开 https://myaccount.google.com/connections "
"移除 dylive,再回到本页点一次「授权」。"
)
_stamp_oauth_error(channel_pk, err)
raise ValueError(err)
click_pk = str(channel_pk)
click_name = str(channel.get("name") or click_pk)
existing = _find_shorts_by_youtube_id(yt_id) if yt_id else None
target_pk = click_pk
resolve_note = ""
created_new = False
removed_stub = False
def _is_empty_stub(ch: dict[str, Any]) -> bool:
return (
not str(ch.get("youtube_channel_id") or "").strip()
and not str(ch.get("refresh_token") or "").strip()
)
if existing and str(existing.get("id") or "") != click_pk:
target_pk = str(existing.get("id") or click_pk)
resolve_note = (
f"选中品牌「{yt_title or yt_id}」已有卡片「{existing.get('name') or target_pk}」,"
f"凭证已写入该卡。"
)
elif existing:
target_pk = str(existing.get("id") or click_pk)
resolve_note = ""
elif expected_uc and expected_uc != yt_id:
# Clicked card bound to another UC; brand is new → create.
try:
created = db.create_shorts_channel(
name=(yt_title or "Shorts Channel").strip() or "Shorts Channel",
youtube_channel_id=yt_id,
oauth_profile_id=profile_id or str(channel.get("oauth_profile_id") or ""),
enabled=True,
)
target_pk = str(created.get("id") or "")
created_new = True
resolve_note = (
f"选中品牌「{yt_title or yt_id}」原先没有卡片,已新建;"
f"你点的「{click_name}」保持原样。"
)
except ValueError as exc:
again = _find_shorts_by_youtube_id(yt_id)
if again:
target_pk = str(again.get("id") or click_pk)
resolve_note = (
f"选中品牌「{yt_title or yt_id}」已有卡片「{again.get('name') or target_pk}」,"
f"凭证已写入该卡({exc})。"
)
else:
raise
else:
# Clicked card empty UC or same UC → update clicked card in place.
target_pk = click_pk
if expected_uc and expected_uc != yt_id:
resolve_note = (
f"选中品牌「{yt_title or yt_id}」与原绑定不同,已更新本卡 UC"
"(卡片显示名不改成品牌名)。"
)
# Empty stub (no UC / no token) used only as authorize entry → remove after
# credentials land on the real brand card. Never delete cards that already have UC/tokens.
if target_pk != click_pk and _is_empty_stub(channel):
try:
db.delete_shorts_channel(click_pk)
removed_stub = True
resolve_note = (
f"{resolve_note} 已自动移除空壳卡「{click_name}」。".strip()
)
_oauth_log(f"removed_empty_stub click={click_pk} target={target_pk}")
except Exception as exc:
_oauth_log(f"remove_stub_fail click={click_pk} err={exc!r}")
try:
db.update_shorts_channel(
click_pk,
enabled=False,
oauth_ok=0,
oauth_error=f"空壳卡:授权已写入「{(existing or {}).get('name') or target_pk}」,可手动删除",
)
except Exception:
pass
elif target_pk != click_pk:
# Real card clicked but brand bound elsewhere — clear stuck「授权中」.
try:
db.update_shorts_channel(
click_pk,
oauth_ok=0,
oauth_checked_at=time.time(),
oauth_error=(
f"本次授权写入了「{(db.get_shorts_channel(target_pk) or existing or {}).get('name') or target_pk}」,"
f"本卡「{click_name}」未改动。"
)[:500],
)
except Exception:
pass
patch: dict[str, Any] = {
"client_id": client_id,
"client_secret": client_secret,
"refresh_token": refresh,
"youtube_channel_id": yt_id,
}
if google_email:
patch["oauth_email"] = google_email
if profile_id:
patch["oauth_profile_id"] = profile_id
# Never rename operator card into brand title on update — except empty / 未命名 stubs.
target_row = db.get_shorts_channel(target_pk) or {}
cur_name = str(target_row.get("name") or "").strip()
if (not created_new) and yt_title and (
not cur_name or cur_name in ("未命名频道", "Shorts Channel", "Shorts")
):
patch["name"] = yt_title
elif created_new and yt_title:
pass # create already named
# Success card: keep oauth_error clean (info goes to warning toast, not 「OAuth 异常」).
updated = db.update_shorts_channel(
target_pk,
**patch,
oauth_ok=1,
oauth_checked_at=time.time(),
oauth_error="",
)
dup_warn = _dedupe_shorts_channel_by_youtube_id(target_pk, yt_id) if yt_id else ""
mismatch_warn = resolve_note
brand_mismatch = bool(resolve_note) and (
created_new or (existing is not None and str(existing.get("id") or "") != click_pk)
)
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
profile_err = ""
ypp_err = ""
try:
from . import youtube_manage as ytm
await ytm.fetch_channel_profile(target_pk)
except Exception as exc:
profile_err = str(exc).strip() or "拉取频道资料失败"
try:
from .yt_long_monetize import refresh_ypp_for_shorts_channel
ypp_r = await refresh_ypp_for_shorts_channel(target_pk)
if not ypp_r.get("ok"):
ypp_err = str(ypp_r.get("error") or "YPP 探测失败")[:200]
except Exception as exc:
ypp_err = str(exc).strip() or "YPP 探测失败"
note = " · ".join(x for x in (profile_err, ypp_err) if x)
if note:
try:
db.update_shorts_channel(target_pk, oauth_error=note[:500])
updated = db.get_shorts_channel(target_pk) or updated
except Exception:
pass
_oauth_log(
f"exchange_ok click={click_pk} target={target_pk} created={created_new} "
f"removed_stub={removed_stub} yt={yt_id} title={yt_title} note={resolve_note!r}"
)
warn_out = " · ".join(x for x in (mismatch_warn, dup_warn) if x)
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,
"profile_ok": not bool(profile_err),
"ypp_ok": not bool(ypp_err),
"profile_error": profile_err,
"ypp_error": ypp_err,
"brand_mismatch": brand_mismatch,
"created_channel": created_new,
"removed_empty_stub": removed_stub,
"target_channel_pk": target_pk,
"duplicate_channel_warning": warn_out,
"return_to": return_to,
}
except ValueError:
raise
except Exception as exc:
err = f"授权处理异常: {type(exc).__name__}: {exc}"
_oauth_log(err)
_stamp_oauth_error(channel_pk, err)
raise ValueError(err) from exc
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"],
)
granted = await token_scopes(str(access))
if granted is None:
# Token refresh succeeded; scope check egress failed — do not false-flag.
err = "OAuth 出口不稳定:令牌可用但权限校验超时,请稍后重试或检查住宅代理"
db.update_shorts_channel(cid, oauth_ok=1, oauth_checked_at=now, oauth_error=err)
return {"ok": True, "channel_id": cid, "warning": err, "scopes_unchecked": True}
missing = missing_required_scopes(granted)
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).strip()[:240] or f"{type(exc).__name__}: OAuth 探测失败"
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}