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
This commit is contained in:
1 parent
0d49311848
commit
b509cd2b60
24 files changed
+1879
No files matched your search
@@ -0,0 +1,89 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { ApiError, api } from "./api.js";
|
||||
import { errorBox, h, replace } from "./dom.js";
|
||||
import { signedInPage } from "./layout.js";
|
||||
|
||||
const root = document.getElementById("approve");
|
||||
const token = new URLSearchParams(location.search).get("token");
|
||||
|
||||
await signedInPage("");
|
||||
|
||||
if (!token) {
|
||||
replace(root, h("h1", {}, "Nothing to approve"), h("p", { class: "lede" }, "This link is missing its token. Start signing in from your player again."));
|
||||
} else {
|
||||
try {
|
||||
const info = await api(`/tokens/${encodeURIComponent(token)}`);
|
||||
info.approved ? showApproved(info.app_name) : showRequest(info.app_name);
|
||||
} catch (error) {
|
||||
showProblem(error);
|
||||
}
|
||||
}
|
||||
|
||||
function showRequest(appName) {
|
||||
const allow = h("button", { type: "button", class: "button" }, "Allow access");
|
||||
allow.addEventListener("click", async () => {
|
||||
allow.disabled = true;
|
||||
try {
|
||||
await api("/tokens/approve", { method: "POST", body: { token } });
|
||||
showApproved(appName);
|
||||
} catch (error) {
|
||||
allow.disabled = false;
|
||||
root.append(errorBox(error.message));
|
||||
}
|
||||
});
|
||||
replace(
|
||||
root,
|
||||
h("h1", {}, "Allow access?"),
|
||||
h("div", { class: "approve-app" }, appName),
|
||||
h("p", { class: "lede" }, "It wants to scrobble to your account and read your listening history. You can revoke this at any time from Sessions."),
|
||||
h("div", { class: "button-row" }, allow, h("a", { class: "button button-quiet", href: "index.html" }, "Don't allow")),
|
||||
);
|
||||
}
|
||||
|
||||
function showApproved(appName) {
|
||||
replace(
|
||||
root,
|
||||
h("h1", {}, "Access allowed"),
|
||||
h("div", { class: "approve-app" }, appName),
|
||||
h("p", { class: "lede" }, "It can now scrobble to your account. Go back to it to finish signing in."),
|
||||
h("a", { class: "button button-quiet", href: "sessions.html" }, "View sessions"),
|
||||
);
|
||||
}
|
||||
|
||||
function showProblem(error) {
|
||||
const expired = error instanceof ApiError && error.status === 404;
|
||||
replace(
|
||||
root,
|
||||
h("h1", {}, expired ? "This link has expired" : "Something went wrong"),
|
||||
expired
|
||||
? h("p", { class: "lede" }, "Sign-in links last an hour and work once. Start signing in from your player again to get a new one.")
|
||||
: errorBox(error.message),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { api, apiBase, describeError } from "./api.js";
|
||||
import { errorBox, formatDate, h, replace } from "./dom.js";
|
||||
import { signedInPage } from "./layout.js";
|
||||
|
||||
const list = document.getElementById("apps");
|
||||
const messages = document.getElementById("messages");
|
||||
const form = document.getElementById("create-app");
|
||||
|
||||
const user = await signedInPage("apps.html");
|
||||
renderSetup();
|
||||
await refresh();
|
||||
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const button = form.querySelector("button");
|
||||
button.disabled = true;
|
||||
replace(messages);
|
||||
try {
|
||||
const created = await api("/apps", { method: "POST", body: { name: form.elements.name.value.trim() } });
|
||||
form.reset();
|
||||
await refresh(created.api_key);
|
||||
replace(messages, h("p", { class: "notice notice-ok", role: "status" }, `Created ${created.name}. Copy its key and secret into the player.`));
|
||||
} catch (error) {
|
||||
replace(messages, errorBox(describeError(error)));
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
async function refresh(revealKey) {
|
||||
try {
|
||||
const apps = await api("/apps");
|
||||
if (!apps.length) {
|
||||
replace(list, h("li", { class: "empty" }, "No apps yet. Create one above for each player you want to connect."));
|
||||
return;
|
||||
}
|
||||
replace(list, apps.map((app) => appRow(app, app.api_key === revealKey)));
|
||||
} catch (error) {
|
||||
replace(list, h("li", {}, errorBox(error.message)));
|
||||
}
|
||||
}
|
||||
|
||||
function appRow(app, reveal) {
|
||||
const row = h("li");
|
||||
const secret = h("code", {}, reveal ? app.shared_secret : "••••••••••••••••");
|
||||
const toggle = h("button", { type: "button", class: "link-button" }, reveal ? "Hide" : "Show");
|
||||
let shown = reveal;
|
||||
toggle.addEventListener("click", () => {
|
||||
shown = !shown;
|
||||
secret.textContent = shown ? app.shared_secret : "••••••••••••••••";
|
||||
toggle.textContent = shown ? "Hide" : "Show";
|
||||
});
|
||||
|
||||
const actions = h("div", { class: "confirm" });
|
||||
const askDelete = () =>
|
||||
replace(
|
||||
actions,
|
||||
h("span", { class: "muted" }, "Players using this app stop scrobbling."),
|
||||
h("button", { type: "button", class: "button button-danger", onclick: () => remove(app, actions) }, "Delete app"),
|
||||
h("button", { type: "button", class: "button button-quiet", onclick: resetActions }, "Keep it"),
|
||||
);
|
||||
const resetActions = () =>
|
||||
replace(actions, h("button", { type: "button", class: "button button-quiet", onclick: askDelete }, "Delete"));
|
||||
resetActions();
|
||||
|
||||
return replace(
|
||||
row,
|
||||
h("div", { class: "row-head" }, h("span", { class: "row-title" }, app.name), actions),
|
||||
h(
|
||||
"dl",
|
||||
{ class: "keys" },
|
||||
h("dt", {}, "API key"),
|
||||
h("dd", {}, h("code", {}, app.api_key), copyButton(app.api_key)),
|
||||
h("dt", {}, "Shared secret"),
|
||||
h("dd", {}, secret, toggle, copyButton(app.shared_secret)),
|
||||
h("dt", {}, "Created"),
|
||||
h("dd", {}, formatDate(app.created_at)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async function remove(app, actions) {
|
||||
try {
|
||||
await api(`/apps/${encodeURIComponent(app.api_key)}`, { method: "DELETE" });
|
||||
await refresh();
|
||||
replace(messages, h("p", { class: "notice notice-ok", role: "status" }, `Deleted ${app.name}.`));
|
||||
} catch (error) {
|
||||
replace(actions, errorBox(error.message));
|
||||
}
|
||||
}
|
||||
|
||||
function copyButton(value) {
|
||||
const button = h("button", { type: "button", class: "link-button" }, "Copy");
|
||||
button.addEventListener("click", async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(value);
|
||||
button.textContent = "Copied";
|
||||
} catch {
|
||||
button.textContent = "Select and copy manually";
|
||||
}
|
||||
setTimeout(() => {
|
||||
button.textContent = "Copy";
|
||||
}, 2000);
|
||||
});
|
||||
return button;
|
||||
}
|
||||
|
||||
function renderSetup() {
|
||||
replace(
|
||||
document.getElementById("setup"),
|
||||
h("dt", {}, "API URL"),
|
||||
h("dd", {}, h("code", {}, `${apiBase}/2.0/`)),
|
||||
h("dt", {}, "Username"),
|
||||
h("dd", {}, h("code", {}, user.username)),
|
||||
h("dt", {}, "Password"),
|
||||
h("dd", {}, "Your Scrobbler password"),
|
||||
h("dt", {}, "Key and secret"),
|
||||
h("dd", {}, "From one of the apps above"),
|
||||
h("dt", {}, "API reference"),
|
||||
h("dd", {}, h("a", { href: `${apiBase}/api/docs` }, "Interactive API docs")),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
import { api } from "./api.js";
|
||||
import { errorBox, formatDate, formatDuration, h, num, replace, timeAgo } from "./dom.js";
|
||||
import { signedInPage } from "./layout.js";
|
||||
|
||||
const PERIODS = [
|
||||
["7day", "7 days"],
|
||||
["1month", "30 days"],
|
||||
["12month", "12 months"],
|
||||
["overall", "All time"],
|
||||
];
|
||||
const PERIOD_KEY = "scrobbler.period";
|
||||
const SEGMENTS = 10; // lit segments per spectrum column at the busiest day
|
||||
const NOW_PLAYING_POLL_MS = 30_000;
|
||||
|
||||
const panel = document.getElementById("panel");
|
||||
const main = document.getElementById("main");
|
||||
|
||||
let progressTimer;
|
||||
|
||||
await signedInPage("index.html");
|
||||
renderPeriodSelector();
|
||||
await Promise.all([loadPanel(), loadTop(currentPeriod()), loadRecent()]).catch(showError);
|
||||
setInterval(() => refreshDisplay().catch(() => {}), NOW_PLAYING_POLL_MS);
|
||||
|
||||
function showError(error) {
|
||||
main.prepend(errorBox(error.message));
|
||||
}
|
||||
|
||||
// ---- Front panel ------------------------------------------------------------
|
||||
|
||||
async function loadPanel() {
|
||||
const [nowPlaying, summary, counts, recent] = await Promise.all([
|
||||
api("/me/now-playing"),
|
||||
api("/me/summary"),
|
||||
api("/me/counts?period=1month&bucket=day"),
|
||||
api("/me/recent?limit=1"),
|
||||
]);
|
||||
const display = h("div", { class: "display" });
|
||||
replace(panel, display, readouts(summary), spectrum(counts));
|
||||
renderDisplay(display, nowPlaying.now_playing, recent.items[0]);
|
||||
}
|
||||
|
||||
async function refreshDisplay() {
|
||||
const display = panel.querySelector(".display");
|
||||
if (!display) return;
|
||||
const [nowPlaying, recent] = await Promise.all([api("/me/now-playing"), api("/me/recent?limit=1")]);
|
||||
renderDisplay(display, nowPlaying.now_playing, recent.items[0]);
|
||||
}
|
||||
|
||||
function renderDisplay(display, playing, last) {
|
||||
clearInterval(progressTimer);
|
||||
display.classList.toggle("display-idle", !playing);
|
||||
|
||||
if (!playing) {
|
||||
replace(
|
||||
display,
|
||||
h("p", { class: "display-status" }, "Idle"),
|
||||
h("p", { class: "display-track" }, "Nothing playing"),
|
||||
last
|
||||
? h(
|
||||
"p",
|
||||
{ class: "display-meta" },
|
||||
"Last played ",
|
||||
h("strong", {}, last.track),
|
||||
" by ",
|
||||
h("strong", {}, last.artist),
|
||||
`, ${timeAgo(last.played_at)}`,
|
||||
)
|
||||
: h("p", { class: "display-meta" }, "Connect a player on the Apps page to start scrobbling."),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const fill = h("div", { class: "progress-fill" });
|
||||
const elapsed = h("span", {});
|
||||
replace(
|
||||
display,
|
||||
h("p", { class: "display-status" }, "Now playing"),
|
||||
h("p", { class: "display-track" }, playing.track),
|
||||
h(
|
||||
"p",
|
||||
{ class: "display-meta" },
|
||||
h("strong", {}, playing.artist),
|
||||
playing.album ? [" from ", h("strong", {}, playing.album)] : null,
|
||||
),
|
||||
playing.duration
|
||||
? h(
|
||||
"div",
|
||||
{ class: "progress" },
|
||||
elapsed,
|
||||
h("div", { class: "progress-track", "aria-hidden": "true" }, fill),
|
||||
h("span", {}, formatDuration(playing.duration)),
|
||||
)
|
||||
: null,
|
||||
);
|
||||
|
||||
if (playing.duration) {
|
||||
const started = new Date(playing.started_at).getTime();
|
||||
const tick = () => {
|
||||
const seconds = Math.min(playing.duration, (Date.now() - started) / 1000);
|
||||
elapsed.textContent = formatDuration(seconds);
|
||||
fill.style.width = `${(seconds / playing.duration) * 100}%`;
|
||||
};
|
||||
tick();
|
||||
progressTimer = setInterval(tick, 1000);
|
||||
}
|
||||
}
|
||||
|
||||
function readouts(summary) {
|
||||
const item = (value, label) => h("div", {}, h("dt", {}, label), h("dd", {}, num(value)));
|
||||
return h(
|
||||
"dl",
|
||||
{ class: "readouts" },
|
||||
item(summary.scrobbles, "scrobbles"),
|
||||
item(summary.artists, "artists"),
|
||||
item(summary.tracks, "tracks"),
|
||||
);
|
||||
}
|
||||
|
||||
// Daily plays for the last 30 days, drawn as a segmented level meter.
|
||||
function spectrum(counts) {
|
||||
const NS = "http://www.w3.org/2000/svg";
|
||||
const width = 1000;
|
||||
const height = 96;
|
||||
const gap = 4;
|
||||
const max = Math.max(1, ...counts.map((c) => c.count));
|
||||
const columnWidth = width / counts.length;
|
||||
const segmentHeight = height / SEGMENTS;
|
||||
const total = counts.reduce((sum, c) => sum + c.count, 0);
|
||||
|
||||
const svg = document.createElementNS(NS, "svg");
|
||||
svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
|
||||
svg.setAttribute("preserveAspectRatio", "none");
|
||||
svg.setAttribute("role", "img");
|
||||
svg.setAttribute("aria-label", `Plays per day over the last ${counts.length} days: ${num(total)} in total`);
|
||||
|
||||
counts.forEach((day, i) => {
|
||||
const lit = day.count ? Math.max(1, Math.round((day.count / max) * SEGMENTS)) : 0;
|
||||
const group = document.createElementNS(NS, "g");
|
||||
const title = document.createElementNS(NS, "title");
|
||||
title.textContent = `${formatDate(day.start)}: ${num(day.count)} ${day.count === 1 ? "play" : "plays"}`;
|
||||
group.append(title);
|
||||
for (let s = 0; s < SEGMENTS; s++) {
|
||||
const rect = document.createElementNS(NS, "rect");
|
||||
rect.setAttribute("x", i * columnWidth + gap / 2);
|
||||
rect.setAttribute("y", height - (s + 1) * segmentHeight + 1.5);
|
||||
rect.setAttribute("width", columnWidth - gap);
|
||||
rect.setAttribute("height", segmentHeight - 3);
|
||||
rect.setAttribute("class", s < lit ? "seg-on" : "seg-off");
|
||||
group.append(rect);
|
||||
}
|
||||
svg.append(group);
|
||||
});
|
||||
|
||||
return h(
|
||||
"div",
|
||||
{ class: "spectrum" },
|
||||
svg,
|
||||
h(
|
||||
"div",
|
||||
{ class: "spectrum-axis" },
|
||||
h("span", {}, formatDate(counts[0].start)),
|
||||
h("span", {}, `${num(total)} plays in 30 days`),
|
||||
h("span", {}, "Today"),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// ---- Most played ------------------------------------------------------------
|
||||
|
||||
function currentPeriod() {
|
||||
try {
|
||||
const saved = localStorage.getItem(PERIOD_KEY);
|
||||
if (PERIODS.some(([value]) => value === saved)) return saved;
|
||||
} catch {
|
||||
// Storage unavailable: fall back to the default.
|
||||
}
|
||||
return "7day";
|
||||
}
|
||||
|
||||
function renderPeriodSelector() {
|
||||
const selector = document.getElementById("period");
|
||||
const active = currentPeriod();
|
||||
for (const [value, label] of PERIODS) {
|
||||
const id = `period-${value}`;
|
||||
selector.append(
|
||||
h("input", { type: "radio", name: "period", id, value, checked: value === active }),
|
||||
h("label", { for: id }, label),
|
||||
);
|
||||
}
|
||||
selector.addEventListener("change", (event) => {
|
||||
try {
|
||||
localStorage.setItem(PERIOD_KEY, event.target.value);
|
||||
} catch {
|
||||
// Not remembered; that's fine.
|
||||
}
|
||||
loadTop(event.target.value).catch(showError);
|
||||
});
|
||||
}
|
||||
|
||||
async function loadTop(period) {
|
||||
const [artists, tracks] = await Promise.all([
|
||||
api(`/me/top/artists?period=${period}&limit=10`),
|
||||
api(`/me/top/tracks?period=${period}&limit=10`),
|
||||
]);
|
||||
renderRanking(document.getElementById("top-artists"), artists.items, false);
|
||||
renderRanking(document.getElementById("top-tracks"), tracks.items, true);
|
||||
}
|
||||
|
||||
function renderRanking(list, items, withArtist) {
|
||||
if (!items.length) {
|
||||
replace(list, h("li", { class: "empty" }, "No plays in this period."));
|
||||
return;
|
||||
}
|
||||
const max = items[0].playcount;
|
||||
replace(
|
||||
list,
|
||||
items.map((item) =>
|
||||
h(
|
||||
"li",
|
||||
{},
|
||||
h("span", { class: "rank" }, item.rank),
|
||||
h("span", { class: "name" }, item.name, withArtist ? h("span", { class: "by" }, item.artist) : null),
|
||||
h("span", { class: "plays" }, num(item.playcount)),
|
||||
h("span", {
|
||||
class: "meter",
|
||||
"aria-hidden": "true",
|
||||
style: `width: calc((100% - 2.75rem) * ${item.playcount / max})`,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// ---- Recently played ----------------------------------------------------------
|
||||
|
||||
async function loadRecent() {
|
||||
const recent = await api("/me/recent?limit=10");
|
||||
const list = document.getElementById("recent");
|
||||
if (!recent.items.length) {
|
||||
replace(list, h("li", { class: "empty" }, "No scrobbles yet. Connect a player on the Apps page."));
|
||||
return;
|
||||
}
|
||||
replace(
|
||||
list,
|
||||
recent.items.map((s) =>
|
||||
h(
|
||||
"li",
|
||||
{},
|
||||
h("time", { datetime: s.played_at, title: new Date(s.played_at).toLocaleString() }, timeAgo(s.played_at)),
|
||||
h("span", {}, h("span", { class: "track" }, s.track), h("span", { class: "by" }, ` by ${s.artist}`)),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// DOM helpers. Server data only ever reaches the page as text nodes or attribute
|
||||
// values, never as HTML, so track names can't inject markup.
|
||||
|
||||
export function h(tag, attrs = {}, ...children) {
|
||||
const el = document.createElement(tag);
|
||||
for (const [key, value] of Object.entries(attrs ?? {})) {
|
||||
if (value === false || value === null || value === undefined) continue;
|
||||
if (key.startsWith("on") && typeof value === "function") el.addEventListener(key.slice(2), value);
|
||||
else if (key === "class") el.className = value;
|
||||
else if (key === "dataset") Object.assign(el.dataset, value);
|
||||
else el.setAttribute(key, value === true ? "" : String(value));
|
||||
}
|
||||
append(el, children);
|
||||
return el;
|
||||
}
|
||||
|
||||
function append(el, children) {
|
||||
for (const child of children.flat(Infinity)) {
|
||||
if (child === null || child === undefined || child === false) continue;
|
||||
el.append(child instanceof Node ? child : document.createTextNode(String(child)));
|
||||
}
|
||||
}
|
||||
|
||||
export function replace(el, ...children) {
|
||||
el.replaceChildren();
|
||||
append(el, children);
|
||||
return el;
|
||||
}
|
||||
|
||||
const numberFormat = new Intl.NumberFormat();
|
||||
export const num = (n) => numberFormat.format(n);
|
||||
|
||||
const relative = new Intl.RelativeTimeFormat(undefined, { numeric: "auto" });
|
||||
const UNITS = [
|
||||
["year", 365 * 86400],
|
||||
["month", 30 * 86400],
|
||||
["week", 7 * 86400],
|
||||
["day", 86400],
|
||||
["hour", 3600],
|
||||
["minute", 60],
|
||||
];
|
||||
|
||||
export function timeAgo(value) {
|
||||
const seconds = (new Date(value).getTime() - Date.now()) / 1000;
|
||||
for (const [unit, size] of UNITS) {
|
||||
if (Math.abs(seconds) >= size) return relative.format(Math.round(seconds / size), unit);
|
||||
}
|
||||
return "just now";
|
||||
}
|
||||
|
||||
export const formatTime = (value) =>
|
||||
new Date(value).toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });
|
||||
|
||||
export const formatDay = (value) =>
|
||||
new Date(value).toLocaleDateString(undefined, { weekday: "long", day: "numeric", month: "long", year: "numeric" });
|
||||
|
||||
export const formatDate = (value) =>
|
||||
new Date(value).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" });
|
||||
|
||||
export function formatDuration(seconds) {
|
||||
const s = Math.max(0, Math.floor(seconds));
|
||||
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export function errorBox(message) {
|
||||
return h("p", { class: "notice notice-error", role: "alert" }, message);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { api } from "./api.js";
|
||||
import { errorBox, formatDay, formatTime, h, num, replace } from "./dom.js";
|
||||
import { signedInPage } from "./layout.js";
|
||||
|
||||
const PER_PAGE = 50;
|
||||
const container = document.getElementById("history");
|
||||
const pager = document.getElementById("pager");
|
||||
|
||||
await signedInPage("history.html");
|
||||
const page = Math.max(1, Number.parseInt(new URLSearchParams(location.search).get("page"), 10) || 1);
|
||||
|
||||
try {
|
||||
const result = await api(`/me/recent?page=${page}&limit=${PER_PAGE}`);
|
||||
render(result);
|
||||
} catch (error) {
|
||||
replace(container, errorBox(error.message));
|
||||
}
|
||||
|
||||
function render(result) {
|
||||
document.getElementById("history-summary").textContent =
|
||||
`${num(result.total)} scrobbles, newest first. Page ${result.page} of ${result.total_pages}.`;
|
||||
|
||||
if (!result.items.length) {
|
||||
replace(container, h("p", { class: "empty" }, "Nothing here yet. Tracks appear once a connected player scrobbles them."));
|
||||
return;
|
||||
}
|
||||
|
||||
// Group by local calendar day.
|
||||
const days = new Map();
|
||||
for (const scrobble of result.items) {
|
||||
const key = new Date(scrobble.played_at).toDateString();
|
||||
if (!days.has(key)) days.set(key, []);
|
||||
days.get(key).push(scrobble);
|
||||
}
|
||||
replace(
|
||||
container,
|
||||
[...days.values()].map((scrobbles) => [
|
||||
h("h2", { class: "log-day" }, formatDay(scrobbles[0].played_at)),
|
||||
h(
|
||||
"ol",
|
||||
{ class: "log log-clock" },
|
||||
scrobbles.map((s) =>
|
||||
h(
|
||||
"li",
|
||||
{},
|
||||
h("time", { datetime: s.played_at }, formatTime(s.played_at)),
|
||||
h(
|
||||
"span",
|
||||
{},
|
||||
h("span", { class: "track" }, s.track),
|
||||
h("span", { class: "by" }, ` by ${s.artist}`),
|
||||
s.album ? h("span", { class: "by" }, `, from ${s.album}`) : null,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
]),
|
||||
);
|
||||
|
||||
replace(
|
||||
pager,
|
||||
result.page > 1 ? h("a", { class: "button button-quiet", href: `?page=${result.page - 1}` }, "Newer") : h("span"),
|
||||
result.page < result.total_pages
|
||||
? h("a", { class: "button button-quiet", href: `?page=${result.page + 1}` }, "Older")
|
||||
: h("span"),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// Shared page shell: site header, navigation, sign-in guard.
|
||||
|
||||
import { api, getToken, redirectToLogin, setToken } from "./api.js";
|
||||
import { h, replace } from "./dom.js";
|
||||
|
||||
const NAV = [
|
||||
["index.html", "Overview"],
|
||||
["history.html", "History"],
|
||||
["apps.html", "Apps"],
|
||||
["sessions.html", "Sessions"],
|
||||
];
|
||||
|
||||
// Renders the header and returns the signed-in user (redirecting if there isn't one).
|
||||
export async function signedInPage(active) {
|
||||
if (!getToken()) {
|
||||
redirectToLogin();
|
||||
return new Promise(() => {}); // navigation is under way
|
||||
}
|
||||
const header = document.getElementById("site-header");
|
||||
replace(header, brand(), nav(active));
|
||||
const user = await api("/auth/me");
|
||||
header.append(
|
||||
h(
|
||||
"div",
|
||||
{ class: "account" },
|
||||
h("span", { class: "account-name" }, user.username),
|
||||
h("button", { type: "button", class: "link-button", onclick: signOut }, "Sign out"),
|
||||
),
|
||||
);
|
||||
return user;
|
||||
}
|
||||
|
||||
export function publicPage() {
|
||||
replace(document.getElementById("site-header"), brand());
|
||||
}
|
||||
|
||||
function brand() {
|
||||
return h("a", { class: "brand", href: "index.html" }, h("span", { class: "brand-mark", "aria-hidden": "true" }), "Scrobbler");
|
||||
}
|
||||
|
||||
function nav(active) {
|
||||
return h(
|
||||
"nav",
|
||||
{ "aria-label": "Main" },
|
||||
h(
|
||||
"ul",
|
||||
{},
|
||||
NAV.map(([href, label]) =>
|
||||
h("li", {}, h("a", { href, "aria-current": href === active ? "page" : false }, label)),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async function signOut() {
|
||||
try {
|
||||
await api("/auth/logout", { method: "POST" });
|
||||
} finally {
|
||||
setToken(null);
|
||||
location.href = "login.html";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { api, describeError, getToken, safeNext, setToken } from "./api.js";
|
||||
import { errorBox, replace } from "./dom.js";
|
||||
import { publicPage } from "./layout.js";
|
||||
|
||||
publicPage();
|
||||
const next = safeNext(new URLSearchParams(location.search).get("next"));
|
||||
if (getToken()) location.replace(next);
|
||||
|
||||
const form = document.getElementById("login");
|
||||
const messages = document.getElementById("messages");
|
||||
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const button = form.querySelector("button");
|
||||
button.disabled = true;
|
||||
replace(messages);
|
||||
try {
|
||||
const { token } = await api("/auth/login", {
|
||||
method: "POST",
|
||||
auth: false,
|
||||
body: { username: form.elements.username.value.trim(), password: form.elements.password.value },
|
||||
});
|
||||
setToken(token);
|
||||
location.href = next;
|
||||
} catch (error) {
|
||||
replace(messages, errorBox(describeError(error)));
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { api, describeError, setToken } from "./api.js";
|
||||
import { errorBox, replace } from "./dom.js";
|
||||
import { publicPage } from "./layout.js";
|
||||
|
||||
publicPage();
|
||||
const form = document.getElementById("register");
|
||||
const messages = document.getElementById("messages");
|
||||
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
if (!form.reportValidity()) return;
|
||||
const button = form.querySelector("button");
|
||||
button.disabled = true;
|
||||
replace(messages);
|
||||
try {
|
||||
const { token } = await api("/auth/register", {
|
||||
method: "POST",
|
||||
auth: false,
|
||||
body: {
|
||||
username: form.elements.username.value.trim(),
|
||||
email: form.elements.email.value.trim(),
|
||||
password: form.elements.password.value,
|
||||
},
|
||||
});
|
||||
setToken(token);
|
||||
location.href = "apps.html";
|
||||
} catch (error) {
|
||||
replace(messages, errorBox(describeError(error)));
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import { api } from "./api.js";
|
||||
import { errorBox, formatDate, h, replace, timeAgo } from "./dom.js";
|
||||
import { signedInPage } from "./layout.js";
|
||||
|
||||
const list = document.getElementById("sessions");
|
||||
const messages = document.getElementById("messages");
|
||||
|
||||
await signedInPage("sessions.html");
|
||||
await refresh();
|
||||
|
||||
async function refresh() {
|
||||
try {
|
||||
const sessions = await api("/sessions");
|
||||
if (!sessions.length) {
|
||||
replace(list, h("li", { class: "empty" }, "No players are signed in. They appear here once they sign in with an app's key."));
|
||||
return;
|
||||
}
|
||||
replace(list, sessions.map(sessionRow));
|
||||
} catch (error) {
|
||||
replace(list, h("li", {}, errorBox(error.message)));
|
||||
}
|
||||
}
|
||||
|
||||
function sessionRow(session) {
|
||||
const actions = h("div", { class: "confirm" });
|
||||
const reset = () =>
|
||||
replace(actions, h("button", { type: "button", class: "button button-quiet", onclick: ask }, "Revoke"));
|
||||
const ask = () =>
|
||||
replace(
|
||||
actions,
|
||||
h("button", { type: "button", class: "button button-danger", onclick: () => revoke(session, actions) }, "Revoke access"),
|
||||
h("button", { type: "button", class: "button button-quiet", onclick: reset }, "Cancel"),
|
||||
);
|
||||
reset();
|
||||
return h(
|
||||
"li",
|
||||
{},
|
||||
h(
|
||||
"div",
|
||||
{ class: "row-head" },
|
||||
h(
|
||||
"span",
|
||||
{},
|
||||
h("span", { class: "row-title" }, session.app_name),
|
||||
h("span", { class: "muted", title: formatDate(session.created_at) }, ` Signed in ${timeAgo(session.created_at)}`),
|
||||
),
|
||||
actions,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async function revoke(session, actions) {
|
||||
try {
|
||||
await api(`/sessions/${session.id}`, { method: "DELETE" });
|
||||
await refresh();
|
||||
replace(messages, h("p", { class: "notice notice-ok", role: "status" }, `Revoked ${session.app_name}.`));
|
||||
} catch (error) {
|
||||
replace(actions, errorBox(error.message));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user