"use client"; import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react"; import { fetchJson } from "@/lib/api"; export type YouTubeLiveEntry = { is_live?: boolean; live_url?: string; title?: string; channel_id?: string; source?: string; error?: string; /** yt_assign_groups.id when this Shorts channel has a Live 分配卡片 */ assign_group_id?: string; }; export type YouTubeLiveMap = { ok?: boolean; checked_at?: number; live_count?: number; source?: string; entries?: Record; svc_error?: string; }; const YouTubeLiveContext = createContext<{ map: YouTubeLiveMap | null; loading: boolean; refresh: () => Promise; }>({ map: null, loading: false, refresh: async () => {}, }); export function groupLiveRef(groupId: string) { return `group:${groupId}`; } export function shortsLiveRef(channelPk: string) { return `shorts:${channelPk}`; } export function channelLiveRef(channelId: string) { return `channel:${channelId}`; } export function useYouTubeLiveProviderValue(intervalMs = 35000) { const [map, setMap] = useState(null); const [loading, setLoading] = useState(false); const refresh = useCallback(async (silent = false) => { if (!silent) setLoading(true); try { // 不 force:读服务端后台轮询写入的缓存(约 15–20s 更新) const data = (await fetchJson("/api/youtube/live-map")) as YouTubeLiveMap; setMap(data); } catch { /* keep last map */ } finally { if (!silent) setLoading(false); } }, []); useEffect(() => { void refresh(true); const id = window.setInterval(() => { if (document.hidden) return; void refresh(true); }, intervalMs); const onVis = () => { if (document.visibilityState === "visible") void refresh(true); }; document.addEventListener("visibilitychange", onVis); return () => { window.clearInterval(id); document.removeEventListener("visibilitychange", onVis); }; }, [intervalMs, refresh]); return useMemo( () => ({ map, loading, refresh: () => refresh(false), }), [map, loading, refresh], ); } export const YouTubeLiveContextProvider = YouTubeLiveContext.Provider; export function useYouTubeLiveMap() { return useContext(YouTubeLiveContext); } export function useYouTubeLiveEntry(refKey?: string): YouTubeLiveEntry | null { const { map } = useYouTubeLiveMap(); if (!refKey) return null; return map?.entries?.[refKey] ?? null; } export function useYouTubeLiveCount() { const { map } = useYouTubeLiveMap(); return Number(map?.live_count || 0); }