434 lines
19 KiB
TypeScript
434 lines
19 KiB
TypeScript
"use client";
|
||
|
||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||
import { Loader2, RefreshCw, Search } from "lucide-react";
|
||
|
||
import { Shell } from "@/components/Shell";
|
||
import { useConfirm } from "@/components/ConfirmDialog";
|
||
import { useToast } from "@/components/Toast";
|
||
import { SessionCharts, type RelayStats } from "@/components/SessionCharts";
|
||
import { SessionDetailModal } from "@/components/SessionDetailModal";
|
||
import { RoomQuickActions } from "@/components/RoomQuickActions";
|
||
import { PlatformBadge } from "@/components/ui";
|
||
import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge";
|
||
import { fetchJson, fmtDuration, fmtTs, sessionCoverSrc, todayBeijingISO, shiftBeijingISO, detectPlatform } from "@/lib/api";
|
||
import { channelLiveRef } from "@/lib/youtubeLive";
|
||
import { useAutoRefresh, type RefreshOpts } from "@/lib/realtime";
|
||
|
||
type Session = {
|
||
id: string;
|
||
anchor_name?: string;
|
||
source_url?: string;
|
||
room_id?: string;
|
||
room_pk?: string;
|
||
title?: string;
|
||
started_at?: number;
|
||
ended_at?: number | null;
|
||
duration_seconds?: number;
|
||
push_date?: string;
|
||
cover_url?: string;
|
||
status?: string;
|
||
end_reason?: string;
|
||
};
|
||
|
||
export default function SessionsPage() {
|
||
const confirm = useConfirm();
|
||
const toast = useToast();
|
||
const [tab, setTab] = useState<"charts" | "list">("list");
|
||
const [q, setQ] = useState("");
|
||
const [dateFrom, setDateFrom] = useState("");
|
||
const [dateTo, setDateTo] = useState("");
|
||
const [status, setStatus] = useState("");
|
||
const [platform, setPlatform] = useState("");
|
||
const [tag, setTag] = useState("");
|
||
const [tagOptions, setTagOptions] = useState<string[]>([]);
|
||
const [sessions, setSessions] = useState<Session[]>([]);
|
||
const [stats, setStats] = useState<RelayStats | null>(null);
|
||
const [total, setTotal] = useState(0);
|
||
const [offset, setOffset] = useState(0);
|
||
const [loading, setLoading] = useState(false);
|
||
const [error, setError] = useState("");
|
||
const [selected, setSelected] = useState<Session | null>(null);
|
||
const limit = 50;
|
||
|
||
useEffect(() => {
|
||
if (typeof window === "undefined") return;
|
||
const p = new URLSearchParams(window.location.search);
|
||
const sq = p.get("q");
|
||
if (sq) setQ(sq);
|
||
const sf = p.get("date_from");
|
||
if (sf) setDateFrom(sf);
|
||
const st = p.get("date_to");
|
||
if (st) setDateTo(st);
|
||
const ss = p.get("status");
|
||
if (ss) setStatus(ss);
|
||
const pf = p.get("platform");
|
||
if (pf) setPlatform(pf);
|
||
const tg = p.get("tag");
|
||
if (tg) setTag(tg);
|
||
const sid = p.get("session");
|
||
if (sid) {
|
||
void fetchJson(`/api/sessions/${sid}`)
|
||
.then((d) => setSelected((d.session || d) as Session))
|
||
.catch(() => undefined);
|
||
}
|
||
}, []);
|
||
|
||
const queryString = useMemo(() => {
|
||
const params = new URLSearchParams();
|
||
if (q.trim()) params.set("q", q.trim());
|
||
if (dateFrom) params.set("date_from", dateFrom);
|
||
if (dateTo) params.set("date_to", dateTo);
|
||
if (status) params.set("status", status);
|
||
if (platform) params.set("platform", platform);
|
||
if (tag) params.set("tag", tag);
|
||
params.set("limit", String(limit));
|
||
params.set("offset", String(offset));
|
||
return params.toString();
|
||
}, [q, dateFrom, dateTo, status, platform, tag, offset]);
|
||
|
||
const statsQuery = useMemo(() => {
|
||
const params = new URLSearchParams();
|
||
if (q.trim()) params.set("q", q.trim());
|
||
if (dateFrom) params.set("date_from", dateFrom);
|
||
if (dateTo) params.set("date_to", dateTo);
|
||
if (status) params.set("status", status);
|
||
if (platform) params.set("platform", platform);
|
||
if (tag) params.set("tag", tag);
|
||
params.set("top_anchors", "25");
|
||
return params.toString();
|
||
}, [q, dateFrom, dateTo, status, platform, tag]);
|
||
|
||
const exportHref = useMemo(() => {
|
||
const params = new URLSearchParams();
|
||
if (q.trim()) params.set("q", q.trim());
|
||
if (dateFrom) params.set("date_from", dateFrom);
|
||
if (dateTo) params.set("date_to", dateTo);
|
||
if (status) params.set("status", status);
|
||
if (platform) params.set("platform", platform);
|
||
if (tag) params.set("tag", tag);
|
||
params.set("format", "csv");
|
||
return `/api/sessions/export?${params.toString()}`;
|
||
}, [q, dateFrom, dateTo, status, platform, tag]);
|
||
|
||
function applyPreset(days: number | "today") {
|
||
const to = todayBeijingISO();
|
||
const from = days === "today" ? to : shiftBeijingISO(to, -(Number(days) - 1));
|
||
setOffset(0);
|
||
setDateFrom(from);
|
||
setDateTo(to);
|
||
}
|
||
|
||
const load = useCallback(async (opts?: RefreshOpts) => {
|
||
const silent = Boolean(opts?.silent);
|
||
if (!silent) {
|
||
setLoading(true);
|
||
setError("");
|
||
}
|
||
try {
|
||
const [listData, statsData] = await Promise.all([
|
||
fetchJson(`/api/sessions?${queryString}`),
|
||
fetchJson(`/api/sessions/stats?${statsQuery}`),
|
||
]);
|
||
setSessions(listData.sessions || []);
|
||
setTotal(Number(listData.total) || 0);
|
||
setStats(statsData);
|
||
} catch (e) {
|
||
if (!silent) setError((e as Error).message);
|
||
} finally {
|
||
if (!silent) setLoading(false);
|
||
}
|
||
}, [queryString, statsQuery]);
|
||
|
||
useAutoRefresh(load, { intervalMs: 20000 });
|
||
|
||
useEffect(() => {
|
||
void fetchJson("/api/rooms/tags")
|
||
.then((d) => setTagOptions(d.tags || []))
|
||
.catch(() => undefined);
|
||
}, []);
|
||
|
||
const pageCount = Math.max(1, Math.ceil(total / limit));
|
||
const pageIndex = Math.floor(offset / limit) + 1;
|
||
|
||
return (
|
||
<Shell>
|
||
<div className="mb-4 flex flex-wrap items-start justify-between gap-3">
|
||
<div>
|
||
<h2 className="font-display text-2xl font-semibold">🎬 场次日志</h2>
|
||
<p className="text-sm text-slate-400">开播/停播明细、播放时长与截图,支持 CSV 导出。</p>
|
||
</div>
|
||
<div className="flex gap-2">
|
||
<button
|
||
type="button"
|
||
onClick={() => void load()}
|
||
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"
|
||
>
|
||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
|
||
刷新
|
||
</button>
|
||
<a
|
||
href={exportHref}
|
||
className="inline-flex items-center gap-2 rounded-lg border border-teal-500/30 bg-teal-500/10 px-3 py-2 text-sm text-teal-100 hover:bg-teal-500/20"
|
||
>
|
||
导出 CSV
|
||
</a>
|
||
<button
|
||
type="button"
|
||
onClick={async () => {
|
||
const ok = await confirm({
|
||
title: "结束全部进行中场次",
|
||
message: "确定结束所有当前进行中的场次?",
|
||
confirmLabel: "全部结束",
|
||
destructive: true,
|
||
});
|
||
if (!ok) return;
|
||
try {
|
||
const data = await fetchJson("/api/sessions/end-all-active", { method: "POST" });
|
||
setError("");
|
||
toast.push(`已结束 ${data.ended || 0} 场`, "ok");
|
||
await load();
|
||
} catch (e) {
|
||
setError((e as Error).message);
|
||
toast.push((e as Error).message, "err");
|
||
}
|
||
}}
|
||
className="rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-sm text-amber-100 hover:bg-amber-500/20"
|
||
>
|
||
⏹ 结束进行中
|
||
</button>
|
||
</div>
|
||
</div>
|
||
|
||
<div className="mb-4 grid gap-3 rounded-xl border border-white/10 bg-black/30 p-4 md:grid-cols-2 xl:grid-cols-6">
|
||
<label className="block text-xs text-slate-400 xl:col-span-2">
|
||
检索(昵称 / URL / 房间号)
|
||
<div className="relative mt-1">
|
||
<Search className="pointer-events-none absolute left-3 top-2.5 h-4 w-4 text-slate-500" />
|
||
<input
|
||
value={q}
|
||
onChange={(e) => {
|
||
setOffset(0);
|
||
setQ(e.target.value);
|
||
}}
|
||
className="w-full rounded-lg border border-white/10 bg-slate-900 py-2 pl-9 pr-3 text-sm"
|
||
placeholder="例如:房间号或主播名"
|
||
/>
|
||
</div>
|
||
</label>
|
||
<label className="block text-xs text-slate-400">
|
||
开始日期
|
||
<input type="date" value={dateFrom} onChange={(e) => { setOffset(0); setDateFrom(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">
|
||
结束日期
|
||
<input type="date" value={dateTo} onChange={(e) => { setOffset(0); setDateTo(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">
|
||
状态
|
||
<select value={status} onChange={(e) => { setOffset(0); setStatus(e.target.value); }} className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm">
|
||
<option value="">全部</option>
|
||
<option value="active">进行中</option>
|
||
<option value="ended">已结束</option>
|
||
</select>
|
||
</label>
|
||
<label className="block text-xs text-slate-400">
|
||
平台
|
||
<select value={platform} onChange={(e) => { setOffset(0); setPlatform(e.target.value); }} className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm">
|
||
<option value="">全部平台</option>
|
||
<option value="douyin">抖音</option>
|
||
<option value="youtube">YouTube</option>
|
||
<option value="shorts">Shorts 频道开播</option>
|
||
</select>
|
||
</label>
|
||
<label className="block text-xs text-slate-400">
|
||
标签
|
||
<select value={tag} onChange={(e) => { setOffset(0); setTag(e.target.value); }} className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm">
|
||
<option value="">全部标签</option>
|
||
<option value="收藏">收藏</option>
|
||
<option value="重点">重点</option>
|
||
{tagOptions.filter((t) => t !== "重点" && t !== "收藏").map((t) => (
|
||
<option key={t} value={t}>{t}</option>
|
||
))}
|
||
</select>
|
||
</label>
|
||
</div>
|
||
|
||
<div className="mb-4 flex flex-wrap gap-2">
|
||
{[
|
||
["今天", "today"] as const,
|
||
["近7天", 7] as const,
|
||
["近30天", 30] as const,
|
||
].map(([label, days]) => (
|
||
<button
|
||
key={label}
|
||
type="button"
|
||
onClick={() => applyPreset(days)}
|
||
className="rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-300 hover:bg-white/10"
|
||
>
|
||
{label}
|
||
</button>
|
||
))}
|
||
<button
|
||
type="button"
|
||
onClick={() => {
|
||
setOffset(0);
|
||
setDateFrom("");
|
||
setDateTo("");
|
||
}}
|
||
className="rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-400 hover:bg-white/10"
|
||
>
|
||
清除日期
|
||
</button>
|
||
<button
|
||
type="button"
|
||
onClick={() => {
|
||
setOffset(0);
|
||
setStatus("active");
|
||
setDateFrom("");
|
||
setDateTo("");
|
||
}}
|
||
className="rounded-lg border border-rose-500/30 bg-rose-500/10 px-3 py-1.5 text-xs text-rose-100 hover:bg-rose-500/20"
|
||
>
|
||
仅进行中
|
||
</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}
|
||
|
||
<div className="mb-4 flex gap-2">
|
||
<button type="button" onClick={() => setTab("charts")} className={`rounded-lg px-3 py-1.5 text-sm ${tab === "charts" ? "bg-white/15 text-white" : "bg-white/5 text-slate-400"}`}>
|
||
可视化分析
|
||
</button>
|
||
<button type="button" onClick={() => setTab("list")} className={`rounded-lg px-3 py-1.5 text-sm ${tab === "list" ? "bg-white/15 text-white" : "bg-white/5 text-slate-400"}`}>
|
||
场次列表 ({total})
|
||
</button>
|
||
</div>
|
||
|
||
{tab === "charts" ? <SessionCharts stats={stats} /> : null}
|
||
|
||
{tab === "list" ? (
|
||
<>
|
||
<div className="overflow-hidden rounded-xl border border-white/10 bg-black/20">
|
||
<div className="overflow-x-auto">
|
||
<table className="min-w-full text-left text-sm">
|
||
<thead className="bg-white/5 text-xs uppercase tracking-wide text-slate-400">
|
||
<tr>
|
||
<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">直播间 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>
|
||
<th className="px-3 py-3">操作</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{sessions.map((session) => (
|
||
<tr key={session.id} className="cursor-pointer border-t border-white/5 hover:bg-white/[0.03]" onClick={() => setSelected(session)}>
|
||
<td className="px-3 py-3">
|
||
{sessionCoverSrc(session) ? (
|
||
// eslint-disable-next-line @next/next/no-img-element
|
||
<img src={sessionCoverSrc(session)} alt="" className="h-16 w-10 rounded object-cover ring-1 ring-white/10" />
|
||
) : (
|
||
<div className="flex h-16 w-10 items-center justify-center rounded bg-slate-900 text-[10px] text-slate-500 ring-1 ring-white/10">N/A</div>
|
||
)}
|
||
</td>
|
||
<td className="px-3 py-3">
|
||
<PlatformBadge platform={detectPlatform(session)} />
|
||
</td>
|
||
<td className="px-3 py-3 font-medium">
|
||
<span className="inline-flex items-center gap-2">
|
||
{session.anchor_name || "—"}
|
||
{detectPlatform(session) === "youtube" &&
|
||
!session.ended_at &&
|
||
session.room_id?.startsWith("yt:UC") ? (
|
||
<YouTubeLiveBadge refKey={channelLiveRef(session.room_id.slice(3))} compact />
|
||
) : null}
|
||
</span>
|
||
</td>
|
||
<td className="max-w-[14rem] truncate px-3 py-3 font-mono text-xs text-cyan-300/90">
|
||
{session.source_url ? (
|
||
<a href={session.source_url} target="_blank" rel="noreferrer" className="hover:underline" onClick={(e) => e.stopPropagation()}>
|
||
{session.source_url.replace(/^https?:\/\//, "")}
|
||
</a>
|
||
) : "—"}
|
||
</td>
|
||
<td className="whitespace-nowrap px-3 py-3 text-slate-300">{fmtTs(session.started_at)}</td>
|
||
<td className="whitespace-nowrap px-3 py-3 text-slate-300">{session.ended_at ? fmtTs(session.ended_at) : "进行中"}</td>
|
||
<td className="whitespace-nowrap px-3 py-3 font-mono">{fmtDuration(session.duration_seconds)}</td>
|
||
<td className="whitespace-nowrap px-3 py-3">{session.push_date || "—"}</td>
|
||
<td className="whitespace-nowrap px-3 py-3" onClick={(e) => e.stopPropagation()}>
|
||
<div className="flex flex-wrap items-center gap-1.5">
|
||
<RoomQuickActions
|
||
compact
|
||
room={{
|
||
room_pk: session.room_pk,
|
||
room_id: session.room_id,
|
||
source_url: session.source_url,
|
||
anchor_name: session.anchor_name,
|
||
}}
|
||
onDone={() => void load({ silent: true })}
|
||
onError={(m) => setError(m)}
|
||
/>
|
||
{!session.ended_at ? (
|
||
<button
|
||
type="button"
|
||
onClick={async () => {
|
||
const ok = await confirm({
|
||
title: "结束场次",
|
||
message: `确定结束「${session.anchor_name || session.room_id}」这场?`,
|
||
confirmLabel: "结束",
|
||
destructive: true,
|
||
});
|
||
if (!ok) return;
|
||
try {
|
||
await fetchJson(`/api/sessions/${session.id}/end`, { method: "POST" });
|
||
toast.push("已结束场次", "ok");
|
||
await load();
|
||
} catch (e) {
|
||
setError((e as Error).message);
|
||
toast.push((e as Error).message, "err");
|
||
}
|
||
}}
|
||
className="rounded border border-amber-500/30 px-2 py-1 text-xs text-amber-100 hover:bg-amber-500/10"
|
||
>
|
||
结束
|
||
</button>
|
||
) : null}
|
||
</div>
|
||
</td>
|
||
</tr>
|
||
))}
|
||
{!loading && sessions.length === 0 ? (
|
||
<tr>
|
||
<td colSpan={9} className="px-3 py-10 text-center text-slate-500">暂无场次。添加直播间后,开播会自动记入。</td>
|
||
</tr>
|
||
) : null}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div className="mt-4 flex items-center justify-between text-sm text-slate-400">
|
||
<span>共 {total} 条 · 第 {pageIndex}/{pageCount}</span>
|
||
<div className="flex gap-2">
|
||
<button type="button" disabled={offset <= 0 || loading} onClick={() => setOffset(Math.max(0, offset - limit))} className="rounded-lg border border-white/10 px-3 py-1.5 disabled:opacity-40">上一页</button>
|
||
<button type="button" disabled={offset + limit >= total || loading} onClick={() => setOffset(offset + limit)} className="rounded-lg border border-white/10 px-3 py-1.5 disabled:opacity-40">下一页</button>
|
||
</div>
|
||
</div>
|
||
</>
|
||
) : null}
|
||
|
||
{selected ? (
|
||
<SessionDetailModal
|
||
session={selected}
|
||
onClose={() => setSelected(null)}
|
||
onUpdated={() => void load()}
|
||
/>
|
||
) : null}
|
||
</Shell>
|
||
);
|
||
}
|