"use client"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import Link from "next/link"; import { 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 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 [showForm, setShowForm] = useState(false); const [editId, setEditId] = useState(""); const [formName, setFormName] = useState("TikTok 账号"); const [formPrivacy, setFormPrivacy] = useState("PUBLIC_TO_EVERYONE"); const [formTitle, setFormTitle] = useState("{anchor} #fyp"); const [formDesc, setFormDesc] = useState("{anchor}\n{url}"); const [sessionChannelId, setSessionChannelId] = useState(""); const [sessionId, setSessionId] = useState(""); const [sessionDcId, setSessionDcId] = useState("useast2a"); const [sessionUsername, setSessionUsername] = useState(""); const [savingSession, setSavingSession] = useState(false); const [showSessionForm, setShowSessionForm] = useState(false); 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(); }); const setup = status?.setup; const hasChannels = channels.length > 0; const authorizedCount = channels.filter((c) => c.authorized).length; const allReady = hasChannels && authorizedCount === channels.length; const setupDone = allReady; const board = status?.board || {}; const boardChannels: BoardChannel[] = board.channels || []; const upcoming: Upcoming[] = board.upcoming || []; const beijingWindow = board.beijing_window || ""; const openAddForm = () => { setEditId(""); setFormName("TikTok 账号"); setFormPrivacy("PUBLIC_TO_EVERYONE"); setFormTitle("{anchor} #fyp"); setFormDesc("{anchor}\n{url}"); setShowForm(true); setShowSessionForm(false); }; 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 applyCookiePayload = (raw: unknown) => { const data = typeof raw === "string" ? JSON.parse(raw) : raw; const sessionid = String((data as any)?.sessionid || "").trim(); const dc_id = String((data as any)?.dc_id || (data as any)?.["tt-target-idc"] || "").trim(); const username = String((data as any)?.tiktok_username || "").trim(); if (!sessionid) throw new Error("剪贴板里没有 sessionid"); setSessionId(sessionid); setSessionDcId(dc_id || "useast2a"); if (username) setSessionUsername(username); }; const importFromClipboard = async () => { try { const text = await navigator.clipboard.readText(); applyCookiePayload(text); toast.push("已从剪贴板填入 Cookie", "ok"); } catch (e: any) { toast.push(e?.message || "读取剪贴板失败", "err"); } }; const importFromExtension = () => { window.dispatchEvent(new Event("dylive-tiktok-cookie-request")); }; useEffect(() => { const onFill = (ev: Event) => { const detail = (ev as CustomEvent).detail; try { applyCookiePayload(detail); toast.push("已从插件填入 Cookie", "ok"); } catch (e: any) { toast.push(e?.message || "插件数据无效", "err"); } }; window.addEventListener("dylive-tiktok-cookie", onFill as EventListener); return () => window.removeEventListener("dylive-tiktok-cookie", onFill as EventListener); }, [toast]); const saveSession = async () => { if (!sessionChannelId) { toast.push("请选择账号", "err"); return; } if (!sessionId.trim()) { toast.push("请填写 sessionid", "err"); return; } setSavingSession(true); try { await fetchJson(`/api/tiktok/channels/${sessionChannelId}/session`, { method: "POST", body: JSON.stringify({ sessionid: sessionId.trim(), dc_id: sessionDcId.trim() || "useast2a", tiktok_username: sessionUsername.trim(), }), }); toast.push("Cookie 会话已保存", "ok"); setShowSessionForm(false); setSessionId(""); void load(); } catch (e: any) { toast.push(e?.message || "保存失败", "err"); } finally { setSavingSession(false); } }; const addChannel = async () => { const r = await fetchJson("/api/tiktok/channels", { method: "POST", body: JSON.stringify({ name: formName, privacy_level: formPrivacy, title_template: formTitle, description_template: formDesc, }), }); toast.push("账号已添加,请粘贴 Cookie", "ok"); setShowForm(false); const ch = r?.channel as Channel | undefined; if (ch?.id) { openSessionForm(ch.id, ch); } 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 openSessionForm = (id: string, ch?: Channel) => { setSessionChannelId(id); setSessionId(""); setSessionDcId("useast2a"); setSessionUsername(ch?.tiktok_username || ""); setShowForm(false); setShowSessionForm(true); }; 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 || "PUBLIC_TO_EVERYONE"); 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: "失败", }), [], ); const displayChannels: BoardChannel[] = boardChannels.length ? boardChannels : channels.map((c) => ({ id: c.id, name: c.name, tiktok_username: c.tiktok_username, enabled: c.enabled, authorized: c.authorized, used: 0, scheduled: 0, uploaded: 0, pending: 0, gap: 9, max_met: false, daily_max: 9, })); if (loading && !status) { return ( ); } return (
{/* Header */}

TikTok 自动上传

Cookie 上传 · TiktokAutoUploader · 抖音直播录屏 → TikTok

{setupDone && ( <> )}
{/* 首次使用:仅显示引导或表单,不堆叠 */} {!hasChannels && !showForm && !showSessionForm && (

开始使用 TikTok 上传

无需 TikTok 开发者应用。浏览器登录 tiktok.com 后复制{" "} sessionid,粘贴即可上传。

  1. 点击下方「添加账号」
  2. 保存后在弹窗中粘贴 Cookie
  3. 全部账号配置完成后,再点「启动自动上传」
{setup?.note &&

⚠️ {setup.note}

}
)} {/* 有账号但未全部配置 Cookie */} {hasChannels && !allReady && !showForm && !showSessionForm && (
还有 {channels.length - authorizedCount} 个账号未粘贴 Cookie,配置完成后才能启动自动上传。
)} {/* Summary cards */} {setupDone && (
今日剩余配额
{status?.quota_gap ?? "—"}
{beijingWindow}
抖音直播中
{status?.douyin_live_count ?? 0}
可取样来源
即将上传
{upcoming.length}
已排程素材
运行状态
{status?.enabled ? "自动上传中" : "已暂停"}
)} {/* 有账号时:顶部操作栏 */} {hasChannels && !showForm && !showSessionForm && (
打开 TikTok 登录
)} {/* Channel form */} {showForm && (

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

)} {showSessionForm && (

粘贴 TikTok Cookie

推荐用 Chrome 插件或油猴导出 Cookie(无需 F12)。sessionid 等同密码,请勿泄露。

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

账号配额({channels.length})

北京日 {beijingWindow || "—"} · 每账号 9 条/日
{displayChannels.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 ? "Cookie 就绪" : "未配置"}
已传 {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 — 有账号即显示 */} {hasChannels && (

任务流水(今日 {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 — 未完成配置时显示 */} {!allReady && (
如何获取 Cookie
  1. 加载 Chrome 插件:extensions/tiktok-cookie-helper (chrome://extensions → 开发者模式 → 加载已解压)
  2. 登录{" "} tiktok.com ,点插件「复制 JSON」或「填入控制台」
  3. 本页打开「粘贴 Cookie」→「从剪贴板导入」→ 保存
)}
); }