diff --git a/docs/openapi.json b/docs/openapi.json index 84633dd..e5f4a02 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -992,6 +992,167 @@ ] } }, + "/api/v1/me/tracks/search": { + "get": { + "parameters": [ + { + "in": "query", + "name": "q", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "required": true + }, + { + "in": "query", + "name": "limit", + "schema": { + "type": "integer", + "default": 20, + "minimum": 1, + "maximum": 50 + }, + "required": false + } + ], + "responses": { + "422": { + "$ref": "#/components/responses/UNPROCESSABLE_CONTENT" + }, + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TrackSearchResult" + } + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Find a song by track or artist name", + "tags": [ + "Tracks" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/api/v1/me/tracks": { + "get": { + "parameters": [ + { + "in": "query", + "name": "page", + "schema": { + "type": "integer", + "default": 1, + "minimum": 1 + }, + "required": false + }, + { + "in": "query", + "name": "limit", + "schema": { + "type": "integer", + "default": 50, + "minimum": 1, + "maximum": 200 + }, + "required": false + }, + { + "in": "query", + "name": "artist", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 500 + }, + "required": true + }, + { + "in": "query", + "name": "track", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 500 + }, + "required": true + } + ], + "responses": { + "422": { + "$ref": "#/components/responses/UNPROCESSABLE_CONTENT" + }, + "404": { + "description": "You've never scrobbled this song", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TrackDetail" + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "A song's play history and recorded metadata", + "tags": [ + "Tracks" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, "/api/v1/imports/options": { "get": { "responses": { @@ -3205,6 +3366,10 @@ "name": "Stats", "description": "Your listening history and statistics" }, + { + "name": "Tracks", + "description": "Look up a specific song's history and metadata" + }, { "name": "Imports", "description": "Import listening history from a Last.fm export file, or straight from Last.fm. Imports run in the background; poll a job to follow its progress." @@ -3662,6 +3827,101 @@ }, "additionalProperties": false }, + "TrackSearchResult": { + "type": "object", + "properties": { + "artist": { + "type": "string" + }, + "track": { + "type": "string" + }, + "playcount": { + "type": "integer" + } + }, + "additionalProperties": false + }, + "TrackMetadata": { + "type": "object", + "properties": { + "album": { + "type": [ + "string", + "null" + ] + }, + "album_artist": { + "type": [ + "string", + "null" + ] + }, + "track_number": { + "type": [ + "integer", + "null" + ] + }, + "duration": { + "type": [ + "integer", + "null" + ] + }, + "mbid": { + "type": [ + "string", + "null" + ] + }, + "playcount": { + "type": "integer" + }, + "first_played_at": { + "type": "string", + "format": "date-time" + }, + "last_played_at": { + "type": "string", + "format": "date-time" + } + }, + "additionalProperties": false + }, + "TrackDetail": { + "type": "object", + "properties": { + "page": { + "type": "integer" + }, + "per_page": { + "type": "integer" + }, + "total": { + "type": "integer" + }, + "total_pages": { + "type": "integer" + }, + "artist": { + "type": "string" + }, + "track": { + "type": "string" + }, + "metadata": { + "$ref": "#/components/schemas/TrackMetadata" + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Scrobble" + } + } + }, + "additionalProperties": false + }, "ImportOptions": { "type": "object", "properties": { diff --git a/frontend/css/style.css b/frontend/css/style.css index 1d80019..ecdfb40 100644 --- a/frontend/css/style.css +++ b/frontend/css/style.css @@ -582,6 +582,16 @@ input { background: var(--slate); } +.ranking a.name { + color: inherit; + text-decoration: none; +} + +.ranking a.name:hover, +.ranking a.name:focus-visible { + text-decoration: underline; +} + /* ---- Listening log -------------------------------------------------------- */ .log { list-style: none; @@ -977,3 +987,79 @@ input { .confirm-off .button-row { margin-top: 0.75rem; } + +/* ---- Song lookup ------------------------------------------------------------ */ +.song-search { + position: relative; + max-width: 28rem; + margin-bottom: 1.5rem; +} + +.song-search .field { + margin-bottom: 0; +} + +.search-results { + position: absolute; + z-index: 10; + inset-inline: 0; + top: 100%; + margin: 0.25rem 0 0; + padding: 0.35rem; + list-style: none; + background: var(--paper-raised); + border: 1px solid var(--rule); + border-radius: var(--radius-control); + box-shadow: 0 8px 24px rgb(0 0 0 / 0.12); + max-height: 18rem; + overflow-y: auto; +} + +.search-results li { + padding: 0; +} + +.search-results a { + display: block; + padding: 0.5rem 0.6rem; + border-radius: var(--radius-control); + color: inherit; + text-decoration: none; +} + +.search-results a:hover, +.search-results a:focus-visible { + background: var(--panel); +} + +.search-results .by { + display: block; + color: var(--ink-soft); + font-size: var(--step--1); +} + +.search-results .empty { + padding: 0.5rem 0.6rem; +} + +.song-meta { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr)); + gap: 1rem 2rem; + margin: 1.25rem 0 2rem; +} + +.song-meta div { + display: grid; + gap: 0.15rem; +} + +.song-meta dt { + font-size: var(--step--1); + color: var(--ink-soft); +} + +.song-meta dd { + margin: 0; + font-weight: 600; +} diff --git a/frontend/index.html b/frontend/index.html index 3372a7d..f3e6fd4 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -14,6 +14,14 @@

Overview

+

Most played

diff --git a/frontend/js/dashboard.js b/frontend/js/dashboard.js index 9b0555e..ee207dd 100644 --- a/frontend/js/dashboard.js +++ b/frontend/js/dashboard.js @@ -19,6 +19,7 @@ let progressTimer; await signedInPage("index.html"); renderPeriodSelector(); +initSongSearch(); await Promise.all([loadPanel(), loadTop(currentPeriod()), loadRecent()]).catch(showError); setInterval(() => refreshDisplay().catch(() => {}), NOW_PLAYING_POLL_MS); @@ -206,10 +207,10 @@ async function loadTop(period) { ]); renderRanking(document.getElementById("top-artists"), artists.items, false); renderRanking(document.getElementById("top-albums"), albums.items, true); - renderRanking(document.getElementById("top-tracks"), tracks.items, true); + renderRanking(document.getElementById("top-tracks"), tracks.items, true, true); } -function renderRanking(list, items, withArtist) { +function renderRanking(list, items, withArtist, linkToSong = false) { if (!items.length) { replace(list, h("li", { class: "empty" }, "No plays in this period.")); return; @@ -217,23 +218,83 @@ function renderRanking(list, items, withArtist) { const max = items[0].playcount; replace( list, - items.map((item) => - h( + items.map((item) => { + const by = withArtist ? h("span", { class: "by" }, item.artist) : null; + const name = linkToSong + ? h("a", { class: "name", href: songHref(item.artist, item.name) }, item.name, by) + : h("span", { class: "name" }, item.name, by); + return h( "li", {}, h("span", { class: "rank" }, item.rank), - h("span", { class: "name" }, item.name, withArtist ? h("span", { class: "by" }, item.artist) : null), + name, h("span", { class: "plays" }, num(item.playcount)), h("span", { class: "meter", "aria-hidden": "true", style: `width: calc((100% - 2.75rem) * ${item.playcount / max})`, }), - ), - ), + ); + }), ); } +function songHref(artist, track) { + return `song.html?artist=${encodeURIComponent(artist)}&track=${encodeURIComponent(track)}`; +} + +// ---- Song search -------------------------------------------------------------- + +function initSongSearch() { + const input = document.getElementById("song-search"); + const results = document.getElementById("song-search-results"); + let debounce; + let hideTimer; + + input.addEventListener("input", () => { + clearTimeout(debounce); + const q = input.value.trim(); + if (q.length < 2) { + results.hidden = true; + return; + } + debounce = setTimeout(() => runSearch(q), 250); + }); + input.addEventListener("focus", () => { + if (results.childElementCount) results.hidden = false; + }); + input.addEventListener("blur", () => { + hideTimer = setTimeout(() => (results.hidden = true), 150); + }); + // Keep focus on mousedown so the subsequent click still lands on the result. + results.addEventListener("mousedown", (event) => event.preventDefault()); + + async function runSearch(q) { + let matches; + try { + matches = await api(`/me/tracks/search?q=${encodeURIComponent(q)}&limit=10`); + } catch { + return; // a flaky search box isn't worth surfacing an error for + } + clearTimeout(hideTimer); + if (!matches.length) { + replace(results, h("li", { class: "empty" }, "No matches.")); + } else { + replace( + results, + matches.map((m) => + h( + "li", + {}, + h("a", { href: songHref(m.artist, m.track) }, m.track, h("span", { class: "by" }, m.artist)), + ), + ), + ); + } + results.hidden = false; + } +} + // ---- Recently played ---------------------------------------------------------- async function loadRecent() { diff --git a/frontend/js/song.js b/frontend/js/song.js new file mode 100644 index 0000000..ac3fdcd --- /dev/null +++ b/frontend/js/song.js @@ -0,0 +1,97 @@ +import { api } from "./api.js"; +import { errorBox, formatDate, formatDay, formatDuration, formatTime, h, num, replace } from "./dom.js"; +import { signedInPage } from "./layout.js"; + +const PER_PAGE = 50; +const title = document.getElementById("song-title"); +const subtitle = document.getElementById("song-subtitle"); +const meta = document.getElementById("song-meta"); +const history = document.getElementById("song-history"); +const pager = document.getElementById("pager"); + +await signedInPage(null); // a permalink, not a top-level nav section + +const params = new URLSearchParams(location.search); +const artist = params.get("artist") ?? ""; +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.")); +} else { + try { + const result = await api( + `/me/tracks?artist=${encodeURIComponent(artist)}&track=${encodeURIComponent(track)}&page=${page}&limit=${PER_PAGE}`, + ); + render(result); + } catch (error) { + title.textContent = track; + subtitle.textContent = `by ${artist}`; + replace( + history, + error.status === 404 + ? h("p", { class: "notice" }, "You've never scrobbled this song.") + : errorBox(error.message), + ); + } +} + +function render(result) { + document.title = `${result.track} · Scrobbler`; + title.textContent = result.track; + subtitle.textContent = `by ${result.artist}`; + + const m = result.metadata; + 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), + row("MusicBrainz ID", m.mbid), + ); + + if (!result.items.length) { + replace(history, h("p", { class: "empty" }, "Nothing here yet.")); + } else { + // Group by local calendar day, same as the full history page. + 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( + history, + [...days.values()].map((scrobbles) => [ + h("h3", { 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)), + s.album ? h("span", { class: "by" }, `from ${s.album}`) : h("span"), + ), + ), + ), + ]), + ); + } + + const link = (p) => `?artist=${encodeURIComponent(artist)}&track=${encodeURIComponent(track)}&page=${p}`; + replace( + pager, + result.page > 1 ? h("a", { class: "button button-quiet", href: link(result.page - 1) }, "Newer") : h("span"), + result.page < result.total_pages + ? h("a", { class: "button button-quiet", href: link(result.page + 1) }, "Older") + : h("span"), + ); +} diff --git a/frontend/song.html b/frontend/song.html new file mode 100644 index 0000000..a85cc10 --- /dev/null +++ b/frontend/song.html @@ -0,0 +1,25 @@ + + + + + + Song · Scrobbler + + + + + + + +
+

Song

+

+
+
+

History

+
+ +
+
+ + diff --git a/src/scrobbler/api/__init__.py b/src/scrobbler/api/__init__.py index ca7615e..a6cfd71 100644 --- a/src/scrobbler/api/__init__.py +++ b/src/scrobbler/api/__init__.py @@ -48,13 +48,14 @@ def init_app(app: Flask) -> None: }, ) - from scrobbler.api import apps, auth, health, imports, sessions, stats, tokens + from scrobbler.api import apps, auth, health, imports, sessions, stats, tokens, tracks api.register_blueprint(auth.blp, url_prefix="/api/v1/auth") api.register_blueprint(apps.blp, url_prefix="/api/v1/apps") api.register_blueprint(sessions.blp, url_prefix="/api/v1/sessions") api.register_blueprint(tokens.blp, url_prefix="/api/v1/tokens") api.register_blueprint(stats.blp, url_prefix="/api/v1/me") + api.register_blueprint(tracks.blp, url_prefix="/api/v1/me/tracks") api.register_blueprint(imports.blp, url_prefix="/api/v1/imports") api.register_blueprint(health.blp) diff --git a/src/scrobbler/api/tracks.py b/src/scrobbler/api/tracks.py new file mode 100644 index 0000000..ba1981c --- /dev/null +++ b/src/scrobbler/api/tracks.py @@ -0,0 +1,52 @@ +from flask import g +from flask_smorest import Blueprint, abort + +from scrobbler.api.decorators import authenticated +from scrobbler.schemas import ( + ErrorSchema, + TrackDetailArgsSchema, + TrackDetailSchema, + TrackSearchArgsSchema, + TrackSearchResultSchema, +) +from scrobbler.services import stats + +blp = Blueprint("Tracks", __name__, description="Look up a specific song's history and metadata") + + +@blp.route("/search", methods=["GET"]) +@authenticated(blp) +@blp.arguments(TrackSearchArgsSchema, location="query") +@blp.response(200, TrackSearchResultSchema(many=True)) +def search(args): + """Find a song by track or artist name""" + return stats.track_search(g.user, args["q"], args["limit"]) + + +@blp.route("", methods=["GET"]) +@authenticated(blp) +@blp.arguments(TrackDetailArgsSchema, location="query") +@blp.response(200, TrackDetailSchema) +@blp.alt_response(404, schema=ErrorSchema, description="You've never scrobbled this song") +def detail(args): + """A song's play history and recorded metadata""" + metadata = stats.track_metadata(g.user, args["artist"], args["track"]) + if metadata is None: + abort(404, code="not_found", message="You've never scrobbled this song") + history = stats.recent( + g.user, + page=args["page"], + per_page=args["limit"], + artist=args["artist"], + track=args["track"], + ) + return { + "artist": metadata.artist, + "track": metadata.track, + "metadata": metadata, + "items": history.items, + "page": history.page, + "per_page": history.per_page, + "total": history.total, + "total_pages": history.total_pages, + } diff --git a/src/scrobbler/schemas/__init__.py b/src/scrobbler/schemas/__init__.py index f6548bb..c0ff820 100644 --- a/src/scrobbler/schemas/__init__.py +++ b/src/scrobbler/schemas/__init__.py @@ -139,6 +139,40 @@ class CountSchema(Schema): count = fields.Integer() +class TrackSearchArgsSchema(Schema): + q = fields.String(required=True, validate=validate.Length(min=1, max=200)) + limit = fields.Integer(load_default=20, validate=validate.Range(min=1, max=50)) + + +class TrackSearchResultSchema(Schema): + artist = fields.String() + track = fields.String(attribute="name") + playcount = fields.Integer() + + +class TrackDetailArgsSchema(PageArgsSchema): + artist = fields.String(required=True, validate=validate.Length(min=1, max=500)) + track = fields.String(required=True, validate=validate.Length(min=1, max=500)) + + +class TrackMetadataSchema(Schema): + album = fields.String(allow_none=True) + album_artist = fields.String(allow_none=True) + track_number = fields.Integer(allow_none=True) + duration = fields.Integer(allow_none=True) + mbid = fields.String(allow_none=True) + playcount = fields.Integer() + first_played_at = fields.DateTime() + last_played_at = fields.DateTime() + + +class TrackDetailSchema(PageMetaSchema): + artist = fields.String() + track = fields.String() + metadata = fields.Nested(TrackMetadataSchema) + items = fields.List(fields.Nested(ScrobbleSchema)) + + class SummarySchema(Schema): scrobbles = fields.Integer() artists = fields.Integer() diff --git a/src/scrobbler/services/stats.py b/src/scrobbler/services/stats.py index 6328c8d..992faa9 100644 --- a/src/scrobbler/services/stats.py +++ b/src/scrobbler/services/stats.py @@ -4,7 +4,7 @@ import math from dataclasses import dataclass from datetime import UTC, date, datetime, timedelta -from sqlalchemy import Select, func, literal_column, select +from sqlalchemy import Select, func, literal_column, or_, select from scrobbler.extensions import db from scrobbler.models import Scrobble, User @@ -67,6 +67,16 @@ def _display(column): return func.mode().within_group(column.collate("C")) +def _mode_text(column): + """Most common non-null spelling in the group, ignoring rows where it's unset.""" + return func.mode().within_group(column.collate("C")).filter(column.is_not(None)) + + +def _mode(column): + """Most common non-null value in the group, ignoring rows where it's unset.""" + return func.mode().within_group(column).filter(column.is_not(None)) + + def _paginate(query: Select, page: int, per_page: int) -> tuple[list, int]: total = db.session.scalar(select(func.count()).select_from(query.subquery())) rows = db.session.execute(query.limit(per_page).offset((page - 1) * per_page)).all() @@ -79,12 +89,18 @@ def recent( per_page: int = 50, start: datetime | None = None, end: datetime | None = None, + artist: str | None = None, + track: str | None = None, ) -> Page: conditions = [Scrobble.user_id == user.id] if start: conditions.append(Scrobble.played_at >= start) if end: conditions.append(Scrobble.played_at <= end) + if artist: + conditions.append(func.lower(Scrobble.artist) == artist.lower()) + if track: + conditions.append(func.lower(Scrobble.track) == track.lower()) query = select(Scrobble).where(*conditions).order_by(Scrobble.played_at.desc()) rows, total = _paginate(query, page, per_page) return Page([row[0] for row in rows], page, per_page, total) @@ -217,6 +233,84 @@ def top_tracks_between( ] +@dataclass +class TrackMetadata: + artist: str + track: str + album: str | None + album_artist: str | None + track_number: int | None + duration: int | None + mbid: str | None + playcount: int + first_played_at: datetime + last_played_at: datetime + + +def track_metadata(user: User, artist: str, track: str) -> TrackMetadata | None: + """Canonical name and aggregated metadata for one song, or None if never played. + + Each metadata field is the most common non-null value recorded for it; an exact tie + is resolved by mode()'s own (unspecified) ordering rather than a hand-rolled tiebreak. + """ + row = db.session.execute( + select( + _display(Scrobble.artist), + _display(Scrobble.track), + _mode_text(Scrobble.album), + _mode_text(Scrobble.album_artist), + _mode(Scrobble.track_number), + _mode(Scrobble.duration), + _mode_text(Scrobble.mbid), + func.count(), + func.min(Scrobble.played_at), + func.max(Scrobble.played_at), + ).where( + Scrobble.user_id == user.id, + func.lower(Scrobble.artist) == artist.lower(), + func.lower(Scrobble.track) == track.lower(), + ) + ).one() + playcount = row[7] + if not playcount: + return None + return TrackMetadata( + artist=row[0], + track=row[1], + album=row[2], + album_artist=row[3], + track_number=row[4], + duration=row[5], + mbid=row[6], + playcount=playcount, + first_played_at=row[8], + last_played_at=row[9], + ) + + +def track_search(user: User, q: str, limit: int = 20) -> list[TopItem]: + """Tracks whose name or artist contains q (case-insensitive), ranked by playcount.""" + q = q.strip().lower() + if not q: + return [] + keys = (func.lower(Scrobble.track), func.lower(Scrobble.artist)) + plays = func.count().label("plays") + query = ( + select(_display(Scrobble.track), _display(Scrobble.artist), plays) + .where( + Scrobble.user_id == user.id, + or_(func.lower(Scrobble.track).contains(q), func.lower(Scrobble.artist).contains(q)), + ) + .group_by(*keys) + .order_by(plays.desc(), *keys) + .limit(limit) + ) + rows = db.session.execute(query).all() + return [ + TopItem(i + 1, name, count, artist=artist) for i, (name, artist, count) in enumerate(rows) + ] + + def summary(user: User) -> dict: row = db.session.execute( select( diff --git a/tests/test_tracks.py b/tests/test_tracks.py new file mode 100644 index 0000000..b37c551 --- /dev/null +++ b/tests/test_tracks.py @@ -0,0 +1,107 @@ +from datetime import UTC, datetime, timedelta + +import pytest + +from scrobbler.extensions import db +from scrobbler.models import Scrobble + +NOW = datetime.now(UTC) + + +def add( + user, + artist, + track, + album=None, + album_artist=None, + track_number=None, + duration=None, + mbid=None, + days_ago=0.0, +): + db.session.add( + Scrobble( + user_id=user.id, + artist=artist, + track=track, + album=album, + album_artist=album_artist, + track_number=track_number, + duration=duration, + mbid=mbid, + played_at=NOW - timedelta(days=days_ago), + ) + ) + + +@pytest.fixture +def history(user, make_user): + # Radiohead: 3 recent plays of Reckoner (mixed capitalisation) + 1 old Nude + add(user, "Radiohead", "Reckoner", "In Rainbows", duration=290, mbid="abc", days_ago=0.1) + add(user, "radiohead", "reckoner", "in rainbows", duration=290, mbid="abc", days_ago=0.2) + add(user, "Radiohead", "Reckoner", None, duration=290, mbid=None, days_ago=0.3) + add(user, "Radiohead", "Nude", "In Rainbows", days_ago=100) + # Someone else's plays must never show up + other = make_user(username="mallory") + add(other, "Radiohead", "Reckoner", "In Rainbows", days_ago=0.1) + db.session.commit() + return user + + +def test_search_matches_track_name_case_insensitively(client, auth, history): + body = client.get("/api/v1/me/tracks/search?q=reck", headers=auth).get_json() + assert [(r["track"], r["artist"], r["playcount"]) for r in body] == [ + ("Reckoner", "Radiohead", 3) + ] + + +def test_search_matches_artist_name(client, auth, history): + body = client.get("/api/v1/me/tracks/search?q=radio", headers=auth).get_json() + tracks = {r["track"] for r in body} + assert tracks == {"Reckoner", "Nude"} + + +def test_search_excludes_other_users_and_respects_limit(client, auth, history): + body = client.get("/api/v1/me/tracks/search?q=e&limit=1", headers=auth).get_json() + assert len(body) == 1 + + +def test_search_requires_a_query(client, auth): + assert client.get("/api/v1/me/tracks/search", headers=auth).status_code == 422 + + +def test_detail_aggregates_metadata_and_merges_capitalisation(client, auth, history): + body = client.get("/api/v1/me/tracks?artist=radiohead&track=RECKONER", headers=auth).get_json() + assert body["artist"] == "Radiohead" + assert body["track"] == "Reckoner" + metadata = body["metadata"] + assert metadata["album"] == "In Rainbows" # most common non-null value + assert metadata["duration"] == 290 + assert metadata["mbid"] == "abc" # most common non-null value + assert metadata["playcount"] == 3 + assert metadata["first_played_at"] is not None + assert metadata["last_played_at"] is not None + assert [s["artist"] for s in body["items"]] == ["Radiohead", "radiohead", "Radiohead"] + assert body["total"] == 3 + + +def test_detail_unknown_track_returns_404(client, auth, history): + response = client.get("/api/v1/me/tracks?artist=Nobody&track=Nothing", headers=auth) + assert response.status_code == 404 + + +def test_detail_requires_auth(client): + assert client.get("/api/v1/me/tracks?artist=A&track=B").status_code == 401 + assert client.get("/api/v1/me/tracks/search?q=a").status_code == 401 + + +def test_detail_pagination(client, auth, history): + first = client.get( + "/api/v1/me/tracks?artist=Radiohead&track=Reckoner&limit=2&page=1", headers=auth + ).get_json() + second = client.get( + "/api/v1/me/tracks?artist=Radiohead&track=Reckoner&limit=2&page=2", headers=auth + ).get_json() + assert (first["total"], first["total_pages"]) == (3, 2) + assert len(first["items"]) == 2 + assert len(second["items"]) == 1