Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25a7ac7a20 | ||
|
|
ae24c4a00e | ||
|
|
86bf9fd302 |
No files matched your search
@@ -3918,6 +3918,13 @@
|
|||||||
"items": {
|
"items": {
|
||||||
"$ref": "#/components/schemas/Scrobble"
|
"$ref": "#/components/schemas/Scrobble"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"counts": {
|
||||||
|
"type": "array",
|
||||||
|
"description": "Daily plays over the last 90 days",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/components/schemas/Count"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"additionalProperties": false
|
"additionalProperties": false
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { api } from "./api.js";
|
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 { signedInPage } from "./layout.js";
|
||||||
|
import { spectrum } from "./spectrum.js";
|
||||||
|
|
||||||
const PERIODS = [
|
const PERIODS = [
|
||||||
["7day", "7 days"],
|
["7day", "7 days"],
|
||||||
@@ -9,7 +10,6 @@ const PERIODS = [
|
|||||||
["overall", "All time"],
|
["overall", "All time"],
|
||||||
];
|
];
|
||||||
const PERIOD_KEY = "scrobbler.period";
|
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 NOW_PLAYING_POLL_MS = 30_000;
|
||||||
|
|
||||||
const panel = document.getElementById("panel");
|
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 ------------------------------------------------------------
|
// ---- Most played ------------------------------------------------------------
|
||||||
|
|
||||||
function currentPeriod() {
|
function currentPeriod() {
|
||||||
|
|||||||
+31
-14
@@ -1,10 +1,10 @@
|
|||||||
import { api } from "./api.js";
|
import { api } from "./api.js";
|
||||||
import { errorBox, formatDate, formatDay, formatDuration, formatTime, h, num, replace } from "./dom.js";
|
import { errorBox, formatDate, formatDay, formatDuration, formatTime, h, num, replace } from "./dom.js";
|
||||||
import { signedInPage } from "./layout.js";
|
import { signedInPage } from "./layout.js";
|
||||||
|
import { spectrum } from "./spectrum.js";
|
||||||
|
|
||||||
const PER_PAGE = 50;
|
const PER_PAGE = 50;
|
||||||
const title = document.getElementById("song-title");
|
const panel = document.getElementById("panel");
|
||||||
const subtitle = document.getElementById("song-subtitle");
|
|
||||||
const meta = document.getElementById("song-meta");
|
const meta = document.getElementById("song-meta");
|
||||||
const history = document.getElementById("song-history");
|
const history = document.getElementById("song-history");
|
||||||
const pager = document.getElementById("pager");
|
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);
|
const page = Math.max(1, Number.parseInt(params.get("page"), 10) || 1);
|
||||||
|
|
||||||
if (!artist || !track) {
|
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 {
|
} else {
|
||||||
try {
|
try {
|
||||||
const result = await api(
|
const result = await api(
|
||||||
@@ -25,12 +25,10 @@ if (!artist || !track) {
|
|||||||
);
|
);
|
||||||
render(result);
|
render(result);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
title.textContent = track;
|
|
||||||
subtitle.textContent = `by ${artist}`;
|
|
||||||
replace(
|
replace(
|
||||||
history,
|
panel,
|
||||||
error.status === 404
|
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),
|
: errorBox(error.message),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -38,18 +36,26 @@ if (!artist || !track) {
|
|||||||
|
|
||||||
function render(result) {
|
function render(result) {
|
||||||
document.title = `${result.track} · Scrobbler`;
|
document.title = `${result.track} · Scrobbler`;
|
||||||
title.textContent = result.track;
|
|
||||||
subtitle.textContent = `by ${result.artist}`;
|
|
||||||
|
|
||||||
const m = result.metadata;
|
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) =>
|
const row = (label, value) =>
|
||||||
value === null || value === undefined ? null : h("div", {}, h("dt", {}, label), h("dd", {}, value));
|
value === null || value === undefined ? null : h("div", {}, h("dt", {}, label), h("dd", {}, value));
|
||||||
replace(
|
replace(
|
||||||
meta,
|
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("Album artist", m.album_artist),
|
||||||
row("Track number", m.track_number),
|
row("Track number", m.track_number),
|
||||||
row("Duration", m.duration ? formatDuration(m.duration) : null),
|
row("Duration", m.duration ? formatDuration(m.duration) : null),
|
||||||
@@ -95,3 +101,14 @@ function render(result) {
|
|||||||
: h("span"),
|
: 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"),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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"),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
+2
-2
@@ -12,8 +12,8 @@
|
|||||||
<body>
|
<body>
|
||||||
<header class="site-header" id="site-header"></header>
|
<header class="site-header" id="site-header"></header>
|
||||||
<main id="main">
|
<main id="main">
|
||||||
<h1 class="page-title" id="song-title">Song</h1>
|
<h1 class="visually-hidden">Song</h1>
|
||||||
<p class="lede" id="song-subtitle"></p>
|
<div id="panel" class="panel" aria-live="polite"></div>
|
||||||
<dl class="song-meta" id="song-meta"></dl>
|
<dl class="song-meta" id="song-meta"></dl>
|
||||||
<section aria-labelledby="song-history-title">
|
<section aria-labelledby="song-history-title">
|
||||||
<h2 id="song-history-title">History</h2>
|
<h2 id="song-history-title">History</h2>
|
||||||
|
|||||||
@@ -40,11 +40,15 @@ def detail(args):
|
|||||||
artist=args["artist"],
|
artist=args["artist"],
|
||||||
track=args["track"],
|
track=args["track"],
|
||||||
)
|
)
|
||||||
|
counts = stats.listen_counts(
|
||||||
|
g.user, period="3month", bucket="day", artist=args["artist"], track=args["track"]
|
||||||
|
)
|
||||||
return {
|
return {
|
||||||
"artist": metadata.artist,
|
"artist": metadata.artist,
|
||||||
"track": metadata.track,
|
"track": metadata.track,
|
||||||
"metadata": metadata,
|
"metadata": metadata,
|
||||||
"items": history.items,
|
"items": history.items,
|
||||||
|
"counts": counts,
|
||||||
"page": history.page,
|
"page": history.page,
|
||||||
"per_page": history.per_page,
|
"per_page": history.per_page,
|
||||||
"total": history.total,
|
"total": history.total,
|
||||||
|
|||||||
@@ -171,6 +171,9 @@ class TrackDetailSchema(PageMetaSchema):
|
|||||||
track = fields.String()
|
track = fields.String()
|
||||||
metadata = fields.Nested(TrackMetadataSchema)
|
metadata = fields.Nested(TrackMetadataSchema)
|
||||||
items = fields.List(fields.Nested(ScrobbleSchema))
|
items = fields.List(fields.Nested(ScrobbleSchema))
|
||||||
|
counts = fields.List(
|
||||||
|
fields.Nested(CountSchema), metadata={"description": "Daily plays over the last 90 days"}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class SummarySchema(Schema):
|
class SummarySchema(Schema):
|
||||||
|
|||||||
@@ -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)
|
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."""
|
"""Scrobbles per bucket (UTC). Empty buckets are included for day buckets."""
|
||||||
if bucket not in BUCKETS: # interpolated into SQL below, so allow-list it
|
if bucket not in BUCKETS: # interpolated into SQL below, so allow-list it
|
||||||
raise ValueError(f"bucket must be one of {BUCKETS}")
|
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")
|
bucket_col = func.date_trunc(literal_column(f"'{bucket}'"), Scrobble.played_at, "UTC")
|
||||||
query = (
|
query = (
|
||||||
select(bucket_col.label("bucket"), func.count())
|
select(bucket_col.label("bucket"), func.count())
|
||||||
.where(*_user_scrobbles(user, period))
|
.where(*conditions)
|
||||||
.group_by("bucket")
|
.group_by("bucket")
|
||||||
.order_by("bucket")
|
.order_by("bucket")
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -95,6 +95,16 @@ def test_detail_requires_auth(client):
|
|||||||
assert client.get("/api/v1/me/tracks/search?q=a").status_code == 401
|
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):
|
def test_detail_pagination(client, auth, history):
|
||||||
first = client.get(
|
first = client.get(
|
||||||
"/api/v1/me/tracks?artist=Radiohead&track=Reckoner&limit=2&page=1", headers=auth
|
"/api/v1/me/tracks?artist=Radiohead&track=Reckoner&limit=2&page=1", headers=auth
|
||||||
|
|||||||
Reference in new issue
Block a user