diff --git a/backend/app/main.py b/backend/app/main.py index db0419c..6f38867 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -348,11 +348,20 @@ def _public_shorts_channel(ch: dict[str, Any]) -> dict[str, Any]: out = dict(ch) secret = str(out.get("client_secret") or "") refresh = str(out.get("refresh_token") or "") + client_id = str(out.get("client_id") or "").strip() + out["has_client_id"] = bool(client_id) out["has_client_secret"] = bool(secret.strip()) out["has_refresh_token"] = bool(refresh.strip()) out["authorized"] = bool(refresh.strip()) + # Multi OAuth app (A/B/C/D): channel-level Client overrides global settings + oauth_meta = shorts_oauth.resolve_oauth_client(ch) + out["oauth_client_source"] = str(oauth_meta.get("source") or "none") + out["has_custom_oauth"] = out["oauth_client_source"] == "channel" + out["can_authorize"] = shorts_oauth.channel_can_authorize(ch) out["client_secret"] = ("***" + secret[-4:]) if len(secret) > 4 else ("***" if secret else "") out["refresh_token"] = ("***" + refresh[-4:]) if len(refresh) > 4 else ("***" if refresh else "") + # client_id is not secret; keep for edit form (empty means use global) + out["client_id"] = client_id try: out["oauth_ok"] = int(out.get("oauth_ok") if out.get("oauth_ok") is not None else -1) except Exception: diff --git a/backend/app/shorts_oauth.py b/backend/app/shorts_oauth.py index d0d9b13..641882d 100644 --- a/backend/app/shorts_oauth.py +++ b/backend/app/shorts_oauth.py @@ -1,5 +1,13 @@ # -*- coding: utf-8 -*- -"""YouTube OAuth for Shorts — click-to-authorize, stores refresh_token on channel.""" +"""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 @@ -26,8 +34,8 @@ YOUTUBE_SCOPES = " ".join( ] ) -# state -> (channel_pk, expires_at) -_oauth_states: dict[str, tuple[str, float]] = {} +# state -> (channel_pk, expires_at, client_id, client_secret) +_oauth_states: dict[str, tuple[str, float, str, str]] = {} def _cfg() -> dict[str, Any]: @@ -50,20 +58,52 @@ def resolve_redirect_uri(request_base: str = "") -> str: 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() - 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): + 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, (_pk, exp) in list(_oauth_states.items()): - if exp < now: + 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) - _oauth_states[state] = (channel_pk, now + 600) + # 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), @@ -85,12 +125,24 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic packed = _oauth_states.pop(state, None) if not packed: raise ValueError("授权 state 无效或已过期,请重新点击授权") - channel_pk, exp = packed + channel_pk = packed[0] + exp = packed[1] 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() + 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) @@ -112,8 +164,7 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic 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() + refresh = str(channel.get("refresh_token") or "").strip() if not refresh: raise ValueError("未拿到 refresh_token,请在 Google 账号权限里撤销本应用后重试") @@ -130,6 +181,7 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic 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, @@ -137,9 +189,8 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic } 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() + 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) @@ -148,15 +199,16 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic "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 + global client fallback.""" - settings = cfg or _cfg() + """Resolve upload credentials: channel token + channel/global client.""" + client = resolve_oauth_client(channel, 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(), + "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(), } diff --git a/frontend/src/app/settings/page.tsx b/frontend/src/app/settings/page.tsx index e87f577..d8847be 100644 --- a/frontend/src/app/settings/page.tsx +++ b/frontend/src/app/settings/page.tsx @@ -449,7 +449,8 @@ export default function SettingsPage() {
- 只需配置一次 Client。各上传频道在「Shorts」页点「Google 授权」自动写入 refresh_token,无需手填。 + 全局只需配置一次默认 Client。各上传频道可在编辑里覆盖专属 Client ID/Secret(谷歌账号 A/B/C/D / + 不同 Cloud 项目),再点「Google 授权」写入该频道的 refresh_token。
diff --git a/frontend/src/app/shorts/page.tsx b/frontend/src/app/shorts/page.tsx index 2b7c6e4..0bba39b 100644 --- a/frontend/src/app/shorts/page.tsx +++ b/frontend/src/app/shorts/page.tsx @@ -46,6 +46,12 @@ type Channel = { note?: string; authorized?: boolean; has_refresh_token?: boolean; + client_id?: string; + has_client_id?: boolean; + has_client_secret?: boolean; + has_custom_oauth?: boolean; + can_authorize?: boolean; + oauth_client_source?: "channel" | "global" | "none" | string; }; type BoardChannel = { @@ -90,6 +96,9 @@ const emptyForm = { description_template: "{anchor}\n{url}\n#Shorts #直播", privacy: "public", note: "", + /** Per-channel Google OAuth app (A/B/C/D). Empty = use global settings. */ + client_id: "", + client_secret: "", }; const STATUS_STYLE: Record专属 OAuth 应用(可选 · 区分谷歌账号 A/B/C/D)
++ 留空则用设置里的全局 Client。若频道在另一个谷歌账号 / Cloud 项目下,在此填写该项目的 Client ID/Secret; + 每个 OAuth 应用都须登记同一回调 URI。授权时选对应谷歌账号登录。 +
+