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 <noreply@anthropic.com>
This commit is contained in:
1 parent
7622f7433a
commit
2702815a1e
6 files changed
+498
-5
No files matched your search
@@ -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)}"
|
||||
|
||||
@@ -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
|
||||
@@ -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=(
|
||||
'<lfm status="ok"><scrobbles accepted="1" ignored="0"><scrobble>'
|
||||
'<track corrected="0">Reckoner</track><artist corrected="0">Radiohead</artist>'
|
||||
'<album corrected="0">In Rainbows</album><albumArtist corrected="0"></albumArtist>'
|
||||
'<timestamp>1700000000</timestamp><ignoredMessage code="0"></ignoredMessage>'
|
||||
"</scrobble></scrobbles></lfm>"
|
||||
),
|
||||
)
|
||||
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=(
|
||||
'<lfm status="ok"><nowplaying><track corrected="0">Reckoner</track>'
|
||||
'<artist corrected="0">Radiohead</artist><album corrected="0"></album>'
|
||||
'<albumArtist corrected="0"></albumArtist><ignoredMessage code="0"></ignoredMessage>'
|
||||
"</nowplaying></lfm>"
|
||||
),
|
||||
)
|
||||
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))
|
||||
@@ -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<name>[A-Za-z]+)\[(?P<index>\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()
|
||||
)
|
||||
)
|
||||
Reference in new issue
Block a user