import type { AudioFile, Directory, FileListing } from "music-server-shared/types"; import type { AppOptions } from "./types"; import { joinPath, toast } from "./utils"; import { createSignal, type ResourceActions, type Signal } from "solid-js"; interface CachedFile { duration: number; } interface Progress { bytes: number; } export type SignalMapEntry = undefined | Progress | "DirectoryProgress" | "CachedFile"; export const signalMap = new Map>(); const metaDataMap = new Map(); export async function fillSignalCache() { try { const db = await openDB(); const files = await db.listFiles(FileMetadataStore); for (const file of files) { signalMap.set(file.path, createSignal("CachedFile")); metaDataMap.set(file.path, file.duration); } } catch (e) { toast("Loading offline files failed", "error", e); console.error(e); } } type FileEntry = { name: string } & ({ type: "Directory" } | { type: "File"; duration: number }); const directoryCache = new Map(); export const clearDirectoryCache = (path: string) => directoryCache.delete(path); async function requestFileList(dir: string, recursive: boolean): Promise { const response = await fetch(`/list/${dir}?recursive=${recursive}`).catch(() => {}); if (response?.status === 404) { toast(`Directory not found: ${dir}`, "error"); return; } if (!response || !response.ok) { toast(`Fetching files for ${dir} failed${response ? `: ${response.statusText}` : ""}`, "error"); return; } const data: Directory = await response.json(); return data.files; } function saveFileListToCache(basePath: string, files: FileListing, recursive: boolean) { const converted: FileEntry[] = files.map((item) => { if ("files" in item) { if (recursive) saveFileListToCache(joinPath(basePath, item.name), item.files, true); return { ...item, type: "Directory" }; } return { ...item, type: "File" }; }); directoryCache.set(basePath, converted); } function cachedToDirectory(fullPath: string, entries: FileEntry[] | undefined, recursive: boolean): FileListing | null { if (!entries) return null; const result = []; for (const item of entries) { const newPath = joinPath(fullPath, item.name); let children = undefined; if (item.type !== "File") { children = recursive ? cachedToDirectory(newPath, directoryCache.get(newPath), true) : []; if (!children) return null; result.push({ name: item.name, files: children }); } else { result.push({ name: item.name, duration: item.duration }); } } return result; } interface TreeDir { dirs: Map; files: Map; } function buildOfflineTree(): TreeDir { const root: TreeDir = { dirs: new Map(), files: new Map() }; for (const [path, duration] of metaDataMap.entries()) { const parts = path.split("/"); let node = root; for (let i = 0; i < parts.length - 1; ++i) { const part = parts[i]; let nextNodes = node.dirs.get(part); if (!nextNodes) { nextNodes = { dirs: new Map(), files: new Map() }; node.dirs.set(part, nextNodes); } node = nextNodes; } const filename = parts[parts.length - 1]; node.files.set(filename, { name: filename, duration }); } return root; } /** * Returns a directory listing mimicking the real filesystem, * based entirely on in-memory offlineCache keys. * @param dir Directory path, "" for root, else e.g. "a/b" * @param recursive Whether to expand subdirectories recursively. * @returns (Array of AudioFile | Directory) */ function listOfflineFiles(targetDir: string, recursive: boolean): FileListing { const tree = buildOfflineTree(); // Normalize targetDir and walk down the tree const normParts = targetDir === "" ? [] : targetDir.split("/").filter(Boolean); let node = tree; for (const part of normParts) { const next = node.dirs.get(part); if (!next) return []; node = next; } // Now node corresponds to the directory we're listing function dirEntries(n: TreeDir): FileListing { const dirs: Directory[] = []; for (const [name, childDir] of n.dirs) { dirs.push({ name, files: recursive ? dirEntries(childDir) : [], }); } const files: AudioFile[] = []; for (const [name, f] of n.files) { files.push({ name, duration: f.duration }); } return [...dirs, ...files].sort((a, b) => a.name.localeCompare(b.name)); } return dirEntries(node); } export async function listFiles(dir: string, offline: boolean, recursive: boolean): Promise { if (offline) { return listOfflineFiles(dir, recursive); } const cached = cachedToDirectory(dir, directoryCache.get(dir), recursive); if (cached !== null) return cached; const files = await requestFileList(dir, recursive); if (!files) return []; saveFileListToCache(dir, files, recursive); return files; } export async function getCover(dir: string, offline: boolean) { const db = await openDB(); const dbResult = await db.get(CoverStore, dir); if (dbResult !== undefined) { const cached = dbResult as StoredCover; return cached.data === null ? undefined : URL.createObjectURL(new Blob([cached.data])); } if (offline) return undefined; const response = await fetch(`/cover/${dir}`, { method: "GET" }).catch(() => {}); if (!response || response.status === 404) { db.put(CoverStore, { path: dir, data: null }); return undefined; } const blob = await response.blob(); db.put(CoverStore, { path: dir, data: new Uint8Array(await blob.arrayBuffer()) }); return URL.createObjectURL(blob); } export const clearCoverCache = async (path: string) => { const db = await openDB(); return db.delete(CoverStore, path); }; export async function getSrc(path: string, options: AppOptions) { const db = await openDB(); const dbResult = (await db.get(FileBlobStore, path)) as StoredFileBlob; if (dbResult) return URL.createObjectURL(new Blob([dbResult.data])); if (options.enableTranscoding) { return `${joinPath("/transcode", path)}?bitrate=${options.bitrate}`; } return joinPath("/download", path); } async function downloadFile( path: string, progressSignal: Signal, options: AppOptions, duration: number, fetchFiles: ResourceActions, ): Promise { const [getProgress, setProgress] = progressSignal; const progress = getProgress(); if (typeof progress === "object" && "bytes" in progress) return; // download already in progress const db = await openDB(); try { setProgress({ bytes: 0 }); let res: Response; if (options.enableTranscoding) { res = await fetch(`${joinPath("/transcode", path)}?bitrate=${options.bitrate}`); } else { res = await fetch(joinPath("/download", path)); } if (!res.ok || !res.body) throw res.statusText; const reader = res.body.getReader(); const chunks: Uint8Array[] = []; let received = 0; let lastUpdate = 0; while (true) { const { done, value } = await reader.read(); if (done) break; chunks.push(value); received += value.length; const now = Date.now(); if (now - lastUpdate < 100) continue; lastUpdate = now; setTimeout(() => { setProgress({ bytes: received }); }, 0); } const data = concatChunks(chunks); await db.put(FileBlobStore, { path, data, } as StoredFileBlob); await db.put(FileMetadataStore, { path, duration, } as StoredFileMetadata); metaDataMap.set(path, duration); setProgress("CachedFile"); fetchFiles.refetch(); } catch (e) { toast(`Downloading ${path} failed`, "error", e); setProgress(undefined); } } export async function deleteItem( item: AudioFile | Directory, basePath: string, fetchFiles: ResourceActions, //allows triggering reloads in the file view listing?: FileListing, ) { const fullPath = joinPath(basePath, item.name); const signal = signalMap.get(fullPath); if (!signal) return; const [getProgress, setProgress] = signal; const isFile = "duration" in item; if (isFile && getProgress() !== "CachedFile") return; if (!isFile) { const newBasePath = joinPath(basePath, item.name); const result = listing ?? listOfflineFiles(newBasePath, true); for (const childItem of result) { deleteItem(childItem, newBasePath, fetchFiles, "files" in childItem ? childItem.files : undefined); } } const db = await openDB(); await db.delete(FileBlobStore, fullPath); await db.delete(FileMetadataStore, fullPath); metaDataMap.delete(fullPath); setProgress(undefined); //TODO: check if current directory shown includes this file, otherwise we uncessesarily refresh the view //idea: maybe make files a signal, sync it to the resource with a create effect, and we just overwrite the signal with the new item here fetchFiles.refetch(); } /** * Download an AudioFile or Directory to local IndexedDB recursively. */ export async function download( item: AudioFile | Directory, basePath: string, options: AppOptions, fetchFiles: ResourceActions, listing?: FileListing, ) { const fullPath = joinPath(basePath, item.name); let signal = signalMap.get(fullPath); if (!signal) { signal = createSignal(); signalMap.set(fullPath, signal); } const [, setProgress] = signal; if ("duration" in item) { await downloadFile(fullPath, signal, options, item.duration, fetchFiles); } else { getCover(fullPath, false); setProgress("DirectoryProgress"); try { const result = listing ?? (await listFiles(fullPath, false, true)); for (const childItem of result) { await download(childItem, fullPath, options, fetchFiles, "files" in childItem ? childItem.files : undefined); } } finally { setProgress(undefined); } } } interface StoredFileBlob { path: string; data: Uint8Array; } interface StoredFileMetadata { path: string; duration: number; } interface StoredCover { path: string; data: Uint8Array | null; } const FileBlobStore = "fileblobs"; const FileMetadataStore = "filemetadata"; const CoverStore = "covers"; async function openDB() { return new Promise((resolve, reject) => { const req = indexedDB.open("music-files"); req.onerror = () => reject(req.error); req.onupgradeneeded = () => { const db = req.result; if (!db.objectStoreNames.contains(FileBlobStore)) db.createObjectStore(FileBlobStore, { keyPath: "path" }); if (!db.objectStoreNames.contains(FileMetadataStore)) db.createObjectStore(FileMetadataStore, { keyPath: "path" }); if (!db.objectStoreNames.contains(CoverStore)) db.createObjectStore(CoverStore, { keyPath: "path" }); }; req.onsuccess = () => resolve(wrapDB(req.result)); }); } interface DatabaseWrapper { get(store: typeof CoverStore, key: string): Promise; get(store: typeof FileBlobStore, key: string): Promise; put(store: typeof FileBlobStore, value: StoredFileBlob): Promise; put(store: typeof FileMetadataStore, value: StoredFileMetadata): Promise; put(store: typeof CoverStore, value: StoredCover): Promise; delete(store: string, key: string): Promise; clear(store: string): Promise; listFiles(store: typeof FileMetadataStore): Promise; } function wrapDB(db: IDBDatabase): DatabaseWrapper { return { get: (store: string, key: string) => new Promise((res, rej) => { const tx = db.transaction(store, "readonly"); const req = tx.objectStore(store).get(key); req.onsuccess = () => res(req.result); req.onerror = () => rej(req.error); }), put: (store: string, value: unknown) => new Promise((res, rej) => { const tx = db.transaction(store, "readwrite"); const req: IDBRequest = tx.objectStore(store).put(value); req.onsuccess = () => res(); req.onerror = () => rej(req.error); }), delete: (store: string, key: string) => new Promise((res, rej) => { const tx = db.transaction(store, "readwrite"); const req = tx.objectStore(store).delete(key); req.onsuccess = () => res(); req.onerror = () => rej(req.error); }), clear: (store: string) => new Promise((res, rej) => { const tx = db.transaction(store, "readwrite"); const req = tx.objectStore(store).clear(); req.onsuccess = () => res(); req.onerror = () => rej(req.error); }), listFiles: (store: typeof FileMetadataStore) => new Promise((res, rej) => { const tx = db.transaction(store, "readonly"); const req = tx.objectStore(store).getAll(); req.onsuccess = () => res(req.result); req.onerror = () => rej(req.error); }), }; } function concatChunks(chunks: Uint8Array[]): Uint8Array { let total = 0; for (const c of chunks) total += c.length; const result = new Uint8Array(total); let offset = 0; for (const c of chunks) { result.set(c, offset); offset += c.length; } return result; }