Skip to content

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

feat(search): 聚合搜索流式化、源级总死线与源健康度自动停用,版本 2.9.5

bestZweid6190d870929
diff --git a/package.json b/package.json
index a8d7742..8db8b35 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "libretv",
- "version": "2.9.4",
+ "version": "2.9.5",
"private": true,
"description": "免费在线视频搜索与观看平台(Next.js 重构版)",
"license": "AGPL-3.0-or-later",
diff --git a/src/app/api/search/route.ts b/src/app/api/search/route.ts
index de5b095..65a89ec 100644
--- a/src/app/api/search/route.ts
+++ b/src/app/api/search/route.ts
@@ -3,7 +3,7 @@ import { guardRequest } from '@/lib/api-guard';
import { cmsRequestHeaders, filterAdultResults, filterRelevantResults, normalizeTitle, parseSearchList } from '@/lib/cms-parser';
import { fetchUpstream, getCache, setCache } from '@/lib/fetch-utils';
import { checkUpstreamAllowed } from '@/lib/ssrf';
-import type { SearchResponse, SourceConfig, SourceSearchOutcome } from '@/lib/types';
+import type { SearchResponse, SearchStreamEvent, SourceConfig, SourceSearchOutcome } from '@/lib/types';
export const runtime = 'nodejs';
@@ -36,88 +36,125 @@ const SEARCH_MAX_PAGES = (() => {
return Math.min(50, Math.max(1, n));
})();
+/**
+ * 单源总死线(毫秒):该源所有分页请求必须在时限内完成,到点中断在途请求并标记超时。
+ * 没有它时慢源最坏要等「首页 8s + 后续页并行 8s」,拖垮整体响应。
+ * 环境变量 SEARCH_SOURCE_TIMEOUT_MS 可配,默认 10s。
+ */
+const SEARCH_SOURCE_TIMEOUT_MS = (() => {
+ const n = parseInt(process.env.SEARCH_SOURCE_TIMEOUT_MS || '10000', 10);
+ if (!Number.isFinite(n)) return 10000;
+ return Math.min(60000, Math.max(3000, n));
+})();
+
+/** AbortSignal.timeout / 源级死线中断均以 TimeoutError 语义呈现(直接抛出或挂在 cause 上) */
+function isTimeoutError(err: unknown): boolean {
+ const candidates: unknown[] = [err, err instanceof Error ? err.cause : undefined];
+ return candidates.some((e) => e instanceof Error && (e.name === 'TimeoutError' || e.name === 'AbortError'));
+}
+
/**
* 服务端聚合搜索:并行请求所有选中源,任一源失败不影响整体。
- * 每个源先取第一页并读取 pagecount,再并行抓取后续页(上限 SEARCH_MAX_PAGES)。
+ * 每个源先取第一页并读取 pagecount,再并行抓取后续页(上限 SEARCH_MAX_PAGES),
+ * 整源受 SEARCH_SOURCE_TIMEOUT_MS 总死线约束。
* 旧版在浏览器里打满 N 个请求(暴露用户 IP、无法缓存、超时失控),现全部上移。
*/
-export async function POST(req: Request) {
- const guarded = guardRequest(req);
- if (guarded) return guarded;
+async function searchSource(source: SourceConfig, wd: string): Promise<SourceSearchOutcome> {
+ const start = Date.now();
+ const finish = (outcome: Omit<SourceSearchOutcome, 'ms'>): SourceSearchOutcome => ({
+ ...outcome,
+ ms: Date.now() - start,
+ });
- let body: SearchBody;
- try {
- body = (await req.json()) as SearchBody;
- } catch {
- return NextResponse.json({ error: '请求格式错误' }, { status: 400 });
+ if (!/^https?:\/\//.test(source.url || '')) {
+ return finish({ sourceKey: source.key, ok: false, list: [], error: '无效的源地址' });
}
-
- const wd = (body.wd || '').trim();
- if (!wd || wd.length > 100) {
- return NextResponse.json({ error: '搜索关键词无效' }, { status: 400 });
+ // 用户可控地址发起服务端请求,必须先过 SSRF 校验(协议白名单 + 内网/保留地址)
+ const verdict = await checkUpstreamAllowed(source.url);
+ if (!verdict.ok) {
+ return finish({ sourceKey: source.key, ok: false, list: [], error: verdict.reason });
}
- if (!Array.isArray(body.sources) || body.sources.length === 0) {
- return NextResponse.json({ error: '请至少选择一个点播源' }, { status: 400 });
- }
- const sources = body.sources.slice(0, 50);
- const cacheKey = searchCacheKey(wd, sources, body.filterAdult !== false);
- const cached = getCache<SearchResponse>(cacheKey);
- if (cached) {
- return NextResponse.json(cached);
- }
+ // 死线到点中断该源所有在途分页请求,避免后台继续空耗
+ const controller = new AbortController();
+ let deadlineTimer: ReturnType<typeof setTimeout> | undefined;
+ const deadline = new Promise<SourceSearchOutcome>((resolve) => {
+ deadlineTimer = setTimeout(() => {
+ controller.abort(new DOMException('源搜索超时', 'TimeoutError'));
+ resolve(
+ finish({
+ sourceKey: source.key,
+ ok: false,
+ list: [],
+ error: `请求超时(>${Math.round(SEARCH_SOURCE_TIMEOUT_MS / 1000)}s)`,
+ timedOut: true,
+ })
+ );
+ }, SEARCH_SOURCE_TIMEOUT_MS);
+ });
- const outcomes: SourceSearchOutcome[] = await Promise.all(
- sources.map(async (source): Promise<SourceSearchOutcome> => {
- if (!/^https?:\/\//.test(source.url || '')) {
- return { sourceKey: source.key, ok: false, list: [], error: '无效的源地址' };
- }
- // 用户可控地址发起服务端请求,必须先过 SSRF 校验(协议白名单 + 内网/保留地址)
- const verdict = await checkUpstreamAllowed(source.url);
- if (!verdict.ok) {
- return { sourceKey: source.key, ok: false, list: [], error: verdict.reason };
- }
- const base = source.url.replace(/\/+$/, '');
- const fetchPage = async (page: number) => {
- const api = `${base}?ac=videolist&wd=${encodeURIComponent(wd)}&pg=${page}`;
- const res = await fetchUpstream(api, {
- timeoutMs: 8000,
- headers: cmsRequestHeaders(),
- });
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- return res.json();
- };
- try {
- const first = await fetchPage(1);
- const list = parseSearchList(first, source);
- // 源站真实总页数与配置上限取较小者;pagecount 缺失或非法时视为 1 页
- const rawPageCount = parseInt(String((first as { pagecount?: unknown }).pagecount ?? '1'), 10);
- const pageCount = Math.min(Number.isFinite(rawPageCount) ? Math.max(1, rawPageCount) : 1, SEARCH_MAX_PAGES);
- if (pageCount > 1) {
- const extraPages = await Promise.all(
- Array.from({ length: pageCount - 1 }, (_, i) => i + 2).map(async (page) => {
- try {
- return parseSearchList(await fetchPage(page), source);
- } catch {
- return [];
- }
- })
- );
- list.push(...extraPages.flat());
- }
- return { sourceKey: source.key, ok: true, list };
- } catch (err) {
- return {
+ const base = source.url.replace(/\/+$/, '');
+ const fetchPage = async (page: number) => {
+ const api = `${base}?ac=videolist&wd=${encodeURIComponent(wd)}&pg=${page}`;
+ const res = await fetchUpstream(api, {
+ timeoutMs: 8000,
+ headers: cmsRequestHeaders(),
+ signal: controller.signal,
+ });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ return res.json();
+ };
+
+ const run = async (): Promise<SourceSearchOutcome> => {
+ const first = await fetchPage(1);
+ const list = parseSearchList(first, source);
+ // 源站真实总页数与配置上限取较小者;pagecount 缺失或非法时视为 1 页
+ const rawPageCount = parseInt(String((first as { pagecount?: unknown }).pagecount ?? '1'), 10);
+ const pageCount = Math.min(Number.isFinite(rawPageCount) ? Math.max(1, rawPageCount) : 1, SEARCH_MAX_PAGES);
+ if (pageCount > 1) {
+ const extraPages = await Promise.all(
+ Array.from({ length: pageCount - 1 }, (_, i) => i + 2).map(async (page) => {
+ try {
+ return parseSearchList(await fetchPage(page), source);
+ } catch {
+ return [];
+ }
+ })
+ );
+ list.push(...extraPages.flat());
+ }
+ return { sourceKey: source.key, ok: true, list };
+ };
+
+ try {
+ // 死线先到时 run 仍会在后台被 abort 并 reject,必须先挂 catch 防未处理 rejection
+ const runPromise = run()
+ .then(finish)
+ .catch((err: unknown): SourceSearchOutcome =>
+ finish({
sourceKey: source.key,
ok: false,
list: [],
error: err instanceof Error ? err.message : '请求失败',
- };
- }
- })
- );
+ timedOut: isTimeoutError(err),
+ })
+ );
+ return await Promise.race([runPromise, deadline]);
+ } catch (err) {
+ return finish({
+ sourceKey: source.key,
+ ok: false,
+ list: [],
+ error: err instanceof Error ? err.message : '请求失败',
+ timedOut: isTimeoutError(err),
+ });
+ } finally {
+ if (deadlineTimer) clearTimeout(deadlineTimer);
+ }
+}
- // 合并 + 跨源去重(同源同 vodId 视为重复)
+/** 合并 + 去重 + 过滤 + 排序,stream 与非 stream 两种模式共用 */
+function aggregateOutcomes(outcomes: SourceSearchOutcome[], wd: string, filterAdult: boolean): SearchResponse {
const seen = new Set<string>();
let list = outcomes.flatMap((o) => o.list).filter((item) => {
const key = `${item.sourceKey}_${item.vodId}`;
@@ -126,7 +163,7 @@ export async function POST(req: Request) {
return true;
});
- list = filterAdultResults(list, body.filterAdult !== false);
+ list = filterAdultResults(list, filterAdult);
// 部分源站做分词/OR 模糊搜索(搜「摔跤吧!爸爸」返回一堆「爸爸XXX」),按关键词过滤
list = filterRelevantResults(list, wd);
@@ -143,9 +180,97 @@ export async function POST(req: Request) {
const failures = outcomes
.filter((o) => !o.ok)
- .map((o) => ({ sourceKey: o.sourceKey, error: o.error || '请求失败' }));
+ .map((o) => ({ sourceKey: o.sourceKey, error: o.error || '请求失败', timedOut: o.timedOut }));
- const payload: SearchResponse = { list, failures };
- setCache(cacheKey, payload, SEARCH_CACHE_TTL);
- return NextResponse.json(payload);
+ return { list, failures };
+}
+
+/**
+ * 服务端聚合搜索:
+ * - 默认返回完整 JSON(换源流程使用);
+ * - `?stream=1` 以 NDJSON 逐源推送(完成一个推一条,健康源的结果不再等坏源超时),
+ * 最终推送聚合后的 done 事件并写入短缓存。
+ */
+export async function POST(req: Request) {
+ const guarded = guardRequest(req);
+ if (guarded) return guarded;
+
+ let body: SearchBody;
+ try {
+ body = (await req.json()) as SearchBody;
+ } catch {
+ return NextResponse.json({ error: '请求格式错误' }, { status: 400 });
+ }
+
+ const wd = (body.wd || '').trim();
+ if (!wd || wd.length > 100) {
+ return NextResponse.json({ error: '搜索关键词无效' }, { status: 400 });
+ }
+ if (!Array.isArray(body.sources) || body.sources.length === 0) {
+ return NextResponse.json({ error: '请至少选择一个点播源' }, { status: 400 });
+ }
+ const sources = body.sources.slice(0, 50);
+ const filterAdult = body.filterAdult !== false;
+
+ const cacheKey = searchCacheKey(wd, sources, filterAdult);
+ const cached = getCache<SearchResponse>(cacheKey);
+ if (cached) {
+ // 流式模式下缓存命中也要走 done 事件,客户端解析逻辑保持单一
+ if (new URL(req.url).searchParams.get('stream') === '1') {
+ const event: SearchStreamEvent = { type: 'done', list: cached.list, failures: cached.failures };
+ return new Response(JSON.stringify(event) + '\n', {
+ headers: { 'Content-Type': 'application/x-ndjson; charset=utf-8', 'Cache-Control': 'no-store' },
+ });
+ }
+ return NextResponse.json(cached);
+ }
+
+ const isStream = new URL(req.url).searchParams.get('stream') === '1';
+ if (!isStream) {
+ const outcomes = await Promise.all(sources.map((source) => searchSource(source, wd)));
+ const payload = aggregateOutcomes(outcomes, wd, filterAdult);
+ setCache(cacheKey, payload, SEARCH_CACHE_TTL);
+ return NextResponse.json(payload);
+ }
+
+ const encoder = new TextEncoder();
+ const stream = new ReadableStream<Uint8Array>({
+ async start(controller) {
+ let closed = false;
+ const send = (event: SearchStreamEvent) => {
+ if (closed) return;
+ try {
+ controller.enqueue(encoder.encode(JSON.stringify(event) + '\n'));
+ } catch {
+ closed = true; // 客户端已断开
+ }
+ };
+
+ // 逐源结算即推送;outcomes 按下标回填保证聚合顺序稳定
+ const outcomes: SourceSearchOutcome[] = new Array(sources.length);
+ await Promise.all(
+ sources.map(async (source, i) => {
+ const outcome = await searchSource(source, wd);
+ outcomes[i] = outcome;
+ send({ type: 'source', ...outcome });
+ })
+ );
+
+ const payload = aggregateOutcomes(outcomes, wd, filterAdult);
+ setCache(cacheKey, payload, SEARCH_CACHE_TTL);
+ send({ type: 'done', list: payload.list, failures: payload.failures });
+ closed = true;
+ try {
+ controller.close();
+ } catch { /* 已断开 */ }
+ },
+ });
+
+ return new Response(stream, {
+ headers: {
+ 'Content-Type': 'application/x-ndjson; charset=utf-8',
+ 'Cache-Control': 'no-store',
+ 'X-Accel-Buffering': 'no',
+ },
+ });
}
diff --git a/src/app/page.tsx b/src/app/page.tsx
index 9adaa6f..07728a7 100644
--- a/src/app/page.tsx
+++ b/src/app/page.tsx
@@ -7,9 +7,9 @@ import { Header } from '@/components/header';
import { RecommendSection } from '@/components/douban-section';
import { DetailModal } from '@/components/detail-modal';
import { AggregatedCard, aggregateResults } from '@/components/video-card';
-import { useAppStore, resolveSource } from '@/lib/store';
+import { useAppStore, resolveSource, isSourceDisabled, SOURCE_DISABLE_TTL_MS } from '@/lib/store';
import { api } from '@/lib/client-api';
-import type { SearchResultItem } from '@/lib/types';
+import type { SearchResultItem, SourceSearchOutcome } from '@/lib/types';
import { addSearchHistory, db, removeSearchHistory } from '@/lib/db';
import { cn, validateSourceUrl } from '@/lib/utils';
import { useToast } from '@/components/toast';
@@ -36,6 +36,8 @@ function HomeContent() {
const store = useAppStore();
const [input, setInput] = useState(urlQuery);
const [detailItem, setDetailItem] = useState<SearchResultItem | null>(null);
+ /** 流式搜索中已结算的源(data 就绪前用于增量渲染) */
+ const [streamedOutcomes, setStreamedOutcomes] = useState<SourceSearchOutcome[]>([]);
const inputRef = useRef<HTMLInputElement>(null);
// URL 驱动搜索:?s= 变化时回填输入框
@@ -43,18 +45,46 @@ function HomeContent() {
if (urlQuery) setInput(urlQuery);
}, [urlQuery]);
- const selectedSources = useMemo(
- () =>
- store.selectedKeys
- .map((key) => resolveSource(store, key))
- .filter((s): s is NonNullable<typeof s> => Boolean(s) && validateSourceUrl(s!.url)),
+ // 源名回显:失败/停用提示里显示友好名称而非裸 key
+ const sourceName = (key: string) =>
+ store.customAPIs.find((a) => a.key === key)?.name ??
+ store.envSources.find((a) => a.key === key)?.name ??
+ key;
+
+ const selectedSources = useMemo(() => {
+ // selectedKeys 可能含历史残留的重复 key:按 key 去重,避免同源重复搜索
+ const seen = new Set<string>();
+ return store.selectedKeys
+ .map((key) => resolveSource(store, key))
+ .filter((s): s is NonNullable<typeof s> => {
+ if (!s || !validateSourceUrl(s.url) || seen.has(s.key)) return false;
+ seen.add(s.key);
+ return true;
+ })
+ // 自动停用期内的源不参与搜索(到期自动恢复)
+ .filter((s) => !isSourceDisabled(store, s.key));
+ }, [store]);
+ const disabledSources = useMemo(
+ () => store.selectedKeys.filter((key) => isSourceDisabled(store, key)),
[store]
);
const searchQuery = useQuery({
queryKey: ['search', urlQuery, store.selectedKeys, store.yellowFilter],
// 与 runSearch 的截断规则保持一致:顶栏搜索 / 手动构造长链接不会绕过上限
- queryFn: ({ signal }) => api.search(urlQuery.slice(0, 100), selectedSources, store.yellowFilter, signal),
+ queryFn: ({ signal }) => {
+ setStreamedOutcomes([]);
+ return api.search(urlQuery.slice(0, 100), selectedSources, store.yellowFilter, {
+ signal,
+ // 逐源结算即更新:结果边搜边渲染,同时滚动健康度
+ onSource: (outcome) => {
+ setStreamedOutcomes((prev) => [...prev, outcome]);
+ for (const key of store.recordSourceHealth([outcome])) {
+ toast(`「${sourceName(key)}」连续超时/失败,已临时停用 30 分钟`, 'warning');
+ }
+ },
+ });
+ },
enabled: Boolean(urlQuery) && selectedSources.length > 0,
// 5 分钟内从播放页返回时直接使用缓存,不重新搜索(服务端另有 60s 结果缓存兜底)
staleTime: 300_000,
@@ -80,17 +110,23 @@ function HomeContent() {
addSearchHistory(query).catch(() => {});
};
- const list = useMemo(() => searchQuery.data?.list ?? [], [searchQuery.data]);
- const failures = searchQuery.data?.failures ?? [];
+ const isSearching = Boolean(urlQuery) && searchQuery.isFetching && !searchQuery.data;
+ // 聚合数据未就绪时,用已结算源的结果增量渲染(健康源不再等坏源超时)
+ const streamedList = useMemo(
+ () => streamedOutcomes.flatMap((o) => o.list),
+ [streamedOutcomes]
+ );
+ const list = useMemo(
+ () => searchQuery.data?.list ?? (isSearching ? streamedList : []),
+ [searchQuery.data, isSearching, streamedList]
+ );
+ const failures =
+ searchQuery.data?.failures ??
+ streamedOutcomes
+ .filter((o) => !o.ok)
+ .map((o) => ({ sourceKey: o.sourceKey, error: o.error || '请求失败', timedOut: o.timedOut }));
// 跨源同名聚合:同名影片合并为一张卡片,展开后可选择具体来源
const groups = useMemo(() => aggregateResults(list), [list]);
- // 失败源显示友好名称而非裸 key
- const failureNames = failures.map(
- (f) =>
- store.customAPIs.find((a) => a.key === f.sourceKey)?.name ??
- store.envSources.find((a) => a.key === f.sourceKey)?.name ??
- f.sourceKey
- );
return (
<div className="min-h-screen flex flex-col">
@@ -189,34 +225,43 @@ function HomeContent() {
<div className="flex items-center justify-between mb-3">
<h2 className="text-sm text-muted">
“<span className="text-content">{urlQuery}</span>” 的搜索结果
- {searchQuery.data && (
+ {isSearching ? (
<span className="text-faint">
- ({groups.length} 部影片 · {list.length} 条结果{failures.length > 0 && `,${failures.length} 个源失败`})
+ (已就绪 {streamedOutcomes.length}/{selectedSources.length} 个源…)
</span>
+ ) : (
+ searchQuery.data && (
+ <span className="text-faint">
+ ({groups.length} 部影片 · {list.length} 条结果{failures.length > 0 && `,${failures.length} 个源失败`})
+ </span>
+ )
)}
</h2>
</div>
{failures.length > 0 && (
+ <div className="mb-3 text-xs bg-chip rounded-lg px-3 py-2 flex flex-wrap gap-x-3 gap-y-1">
+ <span className="text-faint">{isSearching ? '以下源暂时无响应:' : '部分点播源请求失败:'}</span>
+ {failures.map((f) => (
+ <span key={f.sourceKey} className={f.timedOut ? 'text-amber-400' : 'text-faint'}>
+ {f.timedOut ? '⏱' : '✗'} {sourceName(f.sourceKey)}
+ {f.timedOut ? ' 超时' : ''}
+ </span>
+ ))}
+ </div>
+ )}
+
+ {disabledSources.length > 0 && (
<div className="mb-3 text-xs text-faint bg-chip rounded-lg px-3 py-2">
- 部分点播源请求失败:{failureNames.join('、')}
+ {disabledSources.length} 个源因连续超时/失败已临时停用(
+ {Math.round(SOURCE_DISABLE_TTL_MS / 60000)} 分钟后自动恢复):
+ {disabledSources.map((key) => sourceName(key)).join('、')}
</div>
)}
- {searchQuery.isLoading ? (
- <ResultsSkeleton />
- ) : selectedSources.length === 0 ? (
+ {selectedSources.length === 0 ? (
<NoSourceGuide hasSources={store.customAPIs.length > 0 || store.envSources.length > 0} />
- ) : list.length === 0 ? (
- <div className="text-center py-16">
- <svg className="mx-auto h-10 w-10 text-faint mb-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
- d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
- </svg>
- <h3 className="text-base text-muted">没有找到匹配的结果</h3>
- <p className="text-sm text-faint mt-1">请尝试其他关键词或更换点播源</p>
- </div>
- ) : (
+ ) : list.length > 0 ? (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 items-start">
{groups.map((group) => (
<AggregatedCard
@@ -226,6 +271,17 @@ function HomeContent() {
/>
))}
</div>
+ ) : isSearching ? (
+ <ResultsSkeleton />
+ ) : (
+ <div className="text-center py-16">
+ <svg className="mx-auto h-10 w-10 text-faint mb-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
+ d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
+ </svg>
+ <h3 className="text-base text-muted">没有找到匹配的结果</h3>
+ <p className="text-sm text-faint mt-1">请尝试其他关键词或更换点播源</p>
+ </div>
)}
</section>
)}
diff --git a/src/components/source-manager.tsx b/src/components/source-manager.tsx
index cbf6e70..193dc30 100644
--- a/src/components/source-manager.tsx
+++ b/src/components/source-manager.tsx
@@ -2,7 +2,7 @@
import { useEffect, useState } from 'react';
import { Drawer } from './header';
-import { subKeyPrefix, useAppStore } from '@/lib/store';
+import { isSourceDisabled, subKeyPrefix, useAppStore } from '@/lib/store';
import { useToast } from './toast';
import { formatRelativeTime, validateSourceUrl, cn } from '@/lib/utils';
import { exportConfig, importConfig } from '@/lib/db';
@@ -55,6 +55,57 @@ export function SourceManagerDrawer({ open, onClose }: { open: boolean; onClose:
}
};
+ /** 搜索健康度徽章:展示最近一次搜索该源的结果;被自动停用的源提供手动恢复入口 */
+ const healthBadge = (key: string) => {
+ const e = store.sourceHealth[key];
+ if (!e) return null;
+ if (isSourceDisabled(store, key)) {
+ const remainMin = Math.max(1, Math.ceil(((e.disabledUntil ?? 0) - Date.now()) / 60000));
+ return (
+ <span className="flex items-center gap-1 shrink-0">
+ <span
+ className="text-[10px] px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-500"
+ title={`连续 ${e.failStreak} 次超时/失败,${remainMin} 分钟后自动恢复`}
+ >
+ ⏱ 已停用 {remainMin} 分
+ </span>
+ <button
+ className="text-[10px] px-1 text-muted hover:text-accent"
+ aria-label="恢复此源"
+ title="清除健康度记录,立即恢复参与搜索"
+ onClick={() => {
+ store.clearSourceHealth(key);
+ toast('已恢复,下次搜索重新参与', 'success');
+ }}
+ >
+ 恢复
+ </button>
+ </span>
+ );
+ }
+ if (e.ok) {
+ return (
+ <span
+ className="text-[10px] px-1.5 py-0.5 rounded bg-green-500/15 text-green-600 dark:text-green-400 shrink-0"
+ title={`上次搜索 ${e.ms}ms`}
+ >
+ ✓ {e.ms}ms
+ </span>
+ );
+ }
+ return (
+ <span
+ className={cn(
+ 'text-[10px] px-1.5 py-0.5 rounded shrink-0',
+ e.timedOut ? 'bg-amber-500/15 text-amber-500' : 'bg-red-500/15 text-red-500'
+ )}
+ title={e.error}
+ >
+ {e.timedOut ? '⏱' : '✗'} 连续 {e.failStreak} 次失败
+ </span>
+ );
+ };
+
const testButton = (key: string, url: string) => {
const t = tests[key];
return (
@@ -158,6 +209,7 @@ export function SourceManagerDrawer({ open, onClose }: { open: boolean; onClose:
</div>
<div className="text-xs text-faint truncate">{api.url}</div>
</div>
+ {healthBadge(api.key)}
{testButton(api.key, api.url)}
</div>
</li>
@@ -208,6 +260,7 @@ export function SourceManagerDrawer({ open, onClose }: { open: boolean; onClose:
</div>
<div className="text-xs text-faint truncate">{api.url}</div>
</div>
+ {healthBadge(api.key)}
{testButton(api.key, api.url)}
{fromSubscription ? (
// 订阅源由远端列表管理:编辑会被下次同步覆盖,删除会复活,引导到订阅区操作
@@ -270,12 +323,6 @@ export function SourceManagerDrawer({ open, onClose }: { open: boolean; onClose:
<section className="mb-6 pt-5">
<SectionTitle title="播放与过滤" />
<div className="space-y-3">
- <ToggleRow
- label="成人内容过滤"
- description="过滤“伦理片”等分类的结果"
- checked={store.yellowFilter}
- onChange={(v) => store.updateSettings({ yellowFilter: v })}
- />
<ToggleRow
label="广告过滤"
description="过滤 m3u8 中的广告分片"
@@ -288,22 +335,6 @@ export function SourceManagerDrawer({ open, onClose }: { open: boolean; onClose:
checked={store.autoplayNext}
onChange={(v) => store.updateSettings({ autoplayNext: v })}
/>
- <ToggleRow
- label="首页推荐"
- description="在首页展示推荐内容"
- checked={store.doubanEnabled}
- onChange={(v) => store.updateSettings({ doubanEnabled: v })}
- />
- <SelectRow
- label="推荐数据源"
- value={store.recommendSource}
- onChange={(v) => store.updateSettings({ recommendSource: v as 'douban' | 'bangumi' | 'hot-list' })}
- options={[
- { value: 'douban', label: '豆瓣(电影/剧集)' },
- { value: 'bangumi', label: 'Bangumi 新番放送' },
- { value: 'hot-list', label: '影视榜单(豆瓣周榜/百度热播)' },
- ]}
- />
</div>
</section>
@@ -337,6 +368,33 @@ export function SourceManagerDrawer({ open, onClose }: { open: boolean; onClose:
{settingsTab === 'config' && (
<>
<SourceSubscriptions />
+ <section className="mb-6 pt-5 border-t border-line">
+ <SectionTitle title="首页与内容过滤" />
+ <div className="space-y-3">
+ <ToggleRow
+ label="成人内容过滤"
+ description="过滤“伦理片”等分类的结果"
+ checked={store.yellowFilter}
+ onChange={(v) => store.updateSettings({ yellowFilter: v })}
+ />
+ <ToggleRow
+ label="首页推荐"
+ description="在首页展示推荐内容"
+ checked={store.doubanEnabled}
+ onChange={(v) => store.updateSettings({ doubanEnabled: v })}
+ />
+ <SelectRow
+ label="推荐数据源"
+ value={store.recommendSource}
+ onChange={(v) => store.updateSettings({ recommendSource: v as 'douban' | 'bangumi' | 'hot-list' })}
+ options={[
+ { value: 'douban', label: '豆瓣(电影/剧集)' },
+ { value: 'bangumi', label: 'Bangumi 新番放送' },
+ { value: 'hot-list', label: '影视榜单(豆瓣周榜/百度热播)' },
+ ]}
+ />
+ </div>
+ </section>
<section className="mb-6 pt-5 border-t border-line">
<SectionTitle title="配置" />
<ConfigIoButtons />
diff --git a/src/lib/client-api.ts b/src/lib/client-api.ts
index cd35a0a..aaa59de 100644
--- a/src/lib/client-api.ts
+++ b/src/lib/client-api.ts
@@ -1,6 +1,6 @@
'use client';
-import type { SearchResponse, VideoDetail, DoubanResponse, BangumiCalendarResponse, AuthStatusResponse, SourceConfig, SearchResultItem, LivePlaylistResponse, LiveEpgResponse, SourceListPayload } from './types';
+import type { SearchResponse, SearchStreamEvent, SourceSearchOutcome, VideoDetail, DoubanResponse, BangumiCalendarResponse, AuthStatusResponse, SourceConfig, SearchResultItem, LivePlaylistResponse, LiveEpgResponse, SourceListPayload } from './types';
/**
* 客户端 API 封装。401 时触发全局事件打开登录框,
@@ -80,13 +80,29 @@ export const api = {
logout: () => request<{ success: boolean }>('/api/auth', { method: 'DELETE' }),
- search: (wd: string, sources: SourceConfig[], filterAdult: boolean, signal?: AbortSignal) =>
- request<SearchResponse>('/api/search', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ wd, sources, filterAdult }),
- signal,
- }),
+ /**
+ * 聚合搜索。传入 onSource 时走 /api/search?stream=1 的 NDJSON 流:
+ * 每个源结算立即回调(健康源结果不再等坏源超时),最终以聚合结果 resolve。
+ * 未传 onSource 或流不可用时回退为一次性 JSON 请求。
+ */
+ search: async (
+ wd: string,
+ sources: SourceConfig[],
+ filterAdult: boolean,
+ opts?: { signal?: AbortSignal; onSource?: (outcome: SourceSearchOutcome) => void }
+ ): Promise<SearchResponse> => {
+ const signal = opts?.signal;
+ const onSource = opts?.onSource;
+ if (!onSource) {
+ return request<SearchResponse>('/api/search', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ wd, sources, filterAdult }),
+ signal,
+ });
+ }
+ return searchStream(wd, sources, filterAdult, onSource, signal);
+ },
detail: (id: string, source: SourceConfig, signal?: AbortSignal) => {
const sp = new URLSearchParams({ id, source: JSON.stringify(source) });
@@ -232,6 +248,67 @@ export const api = {
export interface SearchFailure {
sourceKey: string;
error: string;
+ timedOut?: boolean;
+}
+
+/** 聚合搜索流式消费:逐源回调 + 最终聚合结果(NDJSON 行协议,同 liveProbeStream) */
+async function searchStream(
+ wd: string,
+ sources: SourceConfig[],
+ filterAdult: boolean,
+ onSource: (outcome: SourceSearchOutcome) => void,
+ signal?: AbortSignal
+): Promise<SearchResponse> {
+ const res = await fetch('/api/search?stream=1', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ wd, sources, filterAdult }),
+ signal,
+ });
+ if (res.status === 401) {
+ window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT));
+ throw new ApiError('需要登录', 401);
+ }
+ if (res.status === 503) {
+ window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT, { detail: 'setup' }));
+ throw new ApiError('服务器未配置密码', 503);
+ }
+ if (!res.ok || !res.body) throw new ApiError(`请求失败 (${res.status})`, res.status);
+
+ const reader = res.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = '';
+ let final: SearchResponse | undefined;
+ const consume = (line: string) => {
+ const text = line.trim();
+ if (!text) return;
+ let event: SearchStreamEvent;
+ try {
+ event = JSON.parse(text) as SearchStreamEvent;
+ } catch {
+ return; // 坏行跳过,不影响其余结果
+ }
+ if (event.type === 'source') {
+ onSource(event);
+ } else if (event.type === 'done') {
+ final = { list: event.list, failures: event.failures };
+ }
+ };
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+ let idx: number;
+ while ((idx = buffer.indexOf('\n')) >= 0) {
+ consume(buffer.slice(0, idx));
+ buffer = buffer.slice(idx + 1);
+ }
+ }
+ buffer += decoder.decode();
+ consume(buffer);
+
+ // done 事件缺失(流被截断)时退化为空结果,不让整次搜索报错
+ return final ?? { list: [], failures: [] };
}
export type { SearchResponse, SearchResultItem };
diff --git a/src/lib/fetch-utils.ts b/src/lib/fetch-utils.ts
index 49dd7ee..015f07d 100644
--- a/src/lib/fetch-utils.ts
+++ b/src/lib/fetch-utils.ts
@@ -34,13 +34,18 @@ export async function fetchUpstream(url: string, options: FetchOptions = {}): Pr
/** 同 fetchUpstream,额外返回重定向后的最终 URL */
export async function fetchUpstreamWithMeta(url: string, options: FetchOptions = {}): Promise<FetchResult> {
const { timeoutMs = 8000, retries = 0, safeRedirects = true, allowPrivate = false, ...init } = options;
+ // 外部 signal(调用方的总死线中断)与单次超时合并:任一触发即中断请求
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
+ const signal = init.signal
+ ? AbortSignal.any([init.signal, timeoutSignal])
+ : timeoutSignal;
let lastError: unknown;
for (let attempt = 0; attempt <= retries; attempt++) {
try {
if (!safeRedirects) {
const res = await fetch(url, {
...init,
- signal: AbortSignal.timeout(timeoutMs),
+ signal,
redirect: init.redirect ?? 'follow',
});
return { res, finalUrl: res.url || url };
@@ -57,7 +62,7 @@ export async function fetchUpstreamWithMeta(url: string, options: FetchOptions =
const res = await fetch(current, {
...init,
redirect: 'manual',
- signal: AbortSignal.timeout(timeoutMs),
+ signal,
});
if (!REDIRECT_STATUSES.has(res.status)) return { res, finalUrl: current };
const location = res.headers.get('location');
diff --git a/src/lib/store.ts b/src/lib/store.ts
index d015475..d2b4045 100644
--- a/src/lib/store.ts
+++ b/src/lib/store.ts
@@ -2,7 +2,7 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
-import type { SourceConfig, LiveSourceConfig } from './types';
+import type { SourceConfig, LiveSourceConfig, SourceSearchOutcome } from './types';
/**
* 全局设置(zustand + localStorage 持久化)。
@@ -89,6 +89,24 @@ export function subKeyPrefix(url: string): string {
return `sub_${h.toString(36)}`;
}
+/** 点播源自动停用阈值:连续失败/超时达到该次数即临时摘除 */
+export const SOURCE_DISABLE_THRESHOLD = 2;
+/** 点播源自动停用时长:到期后自动恢复参与搜索 */
+export const SOURCE_DISABLE_TTL_MS = 30 * 60 * 1000;
+
+/** 点播源健康度条目(按 sourceKey),随搜索结果滚动更新 */
+export interface SourceHealthEntry {
+ ok: boolean;
+ ms?: number;
+ error?: string;
+ timedOut?: boolean;
+ /** 连续失败/超时次数;成功时归零 */
+ failStreak: number;
+ /** 命中阈值后的临时停用截止时间(epoch ms);恢复成功后清除 */
+ disabledUntil?: number;
+ timestamp: number;
+}
+
interface AppState extends AppSettings {
/** 部署者通过 DEFAULT_SOURCES 环境变量预置的源(服务端下发,不持久化) */
envSources: SourceConfig[];
@@ -110,6 +128,8 @@ interface AppState extends AppSettings {
liveRecent: LiveRecentEntry[];
/** 测活结果缓存(6 小时有效,跨会话持久化) */
liveProbeResults: Record<string, LiveProbeEntry>;
+ /** 点播源健康度(随搜索滚动更新,跨会话持久化) */
+ sourceHealth: Record<string, SourceHealthEntry>;
/** 已出现过的 env 预置订阅 URL(持久化:用户删除后不再被自动加回) */
envSubsSeen: string[];
addCustomApi: (api: Omit<SourceConfig, 'key'> & { key?: string }) => void;
@@ -139,6 +159,15 @@ interface AppState extends AppSettings {
/** 合并写入测活结果,并顺带清理过期条目 */
setLiveProbeResults: (entries: Record<string, LiveProbeEntry>) => void;
clearLiveProbeResults: () => void;
+ /**
+ * 记录一次搜索的逐源健康度;连续失败/超时达到阈值即标记临时停用。
+ * 不直接改 selectedKeys(用户勾选意图保留,且避免变更引用触发搜索重发),
+ * 参与搜索与否由调用方经 isSourceDisabled 过滤;到期自动恢复。
+ * 返回本次新被自动停用的源 key 列表(供调用方 toast 提示)。
+ */
+ recordSourceHealth: (outcomes: SourceSearchOutcome[]) => string[];
+ /** 清除单个源的健康度记录(手动恢复入口) */
+ clearSourceHealth: (key: string) => void;
markEnvSubsSeen: (urls: string[]) => void;
updateSettings: (patch: Partial<Omit<AppSettings, 'customAPIs' | 'selectedKeys'>>) => void;
}
@@ -169,6 +198,7 @@ export const useAppStore = create<AppState>()(
liveFavorites: [],
liveRecent: [],
liveProbeResults: {},
+ sourceHealth: {},
envSubsSeen: [],
selectedKeys: [],
yellowFilter: true,
@@ -409,6 +439,46 @@ export const useAppStore = create<AppState>()(
clearLiveProbeResults: () => set({ liveProbeResults: {} }),
+ recordSourceHealth: (outcomes) => {
+ if (outcomes.length === 0) return [];
+ const now = Date.now();
+ const health: Record<string, SourceHealthEntry> = {};
+ // 顺带清理陈旧条目(停用 TTL 早已过期的死记录)
+ for (const [key, e] of Object.entries(get().sourceHealth)) {
+ if (now - e.timestamp < 7 * 24 * 60 * 60 * 1000) health[key] = e;
+ }
+ const newlyDisabled: string[] = [];
+ for (const o of outcomes) {
+ const prev = health[o.sourceKey];
+ const failStreak = o.ok ? 0 : (prev?.failStreak ?? 0) + 1;
+ // entry 直接覆盖旧记录:成功时 disabledUntil 随之消失(立即恢复),
+ // 未达阈值时保留旧停用标记不动
+ const entry: SourceHealthEntry = {
+ ok: o.ok,
+ ms: o.ms,
+ error: o.error,
+ timedOut: o.timedOut,
+ failStreak,
+ timestamp: now,
+ };
+ if (!o.ok && failStreak >= SOURCE_DISABLE_THRESHOLD) {
+ entry.disabledUntil = now + SOURCE_DISABLE_TTL_MS;
+ if (!prev?.disabledUntil || prev.disabledUntil < now) {
+ newlyDisabled.push(o.sourceKey);
+ }
+ }
+ health[o.sourceKey] = entry;
+ }
+ set({ sourceHealth: health });
+ return newlyDisabled;
+ },
+
+ clearSourceHealth: (key) => {
+ const next = { ...get().sourceHealth };
+ delete next[key];
+ set({ sourceHealth: next });
+ },
+
markEnvSubsSeen: (urls) => {
const seen = new Set(get().envSubsSeen);
for (const u of urls) seen.add(u);
@@ -460,6 +530,7 @@ export const useAppStore = create<AppState>()(
liveFavorites: s.liveFavorites,
liveRecent: s.liveRecent,
liveProbeResults: s.liveProbeResults,
+ sourceHealth: s.sourceHealth,
envSubsSeen: s.envSubsSeen,
yellowFilter: s.yellowFilter,
adFilter: s.adFilter,
@@ -495,3 +566,16 @@ export function resolveSource(
}
return undefined;
}
+
+/**
+ * 源当前是否处于自动停用期(连续超时/失败触发)。
+ * 停用到期后此判断自然翻转为 false,即「到期自动恢复参与搜索」的懒实现。
+ */
+export function isSourceDisabled(
+ state: Pick<AppState, 'sourceHealth'>,
+ key: string,
+ now = Date.now()
+): boolean {
+ const e = state.sourceHealth[key];
+ return !!e?.disabledUntil && e.disabledUntil > now;
+}
diff --git a/src/lib/types.ts b/src/lib/types.ts
index fd5adc5..b4fec6a 100644
--- a/src/lib/types.ts
+++ b/src/lib/types.ts
@@ -58,15 +58,24 @@ export interface SourceSearchOutcome {
ok: boolean;
list: SearchResultItem[];
error?: string;
+ /** 因超时失败:源可能只是慢,前端以琥珀色区分于真正的失败 */
+ timedOut?: boolean;
+ /** 该源搜索总耗时(ms),用于健康徽章 */
+ ms?: number;
}
// —— API 响应结构 ——
export interface SearchResponse {
list: SearchResultItem[];
- failures: { sourceKey: string; error: string }[];
+ failures: { sourceKey: string; error: string; timedOut?: boolean }[];
}
+/** /api/search?stream=1 的 NDJSON 事件:逐源推送 + 最终聚合 */
+export type SearchStreamEvent =
+ | ({ type: 'source' } & SourceSearchOutcome)
+ | { type: 'done'; list: SearchResultItem[]; failures: SearchResponse['failures'] };
+
export interface DoubanResponse {
items: DoubanItem[];
}