Add real-time Douyin live status map and badges across card UIs.
Expose /api/douyin/live-map from monitor DB with SSE-triggered client refresh, and show live/offline badges on assign, rooms, anchors, slots, and overview cards. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
f36bbb80a7
commit
5b45fc0aca
@ -3406,6 +3406,42 @@ def shorts_total_quota_gap(push_date: str = "") -> int:
|
||||
return sum(r["gap"] for r in shorts_channels_quota_summary(push_date))
|
||||
|
||||
|
||||
def list_douyin_room_status_entries(
|
||||
*,
|
||||
room_ids: list[str] | None = None,
|
||||
limit: int = 3000,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Monitor-backed Douyin room status rows for live-map (no network probe)."""
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
base = """
|
||||
SELECT room_id, url, last_status, last_anchor, last_checked_at,
|
||||
active_session_id, enabled, note
|
||||
FROM rooms
|
||||
WHERE room_id != ''
|
||||
AND room_id NOT LIKE 'yt:%'
|
||||
AND room_id NOT LIKE 'shorts:%'
|
||||
"""
|
||||
if room_ids:
|
||||
ids = [str(x).strip() for x in room_ids if str(x).strip()]
|
||||
if not ids:
|
||||
return []
|
||||
placeholders = ",".join("?" * len(ids))
|
||||
rows = conn.execute(
|
||||
base + f" AND room_id IN ({placeholders})",
|
||||
ids,
|
||||
).fetchall()
|
||||
else:
|
||||
rows = conn.execute(
|
||||
base + " ORDER BY updated_at DESC LIMIT ?",
|
||||
(max(1, min(int(limit), 5000)),),
|
||||
).fetchall()
|
||||
return [_row_to_dict(r) for r in rows]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def list_live_douyin_rooms_for_shorts(*, limit: int = 300) -> list[dict[str, Any]]:
|
||||
"""Currently-live Douyin rooms from monitor state (no extra network)."""
|
||||
with _lock:
|
||||
|
||||
63
backend/app/douyin_live.py
Normal file
63
backend/app/douyin_live.py
Normal file
@ -0,0 +1,63 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Douyin live status map from monitor DB (rooms.last_status), no extra network probe."""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from . import db
|
||||
|
||||
_CACHE: dict[str, Any] = {"at": 0.0, "payload": None, "key": ""}
|
||||
_CACHE_TTL_SEC = 8.0
|
||||
|
||||
|
||||
def _entry(row: dict[str, Any]) -> dict[str, Any]:
|
||||
status = str(row.get("last_status") or "unknown").strip() or "unknown"
|
||||
rid = str(row.get("room_id") or "").strip()
|
||||
url = str(row.get("url") or "").strip()
|
||||
anchor = str(row.get("last_anchor") or row.get("note") or "").strip()
|
||||
return {
|
||||
"is_live": status == "live",
|
||||
"last_status": status,
|
||||
"anchor": anchor,
|
||||
"url": url,
|
||||
"last_checked_at": row.get("last_checked_at"),
|
||||
"active_session_id": str(row.get("active_session_id") or ""),
|
||||
}
|
||||
|
||||
|
||||
def build_live_map(*, room_ids: list[str] | None = None, force: bool = False) -> dict[str, Any]:
|
||||
key = ",".join(sorted(room_ids or []))
|
||||
now = time.time()
|
||||
cached = _CACHE.get("payload")
|
||||
if (
|
||||
not force
|
||||
and isinstance(cached, dict)
|
||||
and _CACHE.get("key") == key
|
||||
and now - float(_CACHE.get("at") or 0) < _CACHE_TTL_SEC
|
||||
):
|
||||
return cached
|
||||
|
||||
rows = db.list_douyin_room_status_entries(room_ids=room_ids)
|
||||
entries: dict[str, dict[str, Any]] = {}
|
||||
live_count = 0
|
||||
for row in rows:
|
||||
rid = str(row.get("room_id") or "").strip()
|
||||
if not rid:
|
||||
continue
|
||||
ent = _entry(row)
|
||||
entries[rid] = ent
|
||||
if ent["is_live"]:
|
||||
live_count += 1
|
||||
|
||||
payload: dict[str, Any] = {
|
||||
"ok": True,
|
||||
"checked_at": now,
|
||||
"live_count": live_count,
|
||||
"source": "monitor_db",
|
||||
"entries": entries,
|
||||
}
|
||||
_CACHE["at"] = now
|
||||
_CACHE["payload"] = payload
|
||||
_CACHE["key"] = key
|
||||
return payload
|
||||
@ -68,7 +68,7 @@ from .models import (
|
||||
from .monitor import monitor
|
||||
from .stats import summarize_anchor_schedule, summarize_sessions
|
||||
from .youtube_client import YouTubeSvcError
|
||||
from . import youtube_live
|
||||
from . import douyin_live, youtube_live
|
||||
from .auth import ApiKeyMiddleware
|
||||
from .session_auth import (
|
||||
SessionAuthMiddleware,
|
||||
@ -2792,6 +2792,19 @@ async def youtube_live_map(force: bool = Query(False)) -> dict[str, Any]:
|
||||
raise HTTPException(500, str(exc)) from exc
|
||||
|
||||
|
||||
@app.get("/api/douyin/live-map")
|
||||
async def douyin_live_map(
|
||||
room_ids: str = Query(""),
|
||||
force: bool = Query(False),
|
||||
) -> dict[str, Any]:
|
||||
"""Douyin room live status from monitor DB; SSE live/offline triggers client refresh."""
|
||||
ids = [x.strip() for x in room_ids.split(",") if x.strip()] if room_ids.strip() else None
|
||||
try:
|
||||
return await asyncio.to_thread(douyin_live.build_live_map, room_ids=ids, force=force)
|
||||
except Exception as exc:
|
||||
raise HTTPException(500, str(exc)) from exc
|
||||
|
||||
|
||||
@app.get("/api/events")
|
||||
async def events_list(
|
||||
kind: str = "",
|
||||
|
||||
94
desktop/src/components/DouyinLiveBadge.tsx
Normal file
94
desktop/src/components/DouyinLiveBadge.tsx
Normal file
@ -0,0 +1,94 @@
|
||||
import { LivePulse } from "@/components/ui";
|
||||
import {
|
||||
resolveDouyinLive,
|
||||
useDouyinLiveEntry,
|
||||
type DouyinLiveEntry,
|
||||
} from "@/lib/douyinLive";
|
||||
|
||||
type Props = {
|
||||
roomId?: string;
|
||||
lastStatus?: string;
|
||||
entry?: DouyinLiveEntry | null;
|
||||
className?: string;
|
||||
compact?: boolean;
|
||||
overlay?: boolean;
|
||||
showOffline?: boolean;
|
||||
};
|
||||
|
||||
function statusLabel(status: string, isLive: boolean) {
|
||||
if (isLive) return "直播中";
|
||||
if (status === "error") return "异常";
|
||||
if (status === "offline") return "离线";
|
||||
return "检测中";
|
||||
}
|
||||
|
||||
export function DouyinLiveBadge({
|
||||
roomId,
|
||||
lastStatus,
|
||||
entry,
|
||||
className = "",
|
||||
compact = false,
|
||||
overlay = false,
|
||||
showOffline = false,
|
||||
}: Props) {
|
||||
const fromMap = useDouyinLiveEntry(roomId, entry ?? undefined);
|
||||
const live = fromMap;
|
||||
const { status, isLive } = resolveDouyinLive(live, lastStatus);
|
||||
|
||||
if (overlay) {
|
||||
if (!roomId && !lastStatus) return null;
|
||||
const color = isLive
|
||||
? "bg-rose-500 ring-rose-300/60 live-dot"
|
||||
: status === "error"
|
||||
? "bg-amber-400 ring-amber-200/60"
|
||||
: showOffline
|
||||
? "bg-slate-500/80 ring-white/20"
|
||||
: null;
|
||||
if (!color) return null;
|
||||
return (
|
||||
<span
|
||||
className={`inline-block h-2 w-2 rounded-full ring-1 ${color} ${className}`}
|
||||
title={statusLabel(status, isLive)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (isLive) {
|
||||
const label = compact ? "LIVE" : "直播中";
|
||||
const inner = <LivePulse label={label} />;
|
||||
const href = live?.url || (roomId ? `https://live.douyin.com/${roomId}` : "");
|
||||
if (href) {
|
||||
return (
|
||||
<a
|
||||
href={href}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className={`inline-flex items-center hover:opacity-90 ${className}`}
|
||||
title={live?.anchor || "打开直播间"}
|
||||
>
|
||||
{inner}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
return <span className={`inline-flex items-center ${className}`}>{inner}</span>;
|
||||
}
|
||||
|
||||
if (!showOffline) return null;
|
||||
|
||||
const label = statusLabel(status, isLive);
|
||||
const tone =
|
||||
status === "error"
|
||||
? "text-amber-200 ring-amber-500/30 bg-amber-500/10"
|
||||
: status === "offline"
|
||||
? "text-slate-400 ring-white/10 bg-white/5"
|
||||
: "text-slate-500 ring-white/10 bg-white/5";
|
||||
|
||||
return (
|
||||
<span
|
||||
className={`inline-flex items-center rounded px-1.5 py-0.5 text-[10px] ring-1 ${tone} ${className}`}
|
||||
title={live?.anchor || label}
|
||||
>
|
||||
{compact ? (status === "offline" ? "离线" : label) : label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@ -4,6 +4,7 @@ import { useLocation, useNavigate } from "react-router-dom";
|
||||
import { BrandMark, LivePulse } from "@/components/ui";
|
||||
import { GlobalEventAlerts } from "@/components/GlobalEventAlerts";
|
||||
import { fetchJson } from "@/lib/api";
|
||||
import { DouyinLiveContextProvider, useDouyinLiveCount, useDouyinLiveProviderValue } from "@/lib/douyinLive";
|
||||
import { YouTubeLiveContextProvider, useYouTubeLiveCount, useYouTubeLiveMap, useYouTubeLiveProviderValue } from "@/lib/youtubeLive";
|
||||
import { Link } from "react-router-dom";
|
||||
|
||||
@ -25,10 +26,13 @@ const NAV = [
|
||||
const MOBILE_PRIMARY = ["/", "/groups", "/shorts", "/youtube", "/settings"];
|
||||
|
||||
export function Shell({ children }: { children: React.ReactNode }) {
|
||||
const liveCtx = useYouTubeLiveProviderValue();
|
||||
const ytCtx = useYouTubeLiveProviderValue();
|
||||
const dyCtx = useDouyinLiveProviderValue();
|
||||
return (
|
||||
<YouTubeLiveContextProvider value={liveCtx}>
|
||||
<ShellFrame>{children}</ShellFrame>
|
||||
<YouTubeLiveContextProvider value={ytCtx}>
|
||||
<DouyinLiveContextProvider value={dyCtx}>
|
||||
<ShellFrame>{children}</ShellFrame>
|
||||
</DouyinLiveContextProvider>
|
||||
</YouTubeLiveContextProvider>
|
||||
);
|
||||
}
|
||||
@ -37,6 +41,7 @@ function ShellFrame({ children }: { children: React.ReactNode }) {
|
||||
const pathname = useLocation().pathname;
|
||||
const navigate = useNavigate();
|
||||
const ytLiveCount = useYouTubeLiveCount();
|
||||
const dyLiveCount = useDouyinLiveCount();
|
||||
const { map: ytLiveMap } = useYouTubeLiveMap();
|
||||
const [username, setUsername] = useState("");
|
||||
|
||||
@ -74,11 +79,18 @@ function ShellFrame({ children }: { children: React.ReactNode }) {
|
||||
<p className="mt-1 max-w-2xl text-sm text-slate-400">
|
||||
抖音 + YouTube · 开播捕捉 · 停播结场 · 时长统计 · 截图存证 · Windows 客户端
|
||||
</p>
|
||||
{ytLiveCount > 0 ? (
|
||||
{(dyLiveCount > 0 || ytLiveCount > 0) ? (
|
||||
<div className="mt-2 flex flex-wrap items-center gap-2">
|
||||
<Link to="/groups">
|
||||
<LivePulse label={`YouTube ${ytLiveCount} 路在播`} />
|
||||
</Link>
|
||||
{dyLiveCount > 0 ? (
|
||||
<Link to="/rooms">
|
||||
<LivePulse label={`抖音 ${dyLiveCount} 路在播`} />
|
||||
</Link>
|
||||
) : null}
|
||||
{ytLiveCount > 0 ? (
|
||||
<Link to="/groups">
|
||||
<LivePulse label={`YouTube ${ytLiveCount} 路在播`} />
|
||||
</Link>
|
||||
) : null}
|
||||
{ytLiveMap?.checked_at ? (
|
||||
<span className="text-[10px] text-slate-500">
|
||||
轮询 {Math.max(0, Math.round(Date.now() / 1000 - Number(ytLiveMap.checked_at)))}s 前
|
||||
@ -87,13 +99,7 @@ function ShellFrame({ children }: { children: React.ReactNode }) {
|
||||
</div>
|
||||
) : (
|
||||
<div className="mt-2 flex flex-wrap items-center gap-2 text-[11px] text-slate-500">
|
||||
{ytLiveMap?.svc_error ? (
|
||||
<span className="text-amber-300" title={ytLiveMap.svc_error}>
|
||||
⚠ YouTube 探测异常(轮询兜底中)
|
||||
</span>
|
||||
) : (
|
||||
<span>YouTube 直播轮询中</span>
|
||||
)}
|
||||
<span>抖音 / YouTube 直播轮询中</span>
|
||||
{ytLiveMap?.checked_at ? (
|
||||
<span className="text-[10px]">
|
||||
· {Math.max(0, Math.round(Date.now() / 1000 - Number(ytLiveMap.checked_at)))}s 前刷新
|
||||
|
||||
102
desktop/src/lib/douyinLive.ts
Normal file
102
desktop/src/lib/douyinLive.ts
Normal file
@ -0,0 +1,102 @@
|
||||
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { fetchJson } from "@/lib/api";
|
||||
import { useEventStream } from "@/lib/realtime";
|
||||
|
||||
export type DouyinLiveEntry = {
|
||||
is_live?: boolean;
|
||||
last_status?: string;
|
||||
anchor?: string;
|
||||
url?: string;
|
||||
last_checked_at?: number;
|
||||
active_session_id?: string;
|
||||
};
|
||||
|
||||
export type DouyinLiveMap = {
|
||||
ok?: boolean;
|
||||
checked_at?: number;
|
||||
live_count?: number;
|
||||
source?: string;
|
||||
entries?: Record<string, DouyinLiveEntry>;
|
||||
};
|
||||
|
||||
const DouyinLiveContext = createContext<{
|
||||
map: DouyinLiveMap | null;
|
||||
loading: boolean;
|
||||
refresh: () => Promise<void>;
|
||||
}>({
|
||||
map: null,
|
||||
loading: false,
|
||||
refresh: async () => {},
|
||||
});
|
||||
|
||||
export function useDouyinLiveProviderValue(intervalMs = 10000) {
|
||||
const [map, setMap] = useState<DouyinLiveMap | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { tick, last } = useEventStream(true);
|
||||
|
||||
const refresh = useCallback(async (silent = false) => {
|
||||
if (!silent) setLoading(true);
|
||||
try {
|
||||
const data = (await fetchJson("/api/douyin/live-map")) as DouyinLiveMap;
|
||||
setMap(data);
|
||||
} catch {
|
||||
/* keep last map */
|
||||
} finally {
|
||||
if (!silent) setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh(true);
|
||||
const id = window.setInterval(() => 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]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!last?.kind) return;
|
||||
if (!["live", "offline", "risk"].includes(String(last.kind))) return;
|
||||
void refresh(true);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [tick]);
|
||||
|
||||
return useMemo(
|
||||
() => ({
|
||||
map,
|
||||
loading,
|
||||
refresh: () => refresh(false),
|
||||
}),
|
||||
[map, loading, refresh],
|
||||
);
|
||||
}
|
||||
|
||||
export const DouyinLiveContextProvider = DouyinLiveContext.Provider;
|
||||
|
||||
export function useDouyinLiveMap() {
|
||||
return useContext(DouyinLiveContext);
|
||||
}
|
||||
|
||||
export function useDouyinLiveEntry(roomId?: string, fallback?: DouyinLiveEntry | null): DouyinLiveEntry | null {
|
||||
const { map } = useDouyinLiveMap();
|
||||
const rid = String(roomId || "").trim();
|
||||
if (!rid) return fallback ?? null;
|
||||
return map?.entries?.[rid] ?? fallback ?? null;
|
||||
}
|
||||
|
||||
export function useDouyinLiveCount() {
|
||||
const { map } = useDouyinLiveMap();
|
||||
return Number(map?.live_count || 0);
|
||||
}
|
||||
|
||||
export function resolveDouyinLive(entry: DouyinLiveEntry | null | undefined, lastStatus?: string) {
|
||||
const status = String(entry?.last_status || lastStatus || "unknown").trim() || "unknown";
|
||||
const isLive = entry?.is_live ?? status === "live";
|
||||
return { status, isLive };
|
||||
}
|
||||
@ -2,6 +2,7 @@
|
||||
import { Link } from "react-router-dom";
|
||||
import { Loader2, RefreshCw, UserRound } from "lucide-react";
|
||||
|
||||
import { DouyinLiveBadge } from "@/components/DouyinLiveBadge";
|
||||
import { Shell } from "@/components/Shell";
|
||||
import { SessionDetailModal, type SessionDetail } from "@/components/SessionDetailModal";
|
||||
import { RoomQuickActions } from "@/components/RoomQuickActions";
|
||||
@ -202,7 +203,11 @@ export default function AnchorsPage() {
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="truncate font-medium text-white">{a.anchor_name}</span>
|
||||
{a.active ? <LivePulse label="LIVE" /> : null}
|
||||
{a.room_id ? (
|
||||
<DouyinLiveBadge roomId={a.room_id} compact showOffline />
|
||||
) : a.active ? (
|
||||
<LivePulse label="LIVE" />
|
||||
) : null}
|
||||
</div>
|
||||
<div className="mt-1 text-[11px] text-slate-500">
|
||||
{a.sessions} 场 · {Number(a.hours_total || 0).toFixed(1)}h
|
||||
@ -222,7 +227,11 @@ export default function AnchorsPage() {
|
||||
<div className="flex items-center gap-2">
|
||||
<UserRound className="h-5 w-5 text-teal-300" />
|
||||
<h3 className="font-display text-xl font-semibold">{profile.anchor_name}</h3>
|
||||
{profile.overview.active ? <LivePulse /> : null}
|
||||
{profile.room_id ? (
|
||||
<DouyinLiveBadge roomId={profile.room_id} showOffline />
|
||||
) : profile.overview.active ? (
|
||||
<LivePulse />
|
||||
) : null}
|
||||
</div>
|
||||
<p className="mt-1 font-mono text-xs text-cyan-300/80">{profile.room_id || "—"}</p>
|
||||
</div>
|
||||
|
||||
@ -6,6 +6,7 @@ import { Shell } from "@/components/Shell";
|
||||
import { SessionCharts, type RelayStats } from "@/components/SessionCharts";
|
||||
import { SessionDetailModal, type SessionDetail } from "@/components/SessionDetailModal";
|
||||
import { AnimatedNumber, LivePulse, StatTile, PlatformBadge } from "@/components/ui";
|
||||
import { DouyinLiveBadge } from "@/components/DouyinLiveBadge";
|
||||
import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge";
|
||||
import { YouTubeLiveTicker } from "@/components/YouTubeLiveTicker";
|
||||
import { useToast } from "@/components/Toast";
|
||||
@ -596,6 +597,11 @@ export default function HomePage() {
|
||||
<YouTubeLiveBadge refKey={channelLiveRef(s.room_id.slice(3))} compact />
|
||||
</span>
|
||||
) : null}
|
||||
{detectPlatform(s) === "douyin" && s.room_id ? (
|
||||
<span className="ml-1.5 inline-block align-middle">
|
||||
<DouyinLiveBadge roomId={s.room_id} compact />
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="font-mono text-xs text-rose-200">{liveElapsed(s.started_at, now)}</div>
|
||||
</button>
|
||||
|
||||
@ -4,7 +4,7 @@ import { Loader2, Plus, RefreshCw, Trash2, 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 { DouyinLiveBadge } from "@/components/DouyinLiveBadge";
|
||||
import { RoomQuickActions, isFavorited } from "@/components/RoomQuickActions";
|
||||
import { fetchJson, fmtTs } from "@/lib/api";
|
||||
import { useAutoRefresh, type RefreshOpts } from "@/lib/realtime";
|
||||
@ -499,7 +499,7 @@ export default function RoomsPage() {
|
||||
<input type="checkbox" checked={selected.has(room.id)} onChange={() => toggleSelect(room.id)} />
|
||||
</td>
|
||||
<td className="px-3 py-3">
|
||||
<span className={`rounded border px-2 py-0.5 text-xs ${statusBadge(room.last_status)}`}>{room.last_status}</span>
|
||||
<DouyinLiveBadge roomId={room.room_id} lastStatus={room.last_status} showOffline />
|
||||
{overdue ? <div className="mt-1 text-[10px] text-violet-200">积压</div> : null}
|
||||
</td>
|
||||
<td className="px-3 py-3">
|
||||
|
||||
@ -14,6 +14,7 @@ import {
|
||||
Wrench,
|
||||
} from "lucide-react";
|
||||
|
||||
import { DouyinLiveBadge } from "@/components/DouyinLiveBadge";
|
||||
import { Shell } from "@/components/Shell";
|
||||
import { useConfirm } from "@/components/ConfirmDialog";
|
||||
import { useToast } from "@/components/Toast";
|
||||
@ -694,9 +695,10 @@ export default function ShortsPage() {
|
||||
{status.douyin_live_rooms.map((r: { room_id?: string; anchor?: string }) => (
|
||||
<span
|
||||
key={String(r.room_id)}
|
||||
className="rounded-lg border border-white/10 bg-black/30 px-2 py-1 text-[11px] text-slate-200"
|
||||
className="inline-flex items-center gap-1.5 rounded-lg border border-white/10 bg-black/30 px-2 py-1 text-[11px] text-slate-200"
|
||||
title={String(r.room_id || "")}
|
||||
>
|
||||
<DouyinLiveBadge roomId={r.room_id} compact />
|
||||
{r.anchor || r.room_id}
|
||||
</span>
|
||||
))}
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Loader2, RefreshCw } from "lucide-react";
|
||||
|
||||
import { DouyinLiveBadge } from "@/components/DouyinLiveBadge";
|
||||
import { Shell } from "@/components/Shell";
|
||||
import { SessionDetailModal } from "@/components/SessionDetailModal";
|
||||
import { RoomQuickActions } from "@/components/RoomQuickActions";
|
||||
@ -519,7 +520,9 @@ export default function SlotsPage() {
|
||||
<div className="mt-1 flex flex-wrap items-center gap-1.5 text-[11px] text-slate-500">
|
||||
<PlatformBadge platform={detectPlatform(session)} />
|
||||
<span className="font-mono text-slate-400">{fmtClock(session.started_at)} 开播</span>
|
||||
{session.status === "active" || !session.ended_at ? (
|
||||
{session.room_id && detectPlatform(session) === "douyin" ? (
|
||||
<DouyinLiveBadge roomId={session.room_id} compact showOffline />
|
||||
) : session.status === "active" || !session.ended_at ? (
|
||||
<LivePulse />
|
||||
) : (
|
||||
<span>{fmtDuration(session.duration_seconds)}</span>
|
||||
|
||||
@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Loader2, RefreshCw, UserRound } from "lucide-react";
|
||||
|
||||
import { DouyinLiveBadge } from "@/components/DouyinLiveBadge";
|
||||
import { Shell } from "@/components/Shell";
|
||||
import { SessionDetailModal, type SessionDetail } from "@/components/SessionDetailModal";
|
||||
import { RoomQuickActions } from "@/components/RoomQuickActions";
|
||||
@ -247,7 +248,11 @@ export default function AnchorsPage() {
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="truncate font-medium text-white">{a.anchor_name}</span>
|
||||
{a.active ? <LivePulse label="LIVE" /> : null}
|
||||
{a.room_id ? (
|
||||
<DouyinLiveBadge roomId={a.room_id} compact showOffline />
|
||||
) : a.active ? (
|
||||
<LivePulse label="LIVE" />
|
||||
) : null}
|
||||
</div>
|
||||
<div className="mt-1 text-[11px] text-slate-500">
|
||||
{a.sessions} 场 · {Number(a.hours_total || 0).toFixed(1)}h
|
||||
@ -267,7 +272,11 @@ export default function AnchorsPage() {
|
||||
<div className="flex items-center gap-2">
|
||||
<UserRound className="h-5 w-5 text-teal-300" />
|
||||
<h3 className="font-display text-xl font-semibold">{profile.anchor_name}</h3>
|
||||
{profile.overview.active ? <LivePulse /> : null}
|
||||
{profile.room_id ? (
|
||||
<DouyinLiveBadge roomId={profile.room_id} showOffline />
|
||||
) : profile.overview.active ? (
|
||||
<LivePulse />
|
||||
) : null}
|
||||
</div>
|
||||
<p className="mt-1 font-mono text-xs text-cyan-300/80">{profile.room_id || "—"}</p>
|
||||
</div>
|
||||
|
||||
@ -4,6 +4,7 @@ import { useCallback, useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Loader2, RefreshCw, ArrowRight, ShieldOff } from "lucide-react";
|
||||
|
||||
import { DouyinLiveBadge } from "@/components/DouyinLiveBadge";
|
||||
import { Shell } from "@/components/Shell";
|
||||
import { SessionCharts, type RelayStats } from "@/components/SessionCharts";
|
||||
import { SessionDetailModal, type SessionDetail } from "@/components/SessionDetailModal";
|
||||
@ -557,6 +558,11 @@ export default function HomePage() {
|
||||
<YouTubeLiveBadge refKey={channelLiveRef(s.room_id.slice(3))} compact />
|
||||
</span>
|
||||
) : null}
|
||||
{detectPlatform(s) === "douyin" && s.room_id ? (
|
||||
<span className="ml-1.5 inline-block align-middle">
|
||||
<DouyinLiveBadge roomId={s.room_id} compact />
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="font-mono text-xs text-rose-200">{liveElapsed(s.started_at, now)}</div>
|
||||
</button>
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Loader2, Plus, RefreshCw, Trash2, Zap } from "lucide-react";
|
||||
|
||||
import { DouyinLiveBadge } from "@/components/DouyinLiveBadge";
|
||||
import { Shell } from "@/components/Shell";
|
||||
import { useConfirm } from "@/components/ConfirmDialog";
|
||||
import { useToast } from "@/components/Toast";
|
||||
@ -379,7 +380,10 @@ export default function RoomsPage() {
|
||||
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{recommend.map((r) => (
|
||||
<div key={r.room_id} className="rounded-lg border border-white/10 bg-black/25 px-2.5 py-2 text-[11px]">
|
||||
<div className="truncate font-medium text-slate-100">{r.anchor || r.room_id}</div>
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<div className="truncate font-medium text-slate-100">{r.anchor || r.room_id}</div>
|
||||
<DouyinLiveBadge roomId={r.room_id} showOffline compact />
|
||||
</div>
|
||||
<div className="mt-0.5 text-slate-400">
|
||||
成功率 {Math.round((r.success_rate || 0) * 100)}% · {r.ok}/{r.total}
|
||||
</div>
|
||||
@ -570,7 +574,7 @@ export default function RoomsPage() {
|
||||
<input type="checkbox" checked={selected.has(room.id)} onChange={() => toggleSelect(room.id)} />
|
||||
</td>
|
||||
<td className="px-3 py-3">
|
||||
<span className={`rounded border px-2 py-0.5 text-xs ${statusBadge(room.last_status)}`}>{room.last_status}</span>
|
||||
<DouyinLiveBadge roomId={room.room_id} lastStatus={room.last_status} showOffline />
|
||||
{overdue ? <div className="mt-1 text-[10px] text-violet-200">积压</div> : null}
|
||||
</td>
|
||||
<td className="px-3 py-3">
|
||||
|
||||
@ -16,6 +16,7 @@ import {
|
||||
Wrench,
|
||||
} from "lucide-react";
|
||||
|
||||
import { DouyinLiveBadge } from "@/components/DouyinLiveBadge";
|
||||
import { Shell } from "@/components/Shell";
|
||||
import { useConfirm } from "@/components/ConfirmDialog";
|
||||
import { useToast } from "@/components/Toast";
|
||||
@ -892,9 +893,10 @@ export default function ShortsPage() {
|
||||
{status.douyin_live_rooms.map((r: { room_id?: string; anchor?: string }) => (
|
||||
<span
|
||||
key={String(r.room_id)}
|
||||
className="rounded-lg border border-white/10 bg-black/30 px-2 py-1 text-[11px] text-slate-200"
|
||||
className="inline-flex items-center gap-1.5 rounded-lg border border-white/10 bg-black/30 px-2 py-1 text-[11px] text-slate-200"
|
||||
title={String(r.room_id || "")}
|
||||
>
|
||||
<DouyinLiveBadge roomId={r.room_id} compact />
|
||||
{r.anchor || r.room_id}
|
||||
</span>
|
||||
))}
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Loader2, RefreshCw } from "lucide-react";
|
||||
|
||||
import { DouyinLiveBadge } from "@/components/DouyinLiveBadge";
|
||||
import { Shell } from "@/components/Shell";
|
||||
import { SessionDetailModal } from "@/components/SessionDetailModal";
|
||||
import { RoomQuickActions } from "@/components/RoomQuickActions";
|
||||
@ -522,7 +523,9 @@ export default function SlotsPage() {
|
||||
<div className="mt-1 flex flex-wrap items-center gap-1.5 text-[11px] text-slate-500">
|
||||
<PlatformBadge platform={detectPlatform(session)} />
|
||||
<span className="font-mono text-slate-400">{fmtClock(session.started_at)} 开播</span>
|
||||
{session.status === "active" || !session.ended_at ? (
|
||||
{session.room_id && detectPlatform(session) === "douyin" ? (
|
||||
<DouyinLiveBadge roomId={session.room_id} compact showOffline />
|
||||
) : session.status === "active" || !session.ended_at ? (
|
||||
<LivePulse />
|
||||
) : (
|
||||
<span>{fmtDuration(session.duration_seconds)}</span>
|
||||
|
||||
98
frontend/src/components/DouyinLiveBadge.tsx
Normal file
98
frontend/src/components/DouyinLiveBadge.tsx
Normal file
@ -0,0 +1,98 @@
|
||||
"use client";
|
||||
|
||||
import { LivePulse } from "@/components/ui";
|
||||
import {
|
||||
resolveDouyinLive,
|
||||
useDouyinLiveEntry,
|
||||
type DouyinLiveEntry,
|
||||
} from "@/lib/douyinLive";
|
||||
|
||||
type Props = {
|
||||
roomId?: string;
|
||||
/** Fallback when live-map has not loaded this room yet */
|
||||
lastStatus?: string;
|
||||
entry?: DouyinLiveEntry | null;
|
||||
className?: string;
|
||||
compact?: boolean;
|
||||
/** Tiny dot for thumbnail overlay */
|
||||
overlay?: boolean;
|
||||
showOffline?: boolean;
|
||||
};
|
||||
|
||||
function statusLabel(status: string, isLive: boolean) {
|
||||
if (isLive) return "直播中";
|
||||
if (status === "error") return "异常";
|
||||
if (status === "offline") return "离线";
|
||||
return "检测中";
|
||||
}
|
||||
|
||||
export function DouyinLiveBadge({
|
||||
roomId,
|
||||
lastStatus,
|
||||
entry,
|
||||
className = "",
|
||||
compact = false,
|
||||
overlay = false,
|
||||
showOffline = false,
|
||||
}: Props) {
|
||||
const fromMap = useDouyinLiveEntry(roomId, entry ?? undefined);
|
||||
const live = fromMap;
|
||||
const { status, isLive } = resolveDouyinLive(live, lastStatus);
|
||||
|
||||
if (overlay) {
|
||||
if (!roomId && !lastStatus) return null;
|
||||
const color = isLive
|
||||
? "bg-rose-500 ring-rose-300/60 live-dot"
|
||||
: status === "error"
|
||||
? "bg-amber-400 ring-amber-200/60"
|
||||
: showOffline
|
||||
? "bg-slate-500/80 ring-white/20"
|
||||
: null;
|
||||
if (!color) return null;
|
||||
return (
|
||||
<span
|
||||
className={`inline-block h-2 w-2 rounded-full ring-1 ${color} ${className}`}
|
||||
title={statusLabel(status, isLive)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (isLive) {
|
||||
const label = compact ? "LIVE" : "直播中";
|
||||
const inner = <LivePulse label={label} />;
|
||||
const href = live?.url || (roomId ? `https://live.douyin.com/${roomId}` : "");
|
||||
if (href) {
|
||||
return (
|
||||
<a
|
||||
href={href}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className={`inline-flex items-center hover:opacity-90 ${className}`}
|
||||
title={live?.anchor || "打开直播间"}
|
||||
>
|
||||
{inner}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
return <span className={`inline-flex items-center ${className}`}>{inner}</span>;
|
||||
}
|
||||
|
||||
if (!showOffline) return null;
|
||||
|
||||
const label = statusLabel(status, isLive);
|
||||
const tone =
|
||||
status === "error"
|
||||
? "text-amber-200 ring-amber-500/30 bg-amber-500/10"
|
||||
: status === "offline"
|
||||
? "text-slate-400 ring-white/10 bg-white/5"
|
||||
: "text-slate-500 ring-white/10 bg-white/5";
|
||||
|
||||
return (
|
||||
<span
|
||||
className={`inline-flex items-center rounded px-1.5 py-0.5 text-[10px] ring-1 ${tone} ${className}`}
|
||||
title={live?.anchor || label}
|
||||
>
|
||||
{compact ? (status === "offline" ? "离线" : label) : label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@ -9,6 +9,11 @@ import { BrandMark, LivePulse } from "@/components/ui";
|
||||
import { GlobalEventAlerts } from "@/components/GlobalEventAlerts";
|
||||
import { PwaInstallBanner } from "@/components/PwaInstallBanner";
|
||||
import { fetchJson } from "@/lib/api";
|
||||
import {
|
||||
DouyinLiveContextProvider,
|
||||
useDouyinLiveCount,
|
||||
useDouyinLiveProviderValue,
|
||||
} from "@/lib/douyinLive";
|
||||
import {
|
||||
YouTubeLiveContextProvider,
|
||||
useYouTubeLiveCount,
|
||||
@ -45,10 +50,13 @@ function navActive(pathname: string, href: string) {
|
||||
}
|
||||
|
||||
export function Shell({ children }: { children: React.ReactNode }) {
|
||||
const liveCtx = useYouTubeLiveProviderValue();
|
||||
const ytCtx = useYouTubeLiveProviderValue();
|
||||
const dyCtx = useDouyinLiveProviderValue();
|
||||
return (
|
||||
<YouTubeLiveContextProvider value={liveCtx}>
|
||||
<ShellFrame>{children}</ShellFrame>
|
||||
<YouTubeLiveContextProvider value={ytCtx}>
|
||||
<DouyinLiveContextProvider value={dyCtx}>
|
||||
<ShellFrame>{children}</ShellFrame>
|
||||
</DouyinLiveContextProvider>
|
||||
</YouTubeLiveContextProvider>
|
||||
);
|
||||
}
|
||||
@ -57,6 +65,7 @@ function ShellFrame({ children }: { children: React.ReactNode }) {
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
const ytLiveCount = useYouTubeLiveCount();
|
||||
const dyLiveCount = useDouyinLiveCount();
|
||||
const { map: ytLiveMap } = useYouTubeLiveMap();
|
||||
const [username, setUsername] = useState("");
|
||||
const [moreOpen, setMoreOpen] = useState(false);
|
||||
@ -121,11 +130,18 @@ function ShellFrame({ children }: { children: React.ReactNode }) {
|
||||
<p className="mt-0.5 hidden max-w-2xl text-sm text-slate-400 sm:mt-1 sm:block">
|
||||
抖音 + YouTube · 开播捕捉 · 停播结场 · 时长统计 · 截图存证
|
||||
</p>
|
||||
{ytLiveCount > 0 ? (
|
||||
{(dyLiveCount > 0 || ytLiveCount > 0) ? (
|
||||
<div className="mt-1.5 flex flex-wrap items-center gap-2 sm:mt-2">
|
||||
<Link href="/groups">
|
||||
<LivePulse label={`YouTube ${ytLiveCount} 路在播`} />
|
||||
</Link>
|
||||
{dyLiveCount > 0 ? (
|
||||
<Link href="/rooms?q=&status=live">
|
||||
<LivePulse label={`抖音 ${dyLiveCount} 路在播`} />
|
||||
</Link>
|
||||
) : null}
|
||||
{ytLiveCount > 0 ? (
|
||||
<Link href="/groups">
|
||||
<LivePulse label={`YouTube ${ytLiveCount} 路在播`} />
|
||||
</Link>
|
||||
) : null}
|
||||
{ytLiveMap?.checked_at ? (
|
||||
<span className="hidden text-[10px] text-slate-500 sm:inline">
|
||||
轮询 {Math.max(0, Math.round(Date.now() / 1000 - Number(ytLiveMap.checked_at)))}s 前
|
||||
@ -134,13 +150,7 @@ function ShellFrame({ children }: { children: React.ReactNode }) {
|
||||
</div>
|
||||
) : (
|
||||
<div className="mt-1.5 hidden flex-wrap items-center gap-2 text-[11px] text-slate-500 sm:mt-2 sm:flex">
|
||||
{ytLiveMap?.svc_error ? (
|
||||
<span className="text-amber-300" title={ytLiveMap.svc_error}>
|
||||
⚠ YouTube 探测异常(轮询兜底中)
|
||||
</span>
|
||||
) : (
|
||||
<span>YouTube 直播轮询中</span>
|
||||
)}
|
||||
<span>抖音 / YouTube 直播轮询中</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@ -16,6 +16,7 @@ import {
|
||||
Trash2,
|
||||
} from "lucide-react";
|
||||
|
||||
import { DouyinLiveBadge } from "@/components/DouyinLiveBadge";
|
||||
import { useConfirm } from "@/components/ConfirmDialog";
|
||||
import { ImageLightbox } from "@/components/ImageLightbox";
|
||||
import { useToast } from "@/components/Toast";
|
||||
@ -181,26 +182,44 @@ function ManageStyleProfileCard({
|
||||
function CoverThumb({
|
||||
cover,
|
||||
title,
|
||||
roomId,
|
||||
onOpen,
|
||||
}: {
|
||||
cover?: string;
|
||||
title?: string;
|
||||
roomId?: string;
|
||||
onOpen: (src: string) => void;
|
||||
}) {
|
||||
const src = String(cover || "").trim();
|
||||
if (!src) {
|
||||
return <div className="h-8 w-8 shrink-0 rounded bg-white/10" title="无封面" />;
|
||||
return (
|
||||
<div className="relative h-8 w-8 shrink-0">
|
||||
<div className="h-8 w-8 rounded bg-white/10" title="无封面" />
|
||||
{roomId ? (
|
||||
<div className="absolute -right-0.5 -top-0.5">
|
||||
<DouyinLiveBadge roomId={roomId} overlay showOffline />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onOpen(src)}
|
||||
className="h-8 w-8 shrink-0 overflow-hidden rounded border border-white/10 bg-black/40 hover:ring-1 hover:ring-sky-400/40"
|
||||
title="点击查看封面"
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={src} alt={title || "cover"} className="h-full w-full object-cover" />
|
||||
</button>
|
||||
<div className="relative h-8 w-8 shrink-0">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onOpen(src)}
|
||||
className="h-8 w-8 overflow-hidden rounded border border-white/10 bg-black/40 hover:ring-1 hover:ring-sky-400/40"
|
||||
title="点击查看封面"
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={src} alt={title || "cover"} className="h-full w-full object-cover" />
|
||||
</button>
|
||||
{roomId ? (
|
||||
<div className="absolute -right-0.5 -top-0.5">
|
||||
<DouyinLiveBadge roomId={roomId} overlay showOffline />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -980,6 +999,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
||||
<CoverThumb
|
||||
cover={u.cover_url}
|
||||
title={u.title}
|
||||
roomId={u.room_id}
|
||||
onOpen={(src) =>
|
||||
setLightbox({ src, title: u.title || "封面", subtitle: u.url })
|
||||
}
|
||||
@ -987,6 +1007,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<div className="truncate text-sm text-slate-100">{u.title || "未命名主播"}</div>
|
||||
{u.room_id ? <DouyinLiveBadge roomId={u.room_id} compact showOffline /> : null}
|
||||
{banned ? (
|
||||
<span className="rounded bg-fuchsia-500/25 px-1.5 text-[10px] text-fuchsia-100">
|
||||
黑名单
|
||||
@ -1124,6 +1145,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
||||
<CoverThumb
|
||||
cover={s.cover_url}
|
||||
title={s.title}
|
||||
roomId={s.room_id}
|
||||
onOpen={(src) =>
|
||||
setLightbox({ src, title: s.title || "封面", subtitle: s.url })
|
||||
}
|
||||
@ -1131,6 +1153,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<div className="truncate text-sm text-violet-50">{s.title || "未命名主播"}</div>
|
||||
{s.room_id ? <DouyinLiveBadge roomId={s.room_id} compact showOffline /> : null}
|
||||
{timeLabel ? (
|
||||
<span className="rounded bg-violet-500/25 px-1.5 text-[10px] text-violet-100">
|
||||
{timeLabel}
|
||||
@ -1242,6 +1265,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
||||
<CoverThumb
|
||||
cover={f.cover_url}
|
||||
title={f.title}
|
||||
roomId={f.room_id}
|
||||
onOpen={(src) =>
|
||||
setLightbox({ src, title: f.title || "封面", subtitle: f.url })
|
||||
}
|
||||
@ -1249,6 +1273,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<div className="truncate text-sm text-amber-50">{f.title || "未命名主播"}</div>
|
||||
{f.room_id ? <DouyinLiveBadge roomId={f.room_id} compact showOffline /> : null}
|
||||
{banned ? (
|
||||
<span className="rounded bg-fuchsia-500/25 px-1.5 text-[10px] text-fuchsia-100">
|
||||
黑名单
|
||||
|
||||
104
frontend/src/lib/douyinLive.ts
Normal file
104
frontend/src/lib/douyinLive.ts
Normal file
@ -0,0 +1,104 @@
|
||||
"use client";
|
||||
|
||||
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { fetchJson } from "@/lib/api";
|
||||
import { useEventStream } from "@/lib/realtime";
|
||||
|
||||
export type DouyinLiveEntry = {
|
||||
is_live?: boolean;
|
||||
last_status?: string;
|
||||
anchor?: string;
|
||||
url?: string;
|
||||
last_checked_at?: number;
|
||||
active_session_id?: string;
|
||||
};
|
||||
|
||||
export type DouyinLiveMap = {
|
||||
ok?: boolean;
|
||||
checked_at?: number;
|
||||
live_count?: number;
|
||||
source?: string;
|
||||
entries?: Record<string, DouyinLiveEntry>;
|
||||
};
|
||||
|
||||
const DouyinLiveContext = createContext<{
|
||||
map: DouyinLiveMap | null;
|
||||
loading: boolean;
|
||||
refresh: () => Promise<void>;
|
||||
}>({
|
||||
map: null,
|
||||
loading: false,
|
||||
refresh: async () => {},
|
||||
});
|
||||
|
||||
export function useDouyinLiveProviderValue(intervalMs = 10000) {
|
||||
const [map, setMap] = useState<DouyinLiveMap | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { tick, last } = useEventStream(true);
|
||||
|
||||
const refresh = useCallback(async (silent = false) => {
|
||||
if (!silent) setLoading(true);
|
||||
try {
|
||||
const data = (await fetchJson("/api/douyin/live-map")) as DouyinLiveMap;
|
||||
setMap(data);
|
||||
} catch {
|
||||
/* keep last map */
|
||||
} finally {
|
||||
if (!silent) setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh(true);
|
||||
const id = window.setInterval(() => 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]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!last?.kind) return;
|
||||
if (!["live", "offline", "risk"].includes(String(last.kind))) return;
|
||||
void refresh(true);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [tick]);
|
||||
|
||||
return useMemo(
|
||||
() => ({
|
||||
map,
|
||||
loading,
|
||||
refresh: () => refresh(false),
|
||||
}),
|
||||
[map, loading, refresh],
|
||||
);
|
||||
}
|
||||
|
||||
export const DouyinLiveContextProvider = DouyinLiveContext.Provider;
|
||||
|
||||
export function useDouyinLiveMap() {
|
||||
return useContext(DouyinLiveContext);
|
||||
}
|
||||
|
||||
export function useDouyinLiveEntry(roomId?: string, fallback?: DouyinLiveEntry | null): DouyinLiveEntry | null {
|
||||
const { map } = useDouyinLiveMap();
|
||||
const rid = String(roomId || "").trim();
|
||||
if (!rid) return fallback ?? null;
|
||||
return map?.entries?.[rid] ?? fallback ?? null;
|
||||
}
|
||||
|
||||
export function useDouyinLiveCount() {
|
||||
const { map } = useDouyinLiveMap();
|
||||
return Number(map?.live_count || 0);
|
||||
}
|
||||
|
||||
export function resolveDouyinLive(entry: DouyinLiveEntry | null | undefined, lastStatus?: string) {
|
||||
const status = String(entry?.last_status || lastStatus || "unknown").trim() || "unknown";
|
||||
const isLive = entry?.is_live ?? status === "live";
|
||||
return { status, isLive };
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user