Skip to content

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

fix(download): 无 Cache Storage 环境给出可读提示;Failed to fetch 翻译为可操作建议

bestZwei7e4626237307
diff --git a/src/components/download-manager.tsx b/src/components/download-manager.tsx
index 9803568..9f39286 100644
--- a/src/components/download-manager.tsx
+++ b/src/components/download-manager.tsx
@@ -9,6 +9,7 @@ import {
PauseResumeController,
clearDownloadChunks,
runDownloadJob,
+ supportsChunkCache,
type DownloadProgress,
} from '@/lib/m3u8-downloader';
import { detectSavingCapability, pickSaveTarget } from '@/lib/download-saver';
@@ -46,6 +47,7 @@ export function DownloadManager({ isOpen, onClose }: { isOpen: boolean; onClose:
const { toast } = useToast();
const [tasks, setTasks] = useState<DownloadTaskEntry[]>([]);
const [capability, setCapability] = useState<'fs-access' | 'memory'>('memory');
+ const [chunkCache, setChunkCache] = useState(true);
const running = useRef(new Map<string, RunningHandle>());
const refresh = useCallback(() => {
@@ -148,6 +150,12 @@ export function DownloadManager({ isOpen, onClose }: { isOpen: boolean; onClose:
const onAdd = (e: Event) => {
const detail = (e as CustomEvent<AddDownloadPayload>).detail;
if (!detail?.url || !detail?.title) return;
+ // 无 Cache Storage(HTTP 访问 / 老浏览器)时下载必然失败——分片无处暂存。
+ // 在入队这一步就讲清楚,别让用户等到任务跑到一半才看到报错
+ if (!supportsChunkCache()) {
+ toast('当前环境不支持下载缓存(需通过 HTTPS 访问),无法下载', 'error');
+ return;
+ }
void (async () => {
const format = detail.format ?? 'MP4';
const id = `dl_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
@@ -193,6 +201,7 @@ export function DownloadManager({ isOpen, onClose }: { isOpen: boolean; onClose:
useEffect(() => {
if (!isOpen) return;
setCapability(detectSavingCapability());
+ setChunkCache(supportsChunkCache());
refresh();
scheduleNext();
}, [isOpen, refresh, scheduleNext]);
@@ -250,7 +259,8 @@ export function DownloadManager({ isOpen, onClose }: { isOpen: boolean; onClose:
<Drawer open={isOpen} onClose={onClose} title="下载管理" width="max-w-lg">
<div className="space-y-3">
<p className="text-xs text-faint">
- 保存能力:{capability === 'fs-access' ? '磁盘直写(边下边存)' : '内存聚合(完成后浏览器下载)'} ·
+ 保存能力:{capability === 'fs-access' ? '磁盘直写(边下边存)' : '内存聚合(完成后浏览器下载)'}
+ {chunkCache ? ' · 支持断点续传' : ' · 当前环境无断点缓存(需 HTTPS 访问)'} ·
同时进行 {Math.min(running.current.size, MAX_CONCURRENT_DOWNLOADS)}/{MAX_CONCURRENT_DOWNLOADS} 个任务
</p>
{tasks.length === 0 && (
diff --git a/src/lib/m3u8-downloader.test.ts b/src/lib/m3u8-downloader.test.ts
index 75139de..55e85bf 100644
--- a/src/lib/m3u8-downloader.test.ts
+++ b/src/lib/m3u8-downloader.test.ts
@@ -201,4 +201,48 @@ describe('runDownloadJob · 源站缺片与存储错误', () => {
await expect(runDownloadJob(jobOptions())).rejects.toThrow(/存储空间可能不足/);
});
+
+ it('环境无 Cache Storage(HTTP 访问 / 老浏览器)时给出可读提示', async () => {
+ // 不提供 caches:等价于非安全上下文。旧实现会抛裸的 ReferenceError: caches is not defined
+ vi.stubGlobal('caches', undefined);
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input);
+ if (url.endsWith('index.m3u8')) return new Response(PLAYLIST, { status: 200 });
+ return new Response(new Uint8Array([0x47]), { status: 200 });
+ })
+ );
+
+ await expect(runDownloadJob(jobOptions())).rejects.toThrow(/不支持浏览器缓存/);
+ });
+
+ it('跨域或域名不可达导致的 Failed to fetch 翻译成「建议更换来源」', async () => {
+ stubCaches();
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => {
+ throw new TypeError('Failed to fetch');
+ })
+ );
+
+ await expect(runDownloadJob(jobOptions())).rejects.toThrow(
+ /无法直连该来源(跨域限制或域名不可达),建议更换来源/
+ );
+ });
+
+ it('HTTPS 页面遇到 http 来源时提示混合内容被拦截', async () => {
+ stubCaches();
+ vi.stubGlobal('location', { protocol: 'https:' });
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => {
+ throw new TypeError('Failed to fetch');
+ })
+ );
+
+ await expect(runDownloadJob(jobOptions({ url: 'http://cdn.example.com/index.m3u8' }))).rejects.toThrow(
+ /混合内容被拦截/
+ );
+ });
});
diff --git a/src/lib/m3u8-downloader.ts b/src/lib/m3u8-downloader.ts
index 74c2871..16b8530 100644
--- a/src/lib/m3u8-downloader.ts
+++ b/src/lib/m3u8-downloader.ts
@@ -66,6 +66,15 @@ function dlChunkKey(taskId: string, index: number): string {
return `${DL_CHUNK_ORIGIN}/${encodeURIComponent(taskId)}/${index}`;
}
+/**
+ * 是否具备断点缓存能力。Cache Storage 只在安全上下文(HTTPS / localhost)存在,
+ * HTTP 部署、部分 WebView 与旧浏览器都没有它。下载链路依赖它暂存分片,
+ * 缺了只能提前告知,而不是等 caches.open 抛出裸的 ReferenceError。
+ */
+export function supportsChunkCache(): boolean {
+ return typeof caches !== 'undefined';
+}
+
export async function clearDownloadChunks(taskId: string): Promise<void> {
try {
if (typeof caches === 'undefined') return;
@@ -145,6 +154,28 @@ export interface DownloadJobOptions {
target: import('./download-saver').SaveTarget;
}
+/**
+ * 把解析阶段的失败翻译成可操作的原因。浏览器直连被 CORS / 混合内容 / DNS 拦下时,
+ * fetch 只会给出 `TypeError: Failed to fetch`——对用户没有任何信息量。而下载链路
+ * 没有播放器那样的代理回退(player-shell 遇直连致命错误会改走 /api/proxy),
+ * 所以「能播不能下」多半卡在这里,必须把下一步该做什么讲清楚。
+ */
+function describeParseFailure(url: string, err: unknown): string {
+ const reason = err instanceof Error ? err.message : '未知错误';
+ const base = `播放列表解析失败:${reason}`;
+ if (!/failed to fetch|networkerror|load failed/i.test(reason)) return base;
+ if (isMixedContentBlocked(url)) {
+ return `${base}——该来源是 HTTP 地址,HTTPS 页面无法直连下载(混合内容被拦截),建议更换来源`;
+ }
+ return `${base}——无法直连该来源(跨域限制或域名不可达),建议更换来源`;
+}
+
+/** 页面是 HTTPS 而目标是 http:// 时,浏览器按混合内容策略直接拦截 */
+function isMixedContentBlocked(target: string): boolean {
+ if (typeof location === 'undefined' || location.protocol !== 'https:') return false;
+ return /^http:\/\//i.test(target);
+}
+
/**
* 执行一次整集下载。调用方(DownloadManager)负责:
* 在用户手势内 pickSaveTarget、构造 AbortSignal/PauseResumeController、
@@ -183,7 +214,7 @@ export async function runDownloadJob(opts: DownloadJobOptions): Promise<void> {
}
}
if (lastErr || !parsed!) {
- throw new Error(`播放列表解析失败:${lastErr instanceof Error ? lastErr.message : '未知错误'}`);
+ throw new Error(describeParseFailure(url, lastErr));
}
if (parsed.byterange) throw new Error('该集使用 BYTERANGE 分片,暂不支持下载');
@@ -199,6 +230,9 @@ export async function runDownloadJob(opts: DownloadJobOptions): Promise<void> {
}
// —— 并发下载分片(Cache Storage 断点) ——
+ if (!supportsChunkCache()) {
+ throw new Error('当前环境不支持浏览器缓存(需通过 HTTPS 访问或更换支持 Cache Storage 的浏览器),无法下载');
+ }
const cache = await caches.open(DL_CACHE_NAME);
const chunkKey = (index: number) => dlChunkKey(taskId, index);
let cursor = 0;