# -*- coding: utf-8 -*- """YouTube OAuth for Shorts — click-to-authorize, stores refresh_token on channel.""" 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( [ "https://www.googleapis.com/auth/youtube.upload", "https://www.googleapis.com/auth/youtube.readonly", ] ) # state -> (channel_pk, expires_at) _oauth_states: dict[str, tuple[str, float]] = {} 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 build_authorize_url(*, channel_pk: str, request_base: str = "") -> str: cfg = _cfg() client_id = str(cfg.get("shorts_oauth_client_id") or "").strip() if not client_id: raise ValueError("请先在设置里填写 Google OAuth Client ID / Secret") if not db.get_shorts_channel(channel_pk): raise ValueError("频道不存在") # purge expired now = time.time() for k, (_pk, exp) in list(_oauth_states.items()): if exp < now: _oauth_states.pop(k, None) state = secrets.token_urlsafe(24) _oauth_states[state] = (channel_pk, now + 600) 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) 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, exp = packed if exp < time.time(): raise ValueError("授权已过期,请重新点击授权") cfg = _cfg() client_id = str(cfg.get("shorts_oauth_client_id") or "").strip() client_secret = str(cfg.get("shorts_oauth_client_secret") or "").strip() 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 existing = db.get_shorts_channel(channel_pk) or {} refresh = str(existing.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 "") patch: dict[str, Any] = { "client_id": client_id, "client_secret": client_secret, "refresh_token": refresh, } if yt_id: patch["youtube_channel_id"] = yt_id existing = db.get_shorts_channel(channel_pk) or {} # auto-fill name if still placeholder name = str(existing.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, } def channel_oauth_creds(channel: dict[str, Any], cfg: dict[str, Any] | None = None) -> dict[str, str]: """Resolve upload credentials: channel token + global client fallback.""" settings = cfg or _cfg() return { "client_id": str(channel.get("client_id") or settings.get("shorts_oauth_client_id") or "").strip(), "client_secret": str(channel.get("client_secret") or settings.get("shorts_oauth_client_secret") or "").strip(), "refresh_token": str(channel.get("refresh_token") or "").strip(), }