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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
import { defineStore } from 'pinia'
import type { Album } from '../types'
import { sleep } from '../utils'
const CACHE_NAME = 'domsomic-cache-v1'
const META_DB_NAME = 'domsonic-cache-meta-v1'
const META_STORE_NAME = 'entries'
const META_INFO_STORE_NAME = 'meta'
const MAX_CACHE_SIZE_BYTES = 5 * 1024 * 1024 * 1024 // 5 GB
type MetaEntry = {
url: string
size: number
timestamp: number
order: number
lastAccess: number
}
type MetaInfo = {
id: 'meta'
totalBytes: number
nextOrder: number
}
// ---------------------------------------------------------------------------
// IndexedDB helpers
// ---------------------------------------------------------------------------
function openMetaDB(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const req = indexedDB.open(META_DB_NAME, 3)
req.onupgradeneeded = () => {
const db = req.result
let store: IDBObjectStore
if (!db.objectStoreNames.contains(META_STORE_NAME)) {
store = db.createObjectStore(META_STORE_NAME, { keyPath: 'url' })
store.createIndex('order', 'order')
store.createIndex('lastAccess', 'lastAccess')
} else {
store = req.transaction!.objectStore(META_STORE_NAME)
if (!store.indexNames.contains('lastAccess')) {
store.createIndex('lastAccess', 'lastAccess')
}
}
if (!db.objectStoreNames.contains(META_INFO_STORE_NAME)) {
db.createObjectStore(META_INFO_STORE_NAME, { keyPath: 'id' })
}
}
req.onsuccess = () => {
const db = req.result
const tx = db.transaction(META_INFO_STORE_NAME, 'readwrite')
const store = tx.objectStore(META_INFO_STORE_NAME)
const getReq = store.get('meta')
getReq.onsuccess = () => {
if (!getReq.result) {
store.put({ id: 'meta', totalBytes: 0, nextOrder: 1 } as MetaInfo)
}
}
tx.oncomplete = () => resolve(db)
tx.onerror = () => resolve(db)
}
req.onerror = () => reject(req.error)
})
}
async function getMetaInfo(): Promise<MetaInfo> {
const db = await openMetaDB()
return new Promise(resolve => {
const tx = db.transaction(META_INFO_STORE_NAME, 'readonly')
const store = tx.objectStore(META_INFO_STORE_NAME)
const req = store.get('meta')
req.onsuccess = () => {
resolve(req.result || { id: 'meta', totalBytes: 0, nextOrder: 1 })
}
req.onerror = () => {
resolve({ id: 'meta', totalBytes: 0, nextOrder: 1 })
}
})
}
async function touchMeta(url: string) {
const db = await openMetaDB()
const tx = db.transaction(META_STORE_NAME, 'readwrite')
const store = tx.objectStore(META_STORE_NAME)
const req = store.get(url)
req.onsuccess = () => {
const entry = req.result as MetaEntry | undefined
if (!entry) return
entry.lastAccess = Date.now()
store.put(entry)
}
}
async function putMeta(url: string, size: number) {
const db = await openMetaDB()
return new Promise<void>((resolve, reject) => {
const tx = db.transaction([META_STORE_NAME, META_INFO_STORE_NAME], 'readwrite')
const entries = tx.objectStore(META_STORE_NAME)
const metaStore = tx.objectStore(META_INFO_STORE_NAME)
const metaReq = metaStore.get('meta')
metaReq.onsuccess = () => {
const meta = metaReq.result as MetaInfo
const now = Date.now()
const entry: MetaEntry = {
url,
size,
timestamp: now,
order: meta.nextOrder++,
lastAccess: now,
}
meta.totalBytes += size
entries.put(entry)
metaStore.put(meta)
}
tx.oncomplete = () => resolve()
tx.onerror = () => reject(tx.error)
})
}
async function deleteMeta(url: string) {
const db = await openMetaDB()
const tx = db.transaction([META_STORE_NAME, META_INFO_STORE_NAME], 'readwrite')
const entries = tx.objectStore(META_STORE_NAME)
const metaStore = tx.objectStore(META_INFO_STORE_NAME)
const entryReq = entries.get(url)
entryReq.onsuccess = () => {
const entry = entryReq.result as MetaEntry | undefined
if (!entry) return
entries.delete(url)
const metaReq = metaStore.get('meta')
metaReq.onsuccess = () => {
const meta = metaReq.result as MetaInfo
meta.totalBytes = Math.max(0, meta.totalBytes - entry.size)
metaStore.put(meta)
}
}
}
// ---------------------------------------------------------------------------
// LRU eviction
// ---------------------------------------------------------------------------
async function enforceCacheLimitLRU() {
const cache = await caches.open(CACHE_NAME)
const meta = await getMetaInfo()
let total = meta.totalBytes
if (total <= MAX_CACHE_SIZE_BYTES) return
const db = await openMetaDB()
return new Promise<void>((resolve, reject) => {
const tx = db.transaction([META_STORE_NAME, META_INFO_STORE_NAME], 'readwrite')
const store = tx.objectStore(META_STORE_NAME)
const index = store.index('lastAccess')
const metaStore = tx.objectStore(META_INFO_STORE_NAME)
const cursorReq = index.openCursor()
cursorReq.onsuccess = async() => {
let cursor = cursorReq.result as IDBCursorWithValue | null
while (cursor && total > MAX_CACHE_SIZE_BYTES) {
const entry = cursor.value as MetaEntry
await cache.delete(entry.url)
store.delete(entry.url)
total -= entry.size
window.dispatchEvent(
new CustomEvent('audioCacheDeleted', { detail: entry.url }),
)
cursor = await new Promise<IDBCursorWithValue | null>(resolve => {
cursor!.continue()
cursor!.request.onsuccess = () =>
resolve(cursor!.request.result as IDBCursorWithValue | null)
cursor!.request.onerror = () => resolve(null)
})
}
const metaReq = metaStore.get('meta')
metaReq.onsuccess = () => {
const m = metaReq.result as MetaInfo
m.totalBytes = total
metaStore.put(m)
}
tx.oncomplete = () => {
window.dispatchEvent(
new CustomEvent('audioCacheEvicted', { detail: { totalBytes: total } }),
)
resolve()
}
}
cursorReq.onerror = () => reject(cursorReq.error)
})
}
// ---------------------------------------------------------------------------
// Store (FIFO queue enabled)
// ---------------------------------------------------------------------------
export const useCacheStore = defineStore('albumCache', {
state: () => ({
activeCaching: new Map<string, { cancelled: boolean }>(),
queue: [] as string[],
queuedSet: new Set<string>(),
processingQueue: false,
}),
actions: {
// --------------------------------------------------
// FIFO worker
// --------------------------------------------------
async processQueue() {
if (this.processingQueue) return
this.processingQueue = true
const cache = await caches.open(CACHE_NAME)
while (this.queue.length > 0) {
const url = this.queue.shift()!
this.queuedSet.delete(url)
try {
if (await cache.match(url)) {
await touchMeta(url)
continue
}
const res = await fetch(url, { mode: 'cors', cache: 'force-cache' })
if (!res.ok) continue
const clone = res.clone()
const blob = await res.blob()
await cache.put(url, clone)
await putMeta(url, blob.size)
await enforceCacheLimitLRU()
window.dispatchEvent(
new CustomEvent('audioCached', { detail: url }),
)
} catch (err) {
console.error('Cache error:', err)
}
}
this.processingQueue = false
},
// --------------------------------------------------
// Public enqueue method
// --------------------------------------------------
async cacheTrack(url: string) {
if (!url || this.queuedSet.has(url)) return
this.queue.push(url)
this.queuedSet.add(url)
if (!this.processingQueue) {
await this.processQueue()
}
},
async hasTrack(url: string) {
if (!url) return false
const cache = await caches.open(CACHE_NAME)
const match = await cache.match(url)
if (match) await touchMeta(url)
return !!match
},
async deleteTrack(url: string) {
if (!url) return
const cache = await caches.open(CACHE_NAME)
if (await cache.delete(url)) {
await deleteMeta(url)
window.dispatchEvent(
new CustomEvent('audioCacheDeleted', { detail: url }),
)
}
},
async clearAllAudioCache() {
await caches.delete(CACHE_NAME)
indexedDB.deleteDatabase(META_DB_NAME)
window.dispatchEvent(new CustomEvent('audioCacheClearedAll'))
return true
},
async cacheAlbum(album: Album) {
if (!album?.tracks?.length) return
const key = album.id || album.name
this.activeCaching.set(key, { cancelled: false })
const session = this.activeCaching.get(key)!
const urls = album.tracks.map(t => t.url).filter(Boolean) as string[]
for (const url of urls) {
if (session.cancelled) return
await this.cacheTrack(url)
await sleep(200)
}
},
async clearAlbumCache(album: Album) {
if (!album?.tracks?.length) return
const key = album.id || album.name
if (key && this.activeCaching.has(key)) {
this.activeCaching.get(key)!.cancelled = true
await sleep(1000)
}
const cache = await caches.open(CACHE_NAME)
for (const t of album.tracks) {
if (!t.url) continue
if (await cache.delete(t.url)) {
await deleteMeta(t.url)
window.dispatchEvent(
new CustomEvent('audioCacheDeleted', { detail: t.url }),
)
}
}
},
async isCached(album: Album) {
if (!album?.tracks?.length) return false
const cache = await caches.open(CACHE_NAME)
const res = await Promise.all(
album.tracks.map(t => (t.url ? cache.match(t.url) : null)),
)
return res.every(Boolean)
},
async getCacheSizeGB() {
const meta = await getMetaInfo()
return Math.round((meta.totalBytes / 1024 ** 3) * 10) / 10
},
},
})