douyinWEB/desktop/src/pages/GroupsPage.tsx
eric 1112a4d055 Handle YouTube Video Uploads daily quota (429) with project budget and pause-until-reset.
Add shorts_yt_quota module, Shorts UI quota banner, overview tweaks (hide upcoming opens, align events panel height), Electron desktop client scaffold, and deploy scripts; update README.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-11 02:04:44 -05:00

868 lines
34 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<Group[]>([]);
const [total, setTotal] = useState(0);
const [q, setQ] = useState("");
const [enabledFilter, setEnabledFilter] = useState("");
const [form, setForm] = useState(emptyForm);
const [selected, setSelected] = useState<Set<string>>(new Set());
const [loading, setLoading] = useState(false);
const [busy, setBusy] = useState("");
const [error, setError] = useState("");
const [msg, setMsg] = useState("");
const [edit, setEdit] = useState<Group | null>(null);
const [editForm, setEditForm] = useState(emptyForm);
const [editBusy, setEditBusy] = useState(false);
const [probeBusy, setProbeBusy] = useState("");
const [probeInfo, setProbeInfo] = useState<Record<string, any>>({});
const [monStatus, setMonStatus] = useState<any>(null);
const [ytStats, setYtStats] = useState<RelayStats | null>(null);
const [channelStats, setChannelStats] = useState<ChannelStat[]>([]);
const [recentSessions, setRecentSessions] = useState<RecentSession[]>([]);
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 (
<Shell>
<div className="mb-4 flex flex-wrap items-end justify-between gap-3">
<div>
<h2 className="font-display text-2xl font-semibold">📺 YouTube 频道分组</h2>
<p className="text-sm text-slate-400">
开播轮询入库场次,与抖音共用同一套时长 / 时段 / 排行分析。
</p>
</div>
<div className="flex flex-wrap gap-2">
<Link
to="/sessions?platform=youtube"
className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10"
>
场次明细
</Link>
<Link
to="/slots?platform=youtube"
className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10"
>
时段分析
</Link>
<a
href="/api/groups/export"
className="inline-flex items-center gap-2 rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10"
>
<Download className="h-4 w-4" />
导出 CSV
</a>
</div>
</div>
<div className="mb-4 flex flex-wrap gap-2">
<button
type="button"
onClick={() => {
setTab("monitor");
if (typeof window !== "undefined") {
const u = new URL(window.location.href);
u.searchParams.delete("tab");
window.history.replaceState({}, "", u.pathname + u.search);
}
}}
className={`rounded-xl px-4 py-2 text-sm ${
tab === "monitor" ? "bg-teal-500/20 text-teal-50 ring-1 ring-teal-400/30" : "bg-white/5 text-slate-400"
}`}
>
监控
</button>
<button
type="button"
onClick={() => {
setTab("analytics");
if (typeof window !== "undefined") {
const u = new URL(window.location.href);
u.searchParams.set("tab", "analytics");
window.history.replaceState({}, "", u.pathname + u.search);
}
}}
className={`rounded-xl px-4 py-2 text-sm ${
tab === "analytics" ? "bg-amber-500/20 text-amber-50 ring-1 ring-amber-400/30" : "bg-white/5 text-slate-400"
}`}
>
数据分析
</button>
</div>
<div className="mb-4 flex flex-wrap items-center gap-3 rounded-xl border border-white/10 bg-black/25 px-4 py-3 text-sm">
<span className={monStatus?.yt_monitor_enabled ? "text-teal-300" : "text-slate-500"}>
轮询:{monStatus?.yt_monitor_enabled ? "运行中" : "已暂停"}
{monStatus?.running ? "" : " · 任务未启动"}
</span>
<span className="text-slate-500">
启用 {monStatus?.groups?.enabled ?? "—"} · 直播中 {monStatus?.groups?.live ?? "—"} · 积压{" "}
{monStatus?.groups?.overdue ?? "—"} · 已检 {monStatus?.checked_total ?? 0}
</span>
{monStatus?.quiet_hours_active ? <span className="text-amber-300">静默时段中</span> : null}
{monStatus?.youtube_svc?.ok === false ? (
<span className="text-rose-300">youtube-svc 异常</span>
) : null}
<button
type="button"
disabled={busy === "mon-on"}
onClick={() => void toggleYtMonitor(true)}
className="rounded-lg border border-teal-500/30 px-2 py-1 text-xs text-teal-100"
>
开启轮询
</button>
<button
type="button"
disabled={busy === "mon-off"}
onClick={() => void toggleYtMonitor(false)}
className="rounded-lg border border-white/10 px-2 py-1 text-xs"
>
暂停轮询
</button>
</div>
{error ? <div className="mb-4 rounded-lg border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm">{error}</div> : null}
{msg ? <div className="mb-4 rounded-lg border border-teal-500/30 bg-teal-500/10 px-4 py-3 text-sm">{msg}</div> : null}
{tab === "analytics" ? (
<div className="space-y-4">
<div className="flex flex-wrap items-end gap-2 rounded-xl border border-white/10 bg-black/25 p-3">
<label className="text-xs text-slate-400">
起
<input
type="date"
value={dateFrom}
onChange={(e) => setDateFrom(e.target.value)}
className="mt-1 block rounded-lg border border-white/10 bg-slate-900 px-2 py-1.5 text-sm"
/>
</label>
<label className="text-xs text-slate-400">
止
<input
type="date"
value={dateTo}
onChange={(e) => setDateTo(e.target.value)}
className="mt-1 block rounded-lg border border-white/10 bg-slate-900 px-2 py-1.5 text-sm"
/>
</label>
<button
type="button"
onClick={() => void loadAnalytics()}
className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10"
>
{analyticsBusy ? <Loader2 className="inline h-3.5 w-3.5 animate-spin" /> : null} 刷新分析
</button>
<span className="text-xs text-slate-500">北京日 · 与抖音场次统计同一口径</span>
</div>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
{[
["场次", 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]) => (
<div key={label as string} className="rounded-2xl border border-white/10 bg-black/30 px-4 py-3">
<div className="text-xs text-slate-500">{label}</div>
<div className="mt-1 font-display text-2xl text-white">{value}</div>
<div className="mt-1 text-[11px] text-slate-500">{hint}</div>
</div>
))}
</div>
<section className="rounded-2xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-3 font-display text-sm font-medium text-slate-100">可视化分析</h3>
<SessionCharts stats={ytStats} />
</section>
<section className="overflow-hidden rounded-2xl border border-white/10 bg-black/25">
<div className="border-b border-white/5 px-4 py-3 text-sm font-medium text-slate-100">频道排行</div>
<div className="overflow-x-auto">
<table className="min-w-full text-left text-sm">
<thead className="bg-white/5 text-xs uppercase text-slate-400">
<tr>
<th className="px-3 py-2">频道</th>
<th className="px-3 py-2">状态</th>
<th className="px-3 py-2">场次</th>
<th className="px-3 py-2">小时</th>
<th className="px-3 py-2">最近开播</th>
</tr>
</thead>
<tbody>
{channelStats.map((ch) => (
<tr key={String(ch.group_id || ch.room_id || ch.name)} className="border-t border-white/5">
<td className="px-3 py-2">
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium text-slate-100">{ch.name || "—"}</span>
{ch.group_id ? <YouTubeLiveBadge refKey={groupLiveRef(ch.group_id)} compact showOffline /> : null}
</div>
<div className="font-mono text-[10px] text-slate-500">{ch.channel_id || ch.room_id || "—"}</div>
</td>
<td className="px-3 py-2">
<span className={Number(ch.active) > 0 || ch.last_status === "live" ? "text-rose-300" : "text-slate-500"}>
{Number(ch.active) > 0 || ch.last_status === "live" ? "LIVE" : ch.last_status || "offline"}
</span>
</td>
<td className="px-3 py-2 tabular-nums">{ch.sessions ?? 0}</td>
<td className="px-3 py-2 tabular-nums">{Number(ch.hours_total || 0).toFixed(1)}</td>
<td className="px-3 py-2 text-slate-400">{ch.last_started_at ? fmtTs(ch.last_started_at) : "—"}</td>
</tr>
))}
{!channelStats.length ? (
<tr>
<td colSpan={5} className="px-3 py-8 text-center text-slate-500">
暂无 YouTube 场次。开启分组轮询并等频道开播后会出现在这里。
</td>
</tr>
) : null}
</tbody>
</table>
</div>
</section>
<section className="overflow-hidden rounded-2xl border border-white/10 bg-black/25">
<div className="flex items-center justify-between border-b border-white/5 px-4 py-3">
<span className="text-sm font-medium text-slate-100">最近场次</span>
<Link to="/sessions?platform=youtube" className="text-xs text-teal-300 hover:underline">
全部 →
</Link>
</div>
<div className="overflow-x-auto">
<table className="min-w-full text-left text-sm">
<thead className="bg-white/5 text-xs uppercase text-slate-400">
<tr>
<th className="px-3 py-2">频道</th>
<th className="px-3 py-2">标题</th>
<th className="px-3 py-2">开始</th>
<th className="px-3 py-2">时长</th>
<th className="px-3 py-2">状态</th>
</tr>
</thead>
<tbody>
{recentSessions.map((s) => (
<tr key={s.id} className="border-t border-white/5">
<td className="px-3 py-2 text-slate-100">{s.anchor_name || s.room_id || "—"}</td>
<td className="max-w-[240px] truncate px-3 py-2 text-slate-400">{s.title || "—"}</td>
<td className="px-3 py-2 text-slate-400">{fmtTs(s.started_at)}</td>
<td className="px-3 py-2 tabular-nums text-slate-300">{fmtDuration(s.duration_seconds)}</td>
<td className="px-3 py-2">{s.ended_at ? "已结束" : <span className="text-rose-300">在播</span>}</td>
</tr>
))}
{!recentSessions.length ? (
<tr>
<td colSpan={5} className="px-3 py-8 text-center text-slate-500">
暂无场次
</td>
</tr>
) : null}
</tbody>
</table>
</div>
</section>
</div>
) : null}
{tab === "monitor" ? (
<>
<div className="mb-4 grid gap-3 rounded-xl border border-white/10 bg-black/30 p-4 md:grid-cols-2">
<label className="block text-xs text-slate-400">
分组名称
<input
value={form.name}
onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
placeholder="例如:Google Developers"
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="block text-xs text-slate-400">
频道 URL / @handle / UC…
<input
value={form.channel_url}
onChange={(e) => setForm((f) => ({ ...f, channel_url: e.target.value }))}
placeholder="https://www.youtube.com/@xxx 或 UC…"
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="block text-xs text-slate-400 md:col-span-2">
分组内 URL(频道未播时也会探测,每行一条,最多 6 条,共 {urlLineCount})
<textarea
value={form.urls}
onChange={(e) => setForm((f) => ({ ...f, urls: e.target.value }))}
rows={4}
placeholder={"https://www.youtube.com/watch?v=...\nhttps://youtu.be/..."}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 font-mono text-xs"
/>
</label>
<label className="block text-xs text-slate-400">
备注
<input
value={form.note}
onChange={(e) => setForm((f) => ({ ...f, note: e.target.value }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<div className="flex items-end justify-between gap-3">
<label className="flex items-center gap-2 text-sm text-slate-300">
<input
type="checkbox"
checked={form.enabled}
onChange={(e) => setForm((f) => ({ ...f, enabled: e.target.checked }))}
/>
启用
</label>
<button
type="button"
disabled={!form.name.trim() || !form.channel_url.trim() || busy === "create"}
onClick={() => void createGroup()}
className="inline-flex items-center gap-2 rounded-lg bg-teal-500/20 px-4 py-2 text-sm text-teal-100 ring-1 ring-teal-400/30 hover:bg-teal-500/30 disabled:opacity-50"
>
{busy === "create" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}
新建分组
</button>
</div>
</div>
<div className="mb-4 flex flex-wrap items-center gap-2">
<input
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder="搜索名称 / 频道 / URL / 备注"
className="min-w-[200px] flex-1 rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
<select
value={enabledFilter}
onChange={(e) => setEnabledFilter(e.target.value)}
className="rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
>
<option value="">全部状态</option>
<option value="1">仅启用</option>
<option value="0">仅停用</option>
</select>
<button
type="button"
onClick={() => void load()}
className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10"
>
刷新 {loading ? <Loader2 className="ml-1 inline h-3 w-3 animate-spin" /> : null}
</button>
<button type="button" onClick={() => void bulk("enable")} className="rounded-lg border border-white/10 px-3 py-2 text-sm">
批量启用
</button>
<button type="button" onClick={() => void bulk("disable")} className="rounded-lg border border-white/10 px-3 py-2 text-sm">
批量停用
</button>
<button
type="button"
onClick={() => void bulk("delete")}
className="rounded-lg border border-rose-500/30 px-3 py-2 text-sm text-rose-200"
>
批量删除
</button>
<span className="text-xs text-slate-500">共 {total} · 已选 {selected.size}</span>
</div>
<div className="overflow-hidden rounded-xl border border-white/10 bg-black/20">
<table className="min-w-full text-left text-sm">
<thead className="bg-white/5 text-xs uppercase text-slate-400">
<tr>
<th className="px-3 py-3">
<input
type="checkbox"
checked={groups.length > 0 && selected.size === groups.length}
onChange={(e) => toggleAll(e.target.checked)}
/>
</th>
<th className="px-3 py-3">名称</th>
<th className="px-3 py-3">频道</th>
<th className="px-3 py-3">URL 数</th>
<th className="px-3 py-3">轮询状态</th>
<th className="px-3 py-3">启用</th>
<th className="px-3 py-3">更新</th>
<th className="px-3 py-3">操作</th>
</tr>
</thead>
<tbody>
{groups.map((g) => (
<tr key={g.id} className="border-t border-white/5 align-top">
<td className="px-3 py-3">
<input
type="checkbox"
checked={selected.has(g.id)}
onChange={(e) => toggleOne(g.id, e.target.checked)}
/>
</td>
<td className="px-3 py-3">
<div className="flex flex-wrap items-center gap-2">
<div className="font-medium text-white">{g.name}</div>
<YouTubeLiveBadge refKey={groupLiveRef(g.id)} compact />
</div>
{g.note ? <div className="mt-1 text-xs text-slate-500">{g.note}</div> : null}
{g.last_title || probeInfo[g.id]?.live?.title ? (
<div className="mt-1 max-w-[220px] truncate text-xs text-slate-500">
{g.last_title || probeInfo[g.id]?.live?.title}
</div>
) : null}
</td>
<td className="px-3 py-3">
<a
href={g.channel_url}
target="_blank"
rel="noreferrer"
className="font-mono text-xs text-teal-300/90 hover:underline"
>
{g.channel_key || g.channel_url}
</a>
{g.handle ? <div className="mt-1 text-xs text-slate-500">@{g.handle}</div> : null}
</td>
<td className="px-3 py-3">
<div>{g.url_count ?? (g.urls || []).length}</div>
{(g.urls || []).slice(0, 2).map((u) => (
<div key={u} className="mt-0.5 max-w-[220px] truncate font-mono text-[11px] text-slate-500">
{u}
</div>
))}
{(g.urls || []).length > 2 ? (
<div className="text-[11px] text-slate-600">+{(g.urls || []).length - 2} more</div>
) : null}
</td>
<td className="px-3 py-3">
<YouTubeLiveBadge refKey={groupLiveRef(g.id)} showTitle />
{g.last_status === "error" ? (
<span className="mt-1 block text-amber-300" title={g.last_error || ""}>
错误
</span>
) : null}
{g.last_checked_at ? (
<div className="mt-1 text-[11px] text-slate-600">{fmtTs(g.last_checked_at)}</div>
) : null}
</td>
<td className="px-3 py-3">
<span className={g.enabled ? "text-teal-300" : "text-slate-500"}>{g.enabled ? "启用" : "停用"}</span>
</td>
<td className="px-3 py-3 text-slate-400">{fmtTs(g.updated_at)}</td>
<td className="px-3 py-3">
<div className="flex flex-wrap gap-2">
<button
type="button"
onClick={() => void probeOne(g.id)}
className="inline-flex items-center gap-1 rounded border border-teal-500/30 px-2 py-1 text-xs text-teal-100"
>
{probeBusy === g.id ? <Loader2 className="h-3 w-3 animate-spin" /> : <Zap className="h-3 w-3" />}
探测
</button>
<button
type="button"
onClick={() => openEdit(g)}
className="inline-flex items-center gap-1 rounded border border-white/10 px-2 py-1 text-xs"
>
<Pencil className="h-3 w-3" />
编辑
</button>
<button
type="button"
onClick={() => void removeOne(g.id)}
className="inline-flex items-center gap-1 rounded border border-rose-500/30 px-2 py-1 text-xs text-rose-200"
>
{busy === g.id ? <Loader2 className="h-3 w-3 animate-spin" /> : <Trash2 className="h-3 w-3" />}
删除
</button>
</div>
</td>
</tr>
))}
{groups.length === 0 && !loading ? (
<tr>
<td colSpan={8} className="px-3 py-10 text-center text-slate-500">
暂无 YouTube 分组
</td>
</tr>
) : null}
</tbody>
</table>
</div>
</>
) : null}
<Modal open={!!edit} onClose={() => setEdit(null)}>
{edit ? (
<div className="grid gap-3">
<h3 className="font-display text-lg font-semibold text-white">编辑分组</h3>
<label className="block text-xs text-slate-400">
分组名称
<input
value={editForm.name}
onChange={(e) => setEditForm((f) => ({ ...f, name: e.target.value }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="block text-xs text-slate-400">
频道 URL
<input
value={editForm.channel_url}
onChange={(e) => setEditForm((f) => ({ ...f, channel_url: e.target.value }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="block text-xs text-slate-400">
分组内 URL(多行)
<textarea
value={editForm.urls}
onChange={(e) => setEditForm((f) => ({ ...f, urls: e.target.value }))}
rows={6}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 font-mono text-xs"
/>
</label>
<label className="block text-xs text-slate-400">
备注
<input
value={editForm.note}
onChange={(e) => setEditForm((f) => ({ ...f, note: e.target.value }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="flex items-center gap-2 text-sm text-slate-300">
<input
type="checkbox"
checked={editForm.enabled}
onChange={(e) => setEditForm((f) => ({ ...f, enabled: e.target.checked }))}
/>
启用
</label>
<div className="flex justify-end gap-2 pt-2">
<button type="button" onClick={() => setEdit(null)} className="rounded-lg border border-white/10 px-3 py-2 text-sm">
取消
</button>
<button
type="button"
disabled={editBusy || !editForm.name.trim() || !editForm.channel_url.trim()}
onClick={() => void saveEdit()}
className="inline-flex items-center gap-2 rounded-lg bg-teal-500/20 px-4 py-2 text-sm text-teal-100 ring-1 ring-teal-400/30 disabled:opacity-50"
>
{editBusy ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
保存
</button>
</div>
</div>
) : null}
</Modal>
</Shell>
);
}