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 { type Accessor, createSignal, type ResourceActions, type Signal } from "solid-js";
12import { AsyncSemaphore } from "./semaphore";
13
14interface Progress {
15 bytes: number;
16}
17
18//TODO: try using store
19export type SignalMapEntry = undefined | Progress | "DirectoryProgress" | "CachedFile";
20export const signalMap = new Map<string, Signal<SignalMapEntry>>();
21
22export async function loadDataFromDB() {
23 try {
24 const db = await openDB();
25 const files = await db.listFiles(FileMetadataStore);
26 for (const file of files) {
27 signalMap.set(file.path, createSignal<SignalMapEntry>("CachedFile"));
28 updateFileTree(file.path, { metadata: { duration: file.duration } }, true);
29 }
30 } catch (e) {
31 toast("Loading offline files failed", "error", e);
32 console.error(e);
33 }
34}
35
36const offlineTreeRoot: Directory = {
37 files: new Map(),
38};
39
40const onlineTreeRoot: DirectoryWithStatus = {
41 files: new Map(),
42 status: "Unknown",
43};
44
45function mergeTrees(target: DirectoryWithStatus, other: DirectoryWithStatus) {
46 if (other.status === "Unknown") return;
47 target.status = other.status;
48 for (const [fileName, file] of other.files.entries()) {
49 const targetFile = target.files.get(fileName);
50 if (targetFile && "files" in targetFile && "files" in file) {
51 mergeTrees(targetFile, file);
52 } else {
53 target.files.set(fileName, file);
54 }
55 }
56}
57
58//TODO: improve typing to avoid "as"
59//overloads for typecheking
60function updateFileTree(path: string, file: MediaFile, offline: true): void;
61function updateFileTree(path: string, file: DirectoryWithStatus, offline: false): void;
62function updateFileTree(path: string, file: DirectoryWithStatus | MediaFile, offline: boolean): void {
63 if (offline && path === "") throw new Error("Trying to update root in offline mode");
64 const basePath = path.split("/").slice(0, -1).join("/");
65 const fileName = path.split("/").toReversed()[0];
66 const node = getDirInTree(basePath, true, offline);
67
68 if (offline) {
69 node.files.set(fileName, file);
70 } else {
71 if (path === "") mergeTrees(node as DirectoryWithStatus, file as DirectoryWithStatus);
72 else {
73 let target = node.files.get(fileName) as DirectoryWithStatus;
74 if (!target) target = { files: new Map(), status: "Unknown" };
75 mergeTrees(target as DirectoryWithStatus, file as DirectoryWithStatus);
76 node.files.set(fileName, target);
77 }
78 }
79}
80
81//overloads for typecheking
82function getDirInTree(path: string, create: true, offline: true): Directory;
83function getDirInTree(path: string, create: true, offline: false): DirectoryWithStatus;
84function getDirInTree(path: string, create: false, offline: true): Directory | null;
85function getDirInTree(path: string, create: false, offline: false): DirectoryWithStatus | null;
86function getDirInTree(path: string, create: true, offline: boolean): DirectoryWithStatus | Directory;
87function getDirInTree(path: string, create: false, offline: boolean): DirectoryWithStatus | Directory | null;
88
89// get a DirectoryNode from the directory tree, and optionally create it if it doesn't exist yet
90function getDirInTree(path: string, create: boolean, offline: boolean): DirectoryWithStatus | Directory | null {
91 let current = offline ? offlineTreeRoot : onlineTreeRoot;
92 if (path === "") return current;
93 const parts = path.split("/");
94
95 for (const part of parts) {
96 let next: DirectoryWithStatus | Directory | MediaFile | undefined = current.files.get(part);
97 if (!next || "metadata" in next) {
98 if (!create) return null;
99 //if mediafile already exists, we overwrite it with a directory anyway
100 if (offline) next = { files: new Map() };
101 else next = { files: new Map(), status: "Unknown" };
102 current.files.set(part, next);
103 }
104 current = next;
105 }
106 return current;
107}
108
109function deleteOfflinePath(path: string): void {
110 const basePath = path.split("/").slice(0, -1).join("/");
111 const fileName = path.split("/").toReversed()[0];
112
113 const node = getDirInTree(basePath, false, true);
114 if (!node) return;
115
116 node.files.delete(fileName);
117}
118
119export const clearDirectoryCache = (path: string) => {
120 const node = getDirInTree(path, false, false);
121 if (!node) return;
122 node.files.clear();
123 node.status = "Unknown";
124};
125
126async function listOnlineFiles(dir: string, recursive: boolean): Promise<FileListingWithStatus | undefined> {
127 const response = await fetch(`/list/${dir}?recursive=${recursive}`).catch(() => {});
128 if (response?.status === 404) {
129 toast(`Directory not found: ${dir}`, "error");
130 return;
131 }
132 if (!response || !response.ok) {
133 toast(
134 `Fetching files for ${dir === "" ? "root" : dir} failed${response ? `: ${response.statusText}` : ""}`,
135 "error",
136 );
137 return;
138 }
139
140 return parseMap(await response.text()) as FileListingWithStatus;
141}
142
143function listOfflineFiles(dir: string): FileListing {
144 const node = getDirInTree(dir, false, true);
145 if (!node || !node.files) return new Map();
146 return node.files;
147}
148
149function fullyKnown(dir: DirectoryWithStatus) {
150 if (dir.status === "Unknown") {
151 return false;
152 }
153 if (dir.files.values().some((value) => "files" in value && !fullyKnown(value))) {
154 return false;
155 }
156 return true;
157}
158
159export async function listFiles(dir: string, offline: boolean, recursive: boolean): Promise<FileListing> {
160 if (offline) {
161 const res = listOfflineFiles(dir);
162 return res;
163 }
164 const cached = getDirInTree(dir, false, false);
165 if (cached !== null && cached.status === "Scanned" && (!recursive || fullyKnown(cached))) return cached.files;
166 const files = await listOnlineFiles(dir, recursive);
167 if (!files) return new Map();
168 updateFileTree(dir, { files, status: "Scanned" }, false);
169 return files;
170}
171
172export async function getCover(dir: string, offline: boolean) {
173 const db = await openDB();
174 const dbResult = await db.get(CoverStore, dir);
175 if (dbResult !== undefined) {
176 const cached = dbResult as StoredCover;
177 return cached.data === null ? undefined : URL.createObjectURL(new Blob([cached.data]));
178 }
179
180 if (offline) return undefined;
181
182 const response = await fetch(`/cover/${dir}`, { method: "GET" }).catch(() => {});
183 if (!response || response.status === 404) {
184 db.put(CoverStore, { path: dir, data: null });
185 return undefined;
186 }
187 const blob = await response.blob();
188 db.put(CoverStore, { path: dir, data: blob });
189 return URL.createObjectURL(blob);
190}
191
192export const clearCoverCache = async (path: string) => {
193 const db = await openDB();
194 return db.delete(CoverStore, path);
195};
196
197export async function getSrc(path: string, options: AppOptions, offline: boolean) {
198 const db = await openDB();
199 const dbResult = (await db.get(FileBlobStore, path)) as StoredFileBlob;
200 if (dbResult) return URL.createObjectURL(dbResult.data);
201
202 if (offline) {
203 toast("This file is not cached, leave offline mode to play it", "error");
204 return undefined;
205 }
206 if (options.enableTranscoding) {
207 return `${joinPath("/transcode", path)}?bitrate=${options.bitrate}&format=${options.format}&disableChunkedTranscoding=${options.disableChunkedTranscoding}`;
208 }
209 return joinPath("/download", path);
210}
211
212export async function loadPlaylists() {
213 const db = await openDB();
214 return await db.listPlaylists(PlaylistStore);
215}
216
217export async function savePlaylist(playlist: Playlist, overwrite: boolean) {
218 const db = await openDB();
219 playlist.items = playlist.items.map((item) => {
220 //some less space in the db by omitting ids
221 const { id, ...itemWithoutId } = item as PlaylistItem;
222 return itemWithoutId;
223 });
224 if (overwrite) await db.put(PlaylistStore, playlist);
225 else await db.add(PlaylistStore, playlist);
226}
227
228export async function deletePlaylist(name: string) {
229 const db = await openDB();
230 await db.delete(PlaylistStore, name);
231}
232
233export async function deleteFile(
234 fileName: string,
235 item: MediaFile | Directory,
236 basePath: string,
237 fetchFiles: ResourceActions<FileListing>,
238) {
239 const fullPath = joinPath(basePath, fileName);
240 const signal = signalMap.get(fullPath);
241 if (!signal) return;
242
243 //TODO: can techinally remove the recursion, but need to update the signals
244 if (!("duration" in item)) {
245 const newBasePath = joinPath(basePath, fileName);
246 const result = listOfflineFiles(newBasePath);
247 for (const [childName, childItem] of result) {
248 await deleteFile(childName, childItem, newBasePath, fetchFiles);
249 }
250 }
251
252 deleteOfflinePath(fullPath);
253 const db = await openDB();
254 await db.delete(FileBlobStore, fullPath);
255 await db.delete(FileMetadataStore, fullPath);
256 signalMap.get(fullPath)?.[1](undefined);
257 fetchFiles.refetch();
258}
259
260const downloadSemaphore = new AsyncSemaphore(1);
261
262async function downloadFile(
263 path: string,
264 currentDir: Accessor<string>,
265 progressSignal: Signal<SignalMapEntry>,
266 options: AppOptions,
267 item: MediaFile,
268 fetchFiles: ResourceActions<FileListing>,
269): Promise<void> {
270 const [getProgress, setProgress] = progressSignal;
271 const progress = getProgress();
272 if (typeof progress === "object" && "bytes" in progress) return; // download already in progress
273
274 const db = await openDB();
275 let mimeType: string | undefined;
276 try {
277 setProgress({ bytes: 0 });
278
279 downloadSemaphore.setMaxConcurrency(options.enableTranscoding ? options.maxTranscodes : options.maxDownloads);
280 let blob: Blob;
281 try {
282 await downloadSemaphore.acquire();
283 let res: Response;
284 if (options.enableTranscoding) {
285 res = await fetch(
286 `${joinPath("/transcode", path)}?bitrate=${options.bitrate}&format=${options.format}&disableChunkedTranscoding=${options.disableChunkedTranscoding}`,
287 );
288 } else {
289 res = await fetch(joinPath("/download", path));
290 }
291 //let the browser do the actual download
292 const blobPromise = res.clone().blob();
293 if (!res.ok || !res.body) throw res.statusText;
294 //we just iterate over the chunks to get the current progress
295 const reader = res.body.getReader();
296 mimeType = res.headers.get("content-type") ?? undefined;
297 let received = 0;
298
299 let lastUpdate = 0;
300 while (true) {
301 const { done, value } = await reader.read();
302 if (done) break;
303 received += value.length;
304
305 const now = Date.now();
306 if (now - lastUpdate < 250) continue;
307 lastUpdate = now;
308 setProgress({ bytes: received });
309 }
310 blob = await blobPromise;
311 } finally {
312 downloadSemaphore.release();
313 }
314
315 await db.put(FileBlobStore, {
316 path,
317 data: blob,
318 } as StoredFileBlob);
319 await db.put(FileMetadataStore, {
320 path,
321 duration: item.metadata.duration,
322 } as StoredFileMetadata);
323 updateFileTree(path, item, true);
324 setProgress("CachedFile");
325 const basePath = path.split("/").slice(0, -1).join("/");
326 const fileName = path.split("/").toReversed()[0];
327 if (currentDir() === basePath) {
328 fetchFiles.mutate((prev) => {
329 prev.set(fileName, item);
330 //new map to force rerender
331 return new Map(prev);
332 });
333 }
334 } catch (e) {
335 toast(`Downloading ${path} failed`, "error", e);
336 setProgress(undefined);
337 }
338}
339
340export async function download(
341 fileName: string,
342 item: MediaFile | Directory,
343 basePath: string,
344 currentDir: Accessor<string>,
345 options: AppOptions,
346 fetchFiles: ResourceActions<FileListing>,
347) {
348 const fullPath = joinPath(basePath, fileName);
349 let signal = signalMap.get(fullPath);
350 if (!signal) {
351 signal = createSignal<SignalMapEntry>();
352 signalMap.set(fullPath, signal);
353 }
354 const [, setProgress] = signal;
355 if ("metadata" in item) {
356 await downloadFile(fullPath, currentDir, signal, options, item, fetchFiles);
357 } else {
358 setProgress("DirectoryProgress");
359 await getCover(fullPath, false);
360 try {
361 const promises: Promise<unknown>[] = [];
362 for (const [childName, childItem] of await listFiles(fullPath, false, false)) {
363 promises.push(download(childName, childItem, fullPath, currentDir, options, fetchFiles));
364 }
365 await Promise.allSettled(promises);
366 } finally {
367 setProgress(undefined);
368 }
369 }
370}
371
372interface StoredFileBlob {
373 path: string;
374 data: Blob;
375}
376
377interface StoredFileMetadata {
378 path: string;
379 duration: number;
380}
381
382interface StoredCover {
383 path: string;
384 data: Blob | null;
385}
386
387//separate blobs and metadata, so we don't have to load all file contents at startup, which would consume huge amounts of ram, and be very slow
388const FileBlobStore = "fileblobs";
389const FileMetadataStore = "filemetadata";
390const CoverStore = "covers";
391const PlaylistStore = "playlists";
392
393async function openDB() {
394 return new Promise<DatabaseWrapper>((resolve, reject) => {
395 const req = indexedDB.open("music-files");
396 req.onerror = () => reject(req.error);
397 req.onupgradeneeded = () => {
398 const db = req.result;
399 if (!db.objectStoreNames.contains(FileBlobStore)) db.createObjectStore(FileBlobStore, { keyPath: "path" });
400 if (!db.objectStoreNames.contains(FileMetadataStore))
401 db.createObjectStore(FileMetadataStore, { keyPath: "path" });
402 if (!db.objectStoreNames.contains(CoverStore)) db.createObjectStore(CoverStore, { keyPath: "path" });
403 if (!db.objectStoreNames.contains(PlaylistStore)) db.createObjectStore(PlaylistStore, { keyPath: "name" });
404 };
405 req.onsuccess = () => resolve(wrapDB(req.result));
406 });
407}
408
409interface DatabaseWrapper {
410 get(store: typeof CoverStore | typeof FileBlobStore, key: string): Promise<unknown>;
411 put(store: typeof FileBlobStore, value: StoredFileBlob): Promise<void>;
412 put(store: typeof FileMetadataStore, value: StoredFileMetadata): Promise<void>;
413 put(store: typeof CoverStore, value: StoredCover): Promise<void>;
414 put(store: typeof PlaylistStore, value: Playlist): Promise<void>;
415 add(store: typeof PlaylistStore, value: Playlist): Promise<void>;
416 delete(
417 store: typeof FileBlobStore | typeof CoverStore | typeof FileMetadataStore | typeof PlaylistStore,
418 key: string,
419 ): Promise<void>;
420 clear(store: string): Promise<void>;
421 listFiles(store: typeof FileMetadataStore): Promise<StoredFileMetadata[]>;
422 listPlaylists(store: typeof PlaylistStore): Promise<Playlist[]>;
423}
424
425function wrapDB(db: IDBDatabase): DatabaseWrapper {
426 return {
427 get: (store: string, key: string) =>
428 new Promise((res, rej) => {
429 const tx = db.transaction(store, "readonly");
430 const req = tx.objectStore(store).get(key);
431 req.onsuccess = () => res(req.result);
432 req.onerror = () => rej(req.error);
433 }),
434 put: (store: string, value: unknown) =>
435 new Promise<void>((res, rej) => {
436 const tx = db.transaction(store, "readwrite");
437 const req: IDBRequest<IDBValidKey> = tx.objectStore(store).put(value);
438 req.onsuccess = () => res();
439 req.onerror = () => rej(req.error);
440 }),
441 add: (store: string, value: unknown) =>
442 new Promise<void>((res, rej) => {
443 const tx = db.transaction(store, "readwrite");
444 const req: IDBRequest<IDBValidKey> = tx.objectStore(store).add(value);
445 req.onsuccess = () => res();
446 req.onerror = () => rej(req.error);
447 }),
448 delete: (store: string, key: string) =>
449 new Promise<void>((res, rej) => {
450 const tx = db.transaction(store, "readwrite");
451 const req = tx.objectStore(store).delete(key);
452 req.onsuccess = () => res();
453 req.onerror = () => rej(req.error);
454 }),
455 clear: (store: string) =>
456 new Promise<void>((res, rej) => {
457 const tx = db.transaction(store, "readwrite");
458 const req = tx.objectStore(store).clear();
459 req.onsuccess = () => res();
460 req.onerror = () => rej(req.error);
461 }),
462 listFiles: (store: typeof FileMetadataStore) =>
463 new Promise((res, rej) => {
464 const tx = db.transaction(store, "readonly");
465 const req = tx.objectStore(store).getAll();
466 req.onsuccess = () => res(req.result);
467 req.onerror = () => rej(req.error);
468 }),
469 listPlaylists: (store: typeof PlaylistStore) =>
470 new Promise((res, rej) => {
471 const tx = db.transaction(store, "readonly");
472 const req = tx.objectStore(store).getAll();
473 req.onsuccess = () => res(req.result);
474 req.onerror = () => rej(req.error);
475 }),
476 };
477}
478