palico-bot/public/scripts/common.js
Shinuwa 03c410973e Rework the jukebox page: live updates, Discord login, progress, batch uploads
- Follow the queue live through /api/events (read with fetch so the key can
  be sent), reconnect with backoff and reload the state meanwhile; an
  indicator shows whether the page is live.
- Log in with Discord when enabled, the password stays available as a
  fallback; explain failed logins and expired sessions.
- Show a progress bar and durations, the queue length and total time, and a
  hint when the queue waits for listeners.
- Shuffle and loop buttons; search, rename and add the whole library,
  optionally shuffled.
- Upload several files at once with per-file progress (XMLHttpRequest), add
  a direct link, drag and drop files; allow 40 uploads per 15 minutes.
- Style password, URL and search fields, focus rings, and the phone layout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:21:43 +01:00

165 lines
4.6 KiB
JavaScript

const API_KEY_STORAGE_KEY = "palico-api-key";
const DISPLAY_NAME_STORAGE_KEY = "palico-display-name";
// Le stockage peut être indisponible (navigation privée, cookies bloqués) : la page doit
// fonctionner quand même, simplement sans mémoire.
function storageGet(storage, key) {
try {
return storage.getItem(key);
} catch {
return null;
}
}
function storageSet(storage, key, value) {
try {
if (value) {
storage.setItem(key, value);
} else {
storage.removeItem(key);
}
} catch {
// Stockage indisponible.
}
}
export function getStoredApiKey() {
return (
storageGet(sessionStorage, API_KEY_STORAGE_KEY) ||
storageGet(localStorage, API_KEY_STORAGE_KEY) ||
""
);
}
export function isApiKeyRemembered() {
return Boolean(storageGet(localStorage, API_KEY_STORAGE_KEY));
}
// remember : garde la clé sur l'appareil (localStorage) au lieu de l'onglet (sessionStorage).
export function setStoredApiKey(value, { remember = false } = {}) {
storageSet(remember ? localStorage : sessionStorage, API_KEY_STORAGE_KEY, value);
storageSet(remember ? sessionStorage : localStorage, API_KEY_STORAGE_KEY, "");
}
export function getStoredDisplayName() {
return storageGet(localStorage, DISPLAY_NAME_STORAGE_KEY) || "";
}
export function setStoredDisplayName(value) {
storageSet(localStorage, DISPLAY_NAME_STORAGE_KEY, value);
}
export function createStatusManager(statusElement) {
let hideTimeout;
function setStatus(message, type = "info", autoHide = true) {
if (!statusElement) return;
statusElement.textContent = message;
statusElement.className = `status status--${type}`;
statusElement.hidden = false;
if (autoHide) {
clearTimeout(hideTimeout);
hideTimeout = setTimeout(() => {
statusElement.hidden = true;
}, 5000);
}
}
function clearStatus() {
if (!statusElement) return;
statusElement.hidden = true;
statusElement.textContent = "";
clearTimeout(hideTimeout);
}
return { setStatus, clearStatus };
}
export function escapeHtml(text = "") {
return text
.toString()
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
export function formatBytes(bytes = 0) {
if (!Number(bytes)) return "0 B";
const units = ["B", "KB", "MB", "GB", "TB"];
const index = Math.floor(Math.log(bytes) / Math.log(1024));
return `${(bytes / Math.pow(1024, index)).toFixed(1)} ${units[index]}`;
}
// Durée lisible : 3:07, 1:05:09. null si inconnue.
export function formatDuration(seconds) {
const value = Number(seconds);
if (!Number.isFinite(value) || value < 0 || seconds === null) return null;
const total = Math.round(value);
const hours = Math.floor(total / 3600);
const minutes = Math.floor((total % 3600) / 60);
const secs = String(total % 60).padStart(2, "0");
return hours > 0
? `${hours}:${String(minutes).padStart(2, "0")}:${secs}`
: `${minutes}:${secs}`;
}
export function formatDate(value) {
if (!value) return "?";
try {
return new Date(value).toLocaleString();
} catch (_) {
return value;
}
}
export function createApiClient({ getApiKey, basePath = "" } = {}) {
const normalizedBase = (basePath || "").replace(/\/$/, "");
return async function apiFetch(path, options = {}) {
const url = path.startsWith("http")
? path
: `${normalizedBase}${path.startsWith("/") ? "" : "/"}${path}`;
const fetchOptions = {
method: options.method || "GET",
headers: new Headers(options.headers || {}),
};
const apiKey = typeof getApiKey === "function" ? getApiKey() : null;
if (apiKey) {
fetchOptions.headers.set("Authorization", `Bearer ${apiKey}`);
}
if (options.body instanceof FormData) {
fetchOptions.body = options.body;
} else if (options.body) {
if (!fetchOptions.headers.has("Content-Type")) {
fetchOptions.headers.set("Content-Type", "application/json");
}
fetchOptions.body =
typeof options.body === "string" ? options.body : JSON.stringify(options.body);
}
const response = await fetch(url, fetchOptions);
const contentType = response.headers.get("content-type") || "";
let payload = null;
if (contentType.includes("application/json")) {
payload = await response.json();
} else {
payload = await response.text();
}
if (!response.ok) {
const errorMessage = payload?.error || payload?.message || response.statusText;
const error = new Error(errorMessage);
error.status = response.status;
throw error;
}
return payload;
};
}