offline.ts
⎇
Raw
1import type {
2 MediaFile,
3 Directory,
4 FileListing,
5 FileListingWithStatus,
6 DirectoryWithStatus,
7 Metadata,
8} from "music-server-shared/types";
9import { parseMap } from "music-server-shared/mapconversion";
10import type { AppOptions, Playlist } from "./types";
11import { joinPath, toast, unproxy } from "./utils";
12import { batch, from, untrack, type ResourceActions } from "solid-js";
13import { AsyncSemaphore } from "./semaphore";
14import { encodePath } from "music-server-shared/utils";
15import type { FlatFileListing } from "./App";
16import { createStore } from "solid-js/store";
17import Dexie, { liveQuery } from "dexie";
18
19interface StoredFile {
20 path: string;
21 data: Blob;
22 metadata: Metadata;
23}
24
25interface StoredCover {
26 path: string;
27 data: Blob | null;
28}
29
30interface Database extends Dexie {
31 files: Dexie.Table<StoredFile, string>;
32 covers: Dexie.Table<StoredCover, string>;
33 playlists: Dexie.Table<Playlist, string>;
34}
35
36const db = new Dexie("music-files") as Database;
37db.version(1).stores({
38 files: "path",
39 covers: "path",
40 playlists: "name",
41});
42
43export type Progress =
44 | { status: number; abort: () => void }
45 | { status: "Aborted"; retry: () => void }
46 | { status: "Failed"; retry: () => void; reason: string };
47
48interface LoadingChildren {
49 amount: number;
50}
51
52export type DownloadStatus = Progress | LoadingChildren | "Synced" | undefined;
53export const [downloadStatusMap, setDownloadStatusMap] = createStore<Record<string, DownloadStatus>>({});
54
55//creates entry if it doesn't exist, so reactivity works
56export function getDownloadStatus(path: string): DownloadStatus {
57 untrack(() => {
58 if (!Object.keys(downloadStatusMap).includes(path)) setDownloadStatusMap(path, undefined);
59 });
60 return downloadStatusMap[path];
61}
62
63function updateRecursiveStatus(path: string, loadChange: number, includeCurrent: boolean) {
64 function updateProgressAmount(path: string) {
65 const currentStatus = downloadStatusMap[path];
66 if (typeof currentStatus !== "object" || !("amount" in currentStatus)) {
67 setDownloadStatusMap(path, loadChange > 0 ? { amount: loadChange } : undefined);
68 return;
69 }
70
71 const newAmount = currentStatus.amount + loadChange;
72 setDownloadStatusMap(path, newAmount > 0 ? { amount: newAmount } : undefined);
73 }
74
75 if (includeCurrent) updateProgressAmount(path);
76 // Update all parent directories
77 let currentPath = path;
78 while (true) {
79 const lastSlash = currentPath.lastIndexOf("/");
80 if (lastSlash === -1) break;
81 currentPath = currentPath.substring(0, lastSlash);
82 updateProgressAmount(currentPath);
83 }
84}
85
86function startProgress(path: string, status: DownloadStatus) {
87 updateRecursiveStatus(path, 1, false);
88 setDownloadStatusMap(path, status);
89}
90
91function stopProgress(path: string, status: DownloadStatus) {
92 updateRecursiveStatus(path, -1, false);
93 setDownloadStatusMap(path, status);
94}
95
96//initialize filetrees and download statuses from indexedDB
97export async function loadDataFromDB() {
98 try {
99 const files = await db.files.toArray();
100 for (const file of files) {
101 setDownloadStatusMap(file.path, "Synced");
102 updateFileTree(file.path, { metadata: file.metadata }, true);
103 }
104 const covers = await db.covers.toArray();
105 for (const cover of covers) {
106 coverCache.set(cover.path, { data: cover.data });
107 }
108 } catch (e) {
109 toast("Loading offline files failed", "error", e);
110 console.error(e);
111 }
112}
113
114//contains all locally synced files
115const offlineTreeRoot: Directory = {
116 files: new Map(),
117};
118//used for caching online file listings
119const onlineTreeRoot: DirectoryWithStatus = {
120 files: new Map(),
121 status: "Unknown",
122};
123
124//merges "Scanned" directories from "other" to "target"
125function mergeTrees(target: DirectoryWithStatus, other: DirectoryWithStatus) {
126 if (other.status === "Unknown") return;
127 target.status = other.status;
128 for (const [fileName, file] of other.files.entries()) {
129 const targetFile = target.files.get(fileName);
130 if (targetFile && "files" in targetFile && "files" in file) {
131 mergeTrees(targetFile, file);
132 } else {
133 target.files.set(fileName, file);
134 }
135 }
136}
137
138//TODO: improve typing to avoid "as"
139//overloads for typecheking
140//offline tree only stores files, directories are created ad-hoc
141function updateFileTree(path: string, file: MediaFile, offline: true): void;
142//online tree only stores cached directory listings
143function updateFileTree(path: string, file: DirectoryWithStatus, offline: false): void;
144// Updates file tree structure with new data (offline or online)
145function updateFileTree(path: string, file: DirectoryWithStatus | MediaFile, offline: boolean) {
146 if (offline && path === "") throw new Error("Trying to update root in offline mode");
147 const basePath = path.split("/").slice(0, -1).join("/");
148 const fileName = path.split("/").toReversed()[0];
149 const node = getDirInTree(basePath, true, offline);
150
151 if (offline) {
152 node.files.set(fileName, file);
153 } else {
154 if (path === "") mergeTrees(node as DirectoryWithStatus, file as DirectoryWithStatus);
155 else {
156 let target = node.files.get(fileName) as DirectoryWithStatus;
157 if (!target) target = { files: new Map(), status: "Unknown" };
158 mergeTrees(target as DirectoryWithStatus, file as DirectoryWithStatus);
159 node.files.set(fileName, target);
160 }
161 }
162}
163
164//overloads for typechecking
165function getDirInTree(path: string, create: true, offline: true): Directory;
166function getDirInTree(path: string, create: true, offline: false): DirectoryWithStatus;
167function getDirInTree(path: string, create: false, offline: true): Directory | null;
168function getDirInTree(path: string, create: false, offline: false): DirectoryWithStatus | null;
169function getDirInTree(path: string, create: true, offline: boolean): DirectoryWithStatus | Directory;
170function getDirInTree(path: string, create: false, offline: boolean): DirectoryWithStatus | Directory | null;
171// get a DirectoryNode from the directory tree matching the path, and optionally creating missing nodes it if they don't exist yet
172function getDirInTree(path: string, create: boolean, offline: boolean): DirectoryWithStatus | Directory | null {
173 let current = offline ? offlineTreeRoot : onlineTreeRoot;
174 if (path === "") return current;
175 const parts = path.split("/");
176
177 for (const part of parts) {
178 let next: DirectoryWithStatus | Directory | MediaFile | undefined = current.files.get(part);
179 if (!next || "metadata" in next) {
180 if (!create) return null;
181 //if mediafile already exists, we overwrite it with a directory anyway
182 if (offline) next = { files: new Map() };
183 else next = { files: new Map(), status: "Unknown" };
184 current.files.set(part, next);
185 }
186 current = next;
187 }
188 return current;
189}
190
191function deleteInOfflineTree(path: string): void {
192 if (path === "") return;
193 const basePath = path.split("/").slice(0, -1).join("/");
194 const fileName = path.split("/").toReversed()[0];
195
196 const node = getDirInTree(basePath, false, true);
197 if (!node) return;
198
199 node.files.delete(fileName);
200 if (node.files.size === 0) {
201 db.covers.delete(basePath); //remove stored cover for this dir if there are not files left
202 deleteInOfflineTree(basePath);
203 }
204}
205
206export const clearDirectoryCache = async (path: string) => {
207 const node = getDirInTree(path, false, false);
208 if (!node) return;
209
210 // Save existing children before clearing
211 const preservedChildren = new Map(node.files);
212
213 node.files.clear();
214 node.status = "Unknown";
215
216 // restore any preserved subtrees where the parent directory still exist
217 const newListing = await listFiles(path, false, false);
218 for (const [name, child] of preservedChildren.entries()) {
219 if ("files" in child && newListing.has(name)) {
220 node.files.set(name, child);
221 }
222 }
223};
224async function listOnlineFiles(dir: string, recursive: boolean): Promise<FileListingWithStatus | undefined> {
225 const response = await fetch(`/list/${encodePath(dir)}?recursive=${recursive}`, { credentials: "same-origin" }).catch(
226 () => {},
227 );
228 if (response?.status === 404) {
229 toast(`Directory not found: ${dir}`, "error");
230 return;
231 }
232 if (!response || !response.ok) {
233 toast(
234 `Fetching files for ${dir === "" ? "root" : dir} failed${response ? `: ${response.statusText}` : ""}`,
235 "error",
236 );
237 return;
238 }
239
240 return parseMap(await response.text()) as FileListingWithStatus;
241}
242
243function listOfflineFiles(dir: string): FileListing {
244 const node = getDirInTree(dir, false, true);
245 if (!node || !node.files) return new Map();
246 return node.files;
247}
248
249//checks if this Directory is completely scanned, i.e. suitable for a recursive listing result
250function fullyKnown(dir: DirectoryWithStatus) {
251 if (dir.status === "Unknown") {
252 return false;
253 }
254 if (dir.files.values().some((value) => "files" in value && !fullyKnown(value))) {
255 return false;
256 }
257 return true;
258}
259
260//non-recursive listing should not include nested children
261function pruneChildren(listing: FileListing) {
262 const pruned = new Map();
263 for (const [name, item] of listing.entries()) {
264 if ("metadata" in item) pruned.set(name, item);
265 else pruned.set(name, { files: new Map() });
266 }
267 return pruned;
268}
269
270//used for combining the online and offline results, to be able to show files that only exist locally
271function combineFileListings(listing1: FileListing, listing2: FileListing): FileListing {
272 const result = new Map(listing1);
273
274 for (const [key, value2] of listing2.entries()) {
275 const value1 = result.get(key);
276
277 if (value1 && "files" in value1 && "files" in value2) {
278 result.set(key, { files: combineFileListings(value1.files, value2.files) });
279 } else {
280 result.set(key, value2);
281 }
282 }
283
284 return result;
285}
286
287// File listing logic with hybrid online/offline support
288// Combines:
289// 1. Direct IndexedDB lookups for offline mode
290// 2. Cached online listings
291// 3. Merged online+offline results
292export async function listFiles(dir: string, offline: boolean, recursive: boolean): Promise<FileListing> {
293 if (offline) {
294 const files = listOfflineFiles(dir);
295 return recursive ? files : pruneChildren(files);
296 }
297 const cached = getDirInTree(dir, false, false);
298 if (cached !== null && cached.status === "Scanned" && (!recursive || fullyKnown(cached))) {
299 const combined = combineFileListings(cached.files, listOfflineFiles(dir));
300 return recursive ? combined : pruneChildren(combined);
301 }
302 const files = await listOnlineFiles(dir, recursive);
303 if (!files) return new Map();
304 updateFileTree(dir, { files, status: "Scanned" }, false);
305 const combined = combineFileListings(files, listOfflineFiles(dir));
306 return recursive ? combined : pruneChildren(combined);
307}
308
309const coverCache = new Map<string, { data: Blob | null }>();
310
311//get cover art object-url for a file or directory with cache-first strategy
312export async function getCover(
313 dir: string,
314 options: AppOptions,
315 saveToDb: boolean,
316 offline: boolean,
317 forceRefresh = false,
318) {
319 try {
320 const cached = coverCache.get(dir);
321 if (!forceRefresh && cached !== undefined) {
322 if (saveToDb) db.covers.add({ path: dir, data: cached.data }).catch(() => {});
323 return cached.data === null ? undefined : URL.createObjectURL(cached.data);
324 }
325
326 if (offline) return undefined;
327
328 const response = await fetch(`/cover/${encodePath(dir)}${options.transcodeCovers ? "?transcode=true" : ""}`, {
329 method: "GET",
330 credentials: "same-origin",
331 }).catch(() => {});
332 if (!response || response.status === 404) {
333 coverCache.set(dir, { data: null });
334 if (saveToDb) db.covers.add({ path: dir, data: null }).catch(() => {});
335 //if cover already exists in database, update it
336 else if (forceRefresh && db.covers.get(dir) !== undefined) db.covers.put({ path: dir, data: null });
337 return undefined;
338 }
339 const blob = await response.blob();
340 coverCache.set(dir, { data: blob });
341 if (saveToDb) db.covers.add({ path: dir, data: blob }).catch(() => {});
342 //if cover already exists in database, update it
343 else if (forceRefresh && db.covers.get(dir) !== undefined) db.covers.put({ path: dir, data: blob });
344 return URL.createObjectURL(blob);
345 } catch {
346 return undefined;
347 }
348}
349
350//returns an object url to the blob if synced, otherwise the server url
351export async function getSrc(
352 path: string,
353 options: AppOptions,
354 offline: boolean,
355 seekTo: number,
356 forceUrl?: true,
357): Promise<string>;
358export async function getSrc(path: string, options: AppOptions, offline: boolean, seekTo: number, forceUrl?: boolean) {
359 if (!forceUrl) {
360 const dbResult = await db.files.get(path);
361 if (dbResult) return URL.createObjectURL(dbResult.data);
362
363 if (offline) {
364 toast("This file is not cached, leave offline mode to play it", "error");
365 return undefined;
366 }
367 }
368 if (options.enableTranscoding) {
369 return (
370 `${joinPath("/transcode", encodePath(path))}` +
371 `?disableChunkedTranscoding=${options.disableChunkedTranscoding}` +
372 `&container=${options.container}` +
373 `&audioCodec=${options.audioCodec}` +
374 `&audioBitrate=${options.audioBitrate}` +
375 `&videoCodec=${options.videoCodec}` +
376 `&videoBitrate=${options.videoBitrate}` +
377 `${seekTo === 0 ? "" : `&seekTo=${seekTo}`}`
378 );
379 }
380 return joinPath("/download", encodePath(path));
381}
382
383export async function loadPlaylists() {
384 return await db.playlists.toArray();
385}
386
387//save playlist to indexedDB, throws error if playlist with that name already exists and overwrite=false
388export async function savePlaylist(playlist: Playlist, overwrite: boolean) {
389 playlist.items = playlist.items.map((item) => {
390 //some less space in the db by omitting ids
391 return { path: item.path, metadata: unproxy(item.metadata) };
392 });
393
394 if (overwrite) {
395 await db.playlists.put(playlist);
396 } else {
397 await db.playlists.add(playlist);
398 }
399}
400
401export async function deletePlaylist(name: string) {
402 await db.playlists.delete(name);
403}
404
405function collectMediaFilePaths(listing: FileListing, basePath: string): string[] {
406 const paths: string[] = [];
407
408 for (const [name, item] of listing.entries()) {
409 const currentPath = joinPath(basePath, name);
410
411 if ("metadata" in item) {
412 paths.push(currentPath);
413 } else if ("files" in item) {
414 paths.push(...collectMediaFilePaths(item.files, currentPath));
415 }
416 }
417
418 return paths;
419}
420
421//deletes file or directory(+recursive contents) from indexedDB and updates their download statuses
422export async function deleteFile(
423 fullPath: string,
424 item: MediaFile | Directory,
425 fetchFiles: ResourceActions<FlatFileListing>,
426) {
427 try {
428 if ("metadata" in item && downloadStatusMap[fullPath] !== "Synced") return;
429 startProgress(fullPath, { amount: 1 });
430
431 let toDelete: string[];
432 if ("files" in item) {
433 toDelete = collectMediaFilePaths(listOfflineFiles(fullPath), fullPath);
434 } else {
435 toDelete = [fullPath];
436 }
437
438 await db.files.bulkDelete(toDelete); //delete file from database
439 await db.covers.bulkDelete(toDelete); //delete embedded cover from database
440 deleteInOfflineTree(fullPath); //delete node from tree
441 batch(() => {
442 for (const path of toDelete) {
443 setDownloadStatusMap(path, undefined); // set all children to unsynced
444 }
445 });
446 fetchFiles.refetch();
447 } finally {
448 stopProgress(fullPath, undefined);
449 }
450}
451
452const downloadSemaphore = new AsyncSemaphore(1);
453
454//Download file to indexedDB and updates the offline file tree
455//concurrency control via the downloadSemaphore
456async function downloadFile(
457 path: string,
458 options: AppOptions,
459 item: MediaFile,
460 fetchFiles: ResourceActions<FlatFileListing>,
461 redownload: boolean,
462): Promise<void> {
463 const retry = () => downloadFile(path, options, item, fetchFiles, redownload);
464
465 const controller = new AbortController();
466 let abortResolve!: () => void;
467 const abortPromise = new Promise<void>((outerResolve) => {
468 abortResolve = () => {
469 controller.abort();
470 stopProgress(
471 path,
472 // if it was already synced, restore it
473 initialProgress === "Synced" ? "Synced" : { status: "Aborted", retry },
474 );
475 outerResolve();
476 };
477 });
478 // file already downloaded or download already in progress
479 const initialProgress = downloadStatusMap[path];
480 if (
481 (!redownload && initialProgress === "Synced") ||
482 (typeof initialProgress === "object" && "bytes" in initialProgress)
483 )
484 return;
485 startProgress(path, { status: 0, abort: abortResolve });
486
487 try {
488 //options might change at any point, update the semaphore to the current value
489 downloadSemaphore.setMaxConcurrency(options.enableTranscoding ? options.maxTranscodes : options.maxDownloads);
490
491 //make sure to only allow the set amount of parallel downloads
492 const semaphorePromise = downloadSemaphore.acquire();
493 await Promise.race([abortPromise, semaphorePromise]);
494 try {
495 const res = await fetch(await getSrc(path, options, false, 0, true), {
496 signal: controller.signal,
497 credentials: "same-origin",
498 });
499
500 //let the browser do the actual download
501 const blobPromise = res.clone().blob();
502 if (!res.ok || !res.body) throw res.statusText;
503 //we just iterate over the chunks to get the current progress
504 const reader = res.body.getReader();
505 let received = 0;
506
507 let lastUpdate = 0;
508 while (true) {
509 const { done, value } = await reader.read();
510 if (done) break;
511 received += value.length;
512
513 //debouncing logic to not update UI too fast
514 const now = Date.now();
515 if (now - lastUpdate < 250) continue;
516 lastUpdate = now;
517 setDownloadStatusMap(path, { status: received, abort: abortResolve });
518 }
519 const blob = await blobPromise;
520
521 await db.files.put({
522 path,
523 data: blob,
524 metadata: unproxy(item.metadata),
525 });
526
527 updateFileTree(path, item, true);
528 stopProgress(path, "Synced");
529 fetchFiles.refetch();
530
531 //iterate through all parent directories and download their covers to database
532 const parts = path.split("/");
533 while (true) {
534 getCover(parts.join("/"), options, true, false).then((cover) => URL.revokeObjectURL(cover || ""));
535 parts.pop();
536 if (parts.length === 0) break;
537 }
538 } finally {
539 downloadSemaphore.release();
540 }
541 } catch (e) {
542 if (e && typeof e === "object" && "name" in e && e.name === "AbortError") return;
543 stopProgress(
544 path,
545 // if it was already synced, restore it
546 initialProgress === "Synced"
547 ? "Synced"
548 : {
549 status: "Failed",
550 reason: e ? e.toString() : "Unknown error",
551 retry,
552 },
553 );
554 }
555}
556
557export async function download(
558 fullPath: string,
559 item: MediaFile | Directory,
560 options: AppOptions,
561 fetchFiles: ResourceActions<FlatFileListing>,
562 redownload = false,
563) {
564 if ("metadata" in item) {
565 await downloadFile(fullPath, options, item, fetchFiles, redownload || false);
566 } else {
567 updateRecursiveStatus(fullPath, 1, true);
568 try {
569 //start downloads for all children to allow them to run in parallel, then wait for the results
570 const promises: Promise<unknown>[] = [];
571 const listing = await listFiles(fullPath, false, false);
572 batch(() => {
573 for (const [childName, childItem] of listing) {
574 promises.push(download(joinPath(fullPath, childName), childItem, options, fetchFiles, redownload));
575 }
576 });
577 await Promise.allSettled(promises);
578 } finally {
579 updateRecursiveStatus(fullPath, -1, true);
580 }
581 }
582}
583
584export const storedFilesLive = from(
585 liveQuery(async () => await db.files.toCollection().keys()),
586 [],
587);
588