"use client"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import Link from "next/link"; import { Clock3, Eye, KeyRound, Loader2, Plus, RefreshCw, RotateCcw, Trash2, Upload, Video, Wrench, } from "lucide-react"; import { DouyinLiveBadge } from "@/components/DouyinLiveBadge"; import { DailyQuotaGlobalCard } from "@/components/DailyQuotaGlobalCard"; import { EnableSwitch } from "@/components/EnableSwitch"; import { Shell } from "@/components/Shell"; import { useConfirm } from "@/components/ConfirmDialog"; import { useToast } from "@/components/Toast"; import { GoogleOauthSetupWizard, defaultShortsRedirectUri } from "@/components/GoogleOauthSetupWizard"; import { OauthClientBadge, normalizeOauthProfileId } from "@/components/OauthClientBadge"; import { ShortsJobDetailModal } from "@/components/ShortsJobDetailModal"; import { ShortsUploadConfirmModal, ShortsUpcomingUploadRow, useShortsUpload, type ShortsUploadTarget, } from "@/components/ShortsUploadUx"; import { UploadTimeline } from "@/components/UploadTimeline"; import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge"; import { YtChannelProfileSnippet, type YtProfileSnippet } from "@/components/YtChannelProfileSnippet"; 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"; import { shortsLiveRef, useYouTubeLiveMap } from "@/lib/youtubeLive"; import { useLiveFocusScroll } from "@/lib/useLiveFocusScroll"; import { ytLiveShortsDomId } from "@/lib/youtubeLiveNav"; type Channel = { id: string; name: string; youtube_channel_id?: string; enabled?: boolean; daily_min?: number; daily_max?: number; title_template?: string; description_template?: string; privacy?: string; note?: string; authorized?: boolean; has_refresh_token?: boolean; client_id?: string; has_client_id?: boolean; has_client_secret?: boolean; has_custom_oauth?: boolean; can_authorize?: boolean; oauth_profile_id?: string; oauth_profile_label?: string; oauth_client_source?: "profile" | "channel" | "global" | "none" | string; }; type OauthProfile = { id: string; label?: string; email?: string; client_id?: string; configured?: boolean; }; type BoardChannel = { id: string; name?: string; youtube_channel_id?: string; oauth_profile_id?: string; enabled?: boolean; daily_min: number; daily_max: number; authorized?: boolean; used: number; scheduled: number; uploaded: number; pending: number; gap?: number; min_met?: boolean; max_met?: boolean; behind_pace?: boolean; yt_profile?: YtProfileSnippet | null; ypp_ok?: number; oauth_ok?: number; oauth_error?: string; brand_hint?: string; note?: string; last_status?: string; last_title?: string; last_live_url?: string; }; type Job = { id: string; status: string; anchor_name?: string; room_id?: string; push_date?: string; channel_pk?: string; clip_path?: string; clip_ready?: boolean; youtube_url?: string; error?: string; created_at?: number; upload_at?: number; }; const emptyForm = { name: "", enabled: true, daily_min: 9, daily_max: 9, title_template: "{anchor} 直播瞬间 #Shorts", description_template: "{anchor}\n{url}\n#Shorts #直播", privacy: "public", note: "", /** A/B/C/D from settings.shorts_oauth_profiles */ oauth_profile_id: "A", }; const STATUS_STYLE: Record = { pending: "bg-slate-500/20 text-slate-200", recording: "bg-sky-500/20 text-sky-100", recorded: "bg-indigo-500/20 text-indigo-100", scheduled: "bg-amber-500/20 text-amber-100", uploading: "bg-violet-500/20 text-violet-100", uploaded: "bg-teal-500/20 text-teal-100", failed: "bg-rose-500/20 text-rose-100", skipped: "bg-white/10 text-slate-400", }; const JOB_PAGE = 50; export default function ShortsPage() { const confirm = useConfirm(); const toast = useToast(); const [pageTab, setPageTab] = useState<"ops" | "live">("ops"); const [status, setStatus] = useState | null>(null); const leftPanelRef = useRef(null); const rightPanelRef = useRef(null); const [channels, setChannels] = useState([]); const [jobs, setJobs] = useState([]); const [jobTotal, setJobTotal] = useState(0); const [form, setForm] = useState({ ...emptyForm }); const [editId, setEditId] = useState(""); const [busy, setBusy] = useState(false); const [togglingId, setTogglingId] = useState(""); const [msg, setMsg] = useState(""); const [error, setError] = useState(""); const [jobFilter, setJobFilter] = useState(""); const [jobChannel, setJobChannel] = useState(""); const [liveStats, setLiveStats] = useState(null); const [liveChannels, setLiveChannels] = useState([]); const [liveRecent, setLiveRecent] = useState([]); const [liveNow, setLiveNow] = useState(0); const [liveBusy, setLiveBusy] = useState(false); const [liveFrom, setLiveFrom] = useState(() => shiftBeijingISO(todayBeijingISO(), -29)); const [liveTo, setLiveTo] = useState(() => todayBeijingISO()); const [jobDate, setJobDate] = useState(""); const [selectedIds, setSelectedIds] = useState>({}); const [detailJobId, setDetailJobId] = useState(null); const [showWizard, setShowWizard] = useState(false); const [showForm, setShowForm] = useState(false); const [loading, setLoading] = useState(true); const [loadingMoreJobs, setLoadingMoreJobs] = useState(false); const [focusChannelId, setFocusChannelId] = useState(null); const [liveOnlyFilter, setLiveOnlyFilter] = useState(false); const { map: ytLiveMap } = useYouTubeLiveMap(); const load = useCallback( async (opts?: { appendJobs?: boolean; jobOffset?: number }) => { const appendJobs = Boolean(opts?.appendJobs); if (appendJobs) setLoadingMoreJobs(true); else setLoading(true); try { const off = appendJobs ? Number(opts?.jobOffset ?? 0) : 0; const jobQs = new URLSearchParams({ limit: String(JOB_PAGE), offset: String(off) }); if (jobFilter) jobQs.set("status", jobFilter); if (jobChannel) jobQs.set("channel_pk", jobChannel); if (jobDate) jobQs.set("push_date", jobDate); if (appendJobs) { const jb = await fetchJson(`/api/shorts/jobs?${jobQs}`); const rows = jb.jobs || []; setJobs((prev) => [...prev, ...rows]); setJobTotal(jb.total || 0); } else { const [st, ch, jb] = await Promise.all([ fetchJson("/api/shorts/status"), fetchJson("/api/shorts/channels"), fetchJson(`/api/shorts/jobs?${jobQs}`), ]); setStatus(st); setChannels(ch.channels || []); setJobs(jb.jobs || []); setJobTotal(jb.total || 0); setSelectedIds({}); if (!st?.oauth_configured) setShowWizard(true); } } catch (e) { setError((e as Error).message); toast.push((e as Error).message, "err"); } finally { setLoading(false); setLoadingMoreJobs(false); } }, [jobChannel, jobDate, jobFilter, toast], ); const uploadUx = useShortsUpload(load); const loadLiveAnalytics = useCallback(async () => { setLiveBusy(true); try { const p = new URLSearchParams({ top_anchors: "25" }); if (liveFrom) p.set("date_from", liveFrom); if (liveTo) p.set("date_to", liveTo); const data = await fetchJson(`/api/shorts/live-analytics?${p}`); setLiveStats((data.stats || null) as RelayStats | null); setLiveChannels(data.channels || []); setLiveRecent(data.recent_sessions || []); setLiveNow(Number(data.live_now || 0)); } catch (e) { setError((e as Error).message); } finally { setLiveBusy(false); } }, [liveFrom, liveTo]); useEffect(() => { void load(); let tick = 0; const t = setInterval(() => { if (pageTab !== "ops" || document.hidden) return; tick += 1; // Every poll: light status; channels+jobs every other tick (~40s). if (tick % 2 === 0) { void load(); } else { void fetchJson("/api/shorts/status?light=1") .then((st) => setStatus((prev) => ({ ...(prev || {}), ...st, board: st.board ?? prev?.board, history: st.history ?? prev?.history, failed_groups: st.failed_groups ?? prev?.failed_groups, channel_perf: st.channel_perf ?? prev?.channel_perf, heatmap: st.heatmap ?? prev?.heatmap, oauth_profiles: st.oauth_profiles ?? prev?.oauth_profiles, })), ) .catch(() => undefined); } }, 20000); const onVis = () => { if (!document.hidden && pageTab === "ops") void load(); }; document.addEventListener("visibilitychange", onVis); return () => { clearInterval(t); document.removeEventListener("visibilitychange", onVis); }; }, [load, pageTab]); // Sync right panel height to left panel useEffect(() => { const left = leftPanelRef.current; const right = rightPanelRef.current; if (!left || !right) return; const sync = () => { const h = left.getBoundingClientRect().height; right.style.maxHeight = `${h}px`; }; sync(); const ro = new ResizeObserver(sync); ro.observe(left); return () => ro.disconnect(); }); useEffect(() => { if (pageTab !== "live") return; void loadLiveAnalytics(); const t = setInterval(() => { if (document.hidden) return; void loadLiveAnalytics(); }, 30000); return () => clearInterval(t); }, [pageTab, loadLiveAnalytics]); useEffect(() => { if (typeof window === "undefined") return; const sp = new URLSearchParams(window.location.search); if (sp.get("tab") === "live") setPageTab("live"); const focus = sp.get("focus"); if (focus) { setFocusChannelId(focus); setPageTab("ops"); } if (sp.get("live") === "1") setLiveOnlyFilter(true); const oauth = sp.get("oauth"); if (!oauth) return; if (oauth === "ok") { const title = sp.get("title") || ""; const handle = sp.get("handle") || ""; setMsg(`Google 授权成功${title ? `:${title}` : ""}${handle ? ` ${handle}` : ""}`); const dupMsg = sp.get("dup_msg") || ""; if (sp.get("dup") === "1" && dupMsg) { toast.push(dupMsg, "err"); } void load(); } else if (oauth === "error") { const raw = sp.get("msg") || "授权失败"; setError(raw); toast.push(raw, "err"); void load(); } window.history.replaceState({}, "", "/shorts"); }, [load]); const boardChannels: BoardChannel[] = status?.board?.channels || []; const upcoming = status?.board?.upcoming || []; const beijingWindow = status?.board?.beijing_window || status?.stats?.push_date || ""; const quotaGap = Number(status?.quota_gap ?? status?.board?.total_gap ?? 0); const minUnmet = Number(status?.board?.min_unmet_channels ?? 0); const secondsLeft = Number(status?.board?.seconds_left ?? 0); const stats = status?.stats?.by_status || {}; const channelName = useMemo(() => { const m: Record = {}; for (const c of channels) m[c.id] = c.name; for (const c of boardChannels) if (c.name) m[c.id] = c.name; return m; }, [channels, boardChannels]); const channelProfileMap = useMemo(() => { const m: Record = {}; for (const c of channels) m[c.id] = normalizeOauthProfileId(c.oauth_profile_id); for (const c of boardChannels) { const pid = normalizeOauthProfileId(c.oauth_profile_id); if (pid) m[c.id] = pid; } return m; }, [channels, boardChannels]); const displayChannels = useMemo(() => { const base: BoardChannel[] = boardChannels.length ? boardChannels : channels.map((c) => ({ id: c.id, name: c.name, youtube_channel_id: c.youtube_channel_id, oauth_profile_id: c.oauth_profile_id, enabled: c.enabled, daily_min: Number(c.daily_min ?? 9), daily_max: Number(c.daily_max ?? 9), authorized: Boolean(c.authorized || c.has_refresh_token), used: 0, scheduled: 0, uploaded: 0, pending: 0, gap: Number(c.daily_max ?? 9), min_met: false, max_met: false, behind_pace: false, })); return base.map((ch) => ({ ...ch, oauth_profile_id: normalizeOauthProfileId(ch.oauth_profile_id) || channelProfileMap[ch.id] || "", })); }, [boardChannels, channels, channelProfileMap]); const filteredDisplayChannels = useMemo(() => { if (!liveOnlyFilter) return displayChannels; return displayChannels.filter((ch) => ytLiveMap?.entries?.[shortsLiveRef(ch.id)]?.is_live); }, [displayChannels, liveOnlyFilter, ytLiveMap]); useLiveFocusScroll( focusChannelId, "yt-live-shorts-", pageTab === "ops" && !loading && filteredDisplayChannels.some((c) => c.id === focusChannelId), ); const channelGroups = useMemo(() => { const buckets = new Map(); for (const ch of filteredDisplayChannels) { const key = normalizeOauthProfileId(ch.oauth_profile_id) || "_"; const arr = buckets.get(key) || []; arr.push(ch); buckets.set(key, arr); } // Keep card order stable inside each Client group (never sort by used/gap/behind) for (const [k, arr] of buckets) { arr.sort((a, b) => { const an = String(a.name || "").localeCompare(String(b.name || ""), "zh"); if (an !== 0) return an; return String(a.id || "").localeCompare(String(b.id || "")); }); buckets.set(k, arr); } const order = ["A", "B", "C", "D", "_"]; const keys = [...order.filter((k) => buckets.has(k)), ...[...buckets.keys()].filter((k) => !order.includes(k))]; return keys.map((k) => ({ profileId: k === "_" ? "" : k, channels: buckets.get(k) || [], })); }, [filteredDisplayChannels]); const upcomingGroups = useMemo(() => { const buckets = new Map(); for (const u of upcoming) { const pk = String(u.channel_pk || ""); const key = normalizeOauthProfileId(u.oauth_profile_id) || channelProfileMap[pk] || "_"; const arr = buckets.get(key) || []; arr.push(u); buckets.set(key, arr); } const order = ["A", "B", "C", "D", "_"]; const keys = [...order.filter((k) => buckets.has(k)), ...[...buckets.keys()].filter((k) => !order.includes(k))]; return keys.map((k) => ({ profileId: k === "_" ? "" : k, items: buckets.get(k) || [], })); }, [upcoming, channelProfileMap]); const profileLabelMap = useMemo(() => { const m: Record = {}; for (const p of (status?.oauth_profiles || []) as OauthProfile[]) { const pid = normalizeOauthProfileId(p.id); const mail = String(p.email || "").trim(); const base = String(p.label || `谷歌账号 ${p.id}`); m[pid] = mail ? `${base} · ${mail}` : base; } for (const c of channels) { const pid = normalizeOauthProfileId(c.oauth_profile_id); if (pid && c.oauth_profile_label) m[pid] = c.oauth_profile_label; } return m; }, [status?.oauth_profiles, channels]); const totals = useMemo(() => { const uploaded = displayChannels.reduce((s, c) => s + (c.uploaded || 0), 0); const scheduled = displayChannels.reduce((s, c) => s + (c.scheduled || 0), 0); const used = displayChannels.reduce((s, c) => s + (c.used || 0), 0); const cap = displayChannels.reduce((s, c) => s + (c.daily_max || 9), 0); const minTarget = displayChannels.filter((c) => c.enabled !== false).reduce((s, c) => s + (c.daily_min || 9), 0); const gap = displayChannels .filter((c) => c.enabled !== false) .reduce((s, c) => s + (c.gap ?? Math.max(0, (c.daily_max || 9) - (c.used || 0))), 0); return { uploaded, scheduled, used, cap, minTarget, gap }; }, [displayChannels]); const hoursLeft = secondsLeft > 0 ? `${Math.floor(secondsLeft / 3600)}h${Math.floor((secondsLeft % 3600) / 60)}m` : "—"; const behindChannels = displayChannels.filter((c) => c.enabled !== false && c.behind_pace); const oauthIssues = (status?.oauth_issues || []) as Array<{ id: string; name?: string; oauth_ok?: number; oauth_error?: string; }>; function channelMeta(ch: BoardChannel) { const issue = oauthIssues.find((x) => x.id === ch.id); return buildChannelMeta(ch, issue); } async function probeOauth() { setBusy(true); try { const r = await fetchJson("/api/shorts/oauth/probe", { method: "POST" }); const failed = Number(r.failed ?? 0); toast.push( failed > 0 ? `OAuth 探测:${failed} 个频道异常` : `OAuth 探测完成:${r.checked ?? 0} 个频道正常`, failed > 0 ? "warn" : "ok", ); await load(); } catch (e) { toast.push((e as Error).message, "err"); } finally { setBusy(false); } } async function toggle(enabled: boolean) { setBusy(true); setMsg(""); try { await fetchJson(enabled ? "/api/shorts/start" : "/api/shorts/stop", { method: "POST" }); setMsg(enabled ? "已启用 Shorts(监控业务不变)" : "已关闭 Shorts"); await load(); } catch (e) { setError((e as Error).message); } finally { setBusy(false); } } function openOauthPopup(channelId: string, returnTo?: string) { const q = new URLSearchParams({ channel_pk: channelId }); if (returnTo) q.set("return_to", returnTo); const url = `/api/shorts/oauth/start?${q.toString()}`; // Same-tab: callback lands on /shorts?oauth=… so parent can show the real error. // Popup previously swallowed ?oauth=error on a closed child window. setMsg("正在跳转 Google 授权…"); window.location.assign(url); } function goAuthorize(channelId: string) { const full = channels.find((c) => c.id === channelId); // Stale state after create is fine — only block when we know this channel cannot auth if (full && full.can_authorize === false) { setShowWizard(true); setError("请先在「设置」配置对应 OAuth 档(A/B/C/D),并在本频道选择该配置档"); return; } // 点哪张卡就写入哪张卡;不再弹品牌对照提示。 openOauthPopup(channelId); } async function saveChannel(andAuth: boolean) { setBusy(true); setMsg(""); setError(""); try { const profileId = String(form.oauth_profile_id || "").trim().toUpperCase(); const body: Record = { name: form.name, enabled: form.enabled, daily_min: Math.max(1, Number(form.daily_min) || 9), daily_max: Math.max(1, Number(form.daily_max) || 9), title_template: form.title_template, description_template: form.description_template, privacy: form.privacy, note: form.note, oauth_profile_id: profileId, }; if (!String(body.name || "").trim()) body.name = "未命名频道"; 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; if (editId) { await fetchJson(`/api/shorts/channels/${editId}`, { method: "PATCH", body: JSON.stringify(body) }); setMsg("频道已更新"); } else { const created = await fetchJson("/api/shorts/channels", { method: "POST", body: JSON.stringify(body) }); id = created.channel?.id || ""; setMsg("频道已创建"); } setForm(blankFormFromDefaults()); setEditId(""); setShowForm(false); await load(); if (andAuth && id) { openOauthPopup(id); return; } } catch (e) { setError((e as Error).message); } finally { setBusy(false); } } function startEdit(ch: Channel) { setEditId(ch.id); setShowForm(true); setForm({ name: ch.name || "", enabled: ch.enabled !== false, daily_min: Number(ch.daily_min ?? status?.quota_defaults?.daily_min ?? 9), daily_max: Number(ch.daily_max ?? status?.quota_defaults?.daily_max ?? 9), title_template: ch.title_template || "{anchor} 直播瞬间 #Shorts", description_template: ch.description_template || "", privacy: ch.privacy || "public", note: ch.note || "", oauth_profile_id: (ch.oauth_profile_id || "A").toUpperCase(), }); } function blankFormFromDefaults() { const dmin = Number(status?.quota_defaults?.daily_min ?? 9); const dmax = Number(status?.quota_defaults?.daily_max ?? 9); return { ...emptyForm, daily_min: dmin, daily_max: Math.max(dmin, dmax) }; } async function removeChannel(id: string) { const ok = await confirm({ title: "删除 Shorts 频道", message: "确定删除该频道?将同时删除该频道下全部任务与本地成片素材。", confirmLabel: "删除", destructive: true, }); if (!ok) return; const r = await fetchJson(`/api/shorts/channels/${id}`, { method: "DELETE" }); toast.push(`频道已删除(任务 ${r.jobs ?? 0} · 成片 ${r.clips ?? 0})`, "ok"); await load(); } async function toggleChannelEnabled(ch: Channel) { const turningOn = ch.enabled === false; if (!turningOn) { const ok = await confirm({ title: `停用「${ch.name}」?`, message: "关闭后将立即清除该频道全部任务与成片,并停止取样/录制/上传。可随时再开。", confirmLabel: "停用并清任务", destructive: true, }); if (!ok) return; } setTogglingId(ch.id); try { const r = await fetchJson(`/api/shorts/channels/${ch.id}`, { method: "PATCH", body: JSON.stringify({ enabled: turningOn }), }); const cleared = r.cleared as { jobs?: number; clips?: number } | undefined; if (!turningOn && cleared) { toast.push( `已停用 · 清除任务 ${cleared.jobs ?? 0} · 成片 ${cleared.clips ?? 0}`, "ok", ); } else { toast.push(turningOn ? `已启用「${ch.name}」` : `已停用「${ch.name}」`, "ok"); } await load(); } catch (e) { toast.push((e as Error).message, "err"); } finally { setTogglingId(""); } } async function retryJob(id: string) { await fetchJson(`/api/shorts/jobs/${id}/retry`, { method: "POST" }); toast.push("已重新入队", "ok"); await load(); } async function runReconcile() { setBusy(true); try { const r = await fetchJson("/api/shorts/reconcile", { method: "POST" }); toast.push( `修复完成:孤儿任务 ${r.orphan_jobs ?? 0} · 丢失成片 ${r.missing_clips ?? 0} · 误标失败 ${r.false_failed ?? 0} · 卡死上传 ${r.stale_uploads ?? 0}`, "ok", ); await load(); } catch (e) { toast.push((e as Error).message, "err"); } finally { setBusy(false); } } async function bulkAction(action: "retry" | "upload_now") { const ids = Object.keys(selectedIds).filter((id) => selectedIds[id]); if (!ids.length) { toast.push("请先勾选任务", "warn"); return; } if (action === "upload_now") { const ok = await confirm({ title: "批量立即上传", message: `将对 ${ids.length} 条已成片任务跳过错峰立即上传(最多 30 条)。`, confirmLabel: "开始上传", }); if (!ok) return; } setBusy(true); try { const r = await fetchJson("/api/shorts/jobs/bulk", { method: "POST", body: JSON.stringify({ job_ids: ids, action }), }); toast.push(`完成 ${r.ok_count ?? 0}/${r.total ?? ids.length}`, r.ok_count ? "ok" : "warn"); setSelectedIds({}); await load(); } catch (e) { toast.push((e as Error).message, "err"); } finally { setBusy(false); } } const selectedCount = useMemo(() => Object.values(selectedIds).filter(Boolean).length, [selectedIds]); function toggleSelect(id: string) { setSelectedIds((prev) => ({ ...prev, [id]: !prev[id] })); } function toggleSelectAll() { const allOn = jobs.length > 0 && jobs.every((j) => selectedIds[j.id]); if (allOn) { setSelectedIds({}); return; } const next: Record = {}; for (const j of jobs) next[j.id] = true; setSelectedIds(next); } function toUploadTarget(u: Record, channelMap: Record): ShortsUploadTarget { const pk = String(u.channel_pk || ""); return { id: String(u.id || ""), anchor_name: String(u.anchor_name || ""), room_id: String(u.room_id || ""), channel_name: String(u.channel_name || channelMap[pk] || ""), channel_pk: pk, oauth_profile_id: normalizeOauthProfileId(String(u.oauth_profile_id || "")) || channelProfileMap[pk] || "", upload_at: Number(u.upload_at || 0) || undefined, clip_ready: u.clip_ready !== false, status: String(u.status || ""), }; } const uploadBusy = Object.values(uploadUx.tracks).some((t) => t.phase === "uploading"); return ( setDetailJobId(null)} />

Shorts Pipeline

📱 Shorts 分发台

在播放样 → 错峰上传;同时轮询各上传频道自身 YouTube 开播,写入场次做数据分析。

开播场次 设置
{showWizard || !status?.oauth_configured ? ( void load()} /> ) : null} {pageTab === "live" ? (
基于 live-map 轮询写入的 Shorts 频道开播场次(room_id=shorts:…),与抖音场次同一套图表口径
{[ ["当前在播", String(liveNow), "上传频道自身开播"], ["场次", String(liveStats?.overview?.sessions ?? 0), "区间内开播次数"], ["累计小时", Number(liveStats?.overview?.total_hours || 0).toFixed(1), "含进行中"], ["有记录频道", String(liveStats?.overview?.unique_anchors ?? liveChannels.length), "开过播的频道数"], ].map(([label, value, hint]) => (
{label}
{value}
{hint}
))}

可视化分析

频道开播排行
{liveChannels.map((ch) => ( ))} {!liveChannels.length ? ( ) : null}
频道 状态 场次 小时 最近开播
{ch.last_title ? (
{ch.last_title}
) : null}
{Number(ch.active) > 0 || ch.last_status === "live" ? ( YT·LIVE ) : ( {ch.last_status || "offline"} )} {ch.sessions ?? 0} {Number(ch.hours_total || 0).toFixed(1)} {ch.last_started_at ? fmtTs(ch.last_started_at) : "—"}
暂无开播记录。轮询检测到频道 YouTube 开播后会自动入库。
最近开播场次 全部 →
{liveRecent.map((s) => ( ))} {!liveRecent.length ? ( ) : null}
频道 标题 开始 时长 状态
{s.anchor_name || s.room_id || "—"} {s.title || "—"} {fmtTs(s.started_at)} {fmtDuration(s.duration_seconds)} {s.ended_at ? "已结束" : 在播}
暂无场次
) : null} {pageTab === "ops" ? ( <>
{[ ["北京日配额", `${totals.used} / ${totals.cap || "—"}`, beijingWindow ? `${beijingWindow}(北京时间)` : "按各频道日上限合计"], ["当日缺口", String(totals.gap || quotaGap), minUnmet > 0 ? `${minUnmet} 个频道未达 9 条` : "各频道已达 9 条"], ["已上传", String(totals.uploaded), `排队 ${totals.scheduled} · 剩余 ${hoursLeft}`], [ "抖音在播源", String(status?.douyin_live_count ?? "—"), status?.live_sample === false ? "在播放样已关" : "取样来自监控在播直播间", ], [ "错峰间隔", `≥${Math.round((status?.upload_min_gap_sec || 720) / 60)}分`, `同频道 ≥${Math.round((status?.channel_min_gap_sec || 2400) / 60)}分 · 落后自动加速`, ], ].map(([label, value, hint]) => (
{label}
{value}
{hint}
))}
{Array.isArray(status?.douyin_live_rooms) && status.douyin_live_rooms.length > 0 ? (
当前可取样直播间({status.douyin_live_count ?? status.douyin_live_rooms.length}) 来自监控 last_status=live,非 YouTube 上传频道开播
{status.douyin_live_rooms.map((r: { room_id?: string; anchor?: string }) => ( {r.anchor || r.room_id} ))}
) : status?.enabled && status?.live_sample !== false ? (
暂无抖音在播源可取样。Shorts 频道卡上的 LIVE/离线是 YouTube 上传频道自身开播状态(多数情况为离线属正常)。
) : null}
开关 worker {status?.running ? "运行中" : "未运行"} {status?.busy ? " · 忙碌" : ""} · 处理 {status?.processed ?? 0} · 取样 {status?.sampled ?? 0} · 补量 {status?.quota_filled ?? 0} {status?.auto_retry_failed !== false ? ` · 自动重试 ${status?.auto_retried ?? 0}` : ""} {status?.upload_spread !== false ? " · 24h 错峰开" : " · 错峰关"}
{msg ?
{msg}
: null} {error ?
{error}
: null} {Array.isArray(status?.yt_quota_exhausted_hint) && (status.yt_quota_exhausted_hint as string[]).length ? (

部分 Client 本地计数已达参考上限(仅提示,不拦截上传)

提示: {(status.yt_quota_exhausted_hint as string[]).map((p) => `Client ${p}`).join("、")} 。仍可点「立即上传」;以 YouTube 接口返回为准。 {status.yt_quota_reset_at ? ( <> YouTube 侧预计重置:{fmtTs(status.yt_quota_reset_at)}(北京) ) : null}

{Array.isArray(status.yt_quota_by_profile) ? (
{(status.yt_quota_by_profile as Array).map((row) => ( Client {row.id} · {row.used}/{row.limit} {row.exhausted_hint ? " · 参考已满" : ` · 剩 ${row.remaining}`} ))}
) : null}

配额按 OAuth Client A/B/C/D(不同 Google 项目)分别计算,互不影响。本系统不自行暂停上传。

) : Array.isArray(status?.yt_quota_by_profile) ? (
{(status.yt_quota_by_profile as Array).map((row) => ( Client {row.id} · {row.used}/{row.limit}(剩 {row.remaining}) ))}
) : typeof status?.yt_upload_remaining === "number" && status.yt_upload_remaining <= 10 ? (
YouTube 上传配额即将用尽:今日 {status.yt_upload_used ?? 0}/{status.yt_upload_limit ?? 90} 次(太平洋日),剩余{" "} {status.yt_upload_remaining} 次(仅提示,不拦截)。
) : status?.last_error ? (
最近错误:{status.last_error}
) : null} {behindChannels.length > 0 ? (
配额落后:{behindChannels.map((c) => c.name || "频道").slice(0, 4).join("、")} {behindChannels.length > 4 ? ` 等 ${behindChannels.length} 个` : ""} · 北京日进度{" "} {Math.round(Number(status?.board?.day_progress || 0) * 100)}%
) : null} {oauthIssues.length > 0 ? (
OAuth 异常:{oauthIssues.map((c) => c.name || "频道").slice(0, 4).join("、")} {oauthIssues.length > 4 ? ` 等 ${oauthIssues.length} 个` : ""} {oauthIssues[0]?.oauth_error ? ` · ${String(oauthIssues[0].oauth_error).slice(0, 60)}` : ""}
{oauthIssues[0]?.id ? ( ) : null}
) : null} {status?.board?.quota_forecast?.message ? (
配额预演:{status.board.quota_forecast.message}
) : null} { await fetchJson("/api/shorts/quota-defaults", { method: "POST", body: JSON.stringify({ daily_min, daily_max, apply_all: false }), }); toast.push("已保存 Shorts 全局默认配额", "ok"); await load(); }} onApplyAll={async ({ daily_min, daily_max, enabled_only }) => { const ok = await confirm({ title: "应用到全部 Shorts 频道", message: enabled_only ? `将把每日最少 ${daily_min}、上限 ${daily_max} 写入全部已启用频道?` : `将把每日最少 ${daily_min}、上限 ${daily_max} 写入全部频道(含停用)?`, confirmLabel: "应用", }); if (!ok) return; const r = await fetchJson("/api/shorts/quota-defaults", { method: "POST", body: JSON.stringify({ daily_min, daily_max, apply_all: true, enabled_only }), }); toast.push(`已同步 ${r.updated_channels ?? 0} 个频道`, "ok"); await load(); }} /> {loading && !status ? : null} {!loading || status ? ( <>

频道配额({liveOnlyFilter ? filteredDisplayChannels.length : channels.length})

{liveOnlyFilter ? ( 仅显示在播 ) : null} 按 Client A/B/C/D 分组 · 北京日 {beijingWindow || "—"} · 日配额按频道可配
{channelGroups.length === 0 ? (
{liveOnlyFilter ? "当前没有在播的 Shorts 频道" : "暂无频道。点「新频道」并选择 OAuth 配置档 A/B/C/D。"}
) : ( channelGroups.map((group) => (
normalizeOauthProfileId(p.id) === group.profileId )?.email || "" } size="lg" /> {profileLabelMap[group.profileId] || (group.profileId ? `谷歌账号 ${group.profileId}` : "未绑定配置档")} {group.channels.length} 个频道
{group.channels.map((ch) => { const pct = Math.min(100, Math.round((ch.used / Math.max(1, ch.daily_max)) * 100)); const minPct = Math.round((ch.daily_min / Math.max(1, ch.daily_max)) * 100); const full = channels.find((x) => x.id === ch.id); const gap = ch.gap ?? Math.max(0, ch.daily_max - ch.used); const warn = ch.enabled !== false && (ch.behind_pace || (!ch.min_met && gap > 0)); return (
{full ? ( void toggleChannelEnabled(full)} /> ) : null}
= 100 ? "bg-teal-400" : pct >= minPct ? "bg-amber-400" : "bg-rose-400"}`} style={{ width: `${pct}%` }} />
{ch.used}/{ch.daily_max || 9} {gap > 0 ? 缺 {gap} : 已满} 上传 {ch.uploaded} 排队 {ch.scheduled} 待录 {ch.pending}
{full ? ( ) : null}
); })}
)) )}

即将上传(错峰日程)

素材 {upcoming.length}

北京 {status?.board?.beijing_hint || "—"} · 按 Client A/B/C/D 分组 · 点击「立即上传」确认后发布

{status?.board?.timeline?.hours ? (
{ const full = upcoming.find((u: { id: string }) => u.id === j.id); if (full) uploadUx.openConfirm(toUploadTarget(full, channelName)); }} />
) : null}
{upcoming.length === 0 ? (
暂无排程。取样或开播入队后,成片会自动分散到今日各时段。
) : ( upcomingGroups.map((group) => (
{group.items.length} 条待传
{group.items.map((u: any) => ( ))}
)) )}
{showForm ? (

{editId ? "编辑频道" : "新增频道"}

) : null}

任务流水({jobTotal}) pending {stats.pending || 0} · scheduled {stats.scheduled || 0} · uploaded {stats.uploaded || 0} · failed{" "} {stats.failed || 0}

setJobDate(e.target.value)} className="rounded-lg border border-white/10 bg-slate-900 px-2 py-1.5 text-xs" />
{selectedCount > 0 ? (
已选 {selectedCount}
) : null}
{loading && jobs.length === 0 ? ( ) : ( {jobs.map((j) => ( ))} {jobs.length === 0 ? ( ) : null}
0 && jobs.every((j) => selectedIds[j.id])} onChange={toggleSelectAll} className="rounded border-white/20" /> 状态 主播 频道 排程上传 创建 结果 操作
toggleSelect(j.id)} className="rounded border-white/20" /> {j.status}
{channelName[String(j.channel_pk || "")] || "—"}
{j.upload_at ? fmtTs(Number(j.upload_at)) : "—"} {fmtTs(Number(j.created_at || 0))} {j.youtube_url ? ( 已上传 ) : j.error ? ( {j.error} ) : j.clip_ready ? ( 成片待传 ) : j.clip_path ? ( 成片丢失 ) : ( "—" )}
{["scheduled", "recorded"].includes(j.status) && j.clip_ready ? ( ) : null} {["failed", "skipped", "recorded", "scheduled"].includes(j.status) ? ( ) : null}
暂无任务
)}
{jobs.length > 0 && jobs.length < jobTotal ? (
) : null}
) : null} ) : null}
); }