diff --git a/docs/openapi.json b/docs/openapi.json index e5f4a02..1492953 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -3918,6 +3918,13 @@ "items": { "$ref": "#/components/schemas/Scrobble" } + }, + "counts": { + "type": "array", + "description": "Daily plays over the last 90 days", + "items": { + "$ref": "#/components/schemas/Count" + } } }, "additionalProperties": false diff --git a/frontend/js/dashboard.js b/frontend/js/dashboard.js index ee207dd..7c08145 100644 --- a/frontend/js/dashboard.js +++ b/frontend/js/dashboard.js @@ -1,6 +1,7 @@ import { api } from "./api.js"; -import { errorBox, formatDate, formatDuration, h, num, replace, timeAgo } from "./dom.js"; +import { errorBox, formatDuration, h, num, replace, timeAgo } from "./dom.js"; import { signedInPage } from "./layout.js"; +import { spectrum } from "./spectrum.js"; const PERIODS = [ ["7day", "7 days"], @@ -9,7 +10,6 @@ const PERIODS = [ ["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"); @@ -118,55 +118,6 @@ function readouts(summary) { ); } -// 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() { diff --git a/frontend/js/song.js b/frontend/js/song.js index ac3fdcd..ad4d5d2 100644 --- a/frontend/js/song.js +++ b/frontend/js/song.js @@ -1,10 +1,10 @@ import { api } from "./api.js"; import { errorBox, formatDate, formatDay, formatDuration, formatTime, h, num, replace } from "./dom.js"; import { signedInPage } from "./layout.js"; +import { spectrum } from "./spectrum.js"; const PER_PAGE = 50; -const title = document.getElementById("song-title"); -const subtitle = document.getElementById("song-subtitle"); +const panel = document.getElementById("panel"); const meta = document.getElementById("song-meta"); const history = document.getElementById("song-history"); const pager = document.getElementById("pager"); @@ -17,7 +17,7 @@ const track = params.get("track") ?? ""; const page = Math.max(1, Number.parseInt(params.get("page"), 10) || 1); if (!artist || !track) { - replace(history, h("p", { class: "notice" }, "Use the search box on the dashboard to find a song.")); + replace(panel, h("p", { class: "notice" }, "Use the search box on the dashboard to find a song.")); } else { try { const result = await api( @@ -25,12 +25,10 @@ if (!artist || !track) { ); render(result); } catch (error) { - title.textContent = track; - subtitle.textContent = `by ${artist}`; replace( - history, + panel, error.status === 404 - ? h("p", { class: "notice" }, "You've never scrobbled this song.") + ? h("p", { class: "notice" }, `You've never scrobbled "${track}" by ${artist}.`) : errorBox(error.message), ); } @@ -38,18 +36,26 @@ if (!artist || !track) { function render(result) { document.title = `${result.track} ยท Scrobbler`; - title.textContent = result.track; - subtitle.textContent = `by ${result.artist}`; - const m = result.metadata; + + const display = h( + "div", + { class: "display" }, + h("p", { class: "display-status" }, "Now viewing"), + h("p", { class: "display-track" }, result.track), + h( + "p", + { class: "display-meta" }, + h("strong", {}, result.artist), + m.album ? [" from ", h("strong", {}, m.album)] : null, + ), + ); + replace(panel, display, readouts(m), spectrum(result.counts, `Plays of ${result.track}`, "90 days")); + const row = (label, value) => value === null || value === undefined ? null : h("div", {}, h("dt", {}, label), h("dd", {}, value)); replace( meta, - row("Plays", num(m.playcount)), - row("First played", formatDate(m.first_played_at)), - row("Last played", formatDate(m.last_played_at)), - row("Album", m.album), row("Album artist", m.album_artist), row("Track number", m.track_number), row("Duration", m.duration ? formatDuration(m.duration) : null), @@ -95,3 +101,14 @@ function render(result) { : h("span"), ); } + +function readouts(m) { + const item = (value, label) => h("div", {}, h("dt", {}, label), h("dd", {}, value)); + return h( + "dl", + { class: "readouts" }, + item(num(m.playcount), "plays"), + item(formatDate(m.first_played_at), "first played"), + item(formatDate(m.last_played_at), "last played"), + ); +} diff --git a/frontend/js/spectrum.js b/frontend/js/spectrum.js new file mode 100644 index 0000000..6e47d06 --- /dev/null +++ b/frontend/js/spectrum.js @@ -0,0 +1,55 @@ +// A segmented level meter: daily play counts drawn as columns of lit/unlit segments, +// like a hi-fi spectrum analyser. Shared by the dashboard (30 days, all plays) and the +// song page (90 days, one track). + +import { formatDate, h, num } from "./dom.js"; + +const SEGMENTS = 10; // lit segments per column at the busiest day + +export function spectrum(counts, subject = "Plays", windowLabel = "30 days") { + 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", `${subject} 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)} ${subject.toLowerCase()} in ${windowLabel}`), + h("span", {}, "Today"), + ), + ); +} diff --git a/frontend/song.html b/frontend/song.html index a85cc10..db6fa28 100644 --- a/frontend/song.html +++ b/frontend/song.html @@ -12,8 +12,8 @@
-

Song

-

+

Song

+

History

diff --git a/src/scrobbler/api/tracks.py b/src/scrobbler/api/tracks.py index ba1981c..2863778 100644 --- a/src/scrobbler/api/tracks.py +++ b/src/scrobbler/api/tracks.py @@ -40,11 +40,15 @@ def detail(args): artist=args["artist"], track=args["track"], ) + counts = stats.listen_counts( + g.user, period="3month", bucket="day", artist=args["artist"], track=args["track"] + ) return { "artist": metadata.artist, "track": metadata.track, "metadata": metadata, "items": history.items, + "counts": counts, "page": history.page, "per_page": history.per_page, "total": history.total, diff --git a/src/scrobbler/schemas/__init__.py b/src/scrobbler/schemas/__init__.py index c0ff820..f999661 100644 --- a/src/scrobbler/schemas/__init__.py +++ b/src/scrobbler/schemas/__init__.py @@ -171,6 +171,9 @@ class TrackDetailSchema(PageMetaSchema): track = fields.String() metadata = fields.Nested(TrackMetadataSchema) items = fields.List(fields.Nested(ScrobbleSchema)) + counts = fields.List( + fields.Nested(CountSchema), metadata={"description": "Daily plays over the last 90 days"} + ) class SummarySchema(Schema): diff --git a/src/scrobbler/services/stats.py b/src/scrobbler/services/stats.py index 992faa9..c99fcab 100644 --- a/src/scrobbler/services/stats.py +++ b/src/scrobbler/services/stats.py @@ -163,14 +163,25 @@ def top_tracks(user: User, period: str = "overall", page: int = 1, per_page: int return Page(items, page, per_page, total) -def listen_counts(user: User, period: str = "1month", bucket: str = "day") -> list[dict]: +def listen_counts( + user: User, + period: str = "1month", + bucket: str = "day", + artist: str | None = None, + track: str | None = None, +) -> list[dict]: """Scrobbles per bucket (UTC). Empty buckets are included for day buckets.""" if bucket not in BUCKETS: # interpolated into SQL below, so allow-list it raise ValueError(f"bucket must be one of {BUCKETS}") + conditions = _user_scrobbles(user, period) + if artist: + conditions.append(func.lower(Scrobble.artist) == artist.lower()) + if track: + conditions.append(func.lower(Scrobble.track) == track.lower()) bucket_col = func.date_trunc(literal_column(f"'{bucket}'"), Scrobble.played_at, "UTC") query = ( select(bucket_col.label("bucket"), func.count()) - .where(*_user_scrobbles(user, period)) + .where(*conditions) .group_by("bucket") .order_by("bucket") ) diff --git a/tests/test_tracks.py b/tests/test_tracks.py index b37c551..b22adc0 100644 --- a/tests/test_tracks.py +++ b/tests/test_tracks.py @@ -95,6 +95,16 @@ def test_detail_requires_auth(client): assert client.get("/api/v1/me/tracks/search?q=a").status_code == 401 +def test_detail_counts_are_daily_and_scoped_to_the_track(client, auth, history): + body = client.get("/api/v1/me/tracks?artist=Radiohead&track=Reckoner", headers=auth).get_json() + counts = body["counts"] + assert len(counts) == 91 # 90 days back plus today + # Nude (100 days ago, outside the window) and Mallory's Reckoner plays don't count. + assert sum(c["count"] for c in counts) == 3 + assert counts[-1]["start"] == NOW.date().isoformat() + assert counts[-1]["count"] == 3 + + def test_detail_pagination(client, auth, history): first = client.get( "/api/v1/me/tracks?artist=Radiohead&track=Reckoner&limit=2&page=1", headers=auth