"use client"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import Link from "next/link"; import { CheckCircle2, Circle, Clock3, ExternalLink, KeyRound, Loader2, Music2, Plus, RefreshCw, Trash2, Upload, Zap, } from "lucide-react"; import { Shell } from "@/components/Shell"; import { useConfirm } from "@/components/ConfirmDialog"; import { useToast } from "@/components/Toast"; import { PageLoader } from "@/components/ui"; import { fetchJson, fmtTs, todayBeijingISO } from "@/lib/api"; type SetupStep = { id: string; title: string; url?: string; done: boolean }; type Channel = { id: string; name: string; tiktok_username?: string; enabled?: boolean; authorized?: boolean; oauth_ok?: number; oauth_error?: string; privacy_level?: string; title_template?: string; description_template?: string; note?: string; }; type BoardChannel = { id: string; name?: string; tiktok_username?: string; enabled?: boolean; authorized?: boolean; used: number; scheduled: number; uploaded: number; pending: number; gap?: number; max_met?: boolean; daily_max?: number; }; type Upcoming = { id: string; anchor_name?: string; channel_name?: string; upload_at?: number; status?: string; can_upload_now?: boolean; }; type Job = { id: string; anchor_name?: string; channel_name?: string; status?: string; push_date?: string; error?: string; clip_ready?: boolean; tiktok_publish_id?: string; created_at?: number; finished_at?: number; }; export default function TikTokPage() { const toast = useToast(); const confirm = useConfirm(); const leftPanelRef = useRef(null); const rightPanelRef = useRef(null); const [loading, setLoading] = useState(true); const [status, setStatus] = useState(null); const [channels, setChannels] = useState([]); const [jobs, setJobs] = useState([]); const [jobTotal, setJobTotal] = useState(0); const [clientKey, setClientKey] = useState(""); const [clientSecret, setClientSecret] = useState(""); const [savingCreds, setSavingCreds] = useState(false); const [showForm, setShowForm] = useState(false); const [editId, setEditId] = useState(""); const [formName, setFormName] = useState("TikTok 账号"); const [formPrivacy, setFormPrivacy] = useState("SELF_ONLY"); const [formTitle, setFormTitle] = useState("{anchor} #fyp"); const [formDesc, setFormDesc] = useState("{anchor}\n{url}"); const [uploadingId, setUploadingId] = useState(""); const load = useCallback(async () => { const iso = todayBeijingISO(); const [st, j] = await Promise.all([ fetchJson("/api/tiktok/status"), fetchJson(`/api/tiktok/jobs?push_date=${iso}&limit=30`), ]); setStatus(st); setChannels(st?.channels || []); setJobs(j?.jobs || []); setJobTotal(j?.total || 0); setLoading(false); }, []); useEffect(() => { void load(); const t = setInterval(() => void load(), 12000); return () => clearInterval(t); }, [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(); }); useEffect(() => { const params = new URLSearchParams(window.location.search); const oauth = params.get("oauth"); if (oauth === "ok") { toast.push(`TikTok 授权成功:${params.get("title") || ""}`, "ok"); window.history.replaceState({}, "", "/tiktok"); } else if (oauth === "error") { toast.push(`授权失败:${params.get("msg") || ""}`, "err"); window.history.replaceState({}, "", "/tiktok"); } }, [toast]); const setup = status?.setup; const setupDone = setup?.steps?.every((s: SetupStep) => s.done); const board = status?.board || {}; const boardChannels: BoardChannel[] = board.channels || []; const upcoming: Upcoming[] = board.upcoming || []; const beijingWindow = board.beijing_window || ""; const oauthConfigured = status?.oauth_configured; const redirectUri = status?.oauth_redirect_uri || ""; const togglePipeline = async () => { const on = status?.enabled; await fetchJson(on ? "/api/tiktok/stop" : "/api/tiktok/start", { method: "POST" }); toast.push(on ? "TikTok 已暂停" : "TikTok 已启动", "ok"); void load(); }; const saveCredentials = async () => { if (!clientKey.trim()) { toast.push("请填写 Client Key", "err"); return; } setSavingCreds(true); try { await fetchJson("/api/tiktok/oauth/config", { method: "POST", body: JSON.stringify({ client_key: clientKey.trim(), client_secret: clientSecret.trim() }), }); toast.push("凭证已保存", "ok"); setClientSecret(""); void load(); } catch (e: any) { toast.push(e?.message || "保存失败", "err"); } finally { setSavingCreds(false); } }; const addChannel = async () => { await fetchJson("/api/tiktok/channels", { method: "POST", body: JSON.stringify({ name: formName, privacy_level: formPrivacy, title_template: formTitle, description_template: formDesc, }), }); toast.push("账号已添加,请点击「授权」", "ok"); setShowForm(false); void load(); }; const saveChannel = async () => { if (!editId) return; await fetchJson(`/api/tiktok/channels/${editId}`, { method: "PATCH", body: JSON.stringify({ name: formName, privacy_level: formPrivacy, title_template: formTitle, description_template: formDesc, }), }); toast.push("已保存", "ok"); setShowForm(false); setEditId(""); void load(); }; const removeChannel = async (id: string) => { const ok = await confirm({ title: "删除 TikTok 账号", message: "确定删除此账号?", confirmLabel: "删除", destructive: true, }); if (!ok) return; await fetchJson(`/api/tiktok/channels/${id}`, { method: "DELETE" }); toast.push("已删除", "ok"); void load(); }; const authorize = (id: string) => { window.location.href = `/api/tiktok/oauth/start?channel_pk=${encodeURIComponent(id)}`; }; const sampleNow = async () => { const r = await fetchJson("/api/tiktok/sample-now", { method: "POST" }); toast.push(`已取样 ${r.enqueued || 0} 条`, "ok"); void load(); }; const uploadNow = async (jobId: string) => { setUploadingId(jobId); try { await fetchJson(`/api/tiktok/jobs/${jobId}/upload-now`, { method: "POST" }); toast.push("上传成功", "ok"); void load(); } catch (e: any) { toast.push(e?.message || "上传失败", "err"); } finally { setUploadingId(""); } }; const retryJob = async (jobId: string) => { await fetchJson(`/api/tiktok/jobs/${jobId}/retry`, { method: "POST" }); toast.push("已重新排队", "ok"); void load(); }; const startEdit = (ch: Channel) => { setEditId(ch.id); setFormName(ch.name || "TikTok 账号"); setFormPrivacy(ch.privacy_level || "SELF_ONLY"); setFormTitle(ch.title_template || "{anchor} #fyp"); setFormDesc(ch.description_template || "{anchor}\n{url}"); setShowForm(true); }; const statusLabel = useMemo( () => ({ pending: "待录制", recording: "录制中", recorded: "成片就绪", scheduled: "已排程", uploading: "上传中", uploaded: "已上传", failed: "失败", }), [], ); if (loading && !status) { return ( ); } return (
{/* Header */}

TikTok 自动上传

独立模块 · 不影响 Shorts · 抖音直播录屏 → TikTok

{setupDone && ( <> )}
{/* Setup wizard */} {!setupDone && (

🚀 三步完成配置(约 5 分钟)

按顺序完成下面步骤,即可自动上传。未审核应用只能发「仅自己可见」。

{(setup?.steps || []).map((step: SetupStep, i: number) => (
{step.done ? ( ) : ( )}
{i + 1}. {step.title}
{step.url && !step.done && ( 打开官方文档 )}
))}
{!oauthConfigured && (

填写 TikTok 应用凭证

Redirect URI 填:{redirectUri}

)} {oauthConfigured && channels.length === 0 && ( )} {setup?.note_unaudited && (

⚠️ {setup.note_unaudited}

)}
)} {/* Summary cards */} {setupDone && (
今日剩余配额
{status?.quota_gap ?? "—"}
{beijingWindow}
抖音直播中
{status?.douyin_live_count ?? 0}
可取样来源
即将上传
{upcoming.length}
已排程素材
运行状态
{status?.enabled ? "自动上传中" : "已暂停"}
)} {/* Control bar */} {oauthConfigured && (
开发者后台
)} {/* Channel form */} {showForm && (

{editId ? "编辑账号" : "新增 TikTok 账号"}

)} {/* Two-column board */} {channels.length > 0 && (

账号配额({channels.length})

北京日 {beijingWindow || "—"} · 每账号 9 条/日
{(boardChannels.length ? boardChannels : channels).map((ch) => { const full = channels.find((x) => x.id === ch.id); const pct = Math.min(100, Math.round(((ch.used || 0) / Math.max(1, ch.daily_max || 9)) * 100)); return (
{ch.name || "未命名"}
{ch.tiktok_username || "—"}
{full?.authorized ? "已授权" : "未授权"}
已传 {ch.uploaded ?? 0} 排程 {ch.scheduled ?? 0} 待录 {ch.pending ?? 0} {ch.max_met ? "已满" : `余 ${ch.gap ?? 0}`}
{full && ( )}
); })}

即将上传

素材 {upcoming.length}
{upcoming.length === 0 ? (
暂无排程。启动自动上传后,系统会从抖音直播中取样。
) : ( upcoming.map((u) => (
{u.anchor_name || "—"}
{u.channel_name} · {u.upload_at ? fmtTs(u.upload_at) : "—"}
{u.can_upload_now && ( )}
)) )}
)} {/* Jobs table */} {setupDone && (

任务流水(今日 {jobTotal})

{jobs.length === 0 ? ( ) : ( jobs.map((j) => ( )) )}
主播 账号 状态 时间 操作
暂无任务
{j.anchor_name || "—"} {j.channel_name || "—"} {statusLabel[j.status as keyof typeof statusLabel] || j.status} {j.error && (
{j.error}
)}
{j.finished_at ? fmtTs(j.finished_at) : j.created_at ? fmtTs(j.created_at) : "—"}
{j.clip_ready && j.status !== "uploaded" && ( )} {j.status === "failed" && ( )}
)} {/* Quick help */}
使用说明
  1. 在 TikTok 开发者后台创建应用,申请 video.publish 权限
  2. Redirect URI 填:{redirectUri}
  3. 保存 Client Key / Secret → 添加账号 → 点击「授权」
  4. 点击「启动自动上传」,系统会自动从抖音直播取样、录屏、错峰上传
); }