Listening stats: Last.fm user.* methods and /api/v1/me
CI / lint (push) Successful in 12s
CI / test (push) Successful in 30s
CI / notify (push) Successful in 5s

- Stats service shared by both APIs: recent scrobbles, top artists,
  albums and tracks over Last.fm periods, per-day/week/month counts
  (with empty days filled) and totals
- Case-insensitive grouping that displays the most common spelling
- user.getInfo, user.getRecentTracks (now playing first, from/to),
  user.getTopArtists/Albums/Tracks with Last.fm paging attributes
- /api/v1/me: now-playing, recent, top/{artists,albums,tracks},
  counts and summary

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
This commit is contained in:
mattandClaude Opus 5.5 committed 2026-09-25 14:05:20 +01:00
1 parent 2702815a1e
commit 0d49311848
7 files changed
+769 -2

No files matched your search

+2 -1
View File
@@ -43,9 +43,10 @@ def init_app(app: Flask) -> None:
},
)
from scrobbler.api import apps, auth, sessions, tokens
from scrobbler.api import apps, auth, sessions, stats, tokens
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")
+90
View File
@@ -0,0 +1,90 @@
from flask import g
from flask_smorest import Blueprint
from scrobbler.api.decorators import authenticated
from scrobbler.schemas import (
CountsArgsSchema,
CountSchema,
NowPlayingSchema,
PageArgsSchema,
RecentPageSchema,
SummarySchema,
TopArgsSchema,
TopPageSchema,
)
from scrobbler.services import scrobbles, stats
blp = Blueprint("ui_stats", __name__, description="Your listening history and statistics")
TOP_KINDS = {
"artists": stats.top_artists,
"albums": stats.top_albums,
"tracks": stats.top_tracks,
}
def _page_body(page: stats.Page) -> dict:
return {
"items": page.items,
"page": page.page,
"per_page": page.per_page,
"total": page.total,
"total_pages": page.total_pages,
}
@blp.route("/now-playing", methods=["GET"])
@authenticated(blp)
@blp.response(200, NowPlayingSchema)
def now_playing():
"""What you're listening to now"""
return {"now_playing": scrobbles.get_now_playing(g.user)}
@blp.route("/recent", methods=["GET"])
@authenticated(blp)
@blp.arguments(PageArgsSchema, location="query")
@blp.response(200, RecentPageSchema)
def recent(args):
"""Recent scrobbles, newest first"""
return _page_body(stats.recent(g.user, page=args["page"], per_page=args["limit"]))
def _top(kind):
def view(args):
page = TOP_KINDS[kind](g.user, args["period"], args["page"], args["limit"])
return {**_page_body(page), "period": args["period"]}
view.__name__ = f"top_{kind}"
view.__doc__ = f"Top {kind} over a period"
return view
for _kind in TOP_KINDS:
blp.route(f"/top/{_kind}", methods=["GET"])(
authenticated(blp)(
blp.arguments(TopArgsSchema, location="query")(
blp.response(200, TopPageSchema)(_top(_kind))
)
)
)
@blp.route("/counts", methods=["GET"])
@authenticated(blp)
@blp.arguments(CountsArgsSchema, location="query")
@blp.response(200, CountSchema(many=True))
def counts(args):
"""Scrobbles per day, week or month
Day buckets include days with no scrobbles, so the series is continuous.
"""
return stats.listen_counts(g.user, args["period"], args["bucket"])
@blp.route("/summary", methods=["GET"])
@authenticated(blp)
@blp.response(200, SummarySchema)
def summary():
"""Totals: scrobbles, distinct artists and tracks"""
return stats.summary(g.user)
+1 -1
View File
@@ -1,3 +1,3 @@
"""Importing this package registers every Last.fm method handler."""
from scrobbler.lastfm.methods import auth, track # noqa: F401
from scrobbler.lastfm.methods import auth, track, user # noqa: F401
+246
View File
@@ -0,0 +1,246 @@
from datetime import UTC, datetime
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.models import User
from scrobbler.services import accounts, scrobbles, stats
USER_PARAM = Param("user", "Username to fetch data for", required=True, example="alice")
PAGE_PARAMS = (
Param("limit", "Results per page (default 50, max 1000)", example="50"),
Param("page", "Page number (default 1)", example="1"),
)
PERIOD_PARAM = Param(
"period",
"overall | 7day | 1month | 3month | 6month | 12month (default overall)",
example="7day",
)
def _user(call: Call) -> User:
user = accounts.find_user(call.params["user"])
if user is None:
raise LastFMError(errors.INVALID_PARAMETERS, "User not found")
return user
def _int_param(call: Call, name: str, default: int, maximum: int) -> int:
raw = call.get(name)
try:
value = int(raw) if raw is not None else default
except ValueError:
raise LastFMError(errors.INVALID_PARAMETERS, f"{name} must be an integer") from None
if not 1 <= value <= maximum:
raise LastFMError(errors.INVALID_PARAMETERS, f"{name} must be between 1 and {maximum}")
return value
def _paging(call: Call, max_limit: int = 1000) -> tuple[int, int]:
return _int_param(call, "page", 1, 1_000_000), _int_param(call, "limit", 50, max_limit)
def _period(call: Call) -> str:
period = call.get("period", "overall")
if period not in stats.PERIODS:
raise LastFMError(errors.INVALID_PARAMETERS, "Invalid period")
return period
def _page_attrs(user: User, page: stats.Page) -> dict:
return {
"user": user.username,
"page": page.page,
"perPage": page.per_page,
"totalPages": page.total_pages,
"total": page.total,
}
def _artist_el(name: str, tag: str = "artist") -> El:
return El.of(tag, El.text_el("name", name), El.text_el("mbid", ""), El.text_el("url", ""))
@lastfm_method(
"user.getInfo",
summary="A user's profile and play count",
params=(USER_PARAM,),
example_xml=(
'<lfm status="ok"><user><name>alice</name><realname></realname><url></url>'
"<country></country><playcount>1234</playcount><artist_count>210</artist_count>"
"<track_count>800</track_count><subscriber>0</subscriber>"
'<registered unixtime="1700000000">1700000000</registered></user></lfm>'
),
)
def get_info(call: Call) -> El:
user = _user(call)
totals = stats.summary(user)
registered = int(user.created_at.timestamp())
return El.of(
"user",
El.text_el("name", user.username),
El.text_el("realname", ""),
El.text_el("url", ""),
El.text_el("country", ""),
El.text_el("playcount", totals["scrobbles"]),
El.text_el("artist_count", totals["artists"]),
El.text_el("track_count", totals["tracks"]),
El.text_el("subscriber", 0),
El.text_el("registered", registered, unixtime=registered),
)
@lastfm_method(
"user.getRecentTracks",
summary="Recently scrobbled tracks, newest first, led by the now-playing track",
params=(
USER_PARAM,
Param("limit", "Results per page (default 50, max 200)", example="50"),
Param("page", "Page number (default 1)", example="1"),
Param("from", "Only scrobbles at or after this Unix time"),
Param("to", "Only scrobbles at or before this Unix time"),
),
example_xml=(
'<lfm status="ok"><recenttracks user="alice" page="1" perPage="50" totalPages="1" '
'total="1"><track nowplaying="true"><artist mbid="">Radiohead</artist><name>Nude</name>'
'<mbid></mbid><album mbid="">In Rainbows</album><url></url></track><track>'
'<artist mbid="">Radiohead</artist><name>Reckoner</name><mbid></mbid>'
'<album mbid="">In Rainbows</album><url></url>'
'<date uts="1700000000">14 Nov 2023, 22:13</date></track></recenttracks></lfm>'
),
)
def get_recent_tracks(call: Call):
user = _user(call)
page, limit = _paging(call, max_limit=200)
start = _timestamp(call, "from")
end = _timestamp(call, "to")
result = stats.recent(user, page=page, per_page=limit, start=start, end=end)
tracks = []
now_playing = scrobbles.get_now_playing(user) if page == 1 and end is None else None
if now_playing:
tracks.append(
El.of(
"track",
*_recent_fields(now_playing.artist, now_playing.track, now_playing.album, None),
nowplaying="true",
)
)
for row in result.items:
tracks.append(El.of("track", *_recent_fields(row.artist, row.track, row.album, row)))
return El.of("recenttracks", *tracks, **_page_attrs(user, result)), ("track",)
def _timestamp(call: Call, name: str) -> datetime | None:
raw = call.get(name)
if raw is None:
return None
try:
return datetime.fromtimestamp(int(raw), UTC)
except (ValueError, OverflowError, OSError):
raise LastFMError(errors.INVALID_PARAMETERS, f"{name} must be a Unix time") from None
def _recent_fields(artist: str, track: str, album: str | None, scrobble) -> list[El]:
fields = [
El.text_el("artist", artist, mbid=""),
El.text_el("name", track),
El.text_el("mbid", scrobble.mbid if scrobble else ""),
El.text_el("album", album, mbid=""),
El.text_el("url", ""),
]
if scrobble is not None:
uts = int(scrobble.played_at.timestamp())
label = scrobble.played_at.astimezone(UTC).strftime("%d %b %Y, %H:%M")
fields.append(El.text_el("date", label, uts=uts))
return fields
@lastfm_method(
"user.getTopArtists",
summary="Most played artists over a period",
params=(USER_PARAM, PERIOD_PARAM, *PAGE_PARAMS),
example_xml=(
'<lfm status="ok"><topartists user="alice" page="1" perPage="50" totalPages="1" '
'total="1"><artist rank="1"><name>Radiohead</name><playcount>42</playcount>'
"<mbid></mbid><url></url></artist></topartists></lfm>"
),
)
def get_top_artists(call: Call):
user, period, (page, limit) = _user(call), _period(call), _paging(call)
result = stats.top_artists(user, period, page, limit)
artists = [
El.of(
"artist",
El.text_el("name", item.name),
El.text_el("playcount", item.playcount),
El.text_el("mbid", ""),
El.text_el("url", ""),
rank=item.rank,
)
for item in result.items
]
attrs = {**_page_attrs(user, result), "period": period}
return El.of("topartists", *artists, **attrs), ("artist",)
@lastfm_method(
"user.getTopAlbums",
summary="Most played albums over a period",
params=(USER_PARAM, PERIOD_PARAM, *PAGE_PARAMS),
example_xml=(
'<lfm status="ok"><topalbums user="alice" page="1" perPage="50" totalPages="1" '
'total="1"><album rank="1"><name>In Rainbows</name><playcount>20</playcount>'
"<mbid></mbid><url></url><artist><name>Radiohead</name><mbid></mbid><url></url>"
"</artist></album></topalbums></lfm>"
),
)
def get_top_albums(call: Call):
user, period, (page, limit) = _user(call), _period(call), _paging(call)
result = stats.top_albums(user, period, page, limit)
albums = [
El.of(
"album",
El.text_el("name", item.name),
El.text_el("playcount", item.playcount),
El.text_el("mbid", ""),
El.text_el("url", ""),
_artist_el(item.artist),
rank=item.rank,
)
for item in result.items
]
attrs = {**_page_attrs(user, result), "period": period}
return El.of("topalbums", *albums, **attrs), ("album",)
@lastfm_method(
"user.getTopTracks",
summary="Most played tracks over a period",
params=(USER_PARAM, PERIOD_PARAM, *PAGE_PARAMS),
example_xml=(
'<lfm status="ok"><toptracks user="alice" page="1" perPage="50" totalPages="1" '
'total="1"><track rank="1"><name>Reckoner</name><duration>290</duration>'
"<playcount>12</playcount><mbid></mbid><url></url><artist><name>Radiohead</name>"
"<mbid></mbid><url></url></artist></track></toptracks></lfm>"
),
)
def get_top_tracks(call: Call):
user, period, (page, limit) = _user(call), _period(call), _paging(call)
result = stats.top_tracks(user, period, page, limit)
tracks = [
El.of(
"track",
El.text_el("name", item.name),
El.text_el("duration", item.duration or 0),
El.text_el("playcount", item.playcount),
El.text_el("mbid", ""),
El.text_el("url", ""),
_artist_el(item.artist),
rank=item.rank,
)
for item in result.items
]
attrs = {**_page_attrs(user, result), "period": period}
return El.of("toptracks", *tracks, **attrs), ("track",)
+76
View File
@@ -67,3 +67,79 @@ class AuthTokenInfoSchema(Schema):
class ApproveTokenSchema(Schema):
token = fields.String(required=True, metadata={"description": "Token from auth.getToken"})
PERIODS = ["overall", "7day", "1month", "3month", "6month", "12month"]
class PageArgsSchema(Schema):
page = fields.Integer(load_default=1, validate=validate.Range(min=1))
limit = fields.Integer(load_default=50, validate=validate.Range(min=1, max=200))
class TopArgsSchema(PageArgsSchema):
period = fields.String(load_default="7day", validate=validate.OneOf(PERIODS))
class CountsArgsSchema(Schema):
period = fields.String(load_default="1month", validate=validate.OneOf(PERIODS))
bucket = fields.String(load_default="day", validate=validate.OneOf(["day", "week", "month"]))
class PageMetaSchema(Schema):
page = fields.Integer()
per_page = fields.Integer()
total = fields.Integer()
total_pages = fields.Integer()
class ScrobbleSchema(Schema):
artist = fields.String()
track = fields.String()
album = fields.String(allow_none=True)
album_artist = fields.String(allow_none=True)
duration = fields.Integer(allow_none=True)
played_at = fields.DateTime()
class RecentPageSchema(PageMetaSchema):
items = fields.List(fields.Nested(ScrobbleSchema))
class NowPlayingTrackSchema(Schema):
artist = fields.String()
track = fields.String()
album = fields.String(allow_none=True)
duration = fields.Integer(allow_none=True)
started_at = fields.DateTime()
expires_at = fields.DateTime()
class NowPlayingSchema(Schema):
now_playing = fields.Nested(
NowPlayingTrackSchema, allow_none=True, metadata={"description": "null when idle"}
)
class TopItemSchema(Schema):
rank = fields.Integer()
name = fields.String()
artist = fields.String(allow_none=True, metadata={"description": "Albums and tracks only"})
playcount = fields.Integer()
class TopPageSchema(PageMetaSchema):
period = fields.String()
items = fields.List(fields.Nested(TopItemSchema))
class CountSchema(Schema):
start = fields.Date(metadata={"description": "First day of the bucket (UTC)"})
count = fields.Integer()
class SummarySchema(Schema):
scrobbles = fields.Integer()
artists = fields.Integer()
tracks = fields.Integer()
first_scrobble_at = fields.DateTime(allow_none=True)
+181
View File
@@ -0,0 +1,181 @@
"""Listening statistics, shared by the Last.fm user.* methods and /api/v1/me."""
import math
from dataclasses import dataclass
from datetime import UTC, date, datetime, timedelta
from sqlalchemy import Select, func, literal_column, select
from scrobbler.extensions import db
from scrobbler.models import Scrobble, User
# Last.fm period names -> days (None = all time)
PERIODS: dict[str, int | None] = {
"overall": None,
"7day": 7,
"1month": 30,
"3month": 90,
"6month": 180,
"12month": 365,
}
BUCKETS = ("day", "week", "month")
@dataclass
class Page:
items: list
page: int
per_page: int
total: int
@property
def total_pages(self) -> int:
return max(1, math.ceil(self.total / self.per_page)) if self.per_page else 1
@dataclass
class TopItem:
rank: int
name: str
playcount: int
artist: str | None = None # for albums and tracks
duration: int | None = None # for tracks
def since(period: str, now: datetime | None = None) -> datetime | None:
days = PERIODS[period]
return None if days is None else (now or datetime.now(UTC)) - timedelta(days=days)
def _user_scrobbles(user: User, period: str = "overall"):
conditions = [Scrobble.user_id == user.id]
if (start := since(period)) is not None:
conditions.append(Scrobble.played_at >= start)
return conditions
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."""
return func.mode().within_group(column.collate("C"))
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()
return rows, total
def recent(
user: User,
page: int = 1,
per_page: int = 50,
start: datetime | None = None,
end: datetime | 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)
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)
def top_artists(user: User, period: str = "overall", page: int = 1, per_page: int = 50) -> Page:
key = func.lower(Scrobble.artist)
plays = func.count().label("plays")
query = (
select(_display(Scrobble.artist), plays)
.where(*_user_scrobbles(user, period))
.group_by(key)
.order_by(plays.desc(), key)
)
rows, total = _paginate(query, page, per_page)
offset = (page - 1) * per_page
items = [TopItem(offset + i + 1, name, count) for i, (name, count) in enumerate(rows)]
return Page(items, page, per_page, total)
def top_albums(user: User, period: str = "overall", page: int = 1, per_page: int = 50) -> Page:
album_artist = func.coalesce(Scrobble.album_artist, Scrobble.artist)
keys = (func.lower(Scrobble.album), func.lower(album_artist))
plays = func.count().label("plays")
query = (
select(_display(Scrobble.album), _display(album_artist), plays)
.where(*_user_scrobbles(user, period), Scrobble.album.is_not(None))
.group_by(*keys)
.order_by(plays.desc(), *keys)
)
rows, total = _paginate(query, page, per_page)
offset = (page - 1) * per_page
items = [
TopItem(offset + i + 1, name, count, artist=artist)
for i, (name, artist, count) in enumerate(rows)
]
return Page(items, page, per_page, total)
def top_tracks(user: User, period: str = "overall", page: int = 1, per_page: int = 50) -> Page:
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(*_user_scrobbles(user, period))
.group_by(*keys)
.order_by(plays.desc(), *keys)
)
rows, total = _paginate(query, page, per_page)
offset = (page - 1) * per_page
items = [
TopItem(offset + i + 1, name, count, artist=artist, duration=duration)
for i, (name, artist, duration, count) in enumerate(rows)
]
return Page(items, page, per_page, total)
def listen_counts(user: User, period: str = "1month", bucket: str = "day") -> 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}")
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))
.group_by("bucket")
.order_by("bucket")
)
counts = {row[0].date(): row[1] for row in db.session.execute(query)}
if bucket == "day" and (start := since(period)) is not None:
day, today = start.date(), datetime.now(UTC).date()
filled: dict[date, int] = {}
while day <= today:
filled[day] = counts.get(day, 0)
day += timedelta(days=1)
counts = filled
return [{"start": day, "count": count} for day, count in counts.items()]
def summary(user: User) -> dict:
row = db.session.execute(
select(
func.count(),
func.count(func.distinct(func.lower(Scrobble.artist))),
func.count(
func.distinct(func.lower(Scrobble.artist) + "\x1f" + func.lower(Scrobble.track))
),
func.min(Scrobble.played_at),
).where(Scrobble.user_id == user.id)
).one()
return {
"scrobbles": row[0],
"artists": row[1],
"tracks": row[2],
"first_scrobble_at": row[3],
}