utils.ts
| 1 | import type { FileListing, MediaFile } from "music-server-shared/types"; |
| 2 | import Toastify from "toastify-js"; |
| 3 | import { FileDisplay, type PlaylistItem } from "./types"; |
| 4 | |
| 5 | export 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 |
| 10 | export function joinPath(...paths: string[]): string { |
| 11 | return paths.join("/").replace(/\/+/g, "/").replace(/^\//, "").replace(/\/$/, ""); |
| 12 | } |
| 13 | |
| 14 | export 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 | |
| 20 | export 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 | |
| 33 | export 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 | |
| 41 | function stringErr(e: unknown) { |
| 42 | return e && typeof e === "object" && "message" in e ? e.message : e; |
| 43 | } |
| 44 | |
| 45 | export 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 | |
| 69 | export function remoteLog(e: unknown) { |
| 70 | fetch("remote-log", { body: JSON.stringify(e?.toString()), method: "POST", credentials: "same-origin" }); |
| 71 | } |
| 72 | |
| 73 | //debounce so a burst of failing requests (e.g. many covers loading at once) shows a single notification |
| 74 | let lastUnauthorized = 0; |
| 75 | |
| 76 | //registered by the app root so a 401 anywhere can update the logged-in state |
| 77 | let onUnauthorized: (() => void) | undefined; |
| 78 | export function setUnauthorizedHandler(handler: () => void) { |
| 79 | onUnauthorized = handler; |
| 80 | } |
| 81 | |
| 82 | export function handleUnauthorized(response?: Response | { status?: number } | void): boolean { |
| 83 | if (response?.status !== 401) return false; |
| 84 | //not debounced: keeps the logged-in state correct even while the toast is throttled |
| 85 | onUnauthorized?.(); |
| 86 | const now = Date.now(); |
| 87 | if (now - lastUnauthorized > 3000) { |
| 88 | lastUnauthorized = now; |
| 89 | toast("Unauthorized, please sign in", "error"); |
| 90 | } |
| 91 | return true; |
| 92 | } |
| 93 | |
| 94 | export type FileListingRecord = Record<string, MediaFile | { files: FileListingRecord }>; |
| 95 | export function fileListingToObject(listing: FileListing): FileListingRecord { |
| 96 | const result: FileListingRecord = {}; |
| 97 | for (const [name, entry] of listing.entries()) { |
| 98 | if ("files" in entry) { |
| 99 | result[name] = { files: fileListingToObject(entry.files) }; |
| 100 | } else { |
| 101 | result[name] = entry; |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | return result; |
| 106 | } |
| 107 | |
| 108 | export function formatBytes(bytes: number): string { |
| 109 | if (bytes === 0) return "Queued..."; |
| 110 | |
| 111 | const k = 1024; |
| 112 | const sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; |
| 113 | const i = Math.floor(Math.log(bytes) / Math.log(k)); |
| 114 | const value = bytes / k ** i; |
| 115 | |
| 116 | return `${value.toFixed(2)} ${sizes[i]}`; |
| 117 | } |
| 118 | |
| 119 | export function unproxy<T>(value: T): T { |
| 120 | return JSON.parse(JSON.stringify(value)); |
| 121 | } |
| 122 | |
| 123 | function getItemName(item: Pick<PlaylistItem, "path">): string; |
| 124 | function getItemName(item: Pick<PlaylistItem, "path"> | null): string | undefined; |
| 125 | function getItemName(item: Pick<PlaylistItem, "path"> | null) { |
| 126 | if (!item) return undefined; |
| 127 | return item.path.split("/").toReversed()[0]; |
| 128 | } |
| 129 | |
| 130 | export function formatFilename(file: Omit<PlaylistItem, "id">, format: FileDisplay): string { |
| 131 | switch (format) { |
| 132 | case FileDisplay.FILENAME: |
| 133 | return getItemName(file); |
| 134 | case FileDisplay.TITLE: |
| 135 | return file.metadata.title || getItemName(file); |
| 136 | case FileDisplay.TRACKNO_TITLE: { |
| 137 | if (!file.metadata.title) return getItemName(file); |
| 138 | const prefix = file.metadata.trackNumber ? `${file.metadata.trackNumber}. ` : ""; |
| 139 | return `${prefix}${file.metadata.title}`; |
| 140 | } |
| 141 | } |
| 142 | throw new Error(`unhandled: ${format}`); |
| 143 | } |
| 144 |