utils.ts
⎇
Raw
1import type { FileListing, MediaFile } from "music-server-shared/types";
2import Toastify from "toastify-js";
3import { FileDisplay, type PlaylistItem } from "./types";
4
5export function sleep(ms: number) {
6 return new Promise((resolve) => setTimeout(resolve, ms));
7}
8
9//join string and dedup slashes and make sure it doesn't start or end with a slash
10export function joinPath(...paths: string[]): string {
11 return paths.join("/").replace(/\/+/g, "/").replace(/^\//, "").replace(/\/$/, "");
12}
13
14export function formatTime(seconds: number): string {
15 const mins = Math.floor(seconds / 60);
16 const secs = Math.floor(seconds % 60);
17 return `${mins}:${secs < 10 ? "0" : ""}${secs}`;
18}
19
20export const LocalStorageValues = {
21 options: "Options",
22 volume: "Volume",
23 playlist: "Playlist",
24 shuffle: "Shuffle",
25 repeat: "Repeat",
26 offline: "Offline",
27 path: "Path",
28 fileBrowserButtons: "FileBrowserButtons",
29 playlistButtons: "PlaylistButtons",
30 playerControls: "PlayerControls",
31};
32
33export function generateUUID() {
34 return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
35 const r = (Math.random() * 16) | 0;
36 const v = c === "x" ? r : (r & 0x3) | 0x8;
37 return v.toString(16);
38 });
39}
40
41function stringErr(e: unknown) {
42 return e && typeof e === "object" && "message" in e ? e.message : e;
43}
44
45export function toast(text: string, type: "progress" | "info" | "error" | "success", e?: unknown) {
46 if (e) {
47 console.error(e);
48 }
49 const thisToast = Toastify({
50 text: e ? `${text}:\n${stringErr(e)}` : text,
51 duration: type === "progress" ? -1 : 2000,
52 close: true,
53 style: {
54 "border-radius": "0",
55 display: "flex",
56 "align-items": "center",
57 background:
58 type === "success"
59 ? "linear-gradient(135deg,rgb(38, 194, 27),rgb(5, 144, 52))"
60 : type === "error"
61 ? "linear-gradient(135deg,rgb(255, 24, 24),rgb(220, 0, 0))"
62 : "linear-gradient(135deg,rgb(50, 60, 255),rgb(34, 37, 209))",
63 },
64 });
65 thisToast.showToast();
66 return thisToast;
67}
68
69export function remoteLog(e: unknown) {
70 fetch("remote-log", { body: JSON.stringify(e?.toString()), method: "POST" });
71}
72
73export type FileListingRecord = Record<string, MediaFile | { files: FileListingRecord }>;
74export function fileListingToObject(listing: FileListing): FileListingRecord {
75 const result: FileListingRecord = {};
76 for (const [name, entry] of listing.entries()) {
77 if ("files" in entry) {
78 result[name] = { files: fileListingToObject(entry.files) };
79 } else {
80 result[name] = entry;
81 }
82 }
83
84 return result;
85}
86
87export function formatBytes(bytes: number): string {
88 if (bytes === 0) return "Queued...";
89
90 const k = 1024;
91 const sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
92 const i = Math.floor(Math.log(bytes) / Math.log(k));
93 const value = bytes / k ** i;
94
95 return `${value.toFixed(2)} ${sizes[i]}`;
96}
97
98export function unproxy<T>(value: T): T {
99 return JSON.parse(JSON.stringify(value));
100}
101
102function getItemName(item: Pick<PlaylistItem, "path">): string;
103function getItemName(item: Pick<PlaylistItem, "path"> | null): string | undefined;
104function getItemName(item: Pick<PlaylistItem, "path"> | null) {
105 if (!item) return undefined;
106 return item.path.split("/").toReversed()[0];
107}
108
109export function formatFilename(file: Omit<PlaylistItem, "id">, format: FileDisplay): string {
110 switch (format) {
111 case FileDisplay.FILENAME:
112 return getItemName(file);
113 case FileDisplay.TITLE:
114 return file.metadata.title || getItemName(file);
115 case FileDisplay.TRACKNO_TITLE: {
116 if (!file.metadata.title) return getItemName(file);
117 const prefix = file.metadata.trackNumber ? `${file.metadata.trackNumber}. ` : "";
118 return `${prefix}${file.metadata.title}`;
119 }
120 }
121 throw new Error(`unhandled: ${format}`);
122}
123