Spaces:
Paused
Paused
File size: 10,218 Bytes
6d2d8b6 c6eb0d4 6d2d8b6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 | /* 离线章节缓存: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();
}
|