import { useCallback, useEffect, useMemo, useState } from "react"; import { Link } from "react-router-dom"; import { Loader2, Pencil, Plus, Trash2, Download, Zap } from "lucide-react"; import { Shell } from "@/components/Shell"; import { useConfirm } from "@/components/ConfirmDialog"; import { useToast } from "@/components/Toast"; import { Modal } from "@/components/Modal"; import { SessionCharts, type RelayStats } from "@/components/SessionCharts"; import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge"; import { fetchJson, fmtDuration, fmtTs, todayBeijingISO, shiftBeijingISO } from "@/lib/api"; import { groupLiveRef } from "@/lib/youtubeLive"; import { useAutoRefresh, type RefreshOpts } from "@/lib/realtime"; type Group = { id: string; name: string; platform: string; channel_url: string; channel_key?: string; handle?: string; urls?: string[]; url_count?: number; note?: string; enabled: boolean; last_status?: string; last_title?: string; last_live_url?: string; last_checked_at?: number; next_check_at?: number; last_error?: string; updated_at?: number; }; type ChannelStat = { group_id?: string | null; name?: string; channel_id?: string; channel_url?: string; handle?: string; enabled?: boolean | null; last_status?: string; last_title?: string; last_live_url?: string; sessions?: number; hours_total?: number; last_started_at?: number | null; active?: number; room_id?: string; }; type RecentSession = { id: string; anchor_name?: string; title?: string; room_id?: string; started_at?: number; ended_at?: number | null; duration_seconds?: number; status?: string; source_url?: string; }; const emptyForm = { name: "", channel_url: "", urls: "", note: "", enabled: true, }; export default function GroupsPage() { const confirm = useConfirm(); const toast = useToast(); const [tab, setTab] = useState<"monitor" | "analytics">("monitor"); const [groups, setGroups] = useState([]); const [total, setTotal] = useState(0); const [q, setQ] = useState(""); const [enabledFilter, setEnabledFilter] = useState(""); const [form, setForm] = useState(emptyForm); const [selected, setSelected] = useState>(new Set()); const [loading, setLoading] = useState(false); const [busy, setBusy] = useState(""); const [error, setError] = useState(""); const [msg, setMsg] = useState(""); const [edit, setEdit] = useState(null); const [editForm, setEditForm] = useState(emptyForm); const [editBusy, setEditBusy] = useState(false); const [probeBusy, setProbeBusy] = useState(""); const [probeInfo, setProbeInfo] = useState>({}); const [monStatus, setMonStatus] = useState(null); const [ytStats, setYtStats] = useState(null); const [channelStats, setChannelStats] = useState([]); const [recentSessions, setRecentSessions] = useState([]); const [analyticsBusy, setAnalyticsBusy] = useState(false); const [dateFrom, setDateFrom] = useState(() => shiftBeijingISO(todayBeijingISO(), -29)); const [dateTo, setDateTo] = useState(() => todayBeijingISO()); const query = useMemo(() => { const p = new URLSearchParams(); p.set("platform", "youtube"); if (q.trim()) p.set("q", q.trim()); if (enabledFilter === "1") p.set("enabled", "true"); if (enabledFilter === "0") p.set("enabled", "false"); p.set("limit", "500"); return p.toString(); }, [q, enabledFilter]); const load = useCallback(async (opts?: RefreshOpts) => { const silent = Boolean(opts?.silent); if (!silent) { setLoading(true); setError(""); } try { const [data, mon] = await Promise.all([ fetchJson(`/api/groups?${query}`), fetchJson("/api/youtube-monitor/status").catch(() => null), ]); setGroups(data.groups || []); setTotal(Number(data.total) || 0); if (!silent) setSelected(new Set()); if (mon) setMonStatus(mon); } catch (e) { if (!silent) setError((e as Error).message); } finally { if (!silent) setLoading(false); } }, [query]); const loadAnalytics = useCallback(async (opts?: RefreshOpts) => { const silent = Boolean(opts?.silent); if (!silent) setAnalyticsBusy(true); try { const p = new URLSearchParams(); if (dateFrom) p.set("date_from", dateFrom); if (dateTo) p.set("date_to", dateTo); p.set("top_anchors", "25"); const data = await fetchJson(`/api/groups/analytics?${p}`); setYtStats((data.stats || null) as RelayStats | null); setChannelStats((data.channels || []) as ChannelStat[]); setRecentSessions((data.recent_sessions || []) as RecentSession[]); if (data.monitor) setMonStatus(data.monitor); } catch (e) { if (!silent) setError((e as Error).message); } finally { if (!silent) setAnalyticsBusy(false); } }, [dateFrom, dateTo]); useAutoRefresh(load, { intervalMs: 20000, enabled: tab === "monitor" }); useAutoRefresh(loadAnalytics, { intervalMs: 30000, enabled: tab === "analytics" }); useEffect(() => { if (typeof window === "undefined") return; const p = new URLSearchParams(window.location.search); const channel = p.get("channel") || p.get("url") || ""; const name = p.get("name") || ""; const t = p.get("tab"); if (t === "analytics") setTab("analytics"); if (channel || name) { setForm((f) => ({ ...f, channel_url: channel || f.channel_url, name: name || f.name, })); } }, []); useEffect(() => { if (tab === "analytics") void loadAnalytics(); }, [tab, loadAnalytics]); const urlLineCount = form.urls .split(/\r?\n/) .map((l) => l.trim()) .filter((l) => l && !l.startsWith("#")).length; async function createGroup() { setBusy("create"); setError(""); setMsg(""); try { await fetchJson("/api/groups", { method: "POST", body: JSON.stringify({ name: form.name, channel_url: form.channel_url, urls: form.urls, note: form.note, platform: "youtube", enabled: form.enabled, }), }); setForm(emptyForm); setMsg("已创建分组"); await load(); } catch (e) { setError((e as Error).message); } finally { setBusy(""); } } function openEdit(g: Group) { setEdit(g); setEditForm({ name: g.name || "", channel_url: g.channel_url || "", urls: (g.urls || []).join("\n"), note: g.note || "", enabled: !!g.enabled, }); } async function saveEdit() { if (!edit) return; setEditBusy(true); setError(""); try { await fetchJson(`/api/groups/${edit.id}`, { method: "PATCH", body: JSON.stringify({ name: editForm.name, channel_url: editForm.channel_url, urls: editForm.urls, note: editForm.note, enabled: editForm.enabled, }), }); setMsg(`已更新 ${editForm.name}`); setEdit(null); await load(); } catch (e) { setError((e as Error).message); } finally { setEditBusy(false); } } async function removeOne(id: string) { const ok = await confirm({ title: "删除分组", message: "确定删除该 YouTube 分组?关联监控将停止。", confirmLabel: "删除", destructive: true, }); if (!ok) return; setBusy(id); try { await fetchJson(`/api/groups/${id}`, { method: "DELETE" }); toast.push("分组已删除", "ok"); await load(); } catch (e) { setError((e as Error).message); toast.push((e as Error).message, "err"); } finally { setBusy(""); } } async function probeOne(id: string) { setProbeBusy(id); setError(""); try { const data = await fetchJson(`/api/groups/${id}/probe`, { method: "POST" }); const probe = data.probe || data.result || {}; const g = data.group || {}; setProbeInfo((prev) => ({ ...prev, [id]: { ...probe, last_status: g.last_status } })); const live = Boolean(probe.is_live || g.last_status === "live"); setMsg( live ? `${g.name || probe.title || "频道"} 正在直播${g.last_title || probe.live?.title ? `:${g.last_title || probe.live?.title}` : ""}` : `${g.name || probe.title || "频道"} 当前未开播`, ); await load(); } catch (e) { setError((e as Error).message); } finally { setProbeBusy(""); } } async function toggleYtMonitor(enabled: boolean) { setBusy(enabled ? "mon-on" : "mon-off"); try { await fetchJson(enabled ? "/api/youtube-monitor/start" : "/api/youtube-monitor/stop", { method: "POST" }); setMsg(enabled ? "已开启 YouTube 分组轮询" : "已暂停 YouTube 分组轮询"); await load(); } catch (e) { setError((e as Error).message); } finally { setBusy(""); } } async function bulk(action: "enable" | "disable" | "delete") { const ids = Array.from(selected); if (!ids.length) { setMsg("请先勾选分组"); return; } if (action === "delete") { const ok = await confirm({ title: "批量删除分组", message: `确定删除选中的 ${ids.length} 个分组?`, confirmLabel: "删除", destructive: true, }); if (!ok) return; } setBusy(action); setError(""); try { const data = await fetchJson("/api/groups/bulk", { method: "POST", body: JSON.stringify({ action, ids }), }); setMsg(`批量${action}:${data.affected || ids.length}`); await load(); } catch (e) { setError((e as Error).message); } finally { setBusy(""); } } function toggleAll(checked: boolean) { setSelected(checked ? new Set(groups.map((g) => g.id)) : new Set()); } function toggleOne(id: string, checked: boolean) { setSelected((prev) => { const next = new Set(prev); if (checked) next.add(id); else next.delete(id); return next; }); } return (

📺 YouTube 频道分组

开播轮询入库场次,与抖音共用同一套时长 / 时段 / 排行分析。

场次明细 时段分析 导出 CSV
轮询:{monStatus?.yt_monitor_enabled ? "运行中" : "已暂停"} {monStatus?.running ? "" : " · 任务未启动"} 启用 {monStatus?.groups?.enabled ?? "—"} · 直播中 {monStatus?.groups?.live ?? "—"} · 积压{" "} {monStatus?.groups?.overdue ?? "—"} · 已检 {monStatus?.checked_total ?? 0} {monStatus?.quiet_hours_active ? 静默时段中 : null} {monStatus?.youtube_svc?.ok === false ? ( youtube-svc 异常 ) : null}
{error ?
{error}
: null} {msg ?
{msg}
: null} {tab === "analytics" ? (
北京日 · 与抖音场次统计同一口径
{[ ["场次", String(ytStats?.overview?.sessions ?? 0), "YouTube 开播记录"], ["在播", String(ytStats?.overview?.active_sessions ?? 0), "当前未结场"], ["累计小时", Number(ytStats?.overview?.total_hours || 0).toFixed(1), "含进行中时长"], ["频道数", String(ytStats?.overview?.unique_anchors ?? channelStats.length), "有场次的频道"], ].map(([label, value, hint]) => (
{label}
{value}
{hint}
))}

可视化分析

频道排行
{channelStats.map((ch) => ( ))} {!channelStats.length ? ( ) : null}
频道 状态 场次 小时 最近开播
{ch.name || "—"} {ch.group_id ? : null}
{ch.channel_id || ch.room_id || "—"}
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 场次。开启分组轮询并等频道开播后会出现在这里。
最近场次 全部 →
{recentSessions.map((s) => ( ))} {!recentSessions.length ? ( ) : null}
频道 标题 开始 时长 状态
{s.anchor_name || s.room_id || "—"} {s.title || "—"} {fmtTs(s.started_at)} {fmtDuration(s.duration_seconds)} {s.ended_at ? "已结束" : 在播}
暂无场次
) : null} {tab === "monitor" ? ( <>