diff --git a/backend/app/db.py b/backend/app/db.py index c3ea180..5207ff8 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -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: diff --git a/backend/app/douyin_live.py b/backend/app/douyin_live.py new file mode 100644 index 0000000..716590d --- /dev/null +++ b/backend/app/douyin_live.py @@ -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 diff --git a/backend/app/main.py b/backend/app/main.py index 13c462d..63ad03b 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -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 = "", diff --git a/desktop/src/components/DouyinLiveBadge.tsx b/desktop/src/components/DouyinLiveBadge.tsx new file mode 100644 index 0000000..5151d08 --- /dev/null +++ b/desktop/src/components/DouyinLiveBadge.tsx @@ -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 ( + + ); + } + + if (isLive) { + const label = compact ? "LIVE" : "直播中"; + const inner = ; + const href = live?.url || (roomId ? `https://live.douyin.com/${roomId}` : ""); + if (href) { + return ( + + {inner} + + ); + } + return {inner}; + } + + 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 ( + + {compact ? (status === "offline" ? "离线" : label) : label} + + ); +} diff --git a/desktop/src/components/Shell.tsx b/desktop/src/components/Shell.tsx index 29ce5b0..9381305 100644 --- a/desktop/src/components/Shell.tsx +++ b/desktop/src/components/Shell.tsx @@ -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 ( - - {children} + + + {children} + ); } @@ -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 }) {

抖音 + YouTube · 开播捕捉 · 停播结场 · 时长统计 · 截图存证 · Windows 客户端

- {ytLiveCount > 0 ? ( + {(dyLiveCount > 0 || ytLiveCount > 0) ? (
- - - + {dyLiveCount > 0 ? ( + + + + ) : null} + {ytLiveCount > 0 ? ( + + + + ) : null} {ytLiveMap?.checked_at ? ( 轮询 {Math.max(0, Math.round(Date.now() / 1000 - Number(ytLiveMap.checked_at)))}s 前 @@ -87,13 +99,7 @@ function ShellFrame({ children }: { children: React.ReactNode }) {
) : (
- {ytLiveMap?.svc_error ? ( - - ⚠ YouTube 探测异常(轮询兜底中) - - ) : ( - YouTube 直播轮询中 - )} + 抖音 / YouTube 直播轮询中 {ytLiveMap?.checked_at ? ( · {Math.max(0, Math.round(Date.now() / 1000 - Number(ytLiveMap.checked_at)))}s 前刷新 diff --git a/desktop/src/lib/douyinLive.ts b/desktop/src/lib/douyinLive.ts new file mode 100644 index 0000000..80fd459 --- /dev/null +++ b/desktop/src/lib/douyinLive.ts @@ -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; +}; + +const DouyinLiveContext = createContext<{ + map: DouyinLiveMap | null; + loading: boolean; + refresh: () => Promise; +}>({ + map: null, + loading: false, + refresh: async () => {}, +}); + +export function useDouyinLiveProviderValue(intervalMs = 10000) { + const [map, setMap] = useState(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 }; +} diff --git a/desktop/src/pages/AnchorsPage.tsx b/desktop/src/pages/AnchorsPage.tsx index 32a7648..638d84d 100644 --- a/desktop/src/pages/AnchorsPage.tsx +++ b/desktop/src/pages/AnchorsPage.tsx @@ -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() { >
{a.anchor_name} - {a.active ? : null} + {a.room_id ? ( + + ) : a.active ? ( + + ) : null}
{a.sessions} 场 · {Number(a.hours_total || 0).toFixed(1)}h @@ -222,7 +227,11 @@ export default function AnchorsPage() {

{profile.anchor_name}

- {profile.overview.active ? : null} + {profile.room_id ? ( + + ) : profile.overview.active ? ( + + ) : null}

{profile.room_id || "—"}

diff --git a/desktop/src/pages/OverviewPage.tsx b/desktop/src/pages/OverviewPage.tsx index fe38f7c..fe95259 100644 --- a/desktop/src/pages/OverviewPage.tsx +++ b/desktop/src/pages/OverviewPage.tsx @@ -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() {
) : null} + {detectPlatform(s) === "douyin" && s.room_id ? ( + + + + ) : null}
{liveElapsed(s.started_at, now)}
diff --git a/desktop/src/pages/RoomsPage.tsx b/desktop/src/pages/RoomsPage.tsx index 7ccc19b..46faadc 100644 --- a/desktop/src/pages/RoomsPage.tsx +++ b/desktop/src/pages/RoomsPage.tsx @@ -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() { toggleSelect(room.id)} /> - {room.last_status} + {overdue ?
积压
: null} diff --git a/desktop/src/pages/ShortsPage.tsx b/desktop/src/pages/ShortsPage.tsx index 648cee0..0708f2c 100644 --- a/desktop/src/pages/ShortsPage.tsx +++ b/desktop/src/pages/ShortsPage.tsx @@ -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 }) => ( + {r.anchor || r.room_id} ))} diff --git a/desktop/src/pages/SlotsPage.tsx b/desktop/src/pages/SlotsPage.tsx index e199d02..ac83ead 100644 --- a/desktop/src/pages/SlotsPage.tsx +++ b/desktop/src/pages/SlotsPage.tsx @@ -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() {
{fmtClock(session.started_at)} 开播 - {session.status === "active" || !session.ended_at ? ( + {session.room_id && detectPlatform(session) === "douyin" ? ( + + ) : session.status === "active" || !session.ended_at ? ( ) : ( {fmtDuration(session.duration_seconds)} diff --git a/frontend/src/app/anchors/page.tsx b/frontend/src/app/anchors/page.tsx index 50d7b45..796acc6 100644 --- a/frontend/src/app/anchors/page.tsx +++ b/frontend/src/app/anchors/page.tsx @@ -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() { >
{a.anchor_name} - {a.active ? : null} + {a.room_id ? ( + + ) : a.active ? ( + + ) : null}
{a.sessions} 场 · {Number(a.hours_total || 0).toFixed(1)}h @@ -267,7 +272,11 @@ export default function AnchorsPage() {

{profile.anchor_name}

- {profile.overview.active ? : null} + {profile.room_id ? ( + + ) : profile.overview.active ? ( + + ) : null}

{profile.room_id || "—"}

diff --git a/frontend/src/app/page.tsx b/frontend/src/app/page.tsx index 885e690..28232e3 100644 --- a/frontend/src/app/page.tsx +++ b/frontend/src/app/page.tsx @@ -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() { ) : null} + {detectPlatform(s) === "douyin" && s.room_id ? ( + + + + ) : null}
{liveElapsed(s.started_at, now)}
diff --git a/frontend/src/app/rooms/page.tsx b/frontend/src/app/rooms/page.tsx index c80458b..f97d3c2 100644 --- a/frontend/src/app/rooms/page.tsx +++ b/frontend/src/app/rooms/page.tsx @@ -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() {
{recommend.map((r) => (
-
{r.anchor || r.room_id}
+
+
{r.anchor || r.room_id}
+ +
成功率 {Math.round((r.success_rate || 0) * 100)}% · {r.ok}/{r.total}
@@ -570,7 +574,7 @@ export default function RoomsPage() { toggleSelect(room.id)} /> - {room.last_status} + {overdue ?
积压
: null} diff --git a/frontend/src/app/shorts/page.tsx b/frontend/src/app/shorts/page.tsx index 8f129e8..c65d22f 100644 --- a/frontend/src/app/shorts/page.tsx +++ b/frontend/src/app/shorts/page.tsx @@ -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 }) => ( + {r.anchor || r.room_id} ))} diff --git a/frontend/src/app/slots/page.tsx b/frontend/src/app/slots/page.tsx index 72e31eb..7cd0260 100644 --- a/frontend/src/app/slots/page.tsx +++ b/frontend/src/app/slots/page.tsx @@ -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() {
{fmtClock(session.started_at)} 开播 - {session.status === "active" || !session.ended_at ? ( + {session.room_id && detectPlatform(session) === "douyin" ? ( + + ) : session.status === "active" || !session.ended_at ? ( ) : ( {fmtDuration(session.duration_seconds)} diff --git a/frontend/src/components/DouyinLiveBadge.tsx b/frontend/src/components/DouyinLiveBadge.tsx new file mode 100644 index 0000000..3639856 --- /dev/null +++ b/frontend/src/components/DouyinLiveBadge.tsx @@ -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 ( + + ); + } + + if (isLive) { + const label = compact ? "LIVE" : "直播中"; + const inner = ; + const href = live?.url || (roomId ? `https://live.douyin.com/${roomId}` : ""); + if (href) { + return ( + + {inner} + + ); + } + return {inner}; + } + + 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 ( + + {compact ? (status === "offline" ? "离线" : label) : label} + + ); +} diff --git a/frontend/src/components/Shell.tsx b/frontend/src/components/Shell.tsx index fc04be5..dc5f6c6 100644 --- a/frontend/src/components/Shell.tsx +++ b/frontend/src/components/Shell.tsx @@ -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 ( - - {children} + + + {children} + ); } @@ -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 }) {

抖音 + YouTube · 开播捕捉 · 停播结场 · 时长统计 · 截图存证

- {ytLiveCount > 0 ? ( + {(dyLiveCount > 0 || ytLiveCount > 0) ? (
- - - + {dyLiveCount > 0 ? ( + + + + ) : null} + {ytLiveCount > 0 ? ( + + + + ) : null} {ytLiveMap?.checked_at ? ( 轮询 {Math.max(0, Math.round(Date.now() / 1000 - Number(ytLiveMap.checked_at)))}s 前 @@ -134,13 +150,7 @@ function ShellFrame({ children }: { children: React.ReactNode }) {
) : (
- {ytLiveMap?.svc_error ? ( - - ⚠ YouTube 探测异常(轮询兜底中) - - ) : ( - YouTube 直播轮询中 - )} + 抖音 / YouTube 直播轮询中
)}
diff --git a/frontend/src/components/YtAssignPanel.tsx b/frontend/src/components/YtAssignPanel.tsx index f46aa53..0c97009 100644 --- a/frontend/src/components/YtAssignPanel.tsx +++ b/frontend/src/components/YtAssignPanel.tsx @@ -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
; + return ( +
+
+ {roomId ? ( +
+ +
+ ) : null} +
+ ); } return ( - +
+ + {roomId ? ( +
+ +
+ ) : null} +
); } @@ -980,6 +999,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) { setLightbox({ src, title: u.title || "封面", subtitle: u.url }) } @@ -987,6 +1007,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
{u.title || "未命名主播"}
+ {u.room_id ? : null} {banned ? ( 黑名单 @@ -1124,6 +1145,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) { setLightbox({ src, title: s.title || "封面", subtitle: s.url }) } @@ -1131,6 +1153,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
{s.title || "未命名主播"}
+ {s.room_id ? : null} {timeLabel ? ( {timeLabel} @@ -1242,6 +1265,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) { setLightbox({ src, title: f.title || "封面", subtitle: f.url }) } @@ -1249,6 +1273,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
{f.title || "未命名主播"}
+ {f.room_id ? : null} {banned ? ( 黑名单 diff --git a/frontend/src/lib/douyinLive.ts b/frontend/src/lib/douyinLive.ts new file mode 100644 index 0000000..5f2fb72 --- /dev/null +++ b/frontend/src/lib/douyinLive.ts @@ -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; +}; + +const DouyinLiveContext = createContext<{ + map: DouyinLiveMap | null; + loading: boolean; + refresh: () => Promise; +}>({ + map: null, + loading: false, + refresh: async () => {}, +}); + +export function useDouyinLiveProviderValue(intervalMs = 10000) { + const [map, setMap] = useState(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 }; +}