douyinWEB/frontend/src/components/GlobalEventAlerts.tsx
2026-08-10 20:11:23 -05:00

177 lines
5.8 KiB
TypeScript

"use client";
import { useEffect, useRef, useState } from "react";
import { SessionDetailModal, type SessionDetail } from "@/components/SessionDetailModal";
import { useToast } from "@/components/Toast";
import { fetchJson } from "@/lib/api";
import { useEventStream } from "@/lib/realtime";
type NotifyFlags = {
live: boolean;
offline: boolean;
risk: boolean;
shortsFail: boolean;
shortsOk: boolean;
shortsQuota: boolean;
};
function applyFlags(s: Record<string, unknown>): NotifyFlags {
return {
live: s.notify_on_live !== false,
offline: Boolean(s.notify_on_offline),
risk: s.notify_on_risk !== false,
shortsFail: s.notify_on_shorts_fail !== false,
shortsOk: Boolean(s.notify_on_shorts_ok),
shortsQuota: s.notify_on_shorts_quota !== false,
};
}
/**
* App-wide SSE → toast + browser Notification (any page under Shell).
* Clickable alerts open SessionDetailModal when session_id is present.
*/
export function GlobalEventAlerts() {
const toast = useToast();
const { last, tick } = useEventStream(true);
const flagsRef = useRef<NotifyFlags>({
live: true,
offline: false,
risk: true,
shortsFail: true,
shortsOk: false,
shortsQuota: true,
});
const seenRef = useRef<Set<string>>(new Set());
const [detail, setDetail] = useState<SessionDetail | null>(null);
useEffect(() => {
const loadFlags = () => {
void fetchJson("/api/settings")
.then((s) => {
flagsRef.current = applyFlags(s);
})
.catch(() => undefined);
};
loadFlags();
const onChange = () => loadFlags();
window.addEventListener("dy-settings-changed", onChange);
const t = window.setInterval(loadFlags, 30000);
return () => {
window.removeEventListener("dy-settings-changed", onChange);
window.clearInterval(t);
};
}, []);
async function openSession(sessionId?: string) {
if (!sessionId) return;
try {
const data = await fetchJson(`/api/sessions/${sessionId}`);
setDetail((data.session || data) as SessionDetail);
} catch {
/* ignore */
}
}
useEffect(() => {
if (!last?.message) return;
const kind = last.kind || "";
if (!["live", "offline", "risk", "shorts_fail", "shorts_ok", "shorts_quota"].includes(kind)) return;
const flags = flagsRef.current;
if (kind === "live" && !flags.live) return;
if (kind === "offline" && !flags.offline) return;
if (kind === "risk" && !flags.risk) return;
if (kind === "shorts_fail" && !flags.shortsFail) return;
if (kind === "shorts_ok" && !flags.shortsOk) return;
if (kind === "shorts_quota" && !flags.shortsQuota) return;
const key = String(last.id || `${kind}:${last.message}:${last.ts || tick}`);
if (seenRef.current.has(key)) return;
seenRef.current.add(key);
if (seenRef.current.size > 200) {
const keep = Array.from(seenRef.current).slice(-80);
seenRef.current = new Set(keep);
}
const tone =
kind === "risk" || kind === "shorts_fail" || kind === "shorts_quota"
? "warn"
: kind === "offline"
? "err"
: "ok";
const sid = last.session_id;
const meta = (last.meta && typeof last.meta === "object" ? last.meta : {}) as Record<string, unknown>;
const isYt = meta.platform === "youtube" || String(last.room_id || "").startsWith("yt:");
const isShorts = kind === "shorts_fail" || kind === "shorts_ok" || kind === "shorts_quota";
const ytUrl = String(meta.youtube_url || "").trim();
const liveUrl = String(meta.live_url || meta.url || "").trim();
const shortsHref = "/shorts";
const fallbackHref = isShorts
? shortsHref
: !liveUrl
? isYt
? "/groups"
: last.room_id
? `/events?q=${encodeURIComponent(last.room_id)}`
: last.anchor_name
? `/events?q=${encodeURIComponent(last.anchor_name)}`
: undefined
: undefined;
toast.push(last.message, tone, {
onClick: sid
? () => void openSession(sid)
: ytUrl
? () => window.open(ytUrl, "_blank", "noopener,noreferrer")
: liveUrl
? () => window.open(liveUrl, "_blank", "noopener,noreferrer")
: undefined,
href: sid || ytUrl || liveUrl ? undefined : fallbackHref,
actionLabel: sid
? "查看场次 →"
: ytUrl
? "打开 Shorts →"
: liveUrl
? "打开直播 →"
: fallbackHref
? isShorts
? "打开 Shorts →"
: isYt
? "查看分组 →"
: "查看事件 →"
: undefined,
});
if (typeof window !== "undefined" && "Notification" in window && Notification.permission === "granted") {
const title =
kind === "risk"
? "风控告警"
: kind === "offline"
? "停播提醒"
: kind === "shorts_fail"
? "Shorts 失败"
: kind === "shorts_ok"
? "Shorts 已上传"
: kind === "shorts_quota"
? "Shorts 配额落后"
: isYt
? "YouTube 开播"
: "开播提醒";
try {
const n = new Notification(title, { body: last.message, tag: key });
n.onclick = () => {
window.focus();
if (sid) void openSession(sid);
else if (ytUrl) window.open(ytUrl, "_blank", "noopener,noreferrer");
else if (liveUrl) window.open(liveUrl, "_blank", "noopener,noreferrer");
else if (fallbackHref) window.location.href = fallbackHref;
};
} catch {
/* ignore */
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tick]);
return detail ? <SessionDetailModal session={detail} onClose={() => setDetail(null)} /> : null;
}