feat: unified YouTube channel cards with live/YPP/OAuth meta and auto YPP probe on re-auth

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-22 01:03:20 -05:00
parent ee1250c724
commit 6851984983
12 changed files with 341 additions and 41 deletions

View File

@ -535,6 +535,26 @@ async def shorts_live_analytics(
top_anchors=top_anchors,
)
channels = db.shorts_live_channel_stats(date_from=date_from, date_to=date_to)
ypp_by_shorts: dict[str, int] = {}
try:
from . import yt_long_db, youtube_manage
ypp_by_shorts = yt_long_db.ypp_ok_by_shorts_pk()
enriched = []
for c in channels:
row = dict(c)
pk = str(row.get("id") or "")
if pk:
ch = db.get_shorts_channel(pk) or {}
row["yt_profile"] = youtube_manage._snippet_from_channel_row(ch)
row["authorized"] = bool(str(ch.get("refresh_token") or "").strip())
row["oauth_ok"] = ch.get("oauth_ok")
row["oauth_profile_id"] = str(ch.get("oauth_profile_id") or "").strip().upper()
row["ypp_ok"] = ypp_by_shorts.get(pk, -1)
enriched.append(row)
channels = enriched
except Exception:
pass
recent = db.list_sessions(platform="shorts", limit=20, offset=0)
live_now = sum(1 for c in channels if int(c.get("active") or 0) > 0 or str(c.get("last_status") or "") == "live")
return {
@ -1352,6 +1372,14 @@ async def yt_long_channels_import_shorts() -> dict[str, Any]:
return {"ok": True, **result}
@app.post("/api/yt-long/channels/probe-ypp")
async def yt_long_channels_probe_ypp(limit: int = Query(50, ge=1, le=200)) -> dict[str, Any]:
"""Refresh YPP flags for yt_long channels linked to Shorts OAuth."""
from .yt_long_monetize import refresh_all_ypp_from_shorts
return await refresh_all_ypp_from_shorts(limit=limit)
@app.post("/api/yt-long/channels")
async def yt_long_channels_create(body: dict[str, Any] | None = None) -> dict[str, Any]:
from . import yt_long_db

View File

@ -340,6 +340,14 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
if yt_title and (not name or name.startswith("Shorts") or name == "未命名频道"):
patch["name"] = yt_title
updated = db.update_shorts_channel(channel_pk, **patch)
try:
from . import youtube_manage as ytm
from .yt_long_monetize import refresh_ypp_for_shorts_channel
await ytm.fetch_channel_profile(channel_pk)
await refresh_ypp_for_shorts_channel(channel_pk)
except Exception:
pass
return {
"ok": True,
"channel": updated,

View File

@ -213,6 +213,14 @@ def schedule_board(limit: int = 24) -> dict[str, Any]:
from .db import SHORTS_DAILY_FORCE, _normalize_daily_quota
from .upload_timeline import build_timeline
ypp_by_shorts = {}
try:
from . import yt_long_db
ypp_by_shorts = yt_long_db.ypp_ok_by_shorts_pk()
except Exception:
ypp_by_shorts = {}
for c in channels:
cid = str(c["id"])
daily_min = _normalize_daily_quota(c.get("daily_min"), default=SHORTS_DAILY_FORCE)
@ -243,6 +251,12 @@ def schedule_board(limit: int = 24) -> dict[str, Any]:
"max_met": used >= daily_max,
"behind_pace": bool(c.get("enabled") and used < expected_min and used < daily_min),
"yt_profile": youtube_manage._snippet_from_channel_row(c),
"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 ""),
"ypp_ok": ypp_by_shorts.get(cid, -1),
**stats,
}
)

View File

@ -104,9 +104,17 @@ async def _delete(path: str, *, token: str, params: dict[str, Any]) -> None:
def list_managed_channels() -> list[dict[str, Any]]:
rows = db.list_shorts_channels()
ypp_by_shorts: dict[str, int] = {}
try:
from . import yt_long_db
ypp_by_shorts = yt_long_db.ypp_ok_by_shorts_pk()
except Exception:
ypp_by_shorts = {}
out = []
for ch in rows:
sn = _snippet_from_channel_row(ch) or {}
cid = str(ch.get("id") or "")
out.append(
{
"id": ch.get("id"),
@ -114,6 +122,13 @@ def list_managed_channels() -> list[dict[str, Any]]:
"youtube_channel_id": ch.get("youtube_channel_id") or sn.get("youtube_channel_id") or "",
"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 ""),
"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 ""),
"ypp_ok": ypp_by_shorts.get(cid, -1),
"daily_min": ch.get("daily_min"),
"daily_max": ch.get("daily_max"),
"privacy": ch.get("privacy"),

View File

@ -1099,6 +1099,45 @@ def import_channels_from_shorts() -> dict[str, Any]:
return sync_channels_from_shorts()
def ypp_ok_by_shorts_pk() -> dict[str, int]:
"""Map shorts channel pk -> yt_long ypp_ok (-1/0/1)."""
out: dict[str, int] = {}
with _lock:
conn = _connect()
try:
ensure_yt_long_tables(conn)
for row in conn.execute(
"SELECT source_shorts_channel_pk, ypp_ok FROM yt_long_channels WHERE source_shorts_channel_pk != ''"
).fetchall():
pk = str(row["source_shorts_channel_pk"] or "").strip()
if not pk:
continue
try:
out[pk] = int(row["ypp_ok"] if row["ypp_ok"] is not None else -1)
except Exception:
out[pk] = -1
finally:
conn.close()
return out
def get_yt_long_by_shorts_pk(shorts_pk: str) -> dict[str, Any] | None:
pk = str(shorts_pk or "").strip()
if not pk:
return None
with _lock:
conn = _connect()
try:
ensure_yt_long_tables(conn)
row = conn.execute(
"SELECT * FROM yt_long_channels WHERE source_shorts_channel_pk = ? LIMIT 1",
(pk,),
).fetchone()
return dict(row) if row else None
finally:
conn.close()
def public_yt_long_channel(ch: dict[str, Any] | None) -> dict[str, Any] | None:
if not ch:

View File

@ -247,6 +247,12 @@ async def ensure_ypp_and_monetize(
pass
want = ypp if force_monetize is None else bool(force_monetize)
if not want and int((channel_row or {}).get("monetize_default") or 1) == 1:
try:
if int((channel_row or {}).get("ypp_ok") or -1) == 1:
want = True
except Exception:
pass
if not want:
out["skipped"] = "not_ypp"
return out
@ -271,3 +277,66 @@ async def ensure_ypp_and_monetize(
if not mon.get("ok"):
out["monetize_error"] = str(mon.get("error") or "")[:300]
return out
async def refresh_ypp_for_shorts_channel(shorts_pk: str) -> dict[str, Any]:
"""Probe YPP via OAuth and update linked yt_long_channels row."""
from . import db as appdb
from . import yt_long_db as yldb
from .shorts_oauth import channel_oauth_creds
pk = str(shorts_pk or "").strip()
if not pk:
return {"ok": False, "error": "no_pk"}
row = yldb.get_yt_long_by_shorts_pk(pk)
ch = appdb.get_shorts_channel(pk) or {}
creds = channel_oauth_creds(ch if ch else (row or {}))
if not (creds.get("refresh_token") and creds.get("client_id") and creds.get("client_secret")):
return {"ok": False, "error": "no_oauth", "shorts_pk": pk}
try:
access = await refresh_access_token(
client_id=str(creds["client_id"]),
client_secret=str(creds["client_secret"]),
refresh_token=str(creds["refresh_token"]),
)
except Exception as exc:
return {"ok": False, "error": f"token:{exc}"[:200], "shorts_pk": pk}
info = await fetch_channel_ypp_status(access_token=access)
ypp = bool(info.get("ypp"))
yt_id = str(info.get("channel_id") or ch.get("youtube_channel_id") or "").strip()
long_id = str((row or {}).get("id") or "").strip()
if long_id and info.get("ok"):
patch: dict[str, Any] = {
"ypp_ok": 1 if ypp else 0,
"ypp_checked_at": time.time(),
}
if yt_id:
patch["youtube_channel_id"] = yt_id
yldb.update_yt_long_channel(long_id, **patch)
return {
"ok": bool(info.get("ok")),
"ypp": ypp,
"shorts_pk": pk,
"yt_long_pk": long_id,
"youtube_channel_id": yt_id,
"error": info.get("error"),
}
async def refresh_all_ypp_from_shorts(*, limit: int = 50) -> dict[str, Any]:
from . import db as appdb
from . import yt_long_db as yldb
rows = appdb.list_shorts_channels(enabled=None)
results: list[dict[str, Any]] = []
ypp_count = 0
for ch in rows[: max(1, min(limit, 200))]:
if not str(ch.get("refresh_token") or "").strip():
continue
if not yldb.get_yt_long_by_shorts_pk(str(ch.get("id") or "")):
continue
r = await refresh_ypp_for_shorts_channel(str(ch.get("id") or ""))
results.append(r)
if r.get("ypp"):
ypp_count += 1
return {"probed": len(results), "ypp_channels": ypp_count, "results": results}

View File

@ -31,6 +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 { SessionCharts, type RelayStats } from "@/components/SessionCharts";
import { PageLoader, TableSkeleton } from "@/components/ui";
import { fetchJson, fmtDuration, fmtTs, todayBeijingISO, shiftBeijingISO } from "@/lib/api";
@ -84,6 +85,12 @@ type BoardChannel = {
max_met?: boolean;
behind_pace?: boolean;
yt_profile?: YtProfileSnippet | null;
ypp_ok?: number;
oauth_ok?: number;
oauth_error?: string;
last_status?: string;
last_title?: string;
last_live_url?: string;
};
type Job = {
@ -394,6 +401,18 @@ export default function ShortsPage() {
oauth_error?: string;
}>;
function channelMeta(ch: BoardChannel): YtChannelMeta {
const oauthBad = oauthIssues.some((x) => x.id === ch.id);
return {
enabled: ch.enabled,
authorized: ch.authorized,
oauthOk: oauthBad ? 0 : ch.oauth_ok,
oauthError: oauthBad ? oauthIssues.find((x) => x.id === ch.id)?.oauth_error : ch.oauth_error,
yppOk: ch.ypp_ok,
oauthProfileId: ch.oauth_profile_id,
};
}
async function probeOauth() {
setBusy(true);
try {
@ -755,12 +774,22 @@ export default function ShortsPage() {
{liveChannels.map((ch) => (
<tr key={String(ch.id || ch.room_id)} className="border-t border-white/5">
<td className="px-3 py-2">
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium text-slate-100">{ch.name || "—"}</span>
{ch.id ? <YouTubeLiveBadge refKey={shortsLiveRef(ch.id)} compact showOffline /> : null}
</div>
<div className="font-mono text-[10px] text-slate-500">{ch.youtube_channel_id || "—"}</div>
{ch.last_title ? <div className="mt-0.5 max-w-[280px] truncate text-[11px] text-slate-500">{ch.last_title}</div> : null}
<YtChannelProfileSnippet
profile={ch.yt_profile}
fallbackName={ch.name}
fallbackChannelId={ch.youtube_channel_id}
liveChannelPk={ch.id || undefined}
meta={{
enabled: ch.enabled,
authorized: ch.authorized,
yppOk: ch.ypp_ok,
oauthProfileId: ch.oauth_profile_id,
}}
metaLayout="row"
/>
{ch.last_title ? (
<div className="mt-0.5 max-w-[280px] truncate text-[11px] text-slate-500">{ch.last_title}</div>
) : null}
</td>
<td className="px-3 py-2">
<span className={Number(ch.active) > 0 || ch.last_status === "live" ? "text-rose-300" : "text-slate-500"}>
@ -1160,29 +1189,9 @@ export default function ShortsPage() {
fallbackName={ch.name}
fallbackChannelId={ch.youtube_channel_id}
liveChannelPk={ch.id}
trailing={<OauthClientBadge profileId={ch.oauth_profile_id} size="sm" />}
meta={channelMeta(ch)}
/>
</div>
<div className="flex shrink-0 flex-col items-end gap-1 text-[10px]">
<span className={ch.enabled === false ? "text-slate-500" : "text-teal-300"}>
{ch.enabled === false ? "停用" : "启用"}
</span>
<span
className={
oauthIssues.some((x) => x.id === ch.id)
? "text-rose-300"
: ch.authorized
? "text-teal-300"
: "text-amber-300"
}
>
{oauthIssues.some((x) => x.id === ch.id)
? "OAuth 异常"
: ch.authorized
? "已授权"
: "未授权"}
</span>
</div>
</div>
<div className="relative mt-3 h-1.5 overflow-hidden rounded-full bg-white/10">
<div

View File

@ -37,6 +37,10 @@ type ManagedChannel = {
youtube_channel_id?: string;
enabled?: boolean;
authorized?: boolean;
oauth_profile_id?: string;
oauth_ok?: number;
oauth_error?: string;
ypp_ok?: number;
daily_min?: number;
daily_max?: number;
title?: string;
@ -339,6 +343,14 @@ 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,
}}
/>
</button>
);

View File

@ -19,6 +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 { PageLoader, TableSkeleton } from "@/components/ui";
import { fetchJson, fmtTs, todayBeijingISO } from "@/lib/api";
@ -55,6 +56,8 @@ type BoardChannel = {
gap?: number;
ypp_ok?: number;
monetize_default?: boolean;
oauth_ok?: number;
oauth_error?: string;
source_shorts_channel_pk?: string;
yt_profile?: YtProfileSnippet | null;
};
@ -664,22 +667,16 @@ export default function YtLongPage() {
fallbackName={ch.name}
fallbackChannelId={ch.youtube_channel_id}
liveChannelPk={ch.source_shorts_channel_pk || undefined}
trailing={<OauthClientBadge profileId={ch.oauth_profile_id} size="sm" />}
meta={{
enabled: ch.enabled,
authorized: ch.authorized,
oauthOk: ch.oauth_ok,
oauthError: ch.oauth_error,
yppOk: ch.ypp_ok,
oauthProfileId: ch.oauth_profile_id,
}}
/>
</div>
<div className="flex shrink-0 flex-col items-end gap-1 text-[10px]">
<span className={ch.enabled === false ? "text-slate-500" : "text-teal-300"}>
{ch.enabled === false ? "停用" : "启用"}
</span>
<span className={ch.authorized ? "text-teal-300" : "text-amber-300"}>
{ch.authorized ? "已授权" : "未授权"}
</span>
{Number(ch.ypp_ok) === 1 ? (
<span className="text-emerald-300">YPP·默认获利</span>
) : Number(ch.ypp_ok) === 0 ? (
<span className="text-slate-500">非YPP</span>
) : null}
</div>
</div>
<div className="relative mt-3 h-1.5 overflow-hidden rounded-full bg-white/10">
<div

View File

@ -26,6 +26,11 @@ type ManagedChannel = {
name?: string;
youtube_channel_id?: string;
authorized?: boolean;
oauth_profile_id?: string;
oauth_ok?: number;
oauth_error?: string;
ypp_ok?: number;
last_status?: string;
title?: string;
custom_url?: string;
thumb_url?: string;
@ -116,11 +121,13 @@ function ManageStyleProfileCard({
channelPk,
fallbackName,
fallbackChannelId,
channel,
}: {
profile?: YtProfileSnippet | null;
channelPk?: string;
fallbackName?: string;
fallbackChannelId?: string;
channel?: ManagedChannel | null;
}) {
return (
<div className="rounded-2xl border border-white/10 bg-black/30 p-4">
@ -129,6 +136,18 @@ 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
}
/>
</div>
);
@ -607,6 +626,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
<aside className="space-y-2">
{groups.map((g) => {
const pk = String(g.channel_pk || "");
const ch = channelById[pk];
const active = g.id === groupId;
return (
<button
@ -624,6 +644,18 @@ 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
}
/>
<div className="mt-2 flex flex-wrap gap-2 text-[10px] text-slate-500">
<span>池 {(g.pool || []).length}</span>
@ -642,6 +674,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
channelPk={selected.channel_pk}
fallbackName={selected.name}
fallbackChannelId={selected.youtube_channel_id}
channel={channelById[String(selected.channel_pk || "")] || null}
/>
<section className="rounded-2xl border border-white/10 bg-black/25 p-4">

View File

@ -0,0 +1,65 @@
"use client";
import { OauthClientBadge } from "@/components/OauthClientBadge";
export type YtChannelMeta = {
enabled?: boolean;
authorized?: boolean;
oauthOk?: number | boolean | null;
oauthError?: string;
/** -1 unknown, 0 not YPP, 1 YPP */
yppOk?: number | null;
oauthProfileId?: string;
};
function oauthTone(oauthOk?: number | boolean | null, authorized?: boolean) {
if (oauthOk === 0 || oauthOk === false) return "text-rose-300";
if (authorized) return "text-teal-300";
return "text-amber-300";
}
function oauthLabel(oauthOk?: number | boolean | null, authorized?: boolean) {
if (oauthOk === 0 || oauthOk === false) return "OAuth 异常";
if (authorized) return "已授权";
return "未授权";
}
export function YtChannelMetaBadges({
meta,
layout = "column",
className = "",
}: {
meta?: YtChannelMeta | null;
layout?: "column" | "row";
className?: string;
}) {
if (!meta) return null;
const wrap = layout === "row" ? "flex flex-wrap items-center gap-1.5" : "flex flex-col items-end gap-1";
const badge = "text-[10px] leading-none";
return (
<div className={`${wrap} ${className}`}>
{meta.oauthProfileId ? <OauthClientBadge profileId={meta.oauthProfileId} size="sm" /> : null}
{meta.enabled === false ? (
<span className={`${badge} text-slate-500`}>停用</span>
) : meta.enabled === true ? (
<span className={`${badge} text-teal-300`}>启用</span>
) : null}
<span
className={`${badge} ${oauthTone(meta.oauthOk, meta.authorized)}`}
title={meta.oauthError || undefined}
>
{oauthLabel(meta.oauthOk, meta.authorized)}
</span>
{meta.yppOk === 1 ? (
<span className={`${badge} text-emerald-300`} title="YouTube Partner Program · 上传后自动开广告获利">
YPP·获利
</span>
) : meta.yppOk === 0 ? (
<span className={`${badge} text-slate-500`}>非 YPP</span>
) : meta.yppOk === -1 || meta.yppOk === undefined ? (
<span className={`${badge} text-slate-600`}>YPP 未检测</span>
) : null}
</div>
);
}

View File

@ -3,6 +3,7 @@
import { useState, type ReactNode } from "react";
import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge";
import { YtChannelMetaBadges, type YtChannelMeta } from "@/components/YtChannelMetaBadges";
import { shortsLiveRef } from "@/lib/youtubeLive";
export type YtProfileSnippet = {
@ -75,6 +76,8 @@ export function YtChannelProfileSnippet({
fallbackChannelId,
liveChannelPk,
trailing,
meta,
metaLayout = "column",
className = "",
}: {
profile?: YtProfileSnippet | null;
@ -82,6 +85,8 @@ export function YtChannelProfileSnippet({
fallbackChannelId?: string;
liveChannelPk?: string;
trailing?: ReactNode;
meta?: YtChannelMeta | null;
metaLayout?: "column" | "row";
className?: string;
}) {
const ytName = String(profile?.title || "").trim();
@ -120,7 +125,13 @@ export function YtChannelProfileSnippet({
<div className="mt-0.5 text-[11px] text-slate-500">
订阅 {stats?.subscriberCount ?? "—"} · 视频 {stats?.videoCount ?? "—"} · 播放 {stats?.viewCount ?? "—"}
</div>
{meta && metaLayout === "row" ? (
<div className="mt-1.5">
<YtChannelMetaBadges meta={meta} layout="row" />
</div>
) : null}
</div>
{meta && metaLayout === "column" ? <YtChannelMetaBadges meta={meta} layout="column" /> : null}
</div>
);
}