diff --git a/backend/app/db.py b/backend/app/db.py index 867d664..d99eb57 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -217,6 +217,7 @@ def init_db() -> None: ("last_live_url", "TEXT NOT NULL DEFAULT ''"), ("last_live_video_id", "TEXT NOT NULL DEFAULT ''"), ("active_session_id", "TEXT NOT NULL DEFAULT ''"), + ("oauth_profile_id", "TEXT NOT NULL DEFAULT ''"), ]: if col not in sc_cols: conn.execute(f"ALTER TABLE shorts_channels ADD COLUMN {col} {ddl}") @@ -313,6 +314,13 @@ def _seed_defaults(conn: sqlite3.Connection) -> None: "shorts_oauth_client_id": "", "shorts_oauth_client_secret": "", "shorts_oauth_redirect_uri": "https://dylive.nomadro.com/api/shorts/oauth/callback", + # Named OAuth apps A/B/C/D — configure once in settings; channels pick a profile + "shorts_oauth_profiles": [ + {"id": "A", "label": "谷歌账号 A", "client_id": "", "client_secret": ""}, + {"id": "B", "label": "谷歌账号 B", "client_id": "", "client_secret": ""}, + {"id": "C", "label": "谷歌账号 C", "client_id": "", "client_secret": ""}, + {"id": "D", "label": "谷歌账号 D", "client_id": "", "client_secret": ""}, + ], "shorts_gcp_project_id": "live-473104", "shorts_yt_daily_upload_limit": 90, "shorts_yt_upload_blocked_until": 0, @@ -2606,6 +2614,7 @@ def create_shorts_channel( description_template: str = "{anchor}\n{url}\n#Shorts #直播", privacy: str = "public", note: str = "", + oauth_profile_id: str = "", ) -> dict[str, Any]: now = time.time() cid = str(uuid.uuid4()) @@ -2619,8 +2628,8 @@ def create_shorts_channel( INSERT INTO shorts_channels( id, name, youtube_channel_id, client_id, client_secret, refresh_token, enabled, daily_min, daily_max, title_template, description_template, - privacy, last_assigned_at, note, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?) + privacy, last_assigned_at, note, oauth_profile_id, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?) """, ( cid, @@ -2636,6 +2645,7 @@ def create_shorts_channel( description_template or "", (privacy or "public").strip() or "public", (note or "").strip(), + (oauth_profile_id or "").strip().upper(), now, now, ), @@ -2660,6 +2670,7 @@ def update_shorts_channel(channel_pk: str, **fields: Any) -> dict[str, Any]: "description_template", "privacy", "note", + "oauth_profile_id", "last_assigned_at", "oauth_ok", "oauth_checked_at", @@ -2680,6 +2691,8 @@ def update_shorts_channel(channel_pk: str, **fields: Any) -> dict[str, Any]: continue # forced below if k == "enabled": v = 1 if v else 0 + if k == "oauth_profile_id": + v = str(v or "").strip().upper() sets.append(f"{k} = ?") params.append(v) sets.append("daily_min = ?") diff --git a/backend/app/main.py b/backend/app/main.py index 6f38867..eb0bf90 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -349,18 +349,20 @@ def _public_shorts_channel(ch: dict[str, Any]) -> dict[str, Any]: secret = str(out.get("client_secret") or "") refresh = str(out.get("refresh_token") or "") client_id = str(out.get("client_id") or "").strip() + profile_id = str(out.get("oauth_profile_id") or "").strip().upper() + out["oauth_profile_id"] = profile_id 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["has_custom_oauth"] = out["oauth_client_source"] in {"profile", "channel"} out["can_authorize"] = shorts_oauth.channel_can_authorize(ch) + prof = shorts_oauth.get_oauth_profile(profile_id) if profile_id else None + out["oauth_profile_label"] = str((prof or {}).get("label") or "") if prof else "" 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) @@ -371,6 +373,16 @@ def _public_shorts_channel(ch: dict[str, Any]) -> dict[str, Any]: return out +def _public_settings(cfg: dict[str, Any]) -> dict[str, Any]: + """Mask OAuth secrets in settings API responses.""" + out = dict(cfg) + secret = str(out.get("shorts_oauth_client_secret") or "") + if secret and not str(secret).startswith("***"): + out["shorts_oauth_client_secret"] = ("***" + secret[-4:]) if len(secret) > 4 else "***" + out["shorts_oauth_profiles"] = shorts_oauth.list_oauth_profiles(cfg, public=True) + return out + + def _request_public_base(request: Request) -> str: """Prefer reverse-proxy headers for OAuth redirect base.""" proto = (request.headers.get("x-forwarded-proto") or request.url.scheme or "https").split(",")[0].strip() @@ -437,6 +449,7 @@ async def shorts_status() -> dict[str, Any]: st["oauth_scopes"] = shorts_oauth.requested_scopes() cfg = await _db(db.get_settings_map) st["gcp_project_id"] = str(cfg.get("shorts_gcp_project_id") or "live-473104") + st["oauth_profiles"] = shorts_oauth.list_oauth_profiles(cfg, public=True) return st @@ -772,13 +785,24 @@ async def monitor_check_one(room_pk: str) -> dict[str, Any]: @app.get("/api/settings") async def get_settings() -> dict[str, Any]: - return await asyncio.to_thread(db.get_settings_map) + cfg = await asyncio.to_thread(db.get_settings_map) + return _public_settings(cfg) @app.patch("/api/settings") async def patch_settings(body: SettingsUpdate) -> dict[str, Any]: patch = body.model_dump(exclude_none=True) - return await asyncio.to_thread(db.update_settings_map, patch) + if "shorts_oauth_client_secret" in patch: + sec = str(patch.get("shorts_oauth_client_secret") or "").strip() + if (not sec) or sec.startswith("***"): + patch.pop("shorts_oauth_client_secret", None) + if "shorts_oauth_profiles" in patch: + existing = await asyncio.to_thread(db.get_settings_map) + patch["shorts_oauth_profiles"] = shorts_oauth.merge_oauth_profiles_patch( + patch.get("shorts_oauth_profiles"), existing + ) + cfg = await asyncio.to_thread(db.update_settings_map, patch) + return _public_settings(cfg) @app.post("/api/settings/sync-cookie") diff --git a/backend/app/models.py b/backend/app/models.py index 1e0160c..c13af7f 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -228,6 +228,7 @@ class SettingsUpdate(BaseModel): shorts_oauth_client_id: Optional[str] = None shorts_oauth_client_secret: Optional[str] = None shorts_oauth_redirect_uri: Optional[str] = None + shorts_oauth_profiles: Optional[list[dict[str, Any]]] = None shorts_gcp_project_id: Optional[str] = None @@ -244,6 +245,7 @@ class ShortsChannelCreate(BaseModel): description_template: str = "{anchor}\n{url}\n#Shorts #直播" privacy: str = "public" note: str = "" + oauth_profile_id: str = "" class ShortsChannelUpdate(BaseModel): @@ -259,6 +261,7 @@ class ShortsChannelUpdate(BaseModel): description_template: Optional[str] = None privacy: Optional[str] = None note: Optional[str] = None + oauth_profile_id: Optional[str] = None class ShortsJobsBulkBody(BaseModel): diff --git a/backend/app/shorts_oauth.py b/backend/app/shorts_oauth.py index 641882d..2308f78 100644 --- a/backend/app/shorts_oauth.py +++ b/backend/app/shorts_oauth.py @@ -1,12 +1,10 @@ # -*- 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). +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 @@ -34,6 +32,13 @@ YOUTUBE_SCOPES = " ".join( ] ) +DEFAULT_OAUTH_PROFILES: list[dict[str, str]] = [ + {"id": "A", "label": "谷歌账号 A", "client_id": "", "client_secret": ""}, + {"id": "B", "label": "谷歌账号 B", "client_id": "", "client_secret": ""}, + {"id": "C", "label": "谷歌账号 C", "client_id": "", "client_secret": ""}, + {"id": "D", "label": "谷歌账号 D", "client_id": "", "client_secret": ""}, +] + # state -> (channel_pk, expires_at, client_id, client_secret) _oauth_states: dict[str, tuple[str, float, str, str]] = {} @@ -42,9 +47,124 @@ 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(), + } + 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"], + "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 + out.append( + { + "id": pid, + "label": str(row.get("label") or old.get("label") or f"谷歌账号 {pid}").strip(), + "client_id": client_id, + "client_secret": secret, + } + ) + return out + + 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()) + 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: @@ -62,22 +182,37 @@ 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. + """Resolve Client for authorize/upload. Returns: - client_id, client_secret, source ("channel"|"global"|"none") + 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"} + 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"} - return {"client_id": "", "client_secret": "", "source": "none"} + 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: @@ -94,15 +229,13 @@ def build_authorize_url(*, channel_pk: str, request_base: str = "") -> str: client_secret = str(client.get("client_secret") or "") if not client_id or not client_secret: raise ValueError( - "请先在「设置」填写全局 Google OAuth Client,或在本频道填写专属 Client ID/Secret" + "请先在「设置 → OAuth 配置档」填写对应 A/B/C/D 的 Client,并在频道选择该配置档" ) - # 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, @@ -133,16 +266,12 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic 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") + source_meta = resolve_oauth_client(channel, cfg) + source = str(source_meta.get("source") or "none") if not client_id or not client_secret: raise ValueError("缺少 OAuth Client 配置") redirect_uri = resolve_redirect_uri(request_base) @@ -163,7 +292,6 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic 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 账号权限里撤销本应用后重试") @@ -181,7 +309,6 @@ 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, @@ -189,7 +316,6 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic } 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 @@ -200,11 +326,12 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic "youtube_channel_id": yt_id, "youtube_title": yt_title, "oauth_client_source": source, + "oauth_profile_id": source_meta.get("profile_id") or "", } 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.""" + """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 ""), @@ -256,7 +383,6 @@ async def probe_all_enabled_channels(cfg: dict[str, Any] | None = None) -> dict[ 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: diff --git a/frontend/src/app/settings/page.tsx b/frontend/src/app/settings/page.tsx index d8847be..7344173 100644 --- a/frontend/src/app/settings/page.tsx +++ b/frontend/src/app/settings/page.tsx @@ -105,10 +105,24 @@ export default function SettingsPage() { body.shorts_auto_retry_interval_sec = Number(settings.shorts_auto_retry_interval_sec ?? 300); body.shorts_oauth_check_interval_sec = Number(settings.shorts_oauth_check_interval_sec ?? 3600); body.shorts_oauth_client_id = String(settings.shorts_oauth_client_id || ""); - body.shorts_oauth_client_secret = String(settings.shorts_oauth_client_secret || ""); + const gSecret = String(settings.shorts_oauth_client_secret || ""); + if (gSecret && !gSecret.startsWith("***")) body.shorts_oauth_client_secret = gSecret; body.shorts_oauth_redirect_uri = String( settings.shorts_oauth_redirect_uri || "https://dylive.nomadro.com/api/shorts/oauth/callback" ); + const profiles = Array.isArray(settings.shorts_oauth_profiles) ? settings.shorts_oauth_profiles : []; + body.shorts_oauth_profiles = profiles.map((p: any) => ({ + id: String(p.id || "").toUpperCase(), + label: String(p.label || ""), + client_id: String(p.client_id || ""), + client_secret: String(p.client_secret || ""), + })); + // Keep legacy global client in sync with profile A when A is filled + const profA = body.shorts_oauth_profiles.find((p: any) => p.id === "A"); + if (profA?.client_id) body.shorts_oauth_client_id = profA.client_id; + if (profA?.client_secret && !String(profA.client_secret).startsWith("***")) { + body.shorts_oauth_client_secret = profA.client_secret; + } const next = await fetchJson("/api/settings", { method: "PATCH", body: JSON.stringify(body) }); setSettings(next); setMsg("已保存"); @@ -417,28 +431,108 @@ export default function SettingsPage() { /> -
专属 OAuth 应用(可选 · 区分谷歌账号 A/B/C/D)
-- 留空则用设置里的全局 Client。若频道在另一个谷歌账号 / Cloud 项目下,在此填写该项目的 Client ID/Secret; - 每个 OAuth 应用都须登记同一回调 URI。授权时选对应谷歌账号登录。 -
-