diff --git a/backend/app/main.py b/backend/app/main.py index badf7e1..fc32979 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -88,6 +88,12 @@ from .timeutil import stamp_beijing @asynccontextmanager async def lifespan(_: FastAPI): await asyncio.to_thread(db.init_db) + try: + from .yt_channel_meta import ensure_default_brand_hints + + await asyncio.to_thread(ensure_default_brand_hints) + except Exception: + pass try: await asyncio.to_thread(cookie_loader.bootstrap_cookie_into_db) except Exception: diff --git a/backend/app/shorts_pipeline.py b/backend/app/shorts_pipeline.py index 58c4e41..8c5b1e0 100644 --- a/backend/app/shorts_pipeline.py +++ b/backend/app/shorts_pipeline.py @@ -505,9 +505,9 @@ class ShortsPipeline: ok_flag = int(ch.get("oauth_ok") if ch.get("oauth_ok") is not None else -1) err = str(ch.get("oauth_error") or "") has_rt = bool(str(ch.get("refresh_token") or "").strip()) - if ok_flag == 0 or not has_rt: - if has_rt and "重授权中" in err: - continue + if has_rt and "重授权中" in err: + continue + if not has_rt or ok_flag == 0: oauth_issues.append( { "id": ch.get("id"), diff --git a/backend/app/shorts_schedule.py b/backend/app/shorts_schedule.py index ea501cd..871d609 100644 --- a/backend/app/shorts_schedule.py +++ b/backend/app/shorts_schedule.py @@ -212,6 +212,7 @@ def schedule_board(limit: int = 24) -> dict[str, Any]: min_unmet = 0 from .db import SHORTS_DAILY_FORCE, _normalize_daily_quota from .upload_timeline import build_timeline + from .yt_channel_meta import oauth_meta_from_channel ypp_by_shorts = {} try: @@ -236,6 +237,7 @@ def schedule_board(limit: int = 24) -> dict[str, Any]: if c.get("enabled"): total_gap += gap expected_min = daily_min * min(1.0, day_progress * 1.15 + 0.05) + meta = oauth_meta_from_channel(c) channel_rows.append( { "id": cid, @@ -254,8 +256,9 @@ def schedule_board(limit: int = 24) -> dict[str, Any]: "last_status": str(c.get("last_status") or "offline"), "last_title": str(c.get("last_title") or ""), "last_live_url": str(c.get("last_live_url") or ""), - "oauth_ok": c.get("oauth_ok"), - "oauth_error": str(c.get("oauth_error") or ""), + "oauth_ok": meta.get("oauth_ok", c.get("oauth_ok")), + "oauth_error": meta.get("oauth_error", str(c.get("oauth_error") or "")), + "brand_hint": meta.get("brand_hint") or "", "note": str(c.get("note") or ""), "ypp_ok": ypp_by_shorts.get(cid, -1), **stats, diff --git a/backend/app/youtube_manage.py b/backend/app/youtube_manage.py index e6b0d4c..3db9985 100644 --- a/backend/app/youtube_manage.py +++ b/backend/app/youtube_manage.py @@ -115,6 +115,13 @@ def list_managed_channels() -> list[dict[str, Any]]: for ch in rows: sn = _snippet_from_channel_row(ch) or {} cid = str(ch.get("id") or "") + meta: dict[str, Any] = {} + try: + from .yt_channel_meta import oauth_meta_from_channel + + meta = oauth_meta_from_channel(ch) + except Exception: + meta = {} out.append( { "id": ch.get("id"), @@ -123,8 +130,10 @@ def list_managed_channels() -> list[dict[str, Any]]: "enabled": bool(ch.get("enabled")), "authorized": bool(str(ch.get("refresh_token") or "").strip()), "oauth_profile_id": str(ch.get("oauth_profile_id") or "").strip().upper(), - "oauth_ok": ch.get("oauth_ok"), - "oauth_error": str(ch.get("oauth_error") or ""), + "oauth_ok": meta.get("oauth_ok", ch.get("oauth_ok")), + "oauth_error": meta.get("oauth_error", str(ch.get("oauth_error") or "")), + "brand_hint": meta.get("brand_hint") or "", + "note": str(ch.get("note") or ""), "last_status": str(ch.get("last_status") or "offline"), "last_title": str(ch.get("last_title") or ""), "last_live_url": str(ch.get("last_live_url") or ""), diff --git a/backend/app/yt_channel_meta.py b/backend/app/yt_channel_meta.py new file mode 100644 index 0000000..682708e --- /dev/null +++ b/backend/app/yt_channel_meta.py @@ -0,0 +1,97 @@ +"""Build unified YouTube channel card meta (OAuth / YPP / brand hint).""" +from __future__ import annotations + +from typing import Any + + +def brand_hint_for_handle(handle: str, title: str = "", note: str = "") -> str: + from . import db + + h = str(handle or "").strip() + if not h.startswith("@") and h and not h.startswith("UC"): + h = f"@{h.lstrip('@')}" + from_note = "" + raw_note = str(note or "") + for sep in ("Google品牌:", "Google品牌:", "brand:"): + if sep in raw_note: + from_note = raw_note.split(sep, 1)[1].strip().split("\n")[0].strip() + break + if from_note: + return from_note + try: + import json + + settings = db.get_settings_map() + raw = settings.get("shorts_oauth_brand_hints") or "{}" + hints = json.loads(raw) if isinstance(raw, str) else (raw if isinstance(raw, dict) else {}) + if h and hints.get(h): + return str(hints[h]) + t = str(title or "").strip().lower() + for key, val in hints.items(): + if isinstance(key, str) and key.startswith("@") and key.lower() in h.lower(): + return str(val) + title_map = hints.get("_by_title") or {} + if isinstance(title_map, dict): + for k, v in title_map.items(): + if k.lower() in t: + return str(v) + except Exception: + pass + return "" + + +def default_brand_hints() -> dict[str, Any]: + return { + "@ewfwefwefewf": "digitl nomad", + "@nomadstreetfood": "hackrobot-jp", + "@nomadrohub": "nomad Immigration", + "@evanstreetfood": "Nhat Vy", + "@nomadvloglife": "Lyca Hack", + "@walkingtour-c8t": "walking tour", + "@hackrobotlite": "hackrobot-jp", + "_by_title": { + "nomad vlog": "Lyca Hack", + "nomad street food": "hackrobot-jp", + "nomadro hub": "nomad Immigration", + "异度世界": "digitl nomad", + "nomdfsfbjksfbsjk": "digitl nomad", + }, + } + + +def ensure_default_brand_hints() -> None: + from . import db + import json + + settings = db.get_settings_map() + raw = settings.get("shorts_oauth_brand_hints") + if raw: + return + db.update_settings_map({"shorts_oauth_brand_hints": json.dumps(default_brand_hints(), ensure_ascii=False)}) + + +def oauth_meta_from_channel(ch: dict[str, Any] | None) -> dict[str, Any]: + if not ch: + return {} + ok = ch.get("oauth_ok") + err = str(ch.get("oauth_error") or "") + has_rt = bool(str(ch.get("refresh_token") or "").strip()) + profile = None + try: + from . import youtube_manage + + profile = youtube_manage._snippet_from_channel_row(ch) + except Exception: + profile = {} + handle = str((profile or {}).get("custom_url") or ch.get("youtube_channel_id") or "") + return { + "authorized": has_rt, + "oauth_ok": ok, + "oauth_error": err, + "oauth_profile_id": str(ch.get("oauth_profile_id") or "").strip().upper(), + "brand_hint": brand_hint_for_handle( + handle, + str((profile or {}).get("title") or ch.get("name") or ""), + str(ch.get("note") or ""), + ), + } diff --git a/backend/app/yt_long_db.py b/backend/app/yt_long_db.py index 5c80115..e25b1a9 100644 --- a/backend/app/yt_long_db.py +++ b/backend/app/yt_long_db.py @@ -1163,6 +1163,9 @@ def channel_board(push_date: str = "") -> dict[str, Any]: from . import youtube_manage shorts_profile_by_pk = youtube_manage.list_yt_profile_caches() + shorts_by_pk: dict[str, dict[str, Any]] = { + str(c.get("id") or ""): c for c in _db.list_shorts_channels(enabled=None) if c.get("id") + } shorts_by_yt_id: dict[str, dict[str, Any]] = {} for sch in _db.list_shorts_channels(enabled=None): yid = str(sch.get("youtube_channel_id") or "").strip() @@ -1210,15 +1213,32 @@ def channel_board(push_date: str = "") -> dict[str, Any]: yt_profile = shorts_profile_by_pk[src_pk] elif yid and yid in shorts_by_yt_id: yt_profile = shorts_by_yt_id[yid] + oauth_row = ch + if src_pk and src_pk in shorts_by_pk: + sch = shorts_by_pk[src_pk] + if str(sch.get("refresh_token") or "").strip(): + oauth_row = sch + oauth_meta: dict[str, Any] = {} + try: + from .yt_channel_meta import oauth_meta_from_channel + + oauth_meta = oauth_meta_from_channel(oauth_row) + except Exception: + oauth_meta = {} board.append( { "id": cid, "name": ch.get("name"), "youtube_channel_id": ch.get("youtube_channel_id"), - "oauth_profile_id": ch.get("oauth_profile_id"), + "oauth_profile_id": oauth_meta.get("oauth_profile_id") + or ch.get("oauth_profile_id"), "source_shorts_channel_pk": src_pk, "enabled": bool(ch.get("enabled")), - "authorized": bool(str(ch.get("refresh_token") or "").strip()), + "authorized": bool( + oauth_meta.get("authorized") + if oauth_meta + else str(ch.get("refresh_token") or "").strip() + ), "daily_max": dmax, "used": used, "gap": gap, @@ -1226,8 +1246,10 @@ def channel_board(push_date: str = "") -> dict[str, Any]: "scheduled": int(by.get("scheduled") or 0) + int(by.get("uploading") or 0), "pending": int(by.get("pending") or 0) + int(by.get("recording") or 0), "failed": int(by.get("failed") or 0), - "oauth_ok": ch.get("oauth_ok"), - "oauth_error": ch.get("oauth_error") or "", + "oauth_ok": oauth_meta.get("oauth_ok", ch.get("oauth_ok")), + "oauth_error": oauth_meta.get("oauth_error", ch.get("oauth_error") or ""), + "brand_hint": oauth_meta.get("brand_hint") or "", + "note": str(oauth_row.get("note") or ch.get("note") or ""), "ypp_ok": ypp_ok, "monetize_default": bool(int(ch.get("monetize_default") if ch.get("monetize_default") is not None else 1)), "yt_profile": yt_profile, diff --git a/backend/app/yt_long_monetize.py b/backend/app/yt_long_monetize.py index 63d278a..792eb9e 100644 --- a/backend/app/yt_long_monetize.py +++ b/backend/app/yt_long_monetize.py @@ -37,7 +37,20 @@ _CERT_QUESTIONS = [ def _self_cert_no() -> dict[str, Any]: - """Answer the altered-content quiz as all-No (street-food live is not that content).""" + """Answer altered-content quiz as all-No.""" + return { + "newSelfCertificationData": { + "questionnaireAnswers": [ + {"question": q, "answer": 2} + for q in _CERT_QUESTIONS + ], + "certificationMethod": 1, + "questionnaireVersion": 8, + } + } + + +def _self_cert_no_legacy() -> dict[str, Any]: return { "newSelfCertificationData": { "questionnaireAnswers": [ @@ -50,16 +63,36 @@ def _self_cert_no() -> dict[str, Any]: } +def _self_cert_none_above() -> dict[str, Any]: + return { + "newSelfCertificationData": { + "questionnaireAnswers": [], + "noneOfTheAboveSelected": True, + "certificationMethod": 1, + "questionnaireVersion": 8, + } + } + + def _context(*, channel_id: str = "", client_name: Any = "WEB_CREATOR") -> dict[str, Any]: ctx: dict[str, Any] = { "client": { "clientName": client_name, - "clientVersion": "1.20240724.01.00", + "clientVersion": "1.20250218.01.00", "hl": "en", "gl": "US", "utcOffsetMinutes": 0, } } + if client_name == 62 or client_name == "62": + ctx["client"].update( + { + "osName": "Android", + "androidSdkVersion": 33, + "deviceMake": "Google", + "deviceModel": "Pixel 6 Pro", + } + ) ch = str(channel_id or "").strip() if ch: ctx["user"] = { @@ -138,6 +171,36 @@ async def _post_studio( return {"ok": False, "error": str(exc)[:400]} +async def verify_video_monetized( + *, + access_token: str, + video_id: str, + proxy_url: str = "", +) -> dict[str, Any]: + """Best-effort check via Data API monetizationDetails.""" + vid = str(video_id or "").strip() + if not vid: + return {"ok": False, "monetized": False} + try: + async with httpx.AsyncClient(**_client_kwargs(timeout=45.0, proxy_url=proxy_url)) as client: + resp = await client.get( + "https://www.googleapis.com/youtube/v3/videos", + params={"part": "monetizationDetails,status", "id": vid}, + headers={"Authorization": f"Bearer {access_token}"}, + ) + data = resp.json() if resp.content else {} + if resp.status_code >= 400: + return {"ok": False, "monetized": False, "error": str(resp.text[:200])} + items = data.get("items") or [] + if not items: + return {"ok": False, "monetized": False, "error": "no_video"} + md = items[0].get("monetizationDetails") or {} + enabled = bool(md.get("access") and str(md.get("access")).lower() != "blocked") + return {"ok": True, "monetized": enabled, "details": md} + except Exception as exc: + return {"ok": False, "monetized": False, "error": str(exc)[:200]} + + async def enable_video_monetize_with_ads( *, access_token: str, @@ -150,25 +213,34 @@ async def enable_video_monetize_with_ads( if not vid: return {"ok": False, "error": "no_video_id"} ch = str(youtube_channel_id or "").strip() + base = {"encryptedVideoId": vid, "videoReadMask": {"title": True}} + cert_top = _self_cert_no().get("newSelfCertificationData") payloads: list[dict[str, Any]] = [ + {**base, "monetizationSettings": {"newMonetizeWithAds": True}, "context": _context(channel_id=ch, client_name="WEB_CREATOR")}, + {**base, "monetizationSettings": {"newMonetizeWithAds": True}, "context": _context(channel_id=ch, client_name=62)}, + {**base, "monetizationSettings": {"newMonetizeWithAds": True}, "context": _context(channel_id="", client_name="WEB_CREATOR")}, { - "encryptedVideoId": vid, - "videoReadMask": {"title": True}, + **base, "monetizationSettings": {"newMonetizeWithAds": True}, - "context": _context(channel_id="", client_name="WEB_CREATOR"), + "newSelfCertificationData": cert_top, + "context": _context(channel_id=ch, client_name="WEB_CREATOR"), }, { - "encryptedVideoId": vid, - "videoReadMask": {"title": True}, + **base, + "monetizationSettings": {"newMonetizeWithAds": True}, + "selfCertification": _self_cert_none_above(), + "context": _context(channel_id=ch, client_name="WEB_CREATOR"), + }, + { + **base, "monetizationSettings": {"newMonetizeWithAds": True}, "selfCertification": _self_cert_no(), "context": _context(channel_id=ch, client_name="WEB_CREATOR"), }, { - "encryptedVideoId": vid, - "videoReadMask": {}, + **base, "monetizationSettings": {"newMonetizeWithAds": True}, - "selfCertification": _self_cert_no(), + "selfCertification": _self_cert_no_legacy(), "context": _context(channel_id=ch, client_name=62), }, ] @@ -178,10 +250,11 @@ async def enable_video_monetize_with_ads( if last.get("ok"): return last err = str(last.get("error") or "").lower() - # Scope problem will not be fixed by another payload. if "insufficient" in err and "scope" in err: last["error"] = "授权范围不够,请到 Shorts 页重新授权该频道后再传" return last + if "self_certification" in err or "selfcertification" in err: + continue return last @@ -274,6 +347,11 @@ async def ensure_ypp_and_monetize( proxy_url=proxy_url, ) out["monetized"] = bool(mon.get("ok")) + if mon.get("ok"): + verify = await verify_video_monetized(access_token=access, video_id=video_id, proxy_url=proxy_url) + out["monetize_verified"] = bool(verify.get("monetized")) + if verify.get("monetized"): + out["monetized"] = True if not mon.get("ok"): out["monetize_error"] = str(mon.get("error") or "")[:300] return out diff --git a/frontend/src/app/shorts/page.tsx b/frontend/src/app/shorts/page.tsx index 838f69b..8f129e8 100644 --- a/frontend/src/app/shorts/page.tsx +++ b/frontend/src/app/shorts/page.tsx @@ -31,8 +31,7 @@ import { import { UploadTimeline } from "@/components/UploadTimeline"; import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge"; import { YtChannelProfileSnippet, type YtProfileSnippet } from "@/components/YtChannelProfileSnippet"; -import type { YtChannelMeta } from "@/components/YtChannelMetaBadges"; -import { brandHintForChannel } from "@/lib/ytBrandHints"; +import { buildChannelMeta } from "@/lib/ytChannelMeta"; import { SessionCharts, type RelayStats } from "@/components/SessionCharts"; import { PageLoader, TableSkeleton } from "@/components/ui"; import { fetchJson, fmtDuration, fmtTs, todayBeijingISO, shiftBeijingISO } from "@/lib/api"; @@ -89,6 +88,7 @@ type BoardChannel = { ypp_ok?: number; oauth_ok?: number; oauth_error?: string; + brand_hint?: string; note?: string; last_status?: string; last_title?: string; @@ -403,21 +403,9 @@ export default function ShortsPage() { oauth_error?: string; }>; - function channelMeta(ch: BoardChannel): YtChannelMeta { + function channelMeta(ch: BoardChannel) { const issue = oauthIssues.find((x) => x.id === ch.id); - const oauthBad = Boolean(issue); - const staleReauth = Boolean( - ch.authorized && issue?.oauth_error?.includes("重授权中"), - ); - return { - enabled: ch.enabled, - authorized: ch.authorized, - oauthOk: staleReauth ? 1 : oauthBad ? 0 : ch.oauth_ok, - oauthError: issue?.oauth_error || ch.oauth_error, - brandHint: brandHintForChannel(ch.yt_profile, ch.youtube_channel_id, ch.note), - yppOk: ch.ypp_ok, - oauthProfileId: ch.oauth_profile_id, - }; + return buildChannelMeta(ch, issue); } async function probeOauth() { @@ -464,9 +452,15 @@ export default function ShortsPage() { const needHandle = String(board?.yt_profile?.custom_url || "").trim(); const hasBound = Boolean(String(full?.youtube_channel_id || board?.youtube_channel_id || "").trim()); if (hasBound && needTitle) { + const hint = buildChannelMeta({ + yt_profile: board?.yt_profile, + youtube_channel_id: full?.youtube_channel_id || board?.youtube_channel_id, + note: full?.note || board?.note, + brand_hint: board?.brand_hint, + }).brandHint; const ok = window.confirm( `本卡需要的 YouTube 频道:\n${needTitle}${needHandle ? ` ${needHandle}` : ""}\n\n` + - `Google 授权页请选品牌账号:${brandHintForChannel(board?.yt_profile, full?.youtube_channel_id || board?.youtube_channel_id, full?.note || board?.note) || "(见卡片 Google·… 提示)"}\n\n` + + `Google 授权页请选品牌账号:${hint || "(见卡片 Google·… 提示)"}\n\n` + `Google 品牌账号名可能和上面不一样;点错了页面会提示,不会写入。\n\n继续?` ); if (!ok) return; diff --git a/frontend/src/app/youtube/page.tsx b/frontend/src/app/youtube/page.tsx index b1d2f94..6c371ea 100644 --- a/frontend/src/app/youtube/page.tsx +++ b/frontend/src/app/youtube/page.tsx @@ -25,6 +25,7 @@ import { useToast } from "@/components/Toast"; import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge"; import { YtAssignPanel } from "@/components/YtAssignPanel"; import { YtChannelProfileSnippet } from "@/components/YtChannelProfileSnippet"; +import { buildChannelMeta } from "@/lib/ytChannelMeta"; import { fetchJson, fmtTs } from "@/lib/api"; import { shortsLiveRef } from "@/lib/youtubeLive"; @@ -40,6 +41,8 @@ type ManagedChannel = { oauth_profile_id?: string; oauth_ok?: number; oauth_error?: string; + brand_hint?: string; + note?: string; ypp_ok?: number; daily_min?: number; daily_max?: number; @@ -343,14 +346,7 @@ export default function YouTubePage() { fallbackName={c.title || c.name} fallbackChannelId={c.youtube_channel_id || c.custom_url} liveChannelPk={c.id} - meta={{ - enabled: c.enabled, - authorized: c.authorized, - oauthOk: c.oauth_ok, - oauthError: c.oauth_error, - yppOk: c.ypp_ok, - oauthProfileId: c.oauth_profile_id, - }} + meta={buildChannelMeta(c)} /> ); diff --git a/frontend/src/app/yt-long/page.tsx b/frontend/src/app/yt-long/page.tsx index ebe27ce..8545c83 100644 --- a/frontend/src/app/yt-long/page.tsx +++ b/frontend/src/app/yt-long/page.tsx @@ -19,7 +19,7 @@ import { useConfirm } from "@/components/ConfirmDialog"; import { useToast } from "@/components/Toast"; import { OauthClientBadge, normalizeOauthProfileId } from "@/components/OauthClientBadge"; import { YtChannelProfileSnippet, type YtProfileSnippet } from "@/components/YtChannelProfileSnippet"; -import type { YtChannelMeta } from "@/components/YtChannelMetaBadges"; +import { buildChannelMeta } from "@/lib/ytChannelMeta"; import { PageLoader, TableSkeleton } from "@/components/ui"; import { fetchJson, fmtTs, todayBeijingISO } from "@/lib/api"; @@ -58,6 +58,8 @@ type BoardChannel = { monetize_default?: boolean; oauth_ok?: number; oauth_error?: string; + brand_hint?: string; + note?: string; source_shorts_channel_pk?: string; yt_profile?: YtProfileSnippet | null; }; @@ -667,14 +669,7 @@ export default function YtLongPage() { fallbackName={ch.name} fallbackChannelId={ch.youtube_channel_id} liveChannelPk={ch.source_shorts_channel_pk || undefined} - meta={{ - enabled: ch.enabled, - authorized: ch.authorized, - oauthOk: ch.oauth_ok, - oauthError: ch.oauth_error, - yppOk: ch.ypp_ok, - oauthProfileId: ch.oauth_profile_id, - }} + meta={buildChannelMeta(ch)} /> diff --git a/frontend/src/components/YtAssignPanel.tsx b/frontend/src/components/YtAssignPanel.tsx index 2c0d02e..904bbea 100644 --- a/frontend/src/components/YtAssignPanel.tsx +++ b/frontend/src/components/YtAssignPanel.tsx @@ -19,6 +19,7 @@ import { useConfirm } from "@/components/ConfirmDialog"; import { ImageLightbox } from "@/components/ImageLightbox"; import { useToast } from "@/components/Toast"; import { YtChannelProfileSnippet, type YtProfileSnippet } from "@/components/YtChannelProfileSnippet"; +import { buildChannelMeta } from "@/lib/ytChannelMeta"; import { fetchJson } from "@/lib/api"; type ManagedChannel = { @@ -29,6 +30,8 @@ type ManagedChannel = { oauth_profile_id?: string; oauth_ok?: number; oauth_error?: string; + brand_hint?: string; + note?: string; ypp_ok?: number; last_status?: string; title?: string; @@ -136,18 +139,7 @@ function ManageStyleProfileCard({ fallbackName={fallbackName} fallbackChannelId={fallbackChannelId} liveChannelPk={channelPk} - meta={ - channel - ? { - enabled: true, - authorized: channel.authorized, - oauthOk: channel.oauth_ok, - oauthError: channel.oauth_error, - yppOk: channel.ypp_ok, - oauthProfileId: channel.oauth_profile_id, - } - : undefined - } + meta={channel ? buildChannelMeta(channel) : undefined} /> ); @@ -644,18 +636,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) { fallbackName={g.name} fallbackChannelId={g.youtube_channel_id} liveChannelPk={pk || undefined} - meta={ - ch - ? { - enabled: true, - authorized: ch.authorized, - oauthOk: ch.oauth_ok, - oauthError: ch.oauth_error, - yppOk: ch.ypp_ok, - oauthProfileId: ch.oauth_profile_id, - } - : undefined - } + meta={ch ? buildChannelMeta(ch) : undefined} />
池 {(g.pool || []).length} diff --git a/frontend/src/lib/ytBrandHints.ts b/frontend/src/lib/ytBrandHints.ts index 030e1a8..697fd28 100644 --- a/frontend/src/lib/ytBrandHints.ts +++ b/frontend/src/lib/ytBrandHints.ts @@ -6,8 +6,18 @@ export const YT_OAUTH_BRAND_BY_HANDLE: Record = { "@evanstreetfood": "Nhat Vy", "@nomadvloglife": "Lyca Hack", "@walkingtour-c8t": "walking tour", + "@hackrobotlite": "hackrobot-jp", }; +const TITLE_BRAND: Array<[string, string]> = [ + ["nomad vlog", "Lyca Hack"], + ["nomad street food", "hackrobot-jp"], + ["nomadro hub", "nomad Immigration"], + ["异度世界", "digitl nomad"], + ["nomdfsfbjksfbsjk", "digitl nomad"], + ["evan", "Nhat Vy"], +]; + export function normalizeYtHandle(raw?: string | null): string { const s = String(raw || "").trim(); if (!s) return ""; @@ -16,16 +26,18 @@ export function normalizeYtHandle(raw?: string | null): string { return `@${s.replace(/^@/, "")}`; } -export function brandHintForChannel(profile?: { custom_url?: string; title?: string } | null, fallbackChannelId?: string, note?: string): string { +export function brandHintForChannel( + profile?: { custom_url?: string; title?: string } | null, + fallbackChannelId?: string, + note?: string, +): string { const fromNote = String(note || "").match(/Google品牌[::]\s*(.+)/i)?.[1]?.trim(); - if (fromNote) return fromNote; + if (fromNote) return fromNote.split("\n")[0].trim(); const handle = normalizeYtHandle(profile?.custom_url || fallbackChannelId); if (handle && YT_OAUTH_BRAND_BY_HANDLE[handle]) return YT_OAUTH_BRAND_BY_HANDLE[handle]; const title = String(profile?.title || "").trim().toLowerCase(); - if (title.includes("nomad vlog")) return "Lyca Hack"; - if (title.includes("nomad street food")) return "hackrobot-jp"; - if (title.includes("nomadro hub")) return "nomad Immigration"; - if (title.includes("walking tour")) return "walking tour"; - if (title.includes("nomdfsfbjksfbsjk")) return "digitl nomad"; + for (const [key, brand] of TITLE_BRAND) { + if (title.includes(key)) return brand; + } return ""; } diff --git a/frontend/src/lib/ytChannelMeta.ts b/frontend/src/lib/ytChannelMeta.ts new file mode 100644 index 0000000..8c5bd69 --- /dev/null +++ b/frontend/src/lib/ytChannelMeta.ts @@ -0,0 +1,37 @@ +import type { YtChannelMeta } from "@/components/YtChannelMetaBadges"; +import { brandHintForChannel } from "@/lib/ytBrandHints"; +import type { YtProfileSnippet } from "@/components/YtChannelProfileSnippet"; + +export type ChannelMetaInput = { + id?: string; + enabled?: boolean; + authorized?: boolean; + oauth_ok?: number | boolean | null; + oauth_error?: string; + oauth_profile_id?: string; + youtube_channel_id?: string; + note?: string; + brand_hint?: string; + ypp_ok?: number | null; + yt_profile?: YtProfileSnippet | null; +}; + +export function buildChannelMeta( + ch: ChannelMetaInput, + oauthIssue?: { oauth_error?: string } | null, +): YtChannelMeta { + const staleReauth = Boolean(ch.authorized && (ch.oauth_error || "").includes("重授权中")); + const oauthBad = Boolean(oauthIssue) && !staleReauth; + const brandHint = + String(ch.brand_hint || "").trim() || + brandHintForChannel(ch.yt_profile, ch.youtube_channel_id, ch.note); + return { + enabled: ch.enabled, + authorized: ch.authorized, + oauthOk: staleReauth ? 1 : oauthBad ? 0 : ch.oauth_ok, + oauthError: oauthIssue?.oauth_error || ch.oauth_error, + brandHint, + yppOk: ch.ypp_ok, + oauthProfileId: ch.oauth_profile_id, + }; +}