offline.ts
| 1 | import type { |
| 2 | MediaFile, |
| 3 | Directory, |
| 4 | FileListing, |
| 5 | FileListingWithStatus, |
| 6 | DirectoryWithStatus, |
| 7 | } from "music-server-shared/types"; |
| 8 | import { parseMap } from "music-server-shared/mapconversion"; |
| 9 | import type { AppOptions, Playlist, PlaylistItem } from "./types"; |
| 10 | import { joinPath, toast } from "./utils"; |
| 11 | import { type Accessor, createSignal, type ResourceActions, type Signal } from "solid-js"; |
| 12 | import { AsyncSemaphore } from "./semaphore"; |
| 13 | |
| 14 | interface Progress { |
| 15 | bytes: number; |
| 16 | } |
| 17 | |
| 18 | //TODO: try using store |
| 19 | export type SignalMapEntry = undefined | Progress | "DirectoryProgress" | "CachedFile"; |
| 20 | export const signalMap = new Map<string, Signal<SignalMapEntry>>(); |
| 21 | |
| 22 | export async function loadDataFromDB() { |
| 23 | try { |
| 24 | const db = await openDB(); |
| 25 | const files = await db.listFiles(FileMetadataStore); |
| 26 | for (const file of files) { |
| 27 | signalMap.set(file.path, createSignal<SignalMapEntry>("CachedFile")); |
| 28 | updateFileTree(file.path, { metadata: { duration: file.duration } }, true); |
| 29 | } |
| 30 | } catch (e) { |
| 31 | toast("Loading offline files failed", "error", e); |
| 32 | console.error(e); |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | const offlineTreeRoot: Directory = { |
| 37 | files: new Map(), |
| 38 | }; |
| 39 | |
| 40 | const onlineTreeRoot: DirectoryWithStatus = { |
| 41 | files: new Map(), |
| 42 | status: "Unknown", |
| 43 | }; |
| 44 | |
| 45 | function mergeTrees(target: DirectoryWithStatus, other: DirectoryWithStatus) { |
| 46 | if (other.status === "Unknown") return; |
| 47 | target.status = other.status; |
| 48 | for (const [fileName, file] of other.files.entries()) { |
| 49 | const targetFile = target.files.get(fileName); |
| 50 | if (targetFile && "files" in targetFile && "files" in file) { |
| 51 | mergeTrees(targetFile, file); |
| 52 | } else { |
| 53 | target.files.set(fileName, file); |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | //TODO: improve typing to avoid "as" |
| 59 | //overloads for typecheking |
| 60 | function updateFileTree(path: string, file: MediaFile, offline: true): void; |
| 61 | function updateFileTree(path: string, file: DirectoryWithStatus, offline: false): void; |
| 62 | function updateFileTree(path: string, file: DirectoryWithStatus | MediaFile, offline: boolean): void { |
| 63 | if (offline && path === "") throw new Error("Trying to update root in offline mode"); |
| 64 | const basePath = path.split("/").slice(0, -1).join("/"); |
| 65 | const fileName = path.split("/").toReversed()[0]; |
| 66 | const node = getDirInTree(basePath, true, offline); |
| 67 | |
| 68 | if (offline) { |
| 69 | node.files.set(fileName, file); |
| 70 | } else { |
| 71 | if (path === "") mergeTrees(node as DirectoryWithStatus, file as DirectoryWithStatus); |
| 72 | else { |
| 73 | let target = node.files.get(fileName) as DirectoryWithStatus; |
| 74 | if (!target) target = { files: new Map(), status: "Unknown" }; |
| 75 | mergeTrees(target as DirectoryWithStatus, file as DirectoryWithStatus); |
| 76 | node.files.set(fileName, target); |
| 77 | } |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | //overloads for typecheking |
| 82 | function getDirInTree(path: string, create: true, offline: true): Directory; |
| 83 | function getDirInTree(path: string, create: true, offline: false): DirectoryWithStatus; |
| 84 | function getDirInTree(path: string, create: false, offline: true): Directory | null; |
| 85 | function getDirInTree(path: string, create: false, offline: false): DirectoryWithStatus | null; |
| 86 | function getDirInTree(path: string, create: true, offline: boolean): DirectoryWithStatus | Directory; |
| 87 | function getDirInTree(path: string, create: false, offline: boolean): DirectoryWithStatus | Directory | null; |
| 88 | |
| 89 | // get a DirectoryNode from the directory tree, and optionally create it if it doesn't exist yet |
| 90 | function getDirInTree(path: string, create: boolean, offline: boolean): DirectoryWithStatus | Directory | null { |
| 91 | let current = offline ? offlineTreeRoot : onlineTreeRoot; |
| 92 | if (path === "") return current; |
| 93 | const parts = path.split("/"); |
| 94 | |
| 95 | for (const part of parts) { |
| 96 | let next: DirectoryWithStatus | Directory | MediaFile | undefined = current.files.get(part); |
| 97 | if (!next || "metadata" in next) { |
| 98 | if (!create) return null; |
| 99 | //if mediafile already exists, we overwrite it with a directory anyway |
| 100 | if (offline) next = { files: new Map() }; |
| 101 | else next = { files: new Map(), status: "Unknown" }; |
| 102 | current.files.set(part, next); |
| 103 | } |
| 104 | current = next; |
| 105 | } |
| 106 | return current; |
| 107 | } |
| 108 | |
| 109 | function deleteOfflinePath(path: string): void { |
| 110 | const basePath = path.split("/").slice(0, -1).join("/"); |
| 111 | const fileName = path.split("/").toReversed()[0]; |
| 112 | |
| 113 | const node = getDirInTree(basePath, false, true); |
| 114 | if (!node) return; |
| 115 | |
| 116 | node.files.delete(fileName); |
| 117 | } |
| 118 | |
| 119 | export const clearDirectoryCache = (path: string) => { |
| 120 | const node = getDirInTree(path, false, false); |
| 121 | if (!node) return; |
| 122 | node.files.clear(); |
| 123 | node.status = "Unknown"; |
| 124 | }; |
| 125 | |
| 126 | async function listOnlineFiles(dir: string, recursive: boolean): Promise<FileListingWithStatus | undefined> { |
| 127 | const response = await fetch(`/list/${dir}?recursive=${recursive}`).catch(() => {}); |
| 128 | if (response?.status === 404) { |
| 129 | toast(`Directory not found: ${dir}`, "error"); |
| 130 | return; |
| 131 | } |
| 132 | if (!response || !response.ok) { |
| 133 | toast( |
| 134 | `Fetching files for ${dir === "" ? "root" : dir} failed${response ? `: ${response.statusText}` : ""}`, |
| 135 | "error", |
| 136 | ); |
| 137 | return; |
| 138 | } |
| 139 | |
| 140 | return parseMap(await response.text()) as FileListingWithStatus; |
| 141 | } |
| 142 | |
| 143 | function listOfflineFiles(dir: string): FileListing { |
| 144 | const node = getDirInTree(dir, false, true); |
| 145 | if (!node || !node.files) return new Map(); |
| 146 | return node.files; |
| 147 | } |
| 148 | |
| 149 | function fullyKnown(dir: DirectoryWithStatus) { |
| 150 | if (dir.status === "Unknown") { |
| 151 | return false; |
| 152 | } |
| 153 | if (dir.files.values().some((value) => "files" in value && !fullyKnown(value))) { |
| 154 | return false; |
| 155 | } |
| 156 | return true; |
| 157 | } |
| 158 | |
| 159 | export async function listFiles(dir: string, offline: boolean, recursive: boolean): Promise<FileListing> { |
| 160 | if (offline) { |
| 161 | const res = listOfflineFiles(dir); |
| 162 | return res; |
| 163 | } |
| 164 | const cached = getDirInTree(dir, false, false); |
| 165 | if (cached !== null && cached.status === "Scanned" && (!recursive || fullyKnown(cached))) return cached.files; |
| 166 | const files = await listOnlineFiles(dir, recursive); |
| 167 | if (!files) return new Map(); |
| 168 | updateFileTree(dir, { files, status: "Scanned" }, false); |
| 169 | return files; |
| 170 | } |
| 171 | |
| 172 | export async function getCover(dir: string, offline: boolean) { |
| 173 | const db = await openDB(); |
| 174 | const dbResult = await db.get(CoverStore, dir); |
| 175 | if (dbResult !== undefined) { |
| 176 | const cached = dbResult as StoredCover; |
| 177 | return cached.data === null ? undefined : URL.createObjectURL(new Blob([cached.data])); |
| 178 | } |
| 179 | |
| 180 | if (offline) return undefined; |
| 181 | |
| 182 | const response = await fetch(`/cover/${dir}`, { method: "GET" }).catch(() => {}); |
| 183 | if (!response || response.status === 404) { |
| 184 | db.put(CoverStore, { path: dir, data: null }); |
| 185 | return undefined; |
| 186 | } |
| 187 | const blob = await response.blob(); |
| 188 | db.put(CoverStore, { path: dir, data: blob }); |
| 189 | return URL.createObjectURL(blob); |
| 190 | } |
| 191 | |
| 192 | export const clearCoverCache = async (path: string) => { |
| 193 | const db = await openDB(); |
| 194 | return db.delete(CoverStore, path); |
| 195 | }; |
| 196 | |
| 197 | export async function getSrc(path: string, options: AppOptions, offline: boolean) { |
| 198 | const db = await openDB(); |
| 199 | const dbResult = (await db.get(FileBlobStore, path)) as StoredFileBlob; |
| 200 | if (dbResult) return URL.createObjectURL(dbResult.data); |
| 201 | |
| 202 | if (offline) { |
| 203 | toast("This file is not cached, leave offline mode to play it", "error"); |
| 204 | return undefined; |
| 205 | } |
| 206 | if (options.enableTranscoding) { |
| 207 | return `${joinPath("/transcode", path)}?bitrate=${options.bitrate}&format=${options.format}`; |
| 208 | } |
| 209 | return joinPath("/download", path); |
| 210 | } |
| 211 | |
| 212 | export async function loadPlaylists() { |
| 213 | const db = await openDB(); |
| 214 | return await db.listPlaylists(PlaylistStore); |
| 215 | } |
| 216 | |
| 217 | export async function savePlaylist(playlist: Playlist, overwrite: boolean) { |
| 218 | const db = await openDB(); |
| 219 | playlist.items = playlist.items.map((item) => { |
| 220 | //some less space in the db by omitting ids |
| 221 | const { id, ...itemWithoutId } = item as PlaylistItem; |
| 222 | return itemWithoutId; |
| 223 | }); |
| 224 | if (overwrite) await db.put(PlaylistStore, playlist); |
| 225 | else await db.add(PlaylistStore, playlist); |
| 226 | } |
| 227 | |
| 228 | export async function deletePlaylist(name: string) { |
| 229 | const db = await openDB(); |
| 230 | await db.delete(PlaylistStore, name); |
| 231 | } |
| 232 | |
| 233 | export async function deleteFile( |
| 234 | fileName: string, |
| 235 | item: MediaFile | Directory, |
| 236 | basePath: string, |
| 237 | fetchFiles: ResourceActions<FileListing>, |
| 238 | ) { |
| 239 | const fullPath = joinPath(basePath, fileName); |
| 240 | const signal = signalMap.get(fullPath); |
| 241 | if (!signal) return; |
| 242 | |
| 243 | //TODO: can techinally remove the recursion, but need to update the signals |
| 244 | if (!("duration" in item)) { |
| 245 | const newBasePath = joinPath(basePath, fileName); |
| 246 | const result = listOfflineFiles(newBasePath); |
| 247 | for (const [childName, childItem] of result) { |
| 248 | await deleteFile(childName, childItem, newBasePath, fetchFiles); |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | deleteOfflinePath(fullPath); |
| 253 | const db = await openDB(); |
| 254 | await db.delete(FileBlobStore, fullPath); |
| 255 | await db.delete(FileMetadataStore, fullPath); |
| 256 | signalMap.get(fullPath)?.[1](undefined); |
| 257 | fetchFiles.refetch(); |
| 258 | } |
| 259 | |
| 260 | const downloadSemaphore = new AsyncSemaphore(1); |
| 261 | |
| 262 | async function downloadFile( |
| 263 | path: string, |
| 264 | currentDir: Accessor<string>, |
| 265 | progressSignal: Signal<SignalMapEntry>, |
| 266 | options: AppOptions, |
| 267 | item: MediaFile, |
| 268 | fetchFiles: ResourceActions<FileListing>, |
| 269 | ): Promise<void> { |
| 270 | const [getProgress, setProgress] = progressSignal; |
| 271 | const progress = getProgress(); |
| 272 | if (typeof progress === "object" && "bytes" in progress) return; // download already in progress |
| 273 | |
| 274 | const db = await openDB(); |
| 275 | let mimeType: string | undefined; |
| 276 | try { |
| 277 | setProgress({ bytes: 0 }); |
| 278 | |
| 279 | downloadSemaphore.setMaxConcurrency(options.enableTranscoding ? options.maxTranscodes : options.maxDownloads); |
| 280 | let blob: Blob; |
| 281 | try { |
| 282 | await downloadSemaphore.acquire(); |
| 283 | let res: Response; |
| 284 | if (options.enableTranscoding) { |
| 285 | res = await fetch(`${joinPath("/transcode", path)}?bitrate=${options.bitrate}&format=${options.format}`); |
| 286 | } else { |
| 287 | res = await fetch(joinPath("/download", path)); |
| 288 | } |
| 289 | //let the browser do the actual download |
| 290 | const blobPromise = res.clone().blob(); |
| 291 | if (!res.ok || !res.body) throw res.statusText; |
| 292 | //we just iterate over the chunks to get the current progress |
| 293 | const reader = res.body.getReader(); |
| 294 | mimeType = res.headers.get("content-type") ?? undefined; |
| 295 | let received = 0; |
| 296 | |
| 297 | let lastUpdate = 0; |
| 298 | while (true) { |
| 299 | const { done, value } = await reader.read(); |
| 300 | if (done) break; |
| 301 | received += value.length; |
| 302 | |
| 303 | const now = Date.now(); |
| 304 | if (now - lastUpdate < 250) continue; |
| 305 | lastUpdate = now; |
| 306 | setProgress({ bytes: received }); |
| 307 | } |
| 308 | blob = await blobPromise; |
| 309 | } finally { |
| 310 | downloadSemaphore.release(); |
| 311 | } |
| 312 | |
| 313 | await db.put(FileBlobStore, { |
| 314 | path, |
| 315 | data: blob, |
| 316 | } as StoredFileBlob); |
| 317 | await db.put(FileMetadataStore, { |
| 318 | path, |
| 319 | duration: item.metadata.duration, |
| 320 | } as StoredFileMetadata); |
| 321 | updateFileTree(path, item, true); |
| 322 | setProgress("CachedFile"); |
| 323 | const basePath = path.split("/").slice(0, -1).join("/"); |
| 324 | const fileName = path.split("/").toReversed()[0]; |
| 325 | if (currentDir() === basePath) { |
| 326 | fetchFiles.mutate((prev) => { |
| 327 | prev.set(fileName, item); |
| 328 | //new map to force rerender |
| 329 | return new Map(prev); |
| 330 | }); |
| 331 | } |
| 332 | } catch (e) { |
| 333 | toast(`Downloading ${path} failed`, "error", e); |
| 334 | setProgress(undefined); |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | export async function download( |
| 339 | fileName: string, |
| 340 | item: MediaFile | Directory, |
| 341 | basePath: string, |
| 342 | currentDir: Accessor<string>, |
| 343 | options: AppOptions, |
| 344 | fetchFiles: ResourceActions<FileListing>, |
| 345 | ) { |
| 346 | const fullPath = joinPath(basePath, fileName); |
| 347 | let signal = signalMap.get(fullPath); |
| 348 | if (!signal) { |
| 349 | signal = createSignal<SignalMapEntry>(); |
| 350 | signalMap.set(fullPath, signal); |
| 351 | } |
| 352 | const [, setProgress] = signal; |
| 353 | if ("metadata" in item) { |
| 354 | await downloadFile(fullPath, currentDir, signal, options, item, fetchFiles); |
| 355 | } else { |
| 356 | setProgress("DirectoryProgress"); |
| 357 | await getCover(fullPath, false); |
| 358 | try { |
| 359 | const promises: Promise<unknown>[] = []; |
| 360 | for (const [childName, childItem] of await listFiles(fullPath, false, false)) { |
| 361 | promises.push(download(childName, childItem, fullPath, currentDir, options, fetchFiles)); |
| 362 | } |
| 363 | await Promise.allSettled(promises); |
| 364 | } finally { |
| 365 | setProgress(undefined); |
| 366 | } |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | interface StoredFileBlob { |
| 371 | path: string; |
| 372 | data: Blob; |
| 373 | } |
| 374 | |
| 375 | interface StoredFileMetadata { |
| 376 | path: string; |
| 377 | duration: number; |
| 378 | } |
| 379 | |
| 380 | interface StoredCover { |
| 381 | path: string; |
| 382 | data: Blob | null; |
| 383 | } |
| 384 | |
| 385 | //separate blobs and metadata, so we don't have to load all file contents at startup, which would consume huge amounts of ram, and be very slow |
| 386 | const FileBlobStore = "fileblobs"; |
| 387 | const FileMetadataStore = "filemetadata"; |
| 388 | const CoverStore = "covers"; |
| 389 | const PlaylistStore = "playlists"; |
| 390 | |
| 391 | async function openDB() { |
| 392 | return new Promise<DatabaseWrapper>((resolve, reject) => { |
| 393 | const req = indexedDB.open("music-files"); |
| 394 | req.onerror = () => reject(req.error); |
| 395 | req.onupgradeneeded = () => { |
| 396 | const db = req.result; |
| 397 | if (!db.objectStoreNames.contains(FileBlobStore)) db.createObjectStore(FileBlobStore, { keyPath: "path" }); |
| 398 | if (!db.objectStoreNames.contains(FileMetadataStore)) |
| 399 | db.createObjectStore(FileMetadataStore, { keyPath: "path" }); |
| 400 | if (!db.objectStoreNames.contains(CoverStore)) db.createObjectStore(CoverStore, { keyPath: "path" }); |
| 401 | if (!db.objectStoreNames.contains(PlaylistStore)) db.createObjectStore(PlaylistStore, { keyPath: "name" }); |
| 402 | }; |
| 403 | req.onsuccess = () => resolve(wrapDB(req.result)); |
| 404 | }); |
| 405 | } |
| 406 | |
| 407 | interface DatabaseWrapper { |
| 408 | get(store: typeof CoverStore | typeof FileBlobStore, key: string): Promise<unknown>; |
| 409 | put(store: typeof FileBlobStore, value: StoredFileBlob): Promise<void>; |
| 410 | put(store: typeof FileMetadataStore, value: StoredFileMetadata): Promise<void>; |
| 411 | put(store: typeof CoverStore, value: StoredCover): Promise<void>; |
| 412 | put(store: typeof PlaylistStore, value: Playlist): Promise<void>; |
| 413 | add(store: typeof PlaylistStore, value: Playlist): Promise<void>; |
| 414 | delete( |
| 415 | store: typeof FileBlobStore | typeof CoverStore | typeof FileMetadataStore | typeof PlaylistStore, |
| 416 | key: string, |
| 417 | ): Promise<void>; |
| 418 | clear(store: string): Promise<void>; |
| 419 | listFiles(store: typeof FileMetadataStore): Promise<StoredFileMetadata[]>; |
| 420 | listPlaylists(store: typeof PlaylistStore): Promise<Playlist[]>; |
| 421 | } |
| 422 | |
| 423 | function wrapDB(db: IDBDatabase): DatabaseWrapper { |
| 424 | return { |
| 425 | get: (store: string, key: string) => |
| 426 | new Promise((res, rej) => { |
| 427 | const tx = db.transaction(store, "readonly"); |
| 428 | const req = tx.objectStore(store).get(key); |
| 429 | req.onsuccess = () => res(req.result); |
| 430 | req.onerror = () => rej(req.error); |
| 431 | }), |
| 432 | put: (store: string, value: unknown) => |
| 433 | new Promise<void>((res, rej) => { |
| 434 | const tx = db.transaction(store, "readwrite"); |
| 435 | const req: IDBRequest<IDBValidKey> = tx.objectStore(store).put(value); |
| 436 | req.onsuccess = () => res(); |
| 437 | req.onerror = () => rej(req.error); |
| 438 | }), |
| 439 | add: (store: string, value: unknown) => |
| 440 | new Promise<void>((res, rej) => { |
| 441 | const tx = db.transaction(store, "readwrite"); |
| 442 | const req: IDBRequest<IDBValidKey> = tx.objectStore(store).add(value); |
| 443 | req.onsuccess = () => res(); |
| 444 | req.onerror = () => rej(req.error); |
| 445 | }), |
| 446 | delete: (store: string, key: string) => |
| 447 | new Promise<void>((res, rej) => { |
| 448 | const tx = db.transaction(store, "readwrite"); |
| 449 | const req = tx.objectStore(store).delete(key); |
| 450 | req.onsuccess = () => res(); |
| 451 | req.onerror = () => rej(req.error); |
| 452 | }), |
| 453 | clear: (store: string) => |
| 454 | new Promise<void>((res, rej) => { |
| 455 | const tx = db.transaction(store, "readwrite"); |
| 456 | const req = tx.objectStore(store).clear(); |
| 457 | req.onsuccess = () => res(); |
| 458 | req.onerror = () => rej(req.error); |
| 459 | }), |
| 460 | listFiles: (store: typeof FileMetadataStore) => |
| 461 | new Promise((res, rej) => { |
| 462 | const tx = db.transaction(store, "readonly"); |
| 463 | const req = tx.objectStore(store).getAll(); |
| 464 | req.onsuccess = () => res(req.result); |
| 465 | req.onerror = () => rej(req.error); |
| 466 | }), |
| 467 | listPlaylists: (store: typeof PlaylistStore) => |
| 468 | new Promise((res, rej) => { |
| 469 | const tx = db.transaction(store, "readonly"); |
| 470 | const req = tx.objectStore(store).getAll(); |
| 471 | req.onsuccess = () => res(req.result); |
| 472 | req.onerror = () => rej(req.error); |
| 473 | }), |
| 474 | }; |
| 475 | } |
| 476 |