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