# -*- coding: utf-8 -*- """YouTube OAuth for Shorts — click-to-authorize, stores refresh_token on channel. Supports multiple Google OAuth apps (Client ID/Secret pairs): - Global default in settings (shorts_oauth_client_id / secret) - Per-channel override on shorts_channels.client_id / client_secret Use case: Google account A/B/C/D each with its own Cloud OAuth client (or same client with different login — channel override still isolates tokens). """ from __future__ import annotations import secrets import time from typing import Any from urllib.parse import urlencode import httpx from . import db YOUTUBE_SCOPES = " ".join( [ # Full channel management (playlists, captions-ish surface, live bindings, etc.) "https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.force-ssl", # Explicit upload + readonly (kept for clarity / older clients) "https://www.googleapis.com/auth/youtube.upload", "https://www.googleapis.com/auth/youtube.readonly", # Partner / brand-account surfaces when available "https://www.googleapis.com/auth/youtubepartner", # Channel analytics (non-monetary) "https://www.googleapis.com/auth/yt-analytics.readonly", ] ) # state -> (channel_pk, expires_at, client_id, client_secret) _oauth_states: dict[str, tuple[str, float, str, str]] = {} def _cfg() -> dict[str, Any]: return db.get_settings_map() def oauth_client_configured() -> bool: cfg = _cfg() return bool(str(cfg.get("shorts_oauth_client_id") or "").strip() and str(cfg.get("shorts_oauth_client_secret") or "").strip()) def resolve_redirect_uri(request_base: str = "") -> str: cfg = _cfg() custom = str(cfg.get("shorts_oauth_redirect_uri") or "").strip() if custom: return custom.rstrip("/") base = (request_base or "").rstrip("/") if base: return f"{base}/api/shorts/oauth/callback" return "https://dylive.nomadro.com/api/shorts/oauth/callback" def resolve_oauth_client( channel: dict[str, Any] | None = None, cfg: dict[str, Any] | None = None, ) -> dict[str, Any]: """Prefer per-channel Client ID/Secret; fall back to global settings. Returns: client_id, client_secret, source ("channel"|"global"|"none") """ settings = cfg or _cfg() ch = channel or {} 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"} 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"} return {"client_id": "", "client_secret": "", "source": "none"} 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 = "") -> 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( "请先在「设置」填写全局 Google OAuth Client,或在本频道填写专属 Client ID/Secret" ) # purge expired 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) # Bind the exact client used for authorize so exchange matches (A/B/C/D apps) _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": YOUTUBE_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]: return [s for s in YOUTUBE_SCOPES.split() if s] 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 无效或已过期,请重新点击授权") channel_pk = packed[0] exp = packed[1] 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] source = "channel" if ( str(channel.get("client_id") or "").strip() == client_id and str(channel.get("client_secret") or "").strip() == client_secret ) else "bound" else: # Legacy state tuple — re-resolve from channel/global client = resolve_oauth_client(channel, cfg) client_id = str(client.get("client_id") or "") client_secret = str(client.get("client_secret") or "") source = str(client.get("source") or "none") 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() if not refresh: # Google may omit refresh if previously granted; keep existing if any refresh = str(channel.get("refresh_token") or "").strip() if not refresh: raise ValueError("未拿到 refresh_token,请在 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 {} items = ch_data.get("items") or [] yt_id = "" yt_title = "" if items: yt_id = str(items[0].get("id") or "") yt_title = str((items[0].get("snippet") or {}).get("title") or "") # Persist the Client that issued this token (critical for multi-app A/B/C/D) patch: dict[str, Any] = { "client_id": client_id, "client_secret": client_secret, "refresh_token": refresh, } if yt_id: patch["youtube_channel_id"] = yt_id # auto-fill name if still placeholder name = str(channel.get("name") or "").strip() if yt_title and (not name or name.startswith("Shorts") or name == "未命名频道"): patch["name"] = yt_title updated = db.update_shorts_channel(channel_pk, **patch) return { "ok": True, "channel": updated, "youtube_channel_id": yt_id, "youtube_title": yt_title, "oauth_client_source": source, } def channel_oauth_creds(channel: dict[str, Any], cfg: dict[str, Any] | None = None) -> dict[str, str]: """Resolve upload credentials: channel token + channel/global client.""" 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: await refresh_access_token( client_id=creds["client_id"], client_secret=creds["client_secret"], refresh_token=creds["refresh_token"], ) db.update_shorts_channel(cid, oauth_ok=1, oauth_checked_at=now, oauth_error="") return {"ok": True, "channel_id": cid} 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 # Skip recently healthy probes (< half interval) 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}