import type { FileListing, MediaFile } from "music-server-shared/types"; import Toastify from "toastify-js"; import { FileDisplay, type PlaylistItem } from "./types"; export function sleep(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)); } //join string and dedup slashes and make sure it doesn't start or end with a slash export function joinPath(...paths: string[]): string { return paths.join("/").replace(/\/+/g, "/").replace(/^\//, "").replace(/\/$/, ""); } export function formatTime(seconds: number): string { const mins = Math.floor(seconds / 60); const secs = Math.floor(seconds % 60); return `${mins}:${secs < 10 ? "0" : ""}${secs}`; } export const LocalStorageValues = { options: "Options", volume: "Volume", playlist: "Playlist", shuffle: "Shuffle", repeat: "Repeat", offline: "Offline", path: "Path", fileBrowserButtons: "FileBrowserButtons", playlistButtons: "PlaylistButtons", playerControls: "PlayerControls", }; export function generateUUID() { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { const r = (Math.random() * 16) | 0; const v = c === "x" ? r : (r & 0x3) | 0x8; return v.toString(16); }); } function stringErr(e: unknown) { return e && typeof e === "object" && "message" in e ? e.message : e; } export function toast(text: string, type: "progress" | "info" | "error" | "success", e?: unknown) { if (e) { console.error(e); } const thisToast = Toastify({ text: e ? `${text}:\n${stringErr(e)}` : text, duration: type === "progress" ? -1 : 2000, close: true, style: { "border-radius": "0", display: "flex", "align-items": "center", background: type === "success" ? "linear-gradient(135deg,rgb(38, 194, 27),rgb(5, 144, 52))" : type === "error" ? "linear-gradient(135deg,rgb(255, 24, 24),rgb(220, 0, 0))" : "linear-gradient(135deg,rgb(50, 60, 255),rgb(34, 37, 209))", }, }); thisToast.showToast(); return thisToast; } export function remoteLog(e: unknown) { //absolute path and a catch, so the error logger can't itself throw an unhandled rejection while offline fetch("/remote-log", { body: JSON.stringify(e?.toString()), method: "POST", credentials: "same-origin" }).catch( () => {}, ); } //debounce so a burst of failing requests (e.g. many covers loading at once) shows a single notification let lastUnauthorized = 0; //registered by the app root so a 401 anywhere can update the logged-in state let onUnauthorized: (() => void) | undefined; export function setUnauthorizedHandler(handler: () => void) { onUnauthorized = handler; } export function handleUnauthorized(response?: Response | { status?: number } | void): boolean { if (response?.status !== 401) return false; //not debounced: keeps the logged-in state correct even while the toast is throttled onUnauthorized?.(); const now = Date.now(); if (now - lastUnauthorized > 3000) { lastUnauthorized = now; toast("Unauthorized, please sign in", "error"); } return true; } export type FileListingRecord = Record; export function fileListingToObject(listing: FileListing): FileListingRecord { const result: FileListingRecord = {}; for (const [name, entry] of listing.entries()) { if ("files" in entry) { result[name] = { files: fileListingToObject(entry.files) }; } else { result[name] = entry; } } return result; } export function formatBytes(bytes: number): string { if (bytes === 0) return "Queued..."; const k = 1024; const sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; const i = Math.floor(Math.log(bytes) / Math.log(k)); const value = bytes / k ** i; return `${value.toFixed(2)} ${sizes[i]}`; } export function unproxy(value: T): T { return JSON.parse(JSON.stringify(value)); } function getItemName(item: Pick): string; function getItemName(item: Pick | null): string | undefined; function getItemName(item: Pick | null) { if (!item) return undefined; return item.path.split("/").toReversed()[0]; } export function formatFilename(file: Omit, format: FileDisplay): string { switch (format) { case FileDisplay.FILENAME: return getItemName(file); case FileDisplay.TITLE: return file.metadata.title || getItemName(file); case FileDisplay.TRACKNO_TITLE: { if (!file.metadata.title) return getItemName(file); const prefix = file.metadata.trackNumber ? `${file.metadata.trackNumber}. ` : ""; return `${prefix}${file.metadata.title}`; } } throw new Error(`unhandled: ${format}`); }