import { useCallback, useEffect, useMemo, useState } from "react"; import { Link } from "react-router-dom"; import { Clock3, Eye, KeyRound, Loader2, Plus, RefreshCw, RotateCcw, Trash2, Upload, Video, Wrench, } from "lucide-react"; import { Shell } from "@/components/Shell"; import { useConfirm } from "@/components/ConfirmDialog"; import { useToast } from "@/components/Toast"; import { GoogleOauthSetupWizard } from "@/components/GoogleOauthSetupWizard"; import { ShortsJobDetailModal } from "@/components/ShortsJobDetailModal"; import { ShortsUploadConfirmModal, ShortsUpcomingUploadRow, useShortsUpload, type ShortsUploadTarget, } from "@/components/ShortsUploadUx"; import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge"; import { SessionCharts, type RelayStats } from "@/components/SessionCharts"; import { PageLoader, TableSkeleton } from "@/components/ui"; import { fetchJson, fmtDuration, fmtTs, todayBeijingISO, shiftBeijingISO } from "@/lib/api"; import { shortsLiveRef } from "@/lib/youtubeLive"; 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; }; type BoardChannel = { id: string; name?: string; youtube_channel_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; }; 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: "", }; 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 [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 [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 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(); const t = setInterval(() => { if (pageTab === "ops") void load(); }, 10000); return () => clearInterval(t); }, [load, pageTab]); useEffect(() => { if (pageTab !== "live") return; void loadLiveAnalytics(); const t = setInterval(() => void loadLiveAnalytics(), 20000); 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 oauth = sp.get("oauth"); if (!oauth) return; if (oauth === "ok") { setMsg(`Google 授权成功${sp.get("title") ? `:${sp.get("title")}` : ""}`); void load(); } else if (oauth === "error") { setError(sp.get("msg") || "授权失败"); } 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 totals = useMemo(() => { const uploaded = boardChannels.reduce((s, c) => s + (c.uploaded || 0), 0); const scheduled = boardChannels.reduce((s, c) => s + (c.scheduled || 0), 0); const used = boardChannels.reduce((s, c) => s + (c.used || 0), 0); const cap = boardChannels.reduce((s, c) => s + (c.daily_max || 9), 0); const minTarget = boardChannels.filter((c) => c.enabled !== false).reduce((s, c) => s + (c.daily_min || 9), 0); const gap = boardChannels.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 }; }, [boardChannels]); const hoursLeft = secondsLeft > 0 ? `${Math.floor(secondsLeft / 3600)}h${Math.floor((secondsLeft % 3600) / 60)}m` : "—"; const behindChannels = boardChannels.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; }>; 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 goAuthorize(channelId: string) { if (!status?.oauth_configured) { setShowWizard(true); setError("请先配置 Google OAuth Client"); return; } const start = `/api/shorts/oauth/start?channel_pk=${encodeURIComponent(channelId)}`; if (window.desktop?.openExternal) { const origin = window.location.origin; void window.desktop.openExternal(`${origin}${start}`); } else { window.location.href = start; } } async function saveChannel(andAuth: boolean) { setBusy(true); setMsg(""); setError(""); try { const body = { ...form, daily_min: 9, daily_max: 9 }; if (!body.name.trim()) body.name = "未命名频道"; 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({ ...emptyForm }); setEditId(""); setShowForm(false); await load(); if (andAuth && id) { goAuthorize(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: 9, daily_max: 9, title_template: ch.title_template || "{anchor} 直播瞬间 #Shorts", description_template: ch.description_template || "", privacy: ch.privacy || "public", note: ch.note || "", }); } async function removeChannel(id: string) { const ok = await confirm({ title: "删除 Shorts 频道", message: "确定删除该频道?已排程任务不会自动恢复。", confirmLabel: "删除", destructive: true, }); if (!ok) return; await fetchJson(`/api/shorts/channels/${id}`, { method: "DELETE" }); toast.push("频道已删除", "ok"); await load(); } 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.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 { return { id: String(u.id || ""), anchor_name: String(u.anchor_name || ""), room_id: String(u.room_id || ""), channel_name: String(u.channel_name || channelMap[String(u.channel_pk || "")] || ""), channel_pk: String(u.channel_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.name || "—"} {ch.id ? : null}
{ch.youtube_channel_id || "—"}
{ch.last_title ?
{ch.last_title}
: null}
0 || ch.last_status === "live" ? "text-rose-300" : "text-slate-500"}> {Number(ch.active) > 0 || ch.last_status === "live" ? "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}(北京时间)` : "每频道强制 9 条/日"], ["当日缺口", 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} {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} {loading && !status ? : null} {!loading || status ? ( <>

频道配额({channels.length})

北京日 {beijingWindow || "—"} · 每频道强制 9 条/日
{(boardChannels.length ? boardChannels : channels.map((c) => ({ id: c.id, name: c.name, youtube_channel_id: c.youtube_channel_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, }))).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 (
{ch.name || "未命名"}
{ch.youtube_channel_id || "—"}
{ch.enabled === false ? "停用" : "启用"} 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 ? "已授权" : "未授权"}
= 100 ? "bg-teal-400" : pct >= minPct ? "bg-amber-400" : "bg-rose-400"}`} style={{ width: `${pct}%` }} />
{ch.used}/{ch.daily_max || 9} (强制 9) {gap > 0 ? 缺 {gap} : 已满} 上传 {ch.uploaded} 排队 {ch.scheduled} 待录 {ch.pending}
{full ? ( ) : null}
); })}

即将上传(错峰日程)

素材 {upcoming.length}

北京 {status?.board?.beijing_hint || "—"} · 点击「立即上传」确认后发布 · 上传过程有进度提示

{upcoming.length === 0 ? (
暂无排程。取样或开播入队后,成片会自动分散到今日各时段。
) : ( upcoming.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}
); }