From 2702815a1e0d3ca5a3aa2dce0d3d40b0013c50fb Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 14:02:42 +0100 Subject: [PATCH] Scrobbling and now-playing - track.scrobble: batches of up to 50 (array params or a single track), Last.fm ignore rules (empty artist/track, too old, too new), duplicate submissions accepted but stored once - track.updateNowPlaying: upserted per user, expiring after the track's duration; cleared when the same track is scrobbled - Scrobble result, ignore reason, batch size, lag and now-playing metrics Co-Authored-By: Claude Opus 5.5 --- src/scrobbler/lastfm/__init__.py | 7 +- src/scrobbler/lastfm/methods/__init__.py | 2 +- src/scrobbler/lastfm/methods/track.py | 98 +++++++++++ src/scrobbler/services/scrobbles.py | 209 +++++++++++++++++++++++ tests/test_scrobble.py | 176 +++++++++++++++++++ tests/test_ui_apps_sessions.py | 11 +- 6 files changed, 498 insertions(+), 5 deletions(-) create mode 100644 src/scrobbler/lastfm/methods/track.py create mode 100644 src/scrobbler/services/scrobbles.py create mode 100644 tests/test_scrobble.py diff --git a/src/scrobbler/lastfm/__init__.py b/src/scrobbler/lastfm/__init__.py index 740f379..8c7fbdd 100644 --- a/src/scrobbler/lastfm/__init__.py +++ b/src/scrobbler/lastfm/__init__.py @@ -51,7 +51,12 @@ def _authenticate(method: LastfmMethod, params: dict[str, str], fmt: str) -> Cal raise LastFMError(errors.INVALID_SESSION_KEY) call.user = session.user - missing = [p.name for p in method.params if p.required and not params.get(p.name)] + # Array params (artist[i]) are validated by the handler, which knows the batch shape. + missing = [ + p.name + for p in method.params + if p.required and not p.name.endswith("[i]") and not params.get(p.name) + ] if missing: raise LastFMError( errors.INVALID_PARAMETERS, f"Missing required parameter: {', '.join(missing)}" diff --git a/src/scrobbler/lastfm/methods/__init__.py b/src/scrobbler/lastfm/methods/__init__.py index 9dfe015..1cd8923 100644 --- a/src/scrobbler/lastfm/methods/__init__.py +++ b/src/scrobbler/lastfm/methods/__init__.py @@ -1,3 +1,3 @@ """Importing this package registers every Last.fm method handler.""" -from scrobbler.lastfm.methods import auth # noqa: F401 +from scrobbler.lastfm.methods import auth, track # noqa: F401 diff --git a/src/scrobbler/lastfm/methods/track.py b/src/scrobbler/lastfm/methods/track.py new file mode 100644 index 0000000..f442ffc --- /dev/null +++ b/src/scrobbler/lastfm/methods/track.py @@ -0,0 +1,98 @@ +from scrobbler.lastfm import errors +from scrobbler.lastfm.errors import LastFMError +from scrobbler.lastfm.registry import Call, Param, lastfm_method +from scrobbler.lastfm.responses import El +from scrobbler.services import scrobbles +from scrobbler.services.scrobbles import TrackInput + + +def _corrected(tag: str, value) -> El: + # This server never auto-corrects metadata, so corrected is always 0. + return El.text_el(tag, value, corrected=0) + + +def _track_fields(item: TrackInput, ignored_code: int) -> list[El]: + return [ + _corrected("track", item.track), + _corrected("artist", item.artist), + _corrected("album", item.album), + _corrected("albumArtist", item.album_artist), + *([El.text_el("timestamp", item.timestamp)] if item.timestamp is not None else []), + El.text_el("ignoredMessage", scrobbles.IGNORED_MESSAGES[ignored_code], code=ignored_code), + ] + + +_TRACK_PARAMS = ( + Param("artist[i]", "Artist name", required=True, example="Radiohead"), + Param("track[i]", "Track title", required=True, example="Reckoner"), + Param("timestamp[i]", "Unix time the track started playing", required=True), + Param("album[i]", "Album title"), + Param("albumArtist[i]", "Album artist, if different from the track artist"), + Param("duration[i]", "Track length in seconds"), + Param("trackNumber[i]", "Position on the album"), + Param("mbid[i]", "MusicBrainz track id"), +) + + +@lastfm_method( + "track.scrobble", + summary="Scrobble up to 50 tracks", + signed=True, + session=True, + params=_TRACK_PARAMS, + notes=( + "Tracks are array parameters indexed from 0 (`artist[0]`, `track[0]`, ...); a " + "single un-indexed track is also accepted. Tracks are ignored (not an error) when " + "the artist or track is empty (codes 1/2), the timestamp is over 14 days old (3) " + "or more than 5 minutes in the future (4). Re-sending an already stored scrobble " + "is accepted, so retries are safe." + ), + example_xml=( + '' + 'ReckonerRadiohead' + 'In Rainbows' + '1700000000' + "" + ), +) +def scrobble(call: Call) -> El: + try: + items = scrobbles.parse_batch(call.params) + except scrobbles.BatchError as err: + raise LastFMError(errors.INVALID_PARAMETERS, str(err)) from err + results = scrobbles.submit_scrobbles(call.user, call.api_app, items) + ignored = sum(r.status == "ignored" for r in results) + return El.of( + "scrobbles", + *[El.of("scrobble", *_track_fields(r.item, r.ignored_code)) for r in results], + accepted=len(results) - ignored, + ignored=ignored, + ) + + +@lastfm_method( + "track.updateNowPlaying", + summary="Set the track the user is listening to now", + signed=True, + session=True, + params=( + Param("artist", "Artist name", required=True, example="Radiohead"), + Param("track", "Track title", required=True, example="Reckoner"), + Param("album", "Album title"), + Param("albumArtist", "Album artist"), + Param("duration", "Track length in seconds; now-playing expires after it"), + Param("trackNumber", "Position on the album"), + Param("mbid", "MusicBrainz track id"), + ), + notes="Now playing expires after the track's duration (10 minutes if not given).", + example_xml=( + 'Reckoner' + 'Radiohead' + '' + "" + ), +) +def update_now_playing(call: Call) -> El: + item = scrobbles.track_input(call.params) + code = scrobbles.update_now_playing(call.user, item) + return El.of("nowplaying", *_track_fields(item, code)) diff --git a/src/scrobbler/services/scrobbles.py b/src/scrobbler/services/scrobbles.py new file mode 100644 index 0000000..5c934fc --- /dev/null +++ b/src/scrobbler/services/scrobbles.py @@ -0,0 +1,209 @@ +"""Scrobble validation/storage and now-playing state.""" + +import re +from dataclasses import dataclass +from datetime import UTC, datetime, timedelta + +from flask import current_app +from sqlalchemy import func +from sqlalchemy.dialects.postgresql import insert + +from scrobbler import metrics +from scrobbler.extensions import db +from scrobbler.models import ApiApp, NowPlaying, Scrobble, User + +MAX_BATCH = 50 +MAX_TEXT = 1024 + +# Last.fm ignoredMessage codes +NOT_IGNORED = 0 +IGNORED_ARTIST = 1 +IGNORED_TRACK = 2 +IGNORED_TOO_OLD = 3 +IGNORED_TOO_NEW = 4 + +IGNORED_MESSAGES = { + NOT_IGNORED: "", + IGNORED_ARTIST: "Artist was ignored", + IGNORED_TRACK: "Track was ignored", + IGNORED_TOO_OLD: "Timestamp was too old", + IGNORED_TOO_NEW: "Timestamp was too new", +} + +_INDEXED = re.compile(r"^(?P[A-Za-z]+)\[(?P\d+)\]$") + + +class BatchError(ValueError): + pass + + +@dataclass +class TrackInput: + artist: str + track: str + album: str | None = None + album_artist: str | None = None + duration: int | None = None + track_number: int | None = None + mbid: str | None = None + timestamp: int | None = None + + +@dataclass +class ScrobbleResult: + item: TrackInput + status: str # accepted, duplicate or ignored + ignored_code: int = NOT_IGNORED + + @property + def ignored_message(self) -> str: + return IGNORED_MESSAGES[self.ignored_code] + + +def _text(value: str | None) -> str | None: + value = (value or "").strip() + return value[:MAX_TEXT] or None + + +def _int(value: str | None) -> int | None: + try: + return int(value) if value not in (None, "") else None + except ValueError: + return None + + +def track_input(fields: dict[str, str]) -> TrackInput: + return TrackInput( + artist=_text(fields.get("artist")) or "", + track=_text(fields.get("track")) or "", + album=_text(fields.get("album")), + album_artist=_text(fields.get("albumArtist")), + duration=_int(fields.get("duration")), + track_number=_int(fields.get("trackNumber")), + mbid=_text(fields.get("mbid")), + timestamp=_int(fields.get("timestamp")), + ) + + +def parse_batch(params: dict[str, str]) -> list[TrackInput]: + """Parse `artist[0]`, `track[0]`, ... array params (or a single un-indexed track).""" + grouped: dict[int, dict[str, str]] = {} + for key, value in params.items(): + if match := _INDEXED.match(key): + grouped.setdefault(int(match["index"]), {})[match["name"]] = value + if not grouped and ("artist" in params or "track" in params): + grouped[0] = params + if not grouped: + raise BatchError("No tracks supplied") + if len(grouped) > MAX_BATCH: + raise BatchError(f"At most {MAX_BATCH} scrobbles per request") + items = [track_input(grouped[i]) for i in sorted(grouped)] + if any(item.timestamp is None for item in items): + raise BatchError("Every scrobble needs an integer timestamp") + return items + + +def _ignored_code(item: TrackInput, now: datetime) -> int: + if not item.artist: + return IGNORED_ARTIST + if not item.track: + return IGNORED_TRACK + played_at = datetime.fromtimestamp(item.timestamp, UTC) + if now - played_at > timedelta(days=current_app.config["SCROBBLE_MAX_AGE_DAYS"]): + return IGNORED_TOO_OLD + if played_at - now > timedelta(seconds=current_app.config["SCROBBLE_MAX_FUTURE_SECONDS"]): + return IGNORED_TOO_NEW + return NOT_IGNORED + + +def submit_scrobbles(user: User, api_app: ApiApp | None, items: list[TrackInput]): + now = datetime.now(UTC) + results: list[ScrobbleResult] = [] + for item in items: + code = _ignored_code(item, now) + if code != NOT_IGNORED: + results.append(ScrobbleResult(item, "ignored", code)) + continue + played_at = datetime.fromtimestamp(item.timestamp, UTC) + inserted = db.session.execute( + insert(Scrobble) + .values( + user_id=user.id, + artist=item.artist, + track=item.track, + album=item.album, + album_artist=item.album_artist, + track_number=item.track_number, + duration=item.duration, + mbid=item.mbid, + played_at=played_at, + submitted_at=now, + api_app_id=api_app.id if api_app else None, + ) + .on_conflict_do_nothing(constraint="uq_scrobbles_dedupe") + .returning(Scrobble.id) + ).scalar() + results.append(ScrobbleResult(item, "accepted" if inserted else "duplicate")) + if inserted: + metrics.scrobble_lag_seconds.observe(max(0.0, (now - played_at).total_seconds())) + + _clear_now_playing(user, [r.item for r in results if r.status != "ignored"]) + db.session.commit() + + metrics.scrobble_batch_size.observe(len(items)) + for result in results: + metrics.scrobbles_total.labels(result=result.status).inc() + if result.status == "ignored": + metrics.scrobbles_ignored_total.labels(reason=str(result.ignored_code)).inc() + return results + + +def _clear_now_playing(user: User, scrobbled: list[TrackInput]) -> None: + now_playing = db.session.get(NowPlaying, user.id) + if now_playing is None: + return + for item in scrobbled: + if (item.artist.lower(), item.track.lower()) == ( + now_playing.artist.lower(), + now_playing.track.lower(), + ): + db.session.delete(now_playing) + return + + +# --- Now playing --------------------------------------------------------------- + + +def update_now_playing(user: User, item: TrackInput) -> int: + """Store the user's current track. Returns an ignored code (0 when stored).""" + if not item.artist: + return IGNORED_ARTIST + if not item.track: + return IGNORED_TRACK + now = datetime.now(UTC) + seconds = item.duration or current_app.config["NOW_PLAYING_DEFAULT_SECONDS"] + values = { + "artist": item.artist, + "track": item.track, + "album": item.album, + "album_artist": item.album_artist, + "duration": item.duration, + "started_at": now, + "expires_at": now + timedelta(seconds=seconds), + } + db.session.execute( + insert(NowPlaying) + .values(user_id=user.id, **values) + .on_conflict_do_update(index_elements=[NowPlaying.user_id], set_=values) + ) + db.session.commit() + metrics.now_playing_updates_total.inc() + return NOT_IGNORED + + +def get_now_playing(user: User) -> NowPlaying | None: + return db.session.scalar( + db.select(NowPlaying).where( + NowPlaying.user_id == user.id, NowPlaying.expires_at > func.now() + ) + ) diff --git a/tests/test_scrobble.py b/tests/test_scrobble.py new file mode 100644 index 0000000..20a4232 --- /dev/null +++ b/tests/test_scrobble.py @@ -0,0 +1,176 @@ +import time +import xml.etree.ElementTree as ET +from datetime import UTC, datetime, timedelta + +import pytest + +from conftest import days_ago, signed +from scrobbler.extensions import db +from scrobbler.models import NowPlaying, Scrobble + + +@pytest.fixture +def lastfm(client, api_app, session_key): + def call(method, fmt="xml", **params): + data = signed( + {"method": method, "api_key": api_app.api_key, "sk": session_key, **params}, + api_app.shared_secret, + ) + response = client.post("/2.0/", data={**data, "format": fmt}) + return response.get_json() if fmt == "json" else ET.fromstring(response.data) + + return call + + +def batch(*tracks): + params = {} + for i, track in enumerate(tracks): + params.update({f"{key}[{i}]": str(value) for key, value in track.items()}) + return params + + +def stored(): + return db.session.scalars(db.select(Scrobble).order_by(Scrobble.played_at)).all() + + +def test_single_scrobble(lastfm, user): + ts = days_ago(0.01) + root = lastfm( + "track.scrobble", + **batch( + {"artist": "Radiohead", "track": "Reckoner", "album": "In Rainbows", "timestamp": ts} + ), + ) + scrobbles = root.find("scrobbles") + assert (scrobbles.get("accepted"), scrobbles.get("ignored")) == ("1", "0") + assert scrobbles.find("scrobble/track").text == "Reckoner" + assert scrobbles.find("scrobble/ignoredMessage").get("code") == "0" + + [row] = stored() + assert (row.user_id, row.artist, row.album) == (user.id, "Radiohead", "In Rainbows") + assert int(row.played_at.timestamp()) == ts + + +def test_unindexed_single_scrobble(lastfm): + root = lastfm("track.scrobble", artist="A", track="T", timestamp=str(days_ago(0.1))) + assert root.find("scrobbles").get("accepted") == "1" + + +def test_batch_of_fifty(lastfm, metric_delta): + sizes = metric_delta("scrobbler_scrobble_batch_size_count") + start = days_ago(1) + tracks = [{"artist": "A", "track": f"T{i}", "timestamp": start + i * 200} for i in range(50)] + root = lastfm("track.scrobble", **batch(*tracks)) + assert root.find("scrobbles").get("accepted") == "50" + assert len(stored()) == 50 + assert sizes.delta == 1 + + +def test_more_than_fifty_is_rejected(lastfm): + tracks = [{"artist": "A", "track": f"T{i}", "timestamp": days_ago(1) + i} for i in range(51)] + assert lastfm("track.scrobble", **batch(*tracks)).find("error").get("code") == "6" + + +def test_missing_timestamp_is_an_error(lastfm): + root = lastfm("track.scrobble", **batch({"artist": "A", "track": "T"})) + assert root.find("error").get("code") == "6" + + +def test_ignore_rules(lastfm, metric_delta): + ignored = { + code: metric_delta("scrobbler_scrobbles_ignored_total", reason=code) for code in "1234" + } + accepted = metric_delta("scrobbler_scrobbles_total", result="accepted") + now = int(time.time()) + root = lastfm( + "track.scrobble", + **batch( + {"artist": "", "track": "T", "timestamp": now - 60}, + {"artist": "A", "track": " ", "timestamp": now - 60}, + {"artist": "A", "track": "Old", "timestamp": days_ago(15)}, + {"artist": "A", "track": "Future", "timestamp": now + 3600}, + {"artist": "A", "track": "Fine", "timestamp": now - 60}, + ), + ) + scrobbles = root.find("scrobbles") + assert (scrobbles.get("accepted"), scrobbles.get("ignored")) == ("1", "4") + codes = [s.find("ignoredMessage").get("code") for s in scrobbles.findall("scrobble")] + assert codes == ["1", "2", "3", "4", "0"] + assert [row.track for row in stored()] == ["Fine"] + assert {code: m.delta for code, m in ignored.items()} == {"1": 1, "2": 1, "3": 1, "4": 1} + assert accepted.delta == 1 + + +def test_duplicates_are_accepted_but_stored_once(lastfm, metric_delta): + duplicates = metric_delta("scrobbler_scrobbles_total", result="duplicate") + track = {"artist": "A", "track": "T", "timestamp": days_ago(0.5)} + lastfm("track.scrobble", **batch(track)) + root = lastfm("track.scrobble", **batch(track)) + assert root.find("scrobbles").get("accepted") == "1" + assert len(stored()) == 1 + assert duplicates.delta == 1 + + +def test_json_scrobble_response(lastfm): + body = lastfm( + "track.scrobble", + fmt="json", + **batch({"artist": "A", "track": "T", "timestamp": days_ago(0.2)}), + ) + assert body["scrobbles"]["@attr"] == {"accepted": "1", "ignored": "0"} + assert body["scrobbles"]["scrobble"]["artist"] == {"corrected": "0", "#text": "A"} + + +def test_now_playing(lastfm, user, metric_delta): + updates = metric_delta("scrobbler_now_playing_updates_total") + root = lastfm("track.updateNowPlaying", artist="Radiohead", track="Reckoner", duration="290") + assert root.find("nowplaying/track").text == "Reckoner" + row = db.session.get(NowPlaying, user.id) + assert row.track == "Reckoner" + assert timedelta(seconds=289) < row.expires_at - row.started_at < timedelta(seconds=291) + + lastfm("track.updateNowPlaying", artist="Radiohead", track="Nude") + db.session.expire_all() + assert db.session.get(NowPlaying, user.id).track == "Nude" + assert updates.delta == 2 + + +def test_now_playing_requires_artist_and_track(lastfm): + assert lastfm("track.updateNowPlaying", artist="A").find("error").get("code") == "6" + + +def test_scrobbling_the_current_track_clears_now_playing(lastfm, user): + lastfm("track.updateNowPlaying", artist="Radiohead", track="Reckoner") + lastfm( + "track.scrobble", + **batch({"artist": "radiohead", "track": "RECKONER", "timestamp": days_ago(0.001)}), + ) + db.session.expire_all() + assert db.session.get(NowPlaying, user.id) is None + + +def test_scrobbling_another_track_keeps_now_playing(lastfm, user): + lastfm("track.updateNowPlaying", artist="Radiohead", track="Reckoner") + lastfm( + "track.scrobble", + **batch({"artist": "Radiohead", "track": "Nude", "timestamp": days_ago(0.01)}), + ) + db.session.expire_all() + assert db.session.get(NowPlaying, user.id) is not None + + +def test_scrobble_lag_is_recorded(lastfm, metric_delta): + lag = metric_delta("scrobbler_scrobble_lag_seconds_count") + lastfm("track.scrobble", **batch({"artist": "A", "track": "T", "timestamp": days_ago(2)})) + assert lag.delta == 1 + + +def test_expired_now_playing_is_not_returned(app, lastfm, user): + from scrobbler.services.scrobbles import get_now_playing + + lastfm("track.updateNowPlaying", artist="A", track="T", duration="60") + assert get_now_playing(user) is not None + row = db.session.get(NowPlaying, user.id) + row.expires_at = datetime.now(UTC) - timedelta(seconds=1) + db.session.commit() + assert get_now_playing(user) is None diff --git a/tests/test_ui_apps_sessions.py b/tests/test_ui_apps_sessions.py index 1c2437d..dc7825a 100644 --- a/tests/test_ui_apps_sessions.py +++ b/tests/test_ui_apps_sessions.py @@ -27,9 +27,14 @@ def test_revoked_session_key_stops_working(client, auth, api_app, session_key): assert client.delete(f"/api/v1/sessions/{sessions[0]['id']}", headers=auth).status_code == 204 params = signed( - {"method": "track.updateNowPlaying", "api_key": api_app.api_key, "sk": session_key}, + { + "method": "track.updateNowPlaying", + "api_key": api_app.api_key, + "sk": session_key, + "artist": "A", + "track": "T", + }, api_app.shared_secret, ) - # The method is registered in a later step; the session check runs first either way. response = client.post("/2.0/", data={**params, "format": "json"}) - assert response.get_json()["error"] in (3, 9) + assert response.get_json()["error"] == 9