Skip to content

一分钟搭建影视站,支持Docker等部署方式

feat(live): 测活结果持久化,6 小时内有效

bestZwei39cf7838e77a
diff --git a/package.json b/package.json
index f3f87bc..1314ee4 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "libretv",
- "version": "2.4.2",
+ "version": "2.5.0",
"private": true,
"description": "免费在线视频搜索与观看平台(Next.js 重构版)",
"license": "AGPL-3.0-or-later",
diff --git a/src/components/live-channel-list.tsx b/src/components/live-channel-list.tsx
index a1d68e7..27cb425 100644
--- a/src/components/live-channel-list.tsx
+++ b/src/components/live-channel-list.tsx
@@ -37,7 +37,7 @@ export function LiveChannelList({ channels, groups, currentUrl, onSelect }: Chan
const [keyword, setKeyword] = useState('');
const [limit, setLimit] = useState(PAGE_SIZE);
const [onlyAlive, setOnlyAlive] = useState(false);
- const { results: probeResults, progress: probeProgress, probe, clear: clearProbe, isProbing } = useLiveProbe();
+ const { results: probeResults, progress: probeProgress, probe, clear: clearProbe, isProbing, hint: probeHint } = useLiveProbe();
const favSet = useMemo(() => new Set(store.liveFavorites), [store.liveFavorites]);
@@ -119,7 +119,7 @@ export function LiveChannelList({ channels, groups, currentUrl, onSelect }: Chan
className="btn-ghost !py-1 !px-2 text-xs"
disabled={isProbing || filtered.length === 0}
onClick={() => void probe(filtered)}
- title="轻量探测当前列表频道的可达性与延迟(每批 10 条并发探测)"
+ title="轻量探测当前列表频道的可达性与延迟(每批 10 条并发探测,结果 6 小时内有效)"
>
⚡ 测活
</button>
@@ -128,6 +128,9 @@ export function LiveChannelList({ channels, groups, currentUrl, onSelect }: Chan
探测中 {probeProgress.done}/{probeProgress.total}
</span>
)}
+ {probeHint && !isProbing && (
+ <span className="text-[10px] text-faint">{probeHint}</span>
+ )}
{probeResults.size > 0 && !isProbing && (
<>
<button
diff --git a/src/components/use-live-probe.ts b/src/components/use-live-probe.ts
index 12e1cd2..688eae4 100644
--- a/src/components/use-live-probe.ts
+++ b/src/components/use-live-probe.ts
@@ -1,12 +1,14 @@
'use client';
-import { useCallback, useRef, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { api } from '@/lib/client-api';
+import { LIVE_PROBE_TTL_MS, useAppStore, type LiveProbeEntry } from '@/lib/store';
/**
* 直播频道批量测活 hook:
+ * - 结果持久化到 store(liveProbeResults),6 小时内直接复用(LIVE_PROBE_TTL_MS);
+ * - 触发探测时只补测缺失或已过期的频道,全部仍有效则提示跳过;
* - 目标列表分批(每批 10 条)顺序发给 /api/live/probe,服务端批内并发 8;
- * - 结果渐进写入 Map,列表可实时显示状态点;
* - 再次调用自动作废上一轮(runId 比对),clear 重置。
*/
@@ -21,47 +23,86 @@ const CHUNK_SIZE = 10;
const MAX_TARGETS = 400;
export function useLiveProbe() {
- const [results, setResults] = useState<Map<string, ProbeResult>>(new Map());
+ const cache = useAppStore((s) => s.liveProbeResults);
const [progress, setProgress] = useState<{ done: number; total: number } | null>(null);
+ const [hint, setHint] = useState('');
const runIdRef = useRef(0);
+ const hintTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const showHint = useCallback((text: string) => {
+ setHint(text);
+ if (hintTimerRef.current) clearTimeout(hintTimerRef.current);
+ hintTimerRef.current = setTimeout(() => setHint(''), 3000);
+ }, []);
+
+ useEffect(() => () => {
+ if (hintTimerRef.current) clearTimeout(hintTimerRef.current);
+ }, []);
+
+ // 仅暴露 6 小时内的结果,过期条目对 UI 不可见
+ const results = useMemo(() => {
+ const now = Date.now();
+ const map = new Map<string, ProbeResult>();
+ for (const [url, e] of Object.entries(cache)) {
+ if (now - e.timestamp < LIVE_PROBE_TTL_MS) {
+ map.set(url, { ok: e.ok, ms: e.ms, level: e.level, error: e.error });
+ }
+ }
+ return map;
+ }, [cache]);
const clear = useCallback(() => {
runIdRef.current++;
- setResults(new Map());
+ useAppStore.getState().clearLiveProbeResults();
setProgress(null);
}, []);
- const probe = useCallback(async (targets: { url: string }[]) => {
- const urls = [...new Set(targets.map((t) => t.url))].slice(0, MAX_TARGETS);
- if (urls.length === 0) return;
- const runId = ++runIdRef.current;
- setProgress({ done: 0, total: urls.length });
+ const probe = useCallback(
+ async (targets: { url: string }[]) => {
+ const urls = [...new Set(targets.map((t) => t.url))].slice(0, MAX_TARGETS);
+ if (urls.length === 0) return;
- for (let i = 0; i < urls.length; i += CHUNK_SIZE) {
- if (runIdRef.current !== runId) return;
- const chunk = urls.slice(i, i + CHUNK_SIZE);
- try {
- const { results: list } = await api.liveProbe(chunk);
- setResults((prev) => {
- const next = new Map(prev);
- for (const r of list) next.set(r.url, { ok: r.ok, ms: r.ms, level: r.level, error: r.error });
- return next;
- });
- } catch (err) {
- // 整批请求失败(网络断开等):标记为不可达而非静默丢弃
- const msg = err instanceof Error ? err.message : '探测失败';
- setResults((prev) => {
- const next = new Map(prev);
- for (const u of chunk) if (!next.has(u)) next.set(u, { ok: false, error: msg });
- return next;
- });
+ // 6 小时内已测过的直接复用,仅补测缺失或过期的频道
+ const now = Date.now();
+ const cached = useAppStore.getState().liveProbeResults;
+ const stale = urls.filter((u) => {
+ const e = cached[u];
+ return !e || now - e.timestamp >= LIVE_PROBE_TTL_MS;
+ });
+ if (stale.length === 0) {
+ showHint('测活结果 6 小时内有效,无需重测');
+ return;
+ }
+
+ const runId = ++runIdRef.current;
+ setProgress({ done: 0, total: stale.length });
+
+ const writeToCache = (entries: Record<string, LiveProbeEntry>) => {
+ if (runIdRef.current !== runId) return;
+ useAppStore.getState().setLiveProbeResults(entries);
+ };
+
+ for (let i = 0; i < stale.length; i += CHUNK_SIZE) {
+ if (runIdRef.current !== runId) return;
+ const chunk = stale.slice(i, i + CHUNK_SIZE);
+ try {
+ const { results: list } = await api.liveProbe(chunk);
+ const entries: Record<string, LiveProbeEntry> = {};
+ for (const r of list) {
+ entries[r.url] = { ok: r.ok, ms: r.ms, level: r.level, error: r.error, timestamp: Date.now() };
+ }
+ writeToCache(entries);
+ } catch {
+ // 整批请求失败(网络断开等):不写缓存,保持待测状态以便下次重试
+ }
+ if (runIdRef.current !== runId) return;
+ setProgress({ done: Math.min(i + CHUNK_SIZE, stale.length), total: stale.length });
}
if (runIdRef.current !== runId) return;
- setProgress({ done: Math.min(i + CHUNK_SIZE, urls.length), total: urls.length });
- }
- if (runIdRef.current !== runId) return;
- setProgress(null);
- }, []);
+ setProgress(null);
+ },
+ [showHint]
+ );
- return { results, progress, probe, clear, isProbing: progress !== null };
+ return { results, progress, probe, clear, isProbing: progress !== null, hint };
}
diff --git a/src/lib/store.ts b/src/lib/store.ts
index b0b6877..14102fb 100644
--- a/src/lib/store.ts
+++ b/src/lib/store.ts
@@ -53,6 +53,19 @@ export interface LiveRecentEntry {
timestamp: number;
}
+/** 测活结果有效期:6 小时内直接复用,过期后重新探测 */
+export const LIVE_PROBE_TTL_MS = 6 * 60 * 60 * 1000;
+
+/** 直播测活结果缓存条目(按流 URL 唯一标识) */
+export interface LiveProbeEntry {
+ ok: boolean;
+ ms?: number;
+ level?: 'segment' | 'manifest' | 'head';
+ error?: string;
+ /** 测活时间戳(epoch ms),配合 TTL 判断有效性 */
+ timestamp: number;
+}
+
/** 订阅导入的源 key 前缀:sub_<hash8(url)>_<i>,同步时按前缀整体替换 */
export function subKeyPrefix(url: string): string {
let h = 5381;
@@ -79,6 +92,8 @@ interface AppState extends AppSettings {
liveFavorites: string[];
/** 最近观看频道(上限 20) */
liveRecent: LiveRecentEntry[];
+ /** 测活结果缓存(6 小时有效,跨会话持久化) */
+ liveProbeResults: Record<string, LiveProbeEntry>;
addCustomApi: (api: Omit<SourceConfig, 'key'> & { key?: string }) => void;
updateCustomApi: (key: string, patch: Partial<SourceConfig>) => void;
removeCustomApi: (key: string) => void;
@@ -97,6 +112,9 @@ interface AppState extends AppSettings {
toggleLiveSelected: (url: string) => void;
toggleLiveFavorite: (channelUrl: string) => void;
addLiveRecent: (entry: Omit<LiveRecentEntry, 'timestamp'>) => void;
+ /** 合并写入测活结果,并顺带清理过期条目 */
+ setLiveProbeResults: (entries: Record<string, LiveProbeEntry>) => void;
+ clearLiveProbeResults: () => void;
updateSettings: (patch: Partial<Omit<AppSettings, 'customAPIs' | 'selectedKeys'>>) => void;
}
@@ -125,6 +143,7 @@ export const useAppStore = create<AppState>()(
liveSelectedUrls: [],
liveFavorites: [],
liveRecent: [],
+ liveProbeResults: {},
selectedKeys: [],
yellowFilter: true,
adFilter: true,
@@ -296,6 +315,19 @@ export const useAppStore = create<AppState>()(
set({ liveRecent: [{ ...entry, timestamp: Date.now() }, ...rest].slice(0, 20) });
},
+ setLiveProbeResults: (entries) => {
+ const now = Date.now();
+ // 合并新结果并顺带清理过期条目,避免 localStorage 无限增长
+ const next: Record<string, LiveProbeEntry> = {};
+ for (const [url, e] of Object.entries(get().liveProbeResults)) {
+ if (now - e.timestamp < LIVE_PROBE_TTL_MS) next[url] = e;
+ }
+ for (const [url, e] of Object.entries(entries)) next[url] = e;
+ set({ liveProbeResults: next });
+ },
+
+ clearLiveProbeResults: () => set({ liveProbeResults: {} }),
+
updateSettings: (patch) => {
// 打开成人内容过滤时,同步取消勾选所有成人源,避免两者并存
if (patch.yellowFilter === true) {
@@ -326,6 +358,7 @@ export const useAppStore = create<AppState>()(
liveSelectedUrls: s.liveSelectedUrls,
liveFavorites: s.liveFavorites,
liveRecent: s.liveRecent,
+ liveProbeResults: s.liveProbeResults,
yellowFilter: s.yellowFilter,
adFilter: s.adFilter,
doubanEnabled: s.doubanEnabled,