/* 离线章节缓存:IndexedDB 存储 + 全局下载管理器。 */ import { api } from './api'; const DB_NAME = 'novel-reader-cache'; const DB_VERSION = 2; const STORE = 'chapters'; const META_STORE = 'meta'; let dbPromise = null; function openDB() { return new Promise((resolve, reject) => { const request = indexedDB.open(DB_NAME, DB_VERSION); request.onupgradeneeded = () => { const db = request.result; if (!db.objectStoreNames.contains(STORE)) { const store = db.createObjectStore(STORE, { keyPath: 'key' }); store.createIndex('book_id', 'book_id', { unique: false }); } if (!db.objectStoreNames.contains(META_STORE)) { db.createObjectStore(META_STORE, { keyPath: 'book_id' }); } }; request.onsuccess = () => { const db = request.result; // 其他标签页升级数据库时,重置连接以便下次重新打开 db.onversionchange = () => { db.close(); dbPromise = null; }; resolve(db); }; request.onerror = () => reject(request.error); }); } function getDB() { if (!dbPromise) { dbPromise = openDB().catch((error) => { dbPromise = null; // 失败后允许下次重试,避免缓存永久失效 throw error; }); } return dbPromise; } function chapterKey(bookId, chapterId) { return `${bookId}/${chapterId}`; } export async function putChapter(bookId, chapter) { const db = await getDB(); return new Promise((resolve, reject) => { const transaction = db.transaction(STORE, 'readwrite'); transaction.objectStore(STORE).put({ key: chapterKey(bookId, chapter.chapter_id), book_id: bookId, chapter_id: chapter.chapter_id, title: chapter.title, content: chapter.content, prev: chapter.prev || null, next: chapter.next || null, }); transaction.oncomplete = () => resolve(); transaction.onerror = () => reject(transaction.error); }); } export async function getChapter(bookId, chapterId) { const db = await getDB(); return new Promise((resolve, reject) => { const request = db.transaction(STORE).objectStore(STORE).get(chapterKey(bookId, chapterId)); request.onsuccess = () => resolve(request.result || null); request.onerror = () => reject(request.error); }); } export async function countBookChapters(bookId) { const db = await getDB(); return new Promise((resolve, reject) => { const index = db.transaction(STORE).objectStore(STORE).index('book_id'); const request = index.count(IDBKeyRange.only(bookId)); request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); }); } export async function listChapterIds(bookId) { const db = await getDB(); return new Promise((resolve, reject) => { const index = db.transaction(STORE).objectStore(STORE).index('book_id'); const request = index.openKeyCursor(IDBKeyRange.only(bookId)); const ids = new Set(); request.onsuccess = () => { const cursor = request.result; if (cursor) { ids.add(cursor.primaryKey.split('/').pop()); cursor.continue(); } else { resolve(ids); } }; request.onerror = () => reject(request.error); }); } export async function listBookChapters(bookId) { const db = await getDB(); return new Promise((resolve, reject) => { const index = db.transaction(STORE).objectStore(STORE).index('book_id'); const request = index.openCursor(IDBKeyRange.only(bookId)); const items = []; request.onsuccess = () => { const cursor = request.result; if (cursor) { items.push(cursor.value); cursor.continue(); } else { resolve(items); } }; request.onerror = () => reject(request.error); }); } export async function deleteBookChapters(bookId) { const db = await getDB(); return new Promise((resolve, reject) => { const transaction = db.transaction(STORE, 'readwrite'); const index = transaction.objectStore(STORE).index('book_id'); const request = index.openCursor(IDBKeyRange.only(bookId)); request.onsuccess = () => { const cursor = request.result; if (cursor) { cursor.delete(); cursor.continue(); } }; transaction.oncomplete = () => resolve(); transaction.onerror = () => reject(transaction.error); }); } export async function saveDownloadMeta(bookId, total, title) { const db = await getDB(); return new Promise((resolve, reject) => { const transaction = db.transaction(META_STORE, 'readwrite'); transaction.objectStore(META_STORE).put({ book_id: bookId, total, title }); transaction.oncomplete = () => resolve(); transaction.onerror = () => reject(transaction.error); }); } export async function getDownloadMeta(bookId) { const db = await getDB(); return new Promise((resolve, reject) => { const request = db.transaction(META_STORE).objectStore(META_STORE).get(bookId); request.onsuccess = () => resolve(request.result || null); request.onerror = () => reject(request.error); }); } export async function deleteBookMeta(bookId) { const db = await getDB(); return new Promise((resolve, reject) => { const transaction = db.transaction(META_STORE, 'readwrite'); transaction.objectStore(META_STORE).delete(bookId); transaction.oncomplete = () => resolve(); transaction.onerror = () => reject(transaction.error); }); } export async function listCachedBooks() { const db = await getDB(); return new Promise((resolve, reject) => { const index = db.transaction(STORE).objectStore(STORE).index('book_id'); const request = index.openKeyCursor(); const ids = []; const seen = new Set(); request.onsuccess = () => { const cursor = request.result; if (cursor) { const bookId = cursor.primaryKey.split('/')[0]; if (!seen.has(bookId)) { seen.add(bookId); ids.push(bookId); } cursor.continue(); } else { resolve(ids); } }; request.onerror = () => reject(request.error); }); } /* 缓存优先:已缓存的章节直接读本地,未缓存时请求后端并自动补缓存 */ export async function fetchChapterCached(bookId, chapterId) { const cached = await getChapter(bookId, chapterId); if (cached) return { chapter: cached, fromCache: true }; const chapter = await api.chapter(bookId, chapterId); putChapter(bookId, chapter).catch(() => {}); return { chapter, fromCache: false }; } /* ---------- 全局下载管理器 ---------- */ const tasks = new Map(); const listeners = new Set(); const BATCH_SIZE = 20; const BATCH_WORKERS = 2; function emit() { const snapshot = [...tasks.values()]; listeners.forEach((listener) => listener(snapshot)); } export function subscribeDownloads(listener) { listeners.add(listener); return () => listeners.delete(listener); } export function downloadsSnapshot() { return [...tasks.values()]; } export function startDownload(bookId, title) { const existing = tasks.get(bookId); if (existing && existing.status === 'downloading') return existing; if (existing) tasks.delete(bookId); const task = { bookId, title, status: 'downloading', done: 0, total: 0, failed: 0, error: null, cancelled: false, }; tasks.set(bookId, task); emit(); runDownload(task); return task; } export function cancelDownload(bookId) { const task = tasks.get(bookId); if (!task || task.status !== 'downloading') return; task.cancelled = true; task.status = 'cancelled'; emit(); } async function runDownload(task) { try { const detail = await api.book(task.bookId); if (task.cancelled) return; task.total = detail.chapters.length; saveDownloadMeta(task.bookId, task.total, task.title).catch(() => {}); // 断点续传:跳过已缓存的章节,只下载缺失部分 const cachedIds = await listChapterIds(task.bookId); const queue = detail.chapters.filter((chapter) => !cachedIds.has(chapter.chapter_id)); task.skipped = detail.chapters.length - queue.length; task.done = task.skipped; emit(); if (task.cancelled) return; await Promise.all(Array.from({ length: BATCH_WORKERS }, () => downloadWorker(task, queue))); if (task.cancelled) return; task.status = task.failed > 0 ? 'partial' : 'done'; } catch (err) { task.status = 'error'; task.error = err.message || '下载失败'; } finally { emit(); } } async function downloadWorker(task, queue) { while (queue.length > 0 && !task.cancelled) { const batch = queue.splice(0, BATCH_SIZE); try { const data = await api.chapterBatch( task.bookId, batch.map((chapter) => chapter.chapter_id), ); const returned = data.chapters || []; const returnedIds = new Set(returned.map((chapter) => chapter.chapter_id)); for (const chapter of returned) { if (task.cancelled) return; try { await putChapter(task.bookId, chapter); task.done += 1; } catch { task.failed += 1; } emit(); // 每存一章实时刷新进度 } // 批量接口未返回的章节(可能临时失败)→ 逐章补一次 for (const chapter of batch) { if (task.cancelled) return; if (returnedIds.has(chapter.chapter_id)) continue; try { const one = await api.chapter(task.bookId, chapter.chapter_id); await putChapter(task.bookId, one); task.done += 1; } catch { task.failed += 1; } emit(); } } catch { // 批量请求整体失败 → 降级为逐章下载 for (const chapter of batch) { if (task.cancelled) return; try { const one = await api.chapter(task.bookId, chapter.chapter_id); await putChapter(task.bookId, one); task.done += 1; } catch { task.failed += 1; } emit(); } } } } export async function deleteCache(bookId) { await deleteBookChapters(bookId); await deleteBookMeta(bookId); tasks.delete(bookId); emit(); }