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