utils.ts
⎇
Raw
1import type { FileListing, MediaFile } from "music-server-shared/types";
2import Toastify from "toastify-js";
3
4export function sleep(ms: number) {
5 return new Promise((resolve) => setTimeout(resolve, ms));
6}
7
8//join string and dedup slashes and make sure it doesn't start or end with a slash
9export function joinPath(...paths: string[]): string {
10 return paths.join("/").replace(/\/+/g, "/").replace(/^\//, "").replace(/\/$/, "");
11}
12
13export function formatTime(seconds: number): string {
14 const mins = Math.floor(seconds / 60);
15 const secs = Math.floor(seconds % 60);
16 return `${mins}:${secs < 10 ? "0" : ""}${secs}`;
17}
18
19export const LocalStorageValues = {
20 options: "Options",
21 volume: "Volume",
22 playlist: "Playlist",
23 shuffle: "Shuffle",
24 repeat: "Repeat",
25 offline: "Offline",
26 path: "Path",
27 fileBrowserButtons: "FileBrowserButtons",
28 playlistButtons: "PlaylistButtons",
29};
30
31export function generateUUID() {
32 return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
33 const r = (Math.random() * 16) | 0;
34 const v = c === "x" ? r : (r & 0x3) | 0x8;
35 return v.toString(16);
36 });
37}
38
39function stringErr(e: unknown) {
40 return e && typeof e === "object" && "message" in e ? e.message : e;
41}
42
43export function toast(text: string, type: "progress" | "info" | "error" | "success", e?: unknown) {
44 if (e) {
45 console.error(e);
46 }
47 const thisToast = Toastify({
48 text: e ? `${text}:\n${stringErr(e)}` : text,
49 duration: type === "progress" ? -1 : 2000,
50 close: type !== "progress",
51 style: {
52 "border-radius": "0",
53 display: "flex",
54 "align-items": "center",
55 background:
56 type === "success"
57 ? "linear-gradient(135deg,rgb(38, 194, 27),rgb(5, 144, 52))"
58 : type === "error"
59 ? "linear-gradient(135deg,rgb(255, 24, 24),rgb(220, 0, 0))"
60 : "linear-gradient(135deg,rgb(50, 60, 255),rgb(34, 37, 209))",
61 },
62 });
63 thisToast.showToast();
64 return thisToast;
65}
66
67export function remoteLog(e: unknown) {
68 fetch("remote-log", { body: JSON.stringify(e?.toString()), method: "POST" });
69}
70
71export type FileListingRecord = Record<string, MediaFile | { files: FileListingRecord }>;
72export function fileListingToObject(listing: FileListing): FileListingRecord {
73 const result: FileListingRecord = {};
74 for (const [name, entry] of listing.entries()) {
75 if ("files" in entry) {
76 result[name] = { files: fileListingToObject(entry.files) };
77 } else {
78 result[name] = entry;
79 }
80 }
81
82 return result;
83}
84