From ea6b10637ef297a208ea458aee9e5db345b015c1 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Sat, 26 Sep 2026 11:34:08 +0100 Subject: [PATCH] Core: listening stats over an explicit date window (phase 3, step 1) scrobbler.services.stats gains scrobble_count_between, top_artists_between and top_tracks_between, over [start, end) (start inclusive, end exclusive) rather than a rolling period. The existing period-based functions are re-expressed on the same _between() primitive instead of duplicating the windowing logic. These are for federation's weekly summaries (phase 3), which need a fixed Monday-to-Sunday window rather than "N days back". No public API changes; the Last.fm and /api/v1/me endpoints are unaffected (pinned by a regression test). Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- src/scrobbler/services/stats.py | 59 +++++++++++++++++++++++- tests/test_stats.py | 82 +++++++++++++++++++++++++++++++++ 2 files changed, 139 insertions(+), 2 deletions(-) diff --git a/src/scrobbler/services/stats.py b/src/scrobbler/services/stats.py index 6134696..6328c8d 100644 --- a/src/scrobbler/services/stats.py +++ b/src/scrobbler/services/stats.py @@ -47,13 +47,20 @@ def since(period: str, now: datetime | None = None) -> datetime | None: return None if days is None else (now or datetime.now(UTC)) - timedelta(days=days) -def _user_scrobbles(user: User, period: str = "overall"): +def _between(user: User, start: datetime | None, end: datetime | None): + """user_id plus an optional window: start inclusive, end exclusive.""" conditions = [Scrobble.user_id == user.id] - if (start := since(period)) is not None: + if start is not None: conditions.append(Scrobble.played_at >= start) + if end is not None: + conditions.append(Scrobble.played_at < end) return conditions +def _user_scrobbles(user: User, period: str = "overall"): + return _between(user, since(period), None) + + def _display(column): """Most common spelling within a case-insensitive group. Ties go to the capitalised spelling: the C collation sorts uppercase first, regardless of the server locale.""" @@ -162,6 +169,54 @@ def listen_counts(user: User, period: str = "1month", bucket: str = "day") -> li return [{"start": day, "count": count} for day, count in counts.items()] +def scrobble_count_between(user: User, start: datetime, end: datetime) -> int: + """Total plays in [start, end).""" + return db.session.scalar(select(func.count()).where(*_between(user, start, end))) or 0 + + +def top_artists_between( + user: User, start: datetime, end: datetime, limit: int = 10 +) -> list[TopItem]: + """Top artists in [start, end), unpaginated (callers like weekly summaries want a + handful, not a full listing).""" + key = func.lower(Scrobble.artist) + plays = func.count().label("plays") + query = ( + select(_display(Scrobble.artist), plays) + .where(*_between(user, start, end)) + .group_by(key) + .order_by(plays.desc(), key) + .limit(limit) + ) + rows = db.session.execute(query).all() + return [TopItem(i + 1, name, count) for i, (name, count) in enumerate(rows)] + + +def top_tracks_between( + user: User, start: datetime, end: datetime, limit: int = 10 +) -> list[TopItem]: + """Top tracks in [start, end), unpaginated.""" + keys = (func.lower(Scrobble.track), func.lower(Scrobble.artist)) + plays = func.count().label("plays") + query = ( + select( + _display(Scrobble.track), + _display(Scrobble.artist), + func.max(Scrobble.duration), + plays, + ) + .where(*_between(user, start, end)) + .group_by(*keys) + .order_by(plays.desc(), *keys) + .limit(limit) + ) + rows = db.session.execute(query).all() + return [ + TopItem(i + 1, name, count, artist=artist, duration=duration) + for i, (name, artist, duration, count) in enumerate(rows) + ] + + def summary(user: User) -> dict: row = db.session.execute( select( diff --git a/tests/test_stats.py b/tests/test_stats.py index 184311a..e16642a 100644 --- a/tests/test_stats.py +++ b/tests/test_stats.py @@ -171,3 +171,85 @@ def test_me_summary(client, auth, history): def test_me_requires_auth(client): for path in ("recent", "top/artists", "counts", "summary", "now-playing"): assert client.get(f"/api/v1/me/{path}").status_code == 401 + + +# --- Explicit windows (start inclusive, end exclusive) -------------------------------- +# Used by federation's weekly summaries (phase 3): a fixed window, not "N days back". + +WINDOW_START = datetime(2026, 1, 5, tzinfo=UTC) # a Monday +WINDOW_END = datetime(2026, 1, 12, tzinfo=UTC) # the following Monday + + +def played(user, artist, track, when): + db.session.add(Scrobble(user_id=user.id, artist=artist, track=track, played_at=when)) + + +@pytest.fixture +def windowed_history(user): + # Inside the window + played(user, "Radiohead", "Reckoner", WINDOW_START + timedelta(days=1)) + played(user, "Radiohead", "Nude", WINDOW_START + timedelta(days=2)) + played(user, "Björk", "Jóga", WINDOW_START + timedelta(days=3)) + # Exactly at the start boundary: included (inclusive) + played(user, "Radiohead", "Nude", WINDOW_START) + # Exactly at the end boundary: excluded (exclusive) + played(user, "Portishead", "Roads", WINDOW_END) + # Well outside the window on both sides + played(user, "Old Artist", "Old Track", WINDOW_START - timedelta(days=10)) + played(user, "Future Artist", "Future Track", WINDOW_END + timedelta(days=10)) + db.session.commit() + + +def test_scrobble_count_between(user, windowed_history): + from scrobbler.services import stats + + assert stats.scrobble_count_between(user, WINDOW_START, WINDOW_END) == 4 + + +def test_top_artists_between(user, windowed_history): + from scrobbler.services import stats + + items = stats.top_artists_between(user, WINDOW_START, WINDOW_END) + assert [(i.rank, i.name, i.playcount) for i in items] == [(1, "Radiohead", 3), (2, "Björk", 1)] + + +def test_top_tracks_between(user, windowed_history): + from scrobbler.services import stats + + items = stats.top_tracks_between(user, WINDOW_START, WINDOW_END) + assert items[0].name == "Nude" + assert items[0].artist == "Radiohead" + assert items[0].playcount == 2 + + +def test_between_window_has_no_plays_outside_it(user): + from scrobbler.services import stats + + empty_start = WINDOW_END + timedelta(days=100) + empty_end = empty_start + timedelta(days=7) + assert stats.scrobble_count_between(user, empty_start, empty_end) == 0 + assert stats.top_artists_between(user, empty_start, empty_end) == [] + assert stats.top_tracks_between(user, empty_start, empty_end) == [] + + +def test_between_is_scoped_to_the_user(user, make_user, windowed_history): + from scrobbler.services import stats + + other = make_user(username="mallory") + add(other, "Someone Else", "Track", days_ago=(NOW - WINDOW_START).total_seconds() / 86400 - 1) + db.session.commit() + assert stats.scrobble_count_between(user, WINDOW_START, WINDOW_END) == 4 + assert stats.scrobble_count_between(other, WINDOW_START, WINDOW_END) == 1 + + +def test_rolling_periods_are_unaffected_by_the_window_refactor(client, api_app, history): + """_user_scrobbles(user, period) now delegates to _between(); this pins its old + behaviour (unbounded end, inclusive start) so the refactor can't silently change it.""" + response = client.get( + f"/2.0/?method=user.getTopArtists&user=alice&period=7day&api_key={api_app.api_key}" + ) + top = ET.fromstring(response.data).find("topartists") + assert [(a.find("name").text, a.find("playcount").text) for a in top] == [ + ("Radiohead", "3"), + ("Björk", "2"), + ]