import type { MediaFile, Directory, FileListing, FileListingWithStatus, DirectoryWithStatus, } from "music-server-shared/types"; import { parseMap } from "music-server-shared/mapconversion"; import type { AppOptions, Playlist, PlaylistItem } from "./types"; import { joinPath, toast } from "./utils"; import { createSignal, type ResourceActions, type Signal } from "solid-js"; import { AsyncSemaphore } from "./semaphore"; import { encodePath } from "music-server-shared/utils"; import type { FlatFileListing } from "./App"; interface Progress { bytes: number; } interface LoadingItems { amount: number; } export type DownloadStatus = Progress | LoadingItems | "Synced" | undefined; //used to display download status for directories/files in the filebrowser view // export const [downloadStatusMap, setDownloadStatusMap] = createStore>({}); export interface StatusWithChildren { status: Signal; children?: RecursiveStatus; } type RecursiveStatus = Map; const downloadStatusMap: RecursiveStatus = new Map(); function updateProgressAmount(statusSignal: Signal, loadChange: number) { const [getStatus, setStatus] = statusSignal; let status = getStatus(); if (typeof status !== "object" || !("amount" in status)) { status = { amount: 0 }; setStatus(status); } const newAmount = status.amount + loadChange; if (newAmount > 0) setStatus({ amount: newAmount }); else setStatus(undefined); } export function getDownloadStatus(path: string, loadChange?: number) { const parts = path.split("/"); let current = downloadStatusMap; //iterate through the basepath for (const part of parts.slice(0, -1)) { let next = current.get(part); if (!next) { next = { status: createSignal(undefined) }; current.set(part, next); } if (!next.children) { //might be a directory whose children have not been referenced before, in which case "children" would be undefined next.children = new Map(); } if (loadChange) updateProgressAmount(next.status, loadChange); current = next.children as RecursiveStatus; } const fileName = parts.toReversed()[0]; let ret = current.get(fileName); if (!ret) { ret = { status: createSignal(undefined) }; current.set(fileName, ret); } return ret.status; } //increase/decrease load amount for all parents and return requested signal //needed to set parent directories to a loading state when any child is being downloaded/deleted function startProgress(path: string) { return getDownloadStatus(path, 1); } function stopProgress(path: string) { return getDownloadStatus(path, -1); } //initialize filetrees and download statuses from indexedDB export async function loadDataFromDB() { try { const db = await openDB(); const files = await db.listFiles(FileStore); for (const file of files) { getDownloadStatus(file.path)[1]("Synced"); updateFileTree(file.path, { metadata: file.metadata }, true); } } catch (e) { toast("Loading offline files failed", "error", e); console.error(e); } } //contains all locally synced files const offlineTreeRoot: Directory = { files: new Map(), }; //used for caching online file listings const onlineTreeRoot: DirectoryWithStatus = { files: new Map(), status: "Unknown", }; //merges "Scanned" directories from "other" to "target" function mergeTrees(target: DirectoryWithStatus, other: DirectoryWithStatus) { if (other.status === "Unknown") return; target.status = other.status; for (const [fileName, file] of other.files.entries()) { const targetFile = target.files.get(fileName); if (targetFile && "files" in targetFile && "files" in file) { mergeTrees(targetFile, file); } else { target.files.set(fileName, file); } } } //TODO: improve typing to avoid "as" //overloads for typecheking //offline tree only stores files, directories are created ad-hoc function updateFileTree(path: string, file: MediaFile, offline: true): void; //online tree only stores cached directory listings function updateFileTree(path: string, file: DirectoryWithStatus, offline: false): void; // Updates file tree structure with new data (offline or online) function updateFileTree(path: string, file: DirectoryWithStatus | MediaFile, offline: boolean) { if (offline && path === "") throw new Error("Trying to update root in offline mode"); const basePath = path.split("/").slice(0, -1).join("/"); const fileName = path.split("/").toReversed()[0]; const node = getDirInTree(basePath, true, offline); if (offline) { node.files.set(fileName, file); } else { if (path === "") mergeTrees(node as DirectoryWithStatus, file as DirectoryWithStatus); else { let target = node.files.get(fileName) as DirectoryWithStatus; if (!target) target = { files: new Map(), status: "Unknown" }; mergeTrees(target as DirectoryWithStatus, file as DirectoryWithStatus); node.files.set(fileName, target); } } } //overloads for typecheking function getDirInTree(path: string, create: true, offline: true): Directory; function getDirInTree(path: string, create: true, offline: false): DirectoryWithStatus; function getDirInTree(path: string, create: false, offline: true): Directory | null; function getDirInTree(path: string, create: false, offline: false): DirectoryWithStatus | null; function getDirInTree(path: string, create: true, offline: boolean): DirectoryWithStatus | Directory; function getDirInTree(path: string, create: false, offline: boolean): DirectoryWithStatus | Directory | null; // get a DirectoryNode from the directory tree matching the path, and optionally creating missing nodes it if they don't exist yet function getDirInTree(path: string, create: boolean, offline: boolean): DirectoryWithStatus | Directory | null { let current = offline ? offlineTreeRoot : onlineTreeRoot; if (path === "") return current; const parts = path.split("/"); for (const part of parts) { let next: DirectoryWithStatus | Directory | MediaFile | undefined = current.files.get(part); if (!next || "metadata" in next) { if (!create) return null; //if mediafile already exists, we overwrite it with a directory anyway if (offline) next = { files: new Map() }; else next = { files: new Map(), status: "Unknown" }; current.files.set(part, next); } current = next; } return current; } function deleteInOfflineTree(path: string): void { if (path === "") return; const basePath = path.split("/").slice(0, -1).join("/"); const fileName = path.split("/").toReversed()[0]; const node = getDirInTree(basePath, false, true); if (!node) return; node.files.delete(fileName); if (node.files.size === 0) deleteInOfflineTree(basePath); } export const clearDirectoryCache = (path: string) => { const node = getDirInTree(path, false, false); if (!node) return; node.files.clear(); node.status = "Unknown"; }; async function listOnlineFiles(dir: string, recursive: boolean): Promise { const response = await fetch(`/list/${encodePath(dir)}?recursive=${recursive}`).catch(() => {}); if (response?.status === 404) { toast(`Directory not found: ${dir}`, "error"); return; } if (!response || !response.ok) { toast( `Fetching files for ${dir === "" ? "root" : dir} failed${response ? `: ${response.statusText}` : ""}`, "error", ); return; } return parseMap(await response.text()) as FileListingWithStatus; } function listOfflineFiles(dir: string): FileListing { const node = getDirInTree(dir, false, true); if (!node || !node.files) return new Map(); return node.files; } //checks if this Directory is completely scanned, i.e. suitable for a recursive listing result function fullyKnown(dir: DirectoryWithStatus) { if (dir.status === "Unknown") { return false; } if (dir.files.values().some((value) => "files" in value && !fullyKnown(value))) { return false; } return true; } //non-recursive listing should not include nested children function pruneChildren(listing: FileListing) { const pruned = new Map(); for (const [name, item] of listing.entries()) { if ("metadata" in item) pruned.set(name, item); else pruned.set(name, { files: new Map() }); } return pruned; } //used for combining the online and offline results, to be able to show files that only exist locally function combineFileListings(listing1: FileListing, listing2: FileListing): FileListing { const result = new Map(listing1); for (const [key, value2] of listing2.entries()) { const value1 = result.get(key); if (value1 && "files" in value1 && "files" in value2) { result.set(key, { files: combineFileListings(value1.files, value2.files) }); } else { result.set(key, value2); } } return result; } // File listing logic with hybrid online/offline support // Combines: // 1. Direct IndexedDB lookups for offline mode // 2. Cached online listings // 3. Merged online+offline results export async function listFiles(dir: string, offline: boolean, recursive: boolean): Promise { if (offline) { const files = listOfflineFiles(dir); return recursive ? files : pruneChildren(files); } const cached = getDirInTree(dir, false, false); if (cached !== null && cached.status === "Scanned" && (!recursive || fullyKnown(cached))) { const combined = combineFileListings(cached.files, listOfflineFiles(dir)); return recursive ? combined : pruneChildren(combined); } const files = await listOnlineFiles(dir, recursive); if (!files) return new Map(); updateFileTree(dir, { files, status: "Scanned" }, false); const combined = combineFileListings(files, listOfflineFiles(dir)); return recursive ? combined : pruneChildren(combined); } //get cover art for a directory with cache-first strategy 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/${encodePath(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: blob }); return URL.createObjectURL(blob); } export const clearCoverCache = async (path: string) => { const db = await openDB(); return db.delete(CoverStore, path); }; //returns an object url to the blob if synced, otherwise the server url export async function getSrc(path: string, options: AppOptions, offline: boolean, forceUrl?: true): Promise; export async function getSrc(path: string, options: AppOptions, offline: boolean, forceUrl?: boolean) { if (!forceUrl) { const db = await openDB(); const dbResult = (await db.get(FileStore, path)) as StoredFile; if (dbResult) return URL.createObjectURL(dbResult.data); if (offline) { toast("This file is not cached, leave offline mode to play it", "error"); return undefined; } } if (options.enableTranscoding) { return `${joinPath("/transcode", encodePath(path))}?bitrate=${options.bitrate}&format=${options.format}&disableChunkedTranscoding=${options.disableChunkedTranscoding}`; } return joinPath("/download", encodePath(path)); } export async function loadPlaylists() { const db = await openDB(); return await db.listPlaylists(PlaylistStore); } //save playlist to indexedDB, throws error if playlist with that name already exists and overwrite=false export async function savePlaylist(playlist: Playlist, overwrite: boolean) { const db = await openDB(); playlist.items = playlist.items.map((item) => { //some less space in the db by omitting ids const { id, ...itemWithoutId } = item as PlaylistItem; return itemWithoutId; }); if (overwrite) await db.put(PlaylistStore, playlist); else await db.add(PlaylistStore, playlist); } export async function deletePlaylist(name: string) { const db = await openDB(); await db.delete(PlaylistStore, name); } function collectMediaFilePaths(listing: FileListing, basePath: string): string[] { const paths: string[] = []; for (const [name, item] of listing.entries()) { const currentPath = joinPath(basePath, name); if ("metadata" in item) { paths.push(currentPath); } else if ("files" in item) { paths.push(...collectMediaFilePaths(item.files, currentPath)); } } return paths; } //deletes file or directory(+recursive contents) from indexedDB and updates their download statuses export async function deleteFile( fileName: string, item: MediaFile | Directory, basePath: string, fetchFiles: ResourceActions, ) { const fullPath = joinPath(basePath, fileName); const [getStatus] = getDownloadStatus(fullPath); try { if ("metadata" in item && getStatus() !== "Synced") return; startProgress(fullPath)[1]({ amount: 1 }); let toDelete: string[]; if ("files" in item) { toDelete = collectMediaFilePaths(listOfflineFiles(fullPath), fullPath); } else { toDelete = [fullPath]; } const db = await openDB(); await db.deleteAll(FileStore, toDelete); //delete from database deleteInOfflineTree(fullPath); //delete node from tree for (const path of toDelete) { getDownloadStatus(path)[1](undefined); // set all children to unsynced } fetchFiles.refetch(); } finally { stopProgress(fullPath)[1](undefined); } } const downloadSemaphore = new AsyncSemaphore(1); //Download file to indexedDB and updates the offline file tree //concurrency control via the downloadSemaphore async function downloadFile( path: string, options: AppOptions, item: MediaFile, fetchFiles: ResourceActions, ): Promise { const [getStatus, setStatus] = getDownloadStatus(path); const initialProgress = getStatus(); if (typeof initialProgress === "object" && "bytes" in initialProgress) return; // download already in progress try { startProgress(path)[1]({ bytes: 0 }); const db = await openDB(); let mimeType: string | undefined; //options might change at any point, update the semaphore to the current value downloadSemaphore.setMaxConcurrency(options.enableTranscoding ? options.maxTranscodes : options.maxDownloads); let blob: Blob; try { //make sure to only allow the set amount of parallel downloads await downloadSemaphore.acquire(); const res = await fetch(await getSrc(path, options, false, true)); //let the browser do the actual download const blobPromise = res.clone().blob(); if (!res.ok || !res.body) throw res.statusText; //we just iterate over the chunks to get the current progress const reader = res.body.getReader(); mimeType = res.headers.get("content-type") ?? undefined; let received = 0; let lastUpdate = 0; while (true) { const { done, value } = await reader.read(); if (done) break; received += value.length; //debouncing logic to not update UI too fast const now = Date.now(); if (now - lastUpdate < 250) continue; lastUpdate = now; setStatus({ bytes: received }); } blob = await blobPromise; } finally { downloadSemaphore.release(); } await db.put(FileStore, { path, data: blob, metadata: { ...item.metadata }, //spread needed, because item might be a proxy object from the filebrowser, which can't be stored } as StoredFile); updateFileTree(path, item, true); stopProgress(path)[1]("Synced"); fetchFiles.refetch(); } catch (e) { toast(`Downloading ${path} failed`, "error", e); //restore original status stopProgress(path)[1](initialProgress === "Synced" ? "Synced" : undefined); } } export async function download( fileName: string, item: MediaFile | Directory, basePath: string, options: AppOptions, fetchFiles: ResourceActions, ) { const fullPath = joinPath(basePath, fileName); if ("metadata" in item) { await downloadFile(fullPath, options, item, fetchFiles); } else { updateProgressAmount(startProgress(fullPath), 1); try { await getCover(fullPath, false); //start downloads for all children to allow them to run in parallel, then wait for the results const promises: Promise[] = []; for (const [childName, childItem] of await listFiles(fullPath, false, false)) { promises.push(download(childName, childItem, fullPath, options, fetchFiles)); } await Promise.allSettled(promises); } finally { updateProgressAmount(stopProgress(fullPath), -1); } } } export async function getStoredFiles() { const db = await openDB(); return await db.getKeys(FileStore); } interface StoredFile { path: string; data: Blob; metadata: { duration: number; }; } interface StoredCover { path: string; data: Blob | null; } const FileStore = "fileblobs"; const CoverStore = "covers"; const PlaylistStore = "playlists"; 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(FileStore)) db.createObjectStore(FileStore, { keyPath: "path" }).createIndex("index", "path", { unique: true }); if (!db.objectStoreNames.contains(CoverStore)) db.createObjectStore(CoverStore, { keyPath: "path" }).createIndex("index", "path", { unique: true }); if (!db.objectStoreNames.contains(PlaylistStore)) db.createObjectStore(PlaylistStore, { keyPath: "path" }).createIndex("index", "path", { unique: true }); }; req.onsuccess = () => resolve(wrapDB(req.result)); }); } interface DatabaseWrapper { get(store: typeof CoverStore | typeof FileStore, key: string): Promise; put(store: typeof FileStore, value: StoredFile): Promise; put(store: typeof CoverStore, value: StoredCover): Promise; put(store: typeof PlaylistStore, value: Playlist): Promise; add(store: typeof PlaylistStore, value: Playlist): Promise; delete(store: typeof CoverStore | typeof PlaylistStore, key: string): Promise; deleteAll(store: typeof FileStore, keys: string[]): Promise; clear(store: string): Promise; listFiles(store: typeof FileStore): Promise; listPlaylists(store: typeof PlaylistStore): Promise; getKeys(store: typeof FileStore): 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); }), add: (store: string, value: unknown) => new Promise((res, rej) => { const tx = db.transaction(store, "readwrite"); const req: IDBRequest = tx.objectStore(store).add(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); }), deleteAll: (store: typeof FileStore, keys: string[]) => new Promise((res, rej) => { const tx = db.transaction(store, "readwrite"); const objectStore = tx.objectStore(store); for (const key of keys) { objectStore.delete(key); } tx.oncomplete = () => res(); tx.onerror = () => rej(tx.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 FileStore) => 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); }), listPlaylists: (store: typeof PlaylistStore) => 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); }), getKeys: (store: typeof FileStore) => new Promise((res, rej) => { const tx = db.transaction(store, "readonly"); const req = tx.objectStore(store).getAllKeys(); req.onsuccess = () => res(req.result as string[]); req.onerror = () => rej(req.error); }), }; }