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