Files
Scrobbler/frontend/js/api.js
T
mattandClaude Opus 5.5 b509cd2b60
CI / lint (push) Successful in 9s
CI / test (push) Successful in 31s
CI / notify (push) Successful in 5s
Web UI: static HTML/CSS/JS frontend, hosted separately from the API
- Plain HTML + vanilla JS modules, no build step; talks to /api/v1 with
  a bearer token and only ever inserts server data as text
- Overview: now-playing dot-matrix display with live progress, totals,
  30-day plays meter, top artists/tracks by period, recent plays
- History (paged, grouped by day), Apps (create/delete, reveal/copy
  keys, player setup details), Sessions (revoke), sign-in approval page
  for the Last.fm desktop auth flow, sign in and registration
- Light and dark themes, responsive to phone widths, vendored fonts
  (SIL OFL) so the UI has no third-party requests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 14:11:37 +01:00

90 lines
2.5 KiB
JavaScript

// Thin client for the Scrobbler /api/v1 JSON API.
const TOKEN_KEY = "scrobbler.token";
export const apiBase = (window.SCROBBLER_CONFIG?.apiBaseUrl || "http://localhost:5050").replace(/\/+$/, "");
export function getToken() {
try {
return localStorage.getItem(TOKEN_KEY);
} catch {
return null;
}
}
export function setToken(token) {
try {
if (token) localStorage.setItem(TOKEN_KEY, token);
else localStorage.removeItem(TOKEN_KEY);
} catch {
// Storage unavailable (private mode): the session lasts until the tab closes.
}
}
export class ApiError extends Error {
constructor(status, code, message, details) {
super(message);
this.status = status;
this.code = code;
this.details = details;
}
}
// Only same-site page names are allowed as a post-login destination.
export function safeNext(value) {
return /^[a-z]+\.html(\?[\w=&%.-]*)?$/.test(value || "") ? value : "index.html";
}
export function redirectToLogin() {
const here = location.pathname.split("/").pop() || "index.html";
location.href = `login.html?next=${encodeURIComponent(safeNext(here + location.search))}`;
}
export async function api(path, { method = "GET", body, auth = true } = {}) {
const headers = {};
if (body !== undefined) headers["Content-Type"] = "application/json";
const token = getToken();
if (auth && token) headers.Authorization = `Bearer ${token}`;
let response;
try {
response = await fetch(`${apiBase}/api/v1${path}`, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
});
} catch {
throw new ApiError(0, "network", `Can't reach the Scrobbler API at ${apiBase}. Check that it's running.`);
}
if (response.status === 401 && auth) {
setToken(null);
redirectToLogin();
throw new ApiError(401, "unauthorized", "Your session has ended. Sign in again.");
}
if (response.status === 204) return null;
const data = await response.json().catch(() => null);
if (!response.ok) {
const error = data?.error ?? {};
throw new ApiError(
response.status,
error.code ?? "error",
error.message ?? `The API returned an error (${response.status}).`,
error.details,
);
}
return data;
}
// Turn webargs validation details into a single readable sentence.
export function describeError(error) {
const fields = error.details?.json ?? error.details?.query;
if (fields) {
return Object.entries(fields)
.map(([field, messages]) => `${field}: ${[].concat(messages).join(" ")}`)
.join(" ");
}
return error.message;
}