-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbookCache.ts
More file actions
177 lines (162 loc) · 6.14 KB
/
Copy pathbookCache.ts
File metadata and controls
177 lines (162 loc) · 6.14 KB
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
/**
* Desktop book cache utility
* Caches book files, chapters, and chapter content to IndexedDB for offline reading.
*/
const DB_NAME = 'BookDockCache';
const DB_VERSION = 1;
const STORE_FILES = 'files'; // { bookId -> Blob }
const STORE_CHAPTERS = 'chapters'; // { bookId -> Array<{title, index}> }
const STORE_CONTENT = 'content'; // { `${bookId}:${chapterIndex}` -> string }
function openDB(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, DB_VERSION);
req.onerror = () => reject(req.error);
req.onsuccess = () => resolve(req.result);
req.onupgradeneeded = (event) => {
const db = (event.target as IDBOpenDBRequest).result;
if (!db.objectStoreNames.contains(STORE_FILES)) {
db.createObjectStore(STORE_FILES, { keyPath: 'bookId' });
}
if (!db.objectStoreNames.contains(STORE_CHAPTERS)) {
db.createObjectStore(STORE_CHAPTERS, { keyPath: 'bookId' });
}
if (!db.objectStoreNames.contains(STORE_CONTENT)) {
db.createObjectStore(STORE_CONTENT, { keyPath: 'key' });
}
};
});
}
async function getStore(storeName: string, mode: IDBTransactionMode = 'readonly') {
const db = await openDB();
const tx = db.transaction(storeName, mode);
return tx.objectStore(storeName);
}
// ── File cache (PDF blob etc.) ───────────────────────────────────────
export async function getCachedFile(bookId: string): Promise<Blob | null> {
try {
const store = await getStore(STORE_FILES);
const req = store.get(bookId);
return new Promise((resolve, reject) => {
req.onsuccess = () => {
const result = req.result;
resolve(result?.blob ? new Blob([result.blob], { type: result.type || 'application/octet-stream' }) : null);
};
req.onerror = () => reject(req.error);
});
} catch {
return null;
}
}
export async function setCachedFile(bookId: string, blob: Blob, type?: string): Promise<void> {
try {
const store = await getStore(STORE_FILES, 'readwrite');
const arrayBuffer = await blob.arrayBuffer();
const req = store.put({ bookId, blob: arrayBuffer, type: type || blob.type, cachedAt: Date.now() });
return new Promise((resolve, reject) => {
req.onsuccess = () => resolve();
req.onerror = () => reject(req.error);
});
} catch (e) {
console.warn('Failed to cache file:', e);
}
}
export async function deleteCachedFile(bookId: string): Promise<void> {
try {
const store = await getStore(STORE_FILES, 'readwrite');
const req = store.delete(bookId);
return new Promise((resolve, reject) => {
req.onsuccess = () => resolve();
req.onerror = () => reject(req.error);
});
} catch (e) {
console.warn('Failed to delete cached file:', e);
}
}
// ── Chapters cache ─────────────────────────────────────────────────────
export async function getCachedChapters(bookId: string): Promise<Array<{ title: string; index: number }> | null> {
try {
const store = await getStore(STORE_CHAPTERS);
const req = store.get(bookId);
return new Promise((resolve, reject) => {
req.onsuccess = () => {
const result = req.result;
resolve(result?.chapters || null);
};
req.onerror = () => reject(req.error);
});
} catch {
return null;
}
}
export async function setCachedChapters(bookId: string, chapters: Array<{ title: string; index: number }>): Promise<void> {
try {
const store = await getStore(STORE_CHAPTERS, 'readwrite');
const req = store.put({ bookId, chapters, cachedAt: Date.now() });
return new Promise((resolve, reject) => {
req.onsuccess = () => resolve();
req.onerror = () => reject(req.error);
});
} catch (e) {
console.warn('Failed to cache chapters:', e);
}
}
// ── Chapter content cache ──────────────────────────────────────────────
export async function getCachedChapterContent(bookId: string, chapterIndex: number): Promise<string | null> {
try {
const store = await getStore(STORE_CONTENT);
const req = store.get(`${bookId}:${chapterIndex}`);
return new Promise((resolve, reject) => {
req.onsuccess = () => {
const result = req.result;
resolve(result?.content || null);
};
req.onerror = () => reject(req.error);
});
} catch {
return null;
}
}
export async function setCachedChapterContent(bookId: string, chapterIndex: number, content: string): Promise<void> {
try {
const store = await getStore(STORE_CONTENT, 'readwrite');
const req = store.put({ key: `${bookId}:${chapterIndex}`, content, cachedAt: Date.now() });
return new Promise((resolve, reject) => {
req.onsuccess = () => resolve();
req.onerror = () => reject(req.error);
});
} catch (e) {
console.warn('Failed to cache chapter content:', e);
}
}
// ── Clear all cache for a book ─────────────────────────────────────────
export async function clearBookCache(bookId: string): Promise<void> {
await Promise.all([
deleteCachedFile(bookId),
(async () => {
try {
const store = await getStore(STORE_CHAPTERS, 'readwrite');
store.delete(bookId);
} catch { /* ignore */ }
})(),
(async () => {
try {
const store = await getStore(STORE_CONTENT, 'readwrite');
// Delete all content keys for this book
const range = IDBKeyRange.bound(`${bookId}:`, `${bookId}:\xFF`);
const req = store.openCursor(range);
return new Promise<void>((resolve, reject) => {
req.onsuccess = () => {
const cursor = req.result;
if (cursor) {
cursor.delete();
cursor.continue();
} else {
resolve();
}
};
req.onerror = () => reject(req.error);
});
} catch { /* ignore */ }
})(),
]);
}