"use client"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import Link from "next/link"; import { Clock3, Download, Loader2, Plus, RefreshCw, RotateCcw, Trash2, Upload, Video, } from "lucide-react"; import { Shell } from "@/components/Shell"; import { useConfirm } from "@/components/ConfirmDialog"; import { useToast } from "@/components/Toast"; import { DailyQuotaGlobalCard } from "@/components/DailyQuotaGlobalCard"; import { EnableSwitch } from "@/components/EnableSwitch"; import { OauthClientBadge, normalizeOauthProfileId } from "@/components/OauthClientBadge"; import { YtChannelProfileSnippet, type YtProfileSnippet } from "@/components/YtChannelProfileSnippet"; import { buildChannelMeta } from "@/lib/ytChannelMeta"; import { PageLoader, TableSkeleton } from "@/components/ui"; import { fetchJson, fmtTs, todayBeijingISO } from "@/lib/api"; type Channel = { id: string; name: string; youtube_channel_id?: string; enabled?: boolean; daily_max?: number; title_template?: string; description_template?: string; privacy?: string; note?: string; authorized?: boolean; has_refresh_token?: boolean; oauth_profile_id?: string; oauth_error?: string; source_shorts_channel_pk?: string; }; type BoardChannel = { id: string; name?: string; youtube_channel_id?: string; oauth_profile_id?: string; enabled?: boolean; daily_max: number; authorized?: boolean; used: number; scheduled: number; uploaded: number; pending: number; failed?: number; gap?: number; ypp_ok?: number; monetize_default?: boolean; oauth_ok?: number; oauth_error?: string; brand_hint?: string; note?: string; source_shorts_channel_pk?: string; yt_profile?: YtProfileSnippet | null; }; type Job = { id: string; status: string; anchor_name?: string; room_id?: string; push_date?: string; channel_pk?: string; clip_path?: string; clip_ready?: boolean; clip_seconds?: number; youtube_url?: string; title?: string; error?: string; created_at?: number; upload_at?: number; }; const emptyForm = { name: "", enabled: true, daily_max: 5, title_template: "", description_template: "", privacy: "public", note: "", 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 STATUS_LABEL: Record = { pending: "待录制", recording: "录制中", recorded: "已录制", scheduled: "排队上传", uploading: "上传中", uploaded: "已上传", failed: "失败", skipped: "已跳过", }; const STATUS_FILTERS = [ "pending", "recording", "recorded", "scheduled", "uploading", "uploaded", "failed", "skipped", ] as const; function jobResultZh(job: { youtube_url?: string; error?: string; clip_ready?: boolean; clip_path?: string; status?: string; }): { text: string; tone: "ok" | "warn" | "err" | "muted" } { if (job.youtube_url) { const note = String(job.error || "").trim(); if (note.includes("已开启广告获利")) return { text: "已上传 · 已开广告获利", tone: "ok" }; if (note.includes("非YPP")) return { text: "已上传 · 非YPP未开广告", tone: "muted" }; if (note.includes("获利未开") || note.includes("ypp_monetize")) { return { text: note.replace(/^ypp_monetize_fail:/, "获利未开:").slice(0, 80), tone: "warn" }; } return { text: "已上传 YouTube", tone: "ok" }; } const err = String(job.error || "").trim(); if (!err) { if (job.clip_ready || job.clip_path) return { text: "成片已好,等待上传", tone: "muted" }; if (job.status === "pending") return { text: "排队录制", tone: "muted" }; if (job.status === "recording") return { text: "正在录直播", tone: "muted" }; if (job.status === "scheduled") return { text: "已排好上传时间", tone: "muted" }; if (job.status === "uploading") return { text: "正在上传", tone: "muted" }; return { text: "—", tone: "muted" }; } const low = err.toLowerCase(); if (err === "cascade_only" || low.includes("cascade_only")) { const zh = err.includes(":") ? err.split(":").slice(1).join(":").trim() : ""; return { text: zh || "当日上传名额已满,只做了切片,未传 YouTube", tone: "warn", }; } if (err === "source_quota_full" || low.includes("source_quota")) { return { text: "今日录制名额已满,已跳过", tone: "warn" }; } if (low.includes("quota") || low.includes("配额") || low.includes("429")) { return { text: "YouTube 接口限流/配额用尽", tone: "err" }; } if (err.includes("无可用长视频频道") || err.includes("未授权")) { return { text: err, tone: "err" }; } if (err.includes("成片文件不存在") || low.includes("clip")) { return { text: "成片文件已清理,无法直接重传", tone: "warn" }; } // Keep Chinese messages; trim long English API dumps if (/[\u4e00-\u9fff]/.test(err)) return { text: err.slice(0, 120), tone: "err" }; return { text: err.slice(0, 100), tone: "err" }; } const JOB_PAGE = 50; export default function YtLongPage() { const confirm = useConfirm(); const toast = useToast(); const leftPanelRef = useRef(null); const rightPanelRef = useRef(null); const [status, setStatus] = useState | null>(null); const [channels, setChannels] = useState([]); const [jobs, setJobs] = useState([]); const [jobTotal, setJobTotal] = useState(0); const [upcoming, setUpcoming] = useState([]); const [form, setForm] = useState({ ...emptyForm }); const [editId, setEditId] = useState(""); const [togglingId, setTogglingId] = useState(""); const [msg, setMsg] = useState(""); const [error, setError] = useState(""); const [jobFilter, setJobFilter] = useState(""); const [jobChannel, setJobChannel] = useState(""); const [jobDate, setJobDate] = useState(""); const [showForm, setShowForm] = useState(false); const [loading, setLoading] = useState(true); const [loadingMoreJobs, setLoadingMoreJobs] = useState(false); const load = useCallback( async (opts?: { appendJobs?: boolean; jobOffset?: number; soft?: boolean }) => { const appendJobs = Boolean(opts?.appendJobs); const soft = Boolean(opts?.soft); if (appendJobs) setLoadingMoreJobs(true); else if (!soft) 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/yt-long/jobs?${jobQs}`); setJobs((prev) => [...prev, ...(jb.jobs || [])]); setJobTotal(jb.total || 0); } else { const upQs = new URLSearchParams({ limit: "40", offset: "0", status: "scheduled" }); if (!jobDate) upQs.set("push_date", todayBeijingISO()); else upQs.set("push_date", jobDate); const [st, ch, jb, up] = await Promise.all([ fetchJson("/api/yt-long/status"), fetchJson("/api/yt-long/channels"), fetchJson(`/api/yt-long/jobs?${jobQs}`), fetchJson(`/api/yt-long/jobs?${upQs}`), ]); setStatus(st); setChannels(ch.channels || []); setJobs(jb.jobs || []); setJobTotal(jb.total || 0); setUpcoming(up.jobs || []); } } catch (e) { setError((e as Error).message); toast.push((e as Error).message, "err"); } finally { setLoading(false); setLoadingMoreJobs(false); } }, [jobChannel, jobDate, jobFilter, toast], ); useEffect(() => { void load(); let n = 0; const t = setInterval(() => { if (document.hidden) return; n += 1; if (n % 2 === 0) { void load(); } else { void fetchJson("/api/yt-long/status?light=1") .then((st) => setStatus((prev) => ({ ...(prev || {}), ...st, board: st.board ?? prev?.board, cascade_need: st.cascade_need ?? prev?.cascade_need, settings: st.settings ?? prev?.settings, })), ) .catch(() => undefined); } }, 20000); const onVis = () => { if (!document.hidden) void load(); }; document.addEventListener("visibilitychange", onVis); return () => { clearInterval(t); document.removeEventListener("visibilitychange", onVis); }; }, [load]); useEffect(() => { const left = leftPanelRef.current; const right = rightPanelRef.current; if (!left || !right) return; const sync = () => { right.style.maxHeight = `${left.getBoundingClientRect().height}px`; }; sync(); const ro = new ResizeObserver(sync); ro.observe(left); return () => ro.disconnect(); }); const boardChannels: BoardChannel[] = status?.board?.channels || []; const beijingWindow = status?.board?.push_date || status?.stats?.push_date || ""; const quotaGap = Number(status?.quota_gap ?? status?.board?.total_gap ?? 0); const stats = status?.stats?.by_status || {}; const settings = status?.settings || {}; 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_max: Number(c.daily_max ?? 5), authorized: Boolean(c.authorized || c.has_refresh_token), used: 0, scheduled: 0, uploaded: 0, pending: 0, failed: 0, gap: Number(c.daily_max ?? 5), })); return base.map((ch) => ({ ...ch, oauth_profile_id: normalizeOauthProfileId(ch.oauth_profile_id) || channelProfileMap[ch.id] || "", })); }, [boardChannels, channels, channelProfileMap]); const channelGroups = useMemo(() => { const buckets = new Map(); for (const ch of displayChannels) { const key = normalizeOauthProfileId(ch.oauth_profile_id) || "_"; const arr = buckets.get(key) || []; arr.push(ch); buckets.set(key, arr); } 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) || [], })); }, [displayChannels]); const upcomingGroups = useMemo(() => { const buckets = new Map(); for (const u of upcoming) { const pk = String(u.channel_pk || ""); const key = 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 totals = useMemo(() => { const uploaded = displayChannels.reduce((s, c) => s + (c.uploaded || 0), 0); const scheduled = displayChannels.reduce((s, c) => s + (c.scheduled || 0), 0); // Progress / 缺口按「已上传」计(与 Shorts 一致);used 含排队占坑,仅作内部参考。 const used = uploaded; const cap = displayChannels.reduce((s, c) => s + (c.daily_max || 0), 0); const gap = displayChannels .filter((c) => c.enabled !== false) .reduce((s, c) => s + Math.max(0, (c.daily_max || 0) - Number(c.uploaded || 0)), 0); return { uploaded, scheduled, used, cap, gap }; }, [displayChannels]); async function toggle(enabled: boolean) { setMsg(""); setError(""); try { await fetchJson(enabled ? "/api/yt-long/start" : "/api/yt-long/stop", { method: "POST" }); setMsg(enabled ? "已启用长视频(Shorts 不受影响)" : "已关闭长视频"); await load(); } catch (e) { setError((e as Error).message); } } async function importFromShorts() { setMsg(""); setError(""); try { const r = await fetchJson("/api/yt-long/channels/import-shorts", { method: "POST" }); setMsg(`已同步 Shorts 频道:新建 ${r.created ?? 0} · 更新 ${r.updated ?? 0}`); toast.push("频道已同步", "ok"); await load(); } catch (e) { setError((e as Error).message); toast.push((e as Error).message, "err"); } } async function saveChannel() { setMsg(""); setError(""); try { const body: Record = { name: form.name.trim() || "未命名长视频频道", enabled: form.enabled, daily_max: Math.max(0, Number(form.daily_max) || 0), title_template: form.title_template, description_template: form.description_template, privacy: form.privacy, note: form.note, oauth_profile_id: String(form.oauth_profile_id || "A").toUpperCase(), }; if (editId) { await fetchJson(`/api/yt-long/channels/${editId}`, { method: "PATCH", body: JSON.stringify(body) }); setMsg("频道已更新"); } else { await fetchJson("/api/yt-long/channels", { method: "POST", body: JSON.stringify(body) }); setMsg("频道已创建"); } setForm({ ...emptyForm }); setEditId(""); setShowForm(false); await load(); } catch (e) { setError((e as Error).message); } } function startEdit(ch: Channel) { setEditId(ch.id); setShowForm(true); setForm({ name: ch.name || "", enabled: ch.enabled !== false, daily_max: Number(ch.daily_max ?? 5), title_template: ch.title_template || "{anchor} street food live", description_template: ch.description_template || "", privacy: ch.privacy || "public", note: ch.note || "", oauth_profile_id: (ch.oauth_profile_id || "A").toUpperCase(), }); } async function removeChannel(id: string) { const ok = await confirm({ title: "删除长视频频道", message: "确定删除该频道?将同时删除该频道下全部长视频任务(不影响 Shorts)。", confirmLabel: "删除", destructive: true, }); if (!ok) return; const r = await fetchJson(`/api/yt-long/channels/${id}`, { method: "DELETE" }); toast.push(`频道已删除(任务 ${r.jobs ?? 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/yt-long/channels/${ch.id}`, { method: "PATCH", body: JSON.stringify({ enabled: turningOn }), }); const cleared = r.cleared as { jobs?: number } | undefined; if (!turningOn && cleared) { toast.push(`已停用 · 清除任务 ${cleared.jobs ?? 0}`, "ok"); } else { toast.push(turningOn ? `已启用「${ch.name}」` : `已停用「${ch.name}」`, "ok"); } setChannels((prev) => prev.map((c) => (c.id === ch.id ? { ...c, enabled: turningOn } : c)), ); await load({ soft: true }); } catch (e) { toast.push((e as Error).message, "err"); } finally { setTogglingId(""); } } async function retryJob(id: string) { await fetchJson(`/api/yt-long/jobs/${id}/retry`, { method: "POST" }); toast.push("已重新入队", "ok"); await load(); } return (

Long Video Pipeline

📺 长视频分发台

在播放样 → 9:16 成片(3–8 分钟)→ 上传为普通 YouTube 视频(watch?v=)。成片可 cascade 切 TikTok / Shorts / X。频道 OAuth 可从 Shorts 同步,业务数据隔离。

Shorts 设置
{[ [ "YouTube 上传", `${totals.uploaded} / ${totals.cap || status?.daily_max || "—"}`, beijingWindow ? `${beijingWindow} · 已上传 / 各频道日上限合计` : "进度按已上传(不含排队占坑)", ], [ "母片录制", `${status?.source_used ?? 0} / ${status?.source_daily_max ?? "—"}`, `缺口 ${status?.source_gap ?? "—"} · 覆盖 Shorts/TikTok/X`, ], ["已上传", String(totals.uploaded), `排队 ${totals.scheduled}`], [ "抖音在播源", String(status?.douyin_live_count ?? "—"), settings.yt_long_live_sample === false ? "在播放样已关" : "取样来自监控在播直播间", ], [ "成片规格", `${Math.round(Number(settings.yt_long_min_sec || 180) / 60)}–${Math.round(Number(settings.yt_long_max_sec || 480) / 60)}分`, status?.api_quota_limited ? `9:16 · API 限流中,每频道 cap ${status?.channel_daily_max_effective ?? 4}` : "9:16 竖屏 · cascade 切短片", ], ].map(([title, value, sub]) => (

{title}

{value}

{sub}

))}
{status?.api_quota_limited ? (
YouTube 上传接口今日限流(429)。长视频每频道上限已软降为{" "} {status?.channel_daily_max_effective ?? 4};Shorts/长视频自动上传对冷静中的 Client 会跳过,手动上传不拦。
) : null} { await fetchJson("/api/yt-long/settings", { method: "POST", body: JSON.stringify({ yt_long_channel_daily_max: daily_max }), }); toast.push("已保存长视频频道默认上限", "ok"); await load(); }} onApplyAll={async ({ daily_max, enabled_only }) => { const ok = await confirm({ title: "同步长视频频道上限", message: `将每频道每日上限设为 ${daily_max},并写入${enabled_only ? "全部已启用" : "全部"}频道?`, confirmLabel: "同步", }); if (!ok) return; const r = await fetchJson("/api/yt-long/settings", { method: "POST", body: JSON.stringify({ yt_long_channel_daily_max: daily_max, apply_channel_daily_max: true, enabled_only, }), }); toast.push(`已同步 ${r.quota_apply?.updated_channels ?? 0} 个频道`, "ok"); await load(); }} />
开关 worker {status?.running ? "运行中" : "未运行"} {status?.busy ? " · 忙碌" : ""} · 处理 {status?.processed ?? 0} · 取样 {status?.sampled ?? 0}
{msg ?
{msg}
: null} {error ?
{error}
: null} {status?.last_error ? (
最近错误:{status.last_error}
) : null} {loading && !status ? : null} {!loading || status ? ( <>

频道配额({channels.length})

按 Client A/B/C/D 分组 · 北京日 {beijingWindow || "—"} · 独立 yt_long_channels
{channelGroups.length === 0 ? (
暂无频道。点「同步 Shorts 频道」或「新频道」。
) : ( channelGroups.map((group) => (
{group.profileId ? `谷歌账号 ${group.profileId}` : "未绑定配置档"} {group.channels.length} 个频道
{group.channels.map((ch) => { // 进度条只按「已上传」,与 /shorts 一致;排队占坑不算进度。 const progress = Number(ch.uploaded ?? 0); const pct = Math.min(100, Math.round((progress / Math.max(1, ch.daily_max)) * 100)); const full = channels.find((x) => x.id === ch.id); const gap = Math.max(0, (ch.daily_max || 0) - progress); return (
{full ? ( void toggleChannelEnabled(full)} /> ) : null}
= 100 ? "bg-teal-400" : "bg-amber-400"}`} style={{ width: `${pct}%` }} />
上传 {progress}/{ch.daily_max || 0} {gap > 0 ? ( 缺 {gap} ) : ( 已满 )} 排队 {ch.scheduled} 待录 {ch.pending}
{full ? ( ) : null}
); })}
)) )}

即将上传

素材 {upcoming.length}

北京日 {beijingWindow || "—"} · 按 Client A/B/C/D 分组 · 成片后自动排程上传

{upcoming.length === 0 ? (
暂无排程。取样入队并成片后会出现在这里。
) : ( upcomingGroups.map((group) => (
{group.items.length} 条待传
{group.items.map((u) => (
{u.anchor_name || "—"}
{channelName[String(u.channel_pk || "")] || "—"} {u.upload_at ? ` · ${fmtTs(u.upload_at)}` : ""}
{u.status}
))}
)) )}
{showForm ? (

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

) : null}

任务流水({jobTotal}) 待录 {stats.pending || 0} · 排队 {stats.scheduled || 0} · 已上传 {stats.uploaded || 0} · 失败{" "} {stats.failed || 0}

setJobDate(e.target.value)} className="rounded-lg border border-white/10 bg-slate-900 px-2 py-1.5 text-xs" />
{loading && jobs.length === 0 ? ( ) : ( {jobs.map((j) => { const result = jobResultZh(j); const isCascadeOnly = String(j.error || "").includes("cascade_only") || String(j.error || "").includes("当日上传名额已满"); const canRetry = ["failed", "skipped", "scheduled"].includes(j.status) || (j.status === "recorded" && !isCascadeOnly && Boolean(j.clip_path || j.clip_ready)); return ( ); })} {jobs.length === 0 ? ( ) : null}
状态 主播 频道 排程上传 创建 说明 操作
{STATUS_LABEL[j.status] || j.status}
{j.anchor_name || "—"}
{j.room_id || ""}
{j.channel_pk ? (
{channelName[String(j.channel_pk || "")] || "未知频道"}
) : ( 未分配频道 )}
{j.upload_at ? fmtTs(Number(j.upload_at)) : "—"} {fmtTs(Number(j.created_at || 0))} {j.youtube_url ? ( {result.text} ) : ( {result.text} )} {canRetry ? ( ) : isCascadeOnly ? ( 无需重传 ) : ( — )}
暂无任务
)}
{jobs.length > 0 && jobs.length < jobTotal ? (
) : null}
) : null}
); }