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};
28
29export function generateUUID() {
30 return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
31 const r = (Math.random() * 16) | 0;
32 const v = c === "x" ? r : (r & 0x3) | 0x8;
33 return v.toString(16);
34 });
35}
36
37function stringErr(e: unknown) {
38 return e && typeof e === "object" && "message" in e ? e.message : e;
39}
40
41export function toast(text: string, type: "progress" | "info" | "error" | "success", e?: unknown) {
42 if (e) {
43 console.error(e);
44 }
45 const thisToast = Toastify({
46 text: e ? `${text}:\n${stringErr(e)}` : text,
47 duration: type === "progress" ? -1 : 2000,
48 close: type !== "progress",
49 style: {
50 "border-radius": "0",
51 display: "flex",
52 "align-items": "center",
53 background:
54 type === "success"
55 ? "linear-gradient(135deg,rgb(38, 194, 27),rgb(5, 144, 52))"
56 : type === "error"
57 ? "linear-gradient(135deg,rgb(255, 24, 24),rgb(220, 0, 0))"
58 : "linear-gradient(135deg,rgb(50, 60, 255),rgb(34, 37, 209))",
59 },
60 });
61 thisToast.showToast();
62 return thisToast;
63}
64
65export function remoteLog(e: unknown) {
66 fetch("remote-log", { body: JSON.stringify(e?.toString()), method: "POST" });
67}
68
69export type FileListingRecord = Record<string, MediaFile | { files: FileListingRecord }>;
70export function fileListingToObject(listing: FileListing): FileListingRecord {
71 const result: FileListingRecord = {};
72 for (const [name, entry] of listing.entries()) {
73 if ("files" in entry) {
74 result[name] = { files: fileListingToObject(entry.files) };
75 } else {
76 result[name] = entry;
77 }
78 }
79
80 return result;
81}
82