Add reusable A/B/C/D Google OAuth profiles in settings.
Channels pick a profile instead of re-entering Client ID/Secret; existing global/channel credentials keep working as fallback. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
4f144f3daf
commit
0d2f63757a
@ -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 = ?")
|
||||
|
||||
@ -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")
|
||||
|
||||
@ -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):
|
||||
|
||||
@ -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:
|
||||
|
||||
@ -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() {
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
<label className="block text-xs text-slate-400 md:col-span-2">
|
||||
Google OAuth Client ID(Google Cloud 控制台 → 凭据 → OAuth 客户端)
|
||||
<input
|
||||
value={String(settings.shorts_oauth_client_id || "")}
|
||||
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_oauth_client_id: e.target.value }))}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||
placeholder="xxxx.apps.googleusercontent.com"
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-xs text-slate-400 md:col-span-2">
|
||||
Google OAuth Client Secret
|
||||
<input
|
||||
type="password"
|
||||
value={String(settings.shorts_oauth_client_secret || "")}
|
||||
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_oauth_client_secret: e.target.value }))}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||
placeholder="GOCSPX-..."
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-xs text-slate-400 md:col-span-2">
|
||||
授权回调 URI(须原样加到 Google 控制台「已授权的重定向 URI」)
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<h4 className="text-xs font-medium text-slate-200">OAuth 配置档(A / B / C / D)</h4>
|
||||
<p className="mt-1 text-[11px] leading-relaxed text-slate-500">
|
||||
每个谷歌 Cloud 项目填一套 Client,保存一次即可。Shorts 频道只需选择 A/B/C/D,不必再手填密钥。
|
||||
各项目均须登记同一回调 URI。密钥留空或显示 *** 表示不修改已有值。
|
||||
</p>
|
||||
</div>
|
||||
{(["A", "B", "C", "D"] as const).map((pid) => {
|
||||
const profiles = Array.isArray(settings.shorts_oauth_profiles)
|
||||
? (settings.shorts_oauth_profiles as any[])
|
||||
: [];
|
||||
const row =
|
||||
profiles.find((p) => String(p.id || "").toUpperCase() === pid) || {
|
||||
id: pid,
|
||||
label: `谷歌账号 ${pid}`,
|
||||
client_id: pid === "A" ? String(settings.shorts_oauth_client_id || "") : "",
|
||||
client_secret:
|
||||
pid === "A" ? String(settings.shorts_oauth_client_secret || "") : "",
|
||||
};
|
||||
const setProfile = (patch: Record<string, string>) => {
|
||||
setSettings((prev) => {
|
||||
const prevList = Array.isArray(prev.shorts_oauth_profiles)
|
||||
? [...(prev.shorts_oauth_profiles as any[])]
|
||||
: [];
|
||||
const idx = prevList.findIndex((p) => String(p.id || "").toUpperCase() === pid);
|
||||
const nextRow = {
|
||||
id: pid,
|
||||
label: row.label || `谷歌账号 ${pid}`,
|
||||
client_id: row.client_id || "",
|
||||
client_secret: row.client_secret || "",
|
||||
...patch,
|
||||
};
|
||||
if (idx >= 0) prevList[idx] = { ...prevList[idx], ...nextRow };
|
||||
else prevList.push(nextRow);
|
||||
// Ensure A-D exist
|
||||
for (const id of ["A", "B", "C", "D"]) {
|
||||
if (!prevList.some((p) => String(p.id || "").toUpperCase() === id)) {
|
||||
prevList.push({
|
||||
id,
|
||||
label: `谷歌账号 ${id}`,
|
||||
client_id: "",
|
||||
client_secret: "",
|
||||
});
|
||||
}
|
||||
}
|
||||
const next: Record<string, any> = { ...prev, shorts_oauth_profiles: prevList };
|
||||
if (pid === "A" && patch.client_id !== undefined) next.shorts_oauth_client_id = patch.client_id;
|
||||
if (pid === "A" && patch.client_secret !== undefined && !String(patch.client_secret).startsWith("***")) {
|
||||
next.shorts_oauth_client_secret = patch.client_secret;
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
const ready = Boolean(String(row.client_id || "").trim() && String(row.client_secret || "").trim());
|
||||
return (
|
||||
<div
|
||||
key={pid}
|
||||
className={`rounded-xl border p-3 ${ready ? "border-teal-500/25 bg-teal-500/5" : "border-white/10 bg-black/20"}`}
|
||||
>
|
||||
<div className="mb-2 flex flex-wrap items-center gap-2">
|
||||
<span className="rounded bg-white/10 px-2 py-0.5 text-xs font-semibold text-slate-100">
|
||||
{pid}
|
||||
</span>
|
||||
<input
|
||||
value={String(row.label || "")}
|
||||
onChange={(e) => setProfile({ label: e.target.value })}
|
||||
className="min-w-[10rem] flex-1 rounded-lg border border-white/10 bg-slate-900 px-2 py-1 text-xs"
|
||||
placeholder={`谷歌账号 ${pid}`}
|
||||
/>
|
||||
<span className={`text-[10px] ${ready ? "text-teal-300" : "text-amber-300"}`}>
|
||||
{ready ? "已配置" : "未配置"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid gap-2 md:grid-cols-2">
|
||||
<label className="block text-[11px] text-slate-400">
|
||||
Client ID
|
||||
<input
|
||||
value={String(row.client_id || "")}
|
||||
onChange={(e) => setProfile({ client_id: e.target.value })}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-2 py-1.5 font-mono text-[11px]"
|
||||
placeholder="xxxx.apps.googleusercontent.com"
|
||||
autoComplete="off"
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-[11px] text-slate-400">
|
||||
Client Secret
|
||||
<input
|
||||
type="password"
|
||||
value={String(row.client_secret || "")}
|
||||
onChange={(e) => setProfile({ client_secret: e.target.value })}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-2 py-1.5 font-mono text-[11px]"
|
||||
placeholder="GOCSPX-...(*** 表示已保存)"
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<label className="block text-xs text-slate-400">
|
||||
授权回调 URI(所有 A/B/C/D 项目都须登记)
|
||||
<input
|
||||
value={String(
|
||||
settings.shorts_oauth_redirect_uri || "https://dylive.nomadro.com/api/shorts/oauth/callback"
|
||||
@ -449,8 +543,7 @@ export default function SettingsPage() {
|
||||
</label>
|
||||
</div>
|
||||
<p className="text-xs text-slate-500">
|
||||
全局只需配置一次默认 Client。各上传频道可在编辑里覆盖专属 Client ID/Secret(谷歌账号 A/B/C/D /
|
||||
不同 Cloud 项目),再点「Google 授权」写入该频道的 refresh_token。
|
||||
Shorts 页新建/编辑频道时选择配置档 A/B/C/D,再点「Google 授权」登录对应谷歌账号即可。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
@ -51,7 +51,16 @@ type Channel = {
|
||||
has_client_secret?: boolean;
|
||||
has_custom_oauth?: boolean;
|
||||
can_authorize?: boolean;
|
||||
oauth_client_source?: "channel" | "global" | "none" | string;
|
||||
oauth_profile_id?: string;
|
||||
oauth_profile_label?: string;
|
||||
oauth_client_source?: "profile" | "channel" | "global" | "none" | string;
|
||||
};
|
||||
|
||||
type OauthProfile = {
|
||||
id: string;
|
||||
label?: string;
|
||||
client_id?: string;
|
||||
configured?: boolean;
|
||||
};
|
||||
|
||||
type BoardChannel = {
|
||||
@ -96,9 +105,8 @@ 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: "",
|
||||
/** A/B/C/D from settings.shorts_oauth_profiles */
|
||||
oauth_profile_id: "A",
|
||||
};
|
||||
|
||||
const STATUS_STYLE: Record<string, string> = {
|
||||
@ -320,12 +328,9 @@ export default function ShortsPage() {
|
||||
// Stale state after create is fine — only block when we know this channel cannot auth
|
||||
if (ch && !ch.can_authorize) {
|
||||
setShowWizard(true);
|
||||
setError("请先配置全局 Google OAuth,或在该频道填写专属 Client ID/Secret(用于 A/B/C/D 多套应用)");
|
||||
setError("请先在「设置」配置对应 OAuth 档(A/B/C/D),并在本频道选择该配置档");
|
||||
return;
|
||||
}
|
||||
if (!ch && !status?.oauth_configured) {
|
||||
// Channel list not refreshed yet; still try — backend validates channel/global client
|
||||
}
|
||||
window.location.href = `/api/shorts/oauth/start?channel_pk=${encodeURIComponent(channelId)}`;
|
||||
}
|
||||
|
||||
@ -334,6 +339,7 @@ export default function ShortsPage() {
|
||||
setMsg("");
|
||||
setError("");
|
||||
try {
|
||||
const profileId = String(form.oauth_profile_id || "").trim().toUpperCase();
|
||||
const body: Record<string, unknown> = {
|
||||
name: form.name,
|
||||
enabled: form.enabled,
|
||||
@ -343,21 +349,14 @@ export default function ShortsPage() {
|
||||
description_template: form.description_template,
|
||||
privacy: form.privacy,
|
||||
note: form.note,
|
||||
oauth_profile_id: profileId,
|
||||
};
|
||||
if (!String(body.name || "").trim()) body.name = "未命名频道";
|
||||
// Per-channel OAuth app: only send when user typed something (empty secret keeps existing)
|
||||
if (form.client_id.trim()) body.client_id = form.client_id.trim();
|
||||
if (form.client_secret.trim() && !form.client_secret.startsWith("***")) {
|
||||
body.client_secret = form.client_secret.trim();
|
||||
}
|
||||
const hasChannelClient = Boolean(
|
||||
(body.client_id as string | undefined)?.trim() &&
|
||||
((body.client_secret as string | undefined)?.trim() ||
|
||||
(editId && form.client_secret.startsWith("***"))),
|
||||
);
|
||||
if (andAuth && !status?.oauth_configured && !hasChannelClient && !(editId && channels.find((c) => c.id === editId)?.can_authorize)) {
|
||||
setShowWizard(true);
|
||||
setError("授权前请配置全局 OAuth,或为本频道填写成对的 Client ID/Secret");
|
||||
const profiles = (status?.oauth_profiles || []) as OauthProfile[];
|
||||
const selected = profiles.find((p) => String(p.id || "").toUpperCase() === profileId);
|
||||
const profileReady = Boolean(selected?.configured) || Boolean(status?.oauth_configured && profileId === "A");
|
||||
if (andAuth && !profileReady && !(editId && channels.find((c) => c.id === editId)?.can_authorize)) {
|
||||
setError(`配置档 ${profileId || "?"} 尚未在设置里填好 Client,请先去设置保存 A/B/C/D`);
|
||||
return;
|
||||
}
|
||||
let id = editId;
|
||||
@ -374,7 +373,6 @@ export default function ShortsPage() {
|
||||
setShowForm(false);
|
||||
await load();
|
||||
if (andAuth && id) {
|
||||
// Direct redirect — avoid stale can_authorize from React state
|
||||
window.location.href = `/api/shorts/oauth/start?channel_pk=${encodeURIComponent(id)}`;
|
||||
return;
|
||||
}
|
||||
@ -397,8 +395,7 @@ export default function ShortsPage() {
|
||||
description_template: ch.description_template || "",
|
||||
privacy: ch.privacy || "public",
|
||||
note: ch.note || "",
|
||||
client_id: ch.client_id || "",
|
||||
client_secret: ch.has_client_secret ? "***" : "",
|
||||
oauth_profile_id: (ch.oauth_profile_id || "A").toUpperCase(),
|
||||
});
|
||||
}
|
||||
|
||||
@ -1014,13 +1011,13 @@ export default function ShortsPage() {
|
||||
? "已授权"
|
||||
: "未授权"}
|
||||
</span>
|
||||
{full?.has_custom_oauth ? (
|
||||
<span className="text-violet-300" title="使用频道专属 OAuth Client">
|
||||
专属 Client
|
||||
{full?.oauth_profile_id ? (
|
||||
<span className="text-violet-300" title={full.oauth_profile_label || full.oauth_profile_id}>
|
||||
OAuth {full.oauth_profile_id}
|
||||
</span>
|
||||
) : full?.oauth_client_source === "global" ? (
|
||||
<span className="text-slate-500" title="使用全局 OAuth Client">
|
||||
全局 Client
|
||||
<span className="text-slate-500" title="使用全局 / 默认 Client">
|
||||
默认 Client
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
@ -1163,39 +1160,32 @@ export default function ShortsPage() {
|
||||
value={form.note}
|
||||
onChange={(e) => setForm((p) => ({ ...p, note: e.target.value }))}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||
placeholder="如:谷歌账号 B / OAuth 应用 B"
|
||||
placeholder="可选备注"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div className="mt-4 rounded-xl border border-amber-500/20 bg-amber-500/5 p-3">
|
||||
<p className="text-xs font-medium text-amber-100">专属 OAuth 应用(可选 · 区分谷歌账号 A/B/C/D)</p>
|
||||
<p className="mt-1 text-[11px] leading-relaxed text-slate-400">
|
||||
留空则用设置里的全局 Client。若频道在另一个谷歌账号 / Cloud 项目下,在此填写该项目的 Client ID/Secret;
|
||||
每个 OAuth 应用都须登记同一回调 URI。授权时选对应谷歌账号登录。
|
||||
</p>
|
||||
<div className="mt-2 grid gap-2 sm:grid-cols-2">
|
||||
<label className="block text-xs text-slate-400">
|
||||
Client ID
|
||||
<input
|
||||
value={form.client_id}
|
||||
onChange={(e) => setForm((p) => ({ ...p, client_id: e.target.value }))}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 font-mono text-xs"
|
||||
placeholder="xxxx.apps.googleusercontent.com(空=全局)"
|
||||
autoComplete="off"
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-xs text-slate-400">
|
||||
Client Secret
|
||||
<input
|
||||
type="password"
|
||||
value={form.client_secret}
|
||||
onChange={(e) => setForm((p) => ({ ...p, client_secret: e.target.value }))}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 font-mono text-xs"
|
||||
placeholder={editId ? "留空或 *** 表示不修改" : "与 Client ID 成对填写"}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<label className="block text-xs text-slate-400 sm:col-span-2">
|
||||
OAuth 配置档(设置里预先填好的 A/B/C/D)
|
||||
<select
|
||||
value={form.oauth_profile_id || "A"}
|
||||
onChange={(e) => setForm((p) => ({ ...p, oauth_profile_id: e.target.value.toUpperCase() }))}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||
>
|
||||
{((status?.oauth_profiles as OauthProfile[]) || [
|
||||
{ id: "A", label: "谷歌账号 A" },
|
||||
{ id: "B", label: "谷歌账号 B" },
|
||||
{ id: "C", label: "谷歌账号 C" },
|
||||
{ id: "D", label: "谷歌账号 D" },
|
||||
]).map((p) => (
|
||||
<option key={p.id} value={String(p.id).toUpperCase()}>
|
||||
{String(p.id).toUpperCase()} · {p.label || `谷歌账号 ${p.id}`}
|
||||
{p.configured ? "(已配置)" : "(未配置)"}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<span className="mt-1 block text-[10px] text-slate-500">
|
||||
Client 在「设置」页统一维护;这里只选档位,授权时登录对应谷歌账号即可。
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<button
|
||||
|
||||
Loading…
Reference in New Issue
Block a user