From da1be9a07cb548090309498071c7aec4bb0d3506 Mon Sep 17 00:00:00 2001 From: mtvpls Date: Tue, 19 May 2026 20:26:17 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=8D=E8=AF=95=E6=9C=BA=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/books/read/page.tsx | 30 ++++++++++++++++++++++-------- src/lib/legado.client.ts | 37 ++++++++++++++++++++++++------------- 2 files changed, 46 insertions(+), 21 deletions(-) diff --git a/src/app/books/read/page.tsx b/src/app/books/read/page.tsx index 10b8b4d..d50ff92 100644 --- a/src/app/books/read/page.tsx +++ b/src/app/books/read/page.tsx @@ -327,6 +327,24 @@ function findTocLabelByHref(items: TocItem[], currentHref: string): string { return ''; } +async function fetchJsonWithRetry(url: string, init?: RequestInit, retries = 2): Promise { + let lastError: unknown; + for (let attempt = 0; attempt <= retries; attempt += 1) { + try { + const res = await fetch(url, init); + const json = await res.json(); + if (!res.ok) throw new Error(json.error || `请求失败: ${res.status}`); + return json as T; + } catch (error) { + lastError = error; + if (attempt < retries) { + await new Promise((resolve) => setTimeout(resolve, 300 * (attempt + 1))); + } + } + } + throw lastError instanceof Error ? lastError : new Error('请求失败'); +} + async function downloadBookWithProgress( manifest: Pick, onProgress: (received: number, total: number | null) => void @@ -492,10 +510,8 @@ function ChapterReader({ manifest }: { manifest: BookReadManifest }) { setLoading(true); setError(''); const url = manifest.chaptersUrl || `/api/books/read/chapters?sourceId=${encodeURIComponent(manifest.book.sourceId)}&bookId=${encodeURIComponent(manifest.book.id)}`; - fetch(url, { cache: 'no-store' }) - .then(async (res) => { - const json = await res.json(); - if (!res.ok) throw new Error(json.error || '获取目录失败'); + fetchJsonWithRetry<{ chapters?: BookChapter[] }>(url, { cache: 'no-store' }) + .then((json) => { if (cancelled) return; const list = (json.chapters || []) as BookChapter[]; setChapters(list); @@ -520,10 +536,8 @@ function ChapterReader({ manifest }: { manifest: BookReadManifest }) { scrollRef.current?.scrollTo({ top: 0, behavior: 'auto' }); const params = new URLSearchParams({ sourceId: manifest.book.sourceId, href: item.href }); if (manifest.acquisitionHref) params.set('tocHref', manifest.acquisitionHref); - fetch(`/api/books/read/chapter?${params.toString()}`, { cache: 'no-store' }) - .then(async (res) => { - const json = await res.json(); - if (!res.ok) throw new Error(json.error || '获取章节失败'); + fetchJsonWithRetry(`/api/books/read/chapter?${params.toString()}`, { cache: 'no-store' }) + .then((json) => { setChapter({ ...(json as BookChapterContent), title: (json as BookChapterContent).title || item.title }); const progressPercent = chapters.length > 0 ? Math.round(((currentIndex + 1) / chapters.length) * 100) : 0; const record: BookReadRecord = { diff --git a/src/lib/legado.client.ts b/src/lib/legado.client.ts index 7e1d508..d5dce21 100644 --- a/src/lib/legado.client.ts +++ b/src/lib/legado.client.ts @@ -373,6 +373,10 @@ function normalizeConfiguredLegadoSource(item: any, index: number): BookSource | return null; } +function wait(ms: number) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + async function fetchText(source: BookSource, url: string): Promise { const safe = await validateProxyUrlServerSide(url); if (!safe) throw new Error('书源地址未通过安全校验'); @@ -381,20 +385,27 @@ async function fetchText(source: BookSource, url: string): Promise { const { cacheTTL } = await resolveLegadoConfig(); if (cached && cached.expiresAt > Date.now()) return cached.data; - const controller = new AbortController(); - const timeout = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS); - try { - const response = await fetch(url, { headers: buildHeaders(source), signal: controller.signal, cache: 'no-store' }); - if (!response.ok) throw new Error(`请求失败: ${response.status}`); - const contentLength = Number(response.headers.get('content-length') || '0'); - if (contentLength > MAX_TEXT_BYTES) throw new Error('响应内容过大'); - const text = await response.text(); - if (text.length > MAX_TEXT_BYTES) throw new Error('响应内容过大'); - textCache.set(cacheKey, { data: text, expiresAt: Date.now() + cacheTTL }); - return text; - } finally { - clearTimeout(timeout); + let lastError: unknown; + for (let attempt = 0; attempt < 3; attempt += 1) { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS); + try { + const response = await fetch(url, { headers: buildHeaders(source), signal: controller.signal, cache: 'no-store' }); + if (!response.ok) throw new Error(`请求失败: ${response.status}`); + const contentLength = Number(response.headers.get('content-length') || '0'); + if (contentLength > MAX_TEXT_BYTES) throw new Error('响应内容过大'); + const text = await response.text(); + if (text.length > MAX_TEXT_BYTES) throw new Error('响应内容过大'); + textCache.set(cacheKey, { data: text, expiresAt: Date.now() + cacheTTL }); + return text; + } catch (error) { + lastError = error; + if (attempt < 2) await wait(300 * (attempt + 1)); + } finally { + clearTimeout(timeout); + } } + throw lastError instanceof Error ? lastError : new Error('请求失败'); } async function getSourceById(sourceId: string): Promise {