From dfd2ef868bb7392bf3839dd664309bc7830472b6 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Tue, 6 Oct 2026 17:14:44 +0100 Subject: [PATCH] Show album art on the song page, dashboard and history New frontend/js/art.js builds a thumbnail that starts as a placeholder and swaps itself for the real cover once (if) it resolves, fetched via the new /api/v1/art/album endpoint with the existing bearer-auth transport and handed to the browser as a blob: object URL (no query-string tokens, no hotlinking). Wired into all four places a track/album appears: the song page's glowing display, the dashboard's "Most played > Albums" list, the dashboard's "Recently played" list, and the full History page - Artists/Tracks rankings are left alone. Also fixes a real reliability gap found during manual testing: Cover Art Archive's existence check (a HEAD request, redirected through archive.org) had no retry at all, unlike the MusicBrainz search next to it, and an occasional slow/flaky response there was enough to fail a lookup outright. It now retries the same way. Co-Authored-By: Claude Sonnet 5 --- frontend/css/style.css | 68 +++++++++++++++++++++++++++++++++++ frontend/index.html | 4 +-- frontend/js/api.js | 23 ++++++++++++ frontend/js/art.js | 29 +++++++++++++++ frontend/js/dashboard.js | 10 ++++-- frontend/js/history.js | 4 ++- frontend/js/song.js | 8 +++-- src/scrobbler/services/art.py | 31 +++++++++++----- 8 files changed, 160 insertions(+), 17 deletions(-) create mode 100644 frontend/js/art.js diff --git a/frontend/css/style.css b/frontend/css/style.css index 065b60a..4b95173 100644 --- a/frontend/css/style.css +++ b/frontend/css/style.css @@ -1079,3 +1079,71 @@ input { margin: 0; font-weight: 600; } + +/* The song page's glowing display gets an art thumbnail alongside its text, when there's one */ +.display-with-art { + display: flex; + align-items: center; + gap: 1.25rem; +} + +.display-with-art .display-body { + flex: 1; + min-width: 0; +} + +.display-art { + width: 4.5rem; + height: 4.5rem; + flex: none; +} + +/* ---- Album art ---------------------------------------------------------------- */ +.art-thumb { + display: block; + border-radius: var(--radius-control); + object-fit: cover; + background: var(--paper-raised); + border: 1px solid var(--rule); +} + +.art-thumb-empty { + position: relative; +} + +/* No artwork: a plain ring, echoing .brand-mark's small round "lamp" motif */ +.art-thumb-empty::after { + content: ""; + position: absolute; + inset: 32%; + border-radius: 50%; + border: 2px solid var(--bar); +} + +/* Most played > Albums: a thumbnail column ahead of the rank */ +.ranking-art li { + grid-template-columns: 2.25rem 2rem minmax(0, 1fr) auto; +} + +.ranking-art .art-thumb { + width: 2.25rem; + height: 2.25rem; +} + +.ranking-art .meter { + left: 5.75rem; +} + +/* Recently played / History: a thumbnail column ahead of the time */ +.log-art li { + grid-template-columns: 2.25rem 8rem minmax(0, 1fr); +} + +.log-art.log-clock li { + grid-template-columns: 2.25rem 3.5rem minmax(0, 1fr); +} + +.log-art .art-thumb { + width: 2.25rem; + height: 2.25rem; +} diff --git a/frontend/index.html b/frontend/index.html index be3c782..529e587 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -31,7 +31,7 @@

Artists

    -

    Albums

      +

      Albums

        Tracks

          @@ -40,7 +40,7 @@

          Recently played

          Full history -
            +
              diff --git a/frontend/js/api.js b/frontend/js/api.js index 6283117..308f737 100644 --- a/frontend/js/api.js +++ b/frontend/js/api.js @@ -40,6 +40,29 @@ export function redirectToLogin() { location.href = `login.html?next=${encodeURIComponent(safeNext(here + location.search))}`; } +// Fetches a binary resource (e.g. album art) with the same bearer-auth transport as api(), +// returning a blob: object URL, or null on any failure (including a 404 "no art" response) - +// the caller treats "missing" and "couldn't fetch" the same way: show a placeholder. +export async function fetchImage(path) { + const headers = {}; + const token = getToken(); + if (token) headers.Authorization = `Bearer ${token}`; + + let response; + try { + response = await fetch(`${apiBase}/api/v1${path}`, { headers }); + } catch { + return null; + } + if (response.status === 401) { + setToken(null); + redirectToLogin(); + return null; + } + if (!response.ok) return null; + return URL.createObjectURL(await response.blob()); +} + export async function api(path, { method = "GET", body, auth = true } = {}) { const headers = {}; if (body !== undefined) headers["Content-Type"] = "application/json"; diff --git a/frontend/js/art.js b/frontend/js/art.js new file mode 100644 index 0000000..9a0e665 --- /dev/null +++ b/frontend/js/art.js @@ -0,0 +1,29 @@ +// A small thumbnail that starts as a placeholder and swaps itself for the real album art +// once (if) it resolves. Shared by every list/page that shows art. + +import { fetchImage } from "./api.js"; +import { h } from "./dom.js"; + +const cache = new Map(); // dedupes repeat/concurrent lookups for the same album within a page + +export function artThumb(artist, album, extraClass) { + const classes = extraClass ? `art-thumb ${extraClass}` : "art-thumb"; + const el = h("div", { class: `${classes} art-thumb-empty` }); + if (!album) return el; // nothing to look up + + const key = `${artist.toLowerCase()}␟${album.toLowerCase()}`; + if (!cache.has(key)) { + cache.set( + key, + fetchImage(`/art/album?artist=${encodeURIComponent(artist)}&album=${encodeURIComponent(album)}`), + ); + } + cache.get(key).then((url) => { + if (!url) return; // miss or failed fetch: leave the placeholder + const img = h("img", { class: classes, alt: "", loading: "lazy" }); + img.addEventListener("load", () => URL.revokeObjectURL(url), { once: true }); + img.src = url; + el.replaceWith(img); + }); + return el; +} diff --git a/frontend/js/dashboard.js b/frontend/js/dashboard.js index cf92a70..c696418 100644 --- a/frontend/js/dashboard.js +++ b/frontend/js/dashboard.js @@ -1,4 +1,5 @@ import { api } from "./api.js"; +import { artThumb } from "./art.js"; import { errorBox, formatDuration, h, num, replace, timeAgo } from "./dom.js"; import { signedInPage } from "./layout.js"; import { spectrum } from "./spectrum.js"; @@ -157,16 +158,17 @@ async function loadTop(period) { api(`/me/top/tracks?period=${period}&limit=10`), ]); renderRanking(document.getElementById("top-artists"), artists.items, false); - renderRanking(document.getElementById("top-albums"), albums.items, true); + renderRanking(document.getElementById("top-albums"), albums.items, true, false, true); renderRanking(document.getElementById("top-tracks"), tracks.items, true, true); } -function renderRanking(list, items, withArtist, linkToSong = false) { +function renderRanking(list, items, withArtist, linkToSong = false, withArt = false) { if (!items.length) { replace(list, h("li", { class: "empty" }, "No plays in this period.")); return; } const max = items[0].playcount; + const meterOffset = withArt ? "5.75rem" : "2.75rem"; replace( list, items.map((item) => { @@ -177,13 +179,14 @@ function renderRanking(list, items, withArtist, linkToSong = false) { return h( "li", {}, + withArt ? artThumb(item.artist, item.name) : null, h("span", { class: "rank" }, item.rank), name, h("span", { class: "plays" }, num(item.playcount)), h("span", { class: "meter", "aria-hidden": "true", - style: `width: calc((100% - 2.75rem) * ${item.playcount / max})`, + style: `width: calc((100% - ${meterOffset}) * ${item.playcount / max})`, }), ); }), @@ -261,6 +264,7 @@ async function loadRecent() { h( "li", {}, + artThumb(s.album_artist || s.artist, s.album), h("time", { datetime: s.played_at, title: new Date(s.played_at).toLocaleString() }, timeAgo(s.played_at)), h( "a", diff --git a/frontend/js/history.js b/frontend/js/history.js index 6e226d2..fde5dfb 100644 --- a/frontend/js/history.js +++ b/frontend/js/history.js @@ -1,4 +1,5 @@ import { api } from "./api.js"; +import { artThumb } from "./art.js"; import { errorBox, formatDay, formatTime, h, num, replace } from "./dom.js"; import { signedInPage } from "./layout.js"; @@ -38,11 +39,12 @@ function render(result) { h("h2", { class: "log-day" }, formatDay(scrobbles[0].played_at)), h( "ol", - { class: "log log-clock" }, + { class: "log log-clock log-art" }, scrobbles.map((s) => h( "li", {}, + artThumb(s.album_artist || s.artist, s.album), h("time", { datetime: s.played_at }, formatTime(s.played_at)), h( "span", diff --git a/frontend/js/song.js b/frontend/js/song.js index ad4d5d2..2debcf6 100644 --- a/frontend/js/song.js +++ b/frontend/js/song.js @@ -1,4 +1,5 @@ import { api } from "./api.js"; +import { artThumb } from "./art.js"; import { errorBox, formatDate, formatDay, formatDuration, formatTime, h, num, replace } from "./dom.js"; import { signedInPage } from "./layout.js"; import { spectrum } from "./spectrum.js"; @@ -38,9 +39,9 @@ function render(result) { document.title = `${result.track} · Scrobbler`; const m = result.metadata; - const display = h( + const body = h( "div", - { class: "display" }, + { class: "display-body" }, h("p", { class: "display-status" }, "Now viewing"), h("p", { class: "display-track" }, result.track), h( @@ -50,6 +51,9 @@ function render(result) { m.album ? [" from ", h("strong", {}, m.album)] : null, ), ); + const display = m.album + ? h("div", { class: "display display-with-art" }, artThumb(m.album_artist || result.artist, m.album, "display-art"), body) + : h("div", { class: "display" }, body); replace(panel, display, readouts(m), spectrum(result.counts, `Plays of ${result.track}`, "90 days")); const row = (label, value) => diff --git a/src/scrobbler/services/art.py b/src/scrobbler/services/art.py index e0bd76b..738444c 100644 --- a/src/scrobbler/services/art.py +++ b/src/scrobbler/services/art.py @@ -106,17 +106,30 @@ def _find_release_group(artist: str, album: str) -> str | None: def _cover_art_url(release_group_mbid: str) -> str | None: - """The release-group's front cover URL, or None if Cover Art Archive has none.""" + """The release-group's front cover URL, or None if Cover Art Archive has none. + + Cover Art Archive redirects to archive.org for the actual image, which is + occasionally slow — retried the same way as the MusicBrainz search, with a longer + per-attempt timeout to give that redirect room. + """ coverart_url = current_app.config["COVERART_API_URL"] url = f"{coverart_url}release-group/{release_group_mbid}/front-500" - request = urllib.request.Request(url, method="HEAD") - try: - with urllib.request.urlopen(request, timeout=10): - return url - except urllib.error.HTTPError as err: - if err.code == 404: - return None - raise + retries = current_app.config["MUSICBRAINZ_RETRIES"] + for attempt in range(retries + 1): + request = urllib.request.Request(url, method="HEAD") + try: + with urllib.request.urlopen(request, timeout=15): + return url + except urllib.error.HTTPError as err: + if err.code == 404: + return None + if attempt == retries or err.code < 500: + raise + except (urllib.error.URLError, TimeoutError): + if attempt == retries: + raise + time.sleep(min(10, 2**attempt)) + raise TimeoutError("Cover Art Archive request exhausted its retries") def lookup(artist: str, album: str) -> ArtResult: