import type { MediaFile, Directory, FileListing, FileListingWithStatus, DirectoryWithStatus, Metadata, } from "music-server-shared/types"; import { parseMap } from "music-server-shared/mapconversion"; import type { AppOptions, Playlist } from "./types"; import { joinPath, toast, unproxy } from "./utils"; import { batch, from, untrack, type ResourceActions } from "solid-js"; import { AsyncSemaphore } from "./semaphore"; import { encodePath } from "music-server-shared/utils"; import type { FlatFileListing } from "./App"; import { createStore } from "solid-js/store"; import Dexie, { liveQuery } from "dexie"; interface StoredFile { path: string; data: Blob; metadata: Metadata; } interface StoredCover { path: string; data: Blob | null; } interface Database extends Dexie { files: Dexie.Table; covers: Dexie.Table; playlists: Dexie.Table; } const db = new Dexie("music-files") as Database; db.version(1).stores({ files: "path", covers: "path", playlists: "name", }); export type Progress = | { status: number; abort: () => void } | { status: "Aborted"; retry: () => void } | { status: "Failed"; retry: () => void; reason: string }; interface LoadingChildren { amount: number; } export type DownloadStatus = Progress | LoadingChildren | "Synced" | undefined; export const [downloadStatusMap, setDownloadStatusMap] = createStore>({}); //creates entry if it doesn't exist, so reactivity works export function getDownloadStatus(path: string): DownloadStatus { untrack(() => { if (!Object.keys(downloadStatusMap).includes(path)) setDownloadStatusMap(path, undefined); }); return downloadStatusMap[path]; } function updateRecursiveStatus(path: string, loadChange: number, includeCurrent: boolean) { function updateProgressAmount(path: string) { const currentStatus = downloadStatusMap[path]; if (typeof currentStatus !== "object" || !("amount" in currentStatus)) { setDownloadStatusMap(path, loadChange > 0 ? { amount: loadChange } : undefined); return; } const newAmount = currentStatus.amount + loadChange; setDownloadStatusMap(path, newAmount > 0 ? { amount: newAmount } : undefined); } if (includeCurrent) updateProgressAmount(path); // Update all parent directories let currentPath = path; while (true) { const lastSlash = currentPath.lastIndexOf("/"); if (lastSlash === -1) break; currentPath = currentPath.substring(0, lastSlash); updateProgressAmount(currentPath); } } function startProgress(path: string, status: DownloadStatus) { updateRecursiveStatus(path, 1, false); setDownloadStatusMap(path, status); } function stopProgress(path: string, status: DownloadStatus) { updateRecursiveStatus(path, -1, false); setDownloadStatusMap(path, status); } //initialize filetrees and download statuses from indexedDB export async function loadDataFromDB() { try { const files = await db.files.toArray(); for (const file of files) { setDownloadStatusMap(file.path, "Synced"); updateFileTree(file.path, { metadata: file.metadata }, true); } const covers = await db.covers.toArray(); for (const cover of covers) { coverCache.set(cover.path, { data: cover.data }); } } 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 typechecking 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) { db.covers.delete(basePath); //remove stored cover for this dir if there are not files left deleteInOfflineTree(basePath); } } export const clearDirectoryCache = async (path: string) => { const node = getDirInTree(path, false, false); if (!node) return; // Save existing children before clearing const preservedChildren = new Map(node.files); node.files.clear(); node.status = "Unknown"; // restore any preserved subtrees where the parent directory still exist const newListing = await listFiles(path, false, false); for (const [name, child] of preservedChildren.entries()) { if ("files" in child && newListing.has(name)) { node.files.set(name, child); } } }; async function listOnlineFiles(dir: string, recursive: boolean): Promise { const response = await fetch(`/list/${encodePath(dir)}?recursive=${recursive}`, { credentials: "same-origin" }).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); } const coverCache = new Map(); //get cover art object-url for a file or directory with cache-first strategy export async function getCover( dir: string, options: AppOptions, saveToDb: boolean, offline: boolean, forceRefresh = false, ) { try { const cached = coverCache.get(dir); if (!forceRefresh && cached !== undefined) { if (saveToDb) db.covers.add({ path: dir, data: cached.data }).catch(() => {}); return cached.data === null ? undefined : URL.createObjectURL(cached.data); } if (offline) return undefined; const response = await fetch(`/cover/${encodePath(dir)}${options.transcodeCovers ? "?transcode=true" : ""}`, { method: "GET", credentials: "same-origin", }).catch(() => {}); if (!response || response.status === 404) { coverCache.set(dir, { data: null }); if (saveToDb) db.covers.add({ path: dir, data: null }).catch(() => {}); //if cover already exists in database, update it else if (forceRefresh && db.covers.get(dir) !== undefined) db.covers.put({ path: dir, data: null }); return undefined; } const blob = await response.blob(); coverCache.set(dir, { data: blob }); if (saveToDb) db.covers.add({ path: dir, data: blob }).catch(() => {}); //if cover already exists in database, update it else if (forceRefresh && db.covers.get(dir) !== undefined) db.covers.put({ path: dir, data: blob }); return URL.createObjectURL(blob); } catch { return undefined; } } //returns an object url to the blob if synced, otherwise the server url export async function getSrc( path: string, options: AppOptions, offline: boolean, seekTo: number, forceUrl?: true, ): Promise; export async function getSrc(path: string, options: AppOptions, offline: boolean, seekTo: number, forceUrl?: boolean) { if (!forceUrl) { const dbResult = await db.files.get(path); 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))}` + `?disableChunkedTranscoding=${options.disableChunkedTranscoding}` + `&container=${options.container}` + `&audioCodec=${options.audioCodec}` + `&audioBitrate=${options.audioBitrate}` + `&videoCodec=${options.videoCodec}` + `&videoBitrate=${options.videoBitrate}` + `${seekTo === 0 ? "" : `&seekTo=${seekTo}`}` ); } return joinPath("/download", encodePath(path)); } export async function loadPlaylists() { return await db.playlists.toArray(); } //save playlist to indexedDB, throws error if playlist with that name already exists and overwrite=false export async function savePlaylist(playlist: Playlist, overwrite: boolean) { playlist.items = playlist.items.map((item) => { //some less space in the db by omitting ids return { path: item.path, metadata: unproxy(item.metadata) }; }); if (overwrite) { await db.playlists.put(playlist); } else { await db.playlists.add(playlist); } } export async function deletePlaylist(name: string) { await db.playlists.delete(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( fullPath: string, item: MediaFile | Directory, fetchFiles: ResourceActions, ) { try { if ("metadata" in item && downloadStatusMap[fullPath] !== "Synced") return; startProgress(fullPath, { amount: 1 }); let toDelete: string[]; if ("files" in item) { toDelete = collectMediaFilePaths(listOfflineFiles(fullPath), fullPath); } else { toDelete = [fullPath]; } await db.files.bulkDelete(toDelete); //delete file from database await db.covers.bulkDelete(toDelete); //delete embedded cover from database deleteInOfflineTree(fullPath); //delete node from tree batch(() => { for (const path of toDelete) { setDownloadStatusMap(path, undefined); // set all children to unsynced } }); fetchFiles.refetch(); } finally { stopProgress(fullPath, 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, redownload: boolean, ): Promise { const retry = () => downloadFile(path, options, item, fetchFiles, redownload); const controller = new AbortController(); let abortResolve!: () => void; const abortPromise = new Promise((outerResolve) => { abortResolve = () => { controller.abort(); stopProgress( path, // if it was already synced, restore it initialProgress === "Synced" ? "Synced" : { status: "Aborted", retry }, ); outerResolve(); }; }); // file already downloaded or download already in progress const initialProgress = downloadStatusMap[path]; if ( (!redownload && initialProgress === "Synced") || (typeof initialProgress === "object" && "bytes" in initialProgress) ) return; startProgress(path, { status: 0, abort: abortResolve }); try { //options might change at any point, update the semaphore to the current value downloadSemaphore.setMaxConcurrency(options.enableTranscoding ? options.maxTranscodes : options.maxDownloads); //make sure to only allow the set amount of parallel downloads const semaphorePromise = downloadSemaphore.acquire(); await Promise.race([abortPromise, semaphorePromise]); try { const res = await fetch(await getSrc(path, options, false, 0, true), { signal: controller.signal, credentials: "same-origin", }); //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(); 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; setDownloadStatusMap(path, { status: received, abort: abortResolve }); } const blob = await blobPromise; await db.files.put({ path, data: blob, metadata: unproxy(item.metadata), }); updateFileTree(path, item, true); stopProgress(path, "Synced"); fetchFiles.refetch(); //iterate through all parent directories and download their covers to database const parts = path.split("/"); while (true) { getCover(parts.join("/"), options, true, false).then((cover) => URL.revokeObjectURL(cover || "")); parts.pop(); if (parts.length === 0) break; } } finally { downloadSemaphore.release(); } } catch (e) { if (e && typeof e === "object" && "name" in e && e.name === "AbortError") return; stopProgress( path, // if it was already synced, restore it initialProgress === "Synced" ? "Synced" : { status: "Failed", reason: e ? e.toString() : "Unknown error", retry, }, ); } } export async function download( fullPath: string, item: MediaFile | Directory, options: AppOptions, fetchFiles: ResourceActions, redownload = false, ) { if ("metadata" in item) { await downloadFile(fullPath, options, item, fetchFiles, redownload || false); } else { updateRecursiveStatus(fullPath, 1, true); try { //start downloads for all children to allow them to run in parallel, then wait for the results const promises: Promise[] = []; const listing = await listFiles(fullPath, false, false); batch(() => { for (const [childName, childItem] of listing) { promises.push(download(joinPath(fullPath, childName), childItem, options, fetchFiles, redownload)); } }); await Promise.allSettled(promises); } finally { updateRecursiveStatus(fullPath, -1, true); } } } export const storedFilesLive = from( liveQuery(async () => await db.files.toCollection().keys()), [], );