diff --git a/src/scrobbler/federation/protocol/vocab.py b/src/scrobbler/federation/protocol/vocab.py index d712f07..ff77353 100644 --- a/src/scrobbler/federation/protocol/vocab.py +++ b/src/scrobbler/federation/protocol/vocab.py @@ -250,10 +250,11 @@ def note( to: list[str], cc: list[str], tags: list[str] = (), + attachment: list[dict] = (), ) -> dict: - """A post (weekly summary or milestone). No `@context`: it's always embedded in the - Create that carries the same addressing, as Mastodon does.""" - return { + """A post (now playing, weekly summary or milestone). No `@context`: it's always + embedded in the Create that carries the same addressing, as Mastodon does.""" + doc = { "id": note_id, "type": "Note", "attributedTo": actor_id, @@ -266,6 +267,9 @@ def note( "tag": [hashtag(t) for t in tags], "sensitive": False, } + if attachment: + doc["attachment"] = list(attachment) + return doc def create(activity_id: str, actor_id: str, obj: dict, *, to: list[str], cc: list[str]) -> dict: diff --git a/src/scrobbler/federation/publishing/base.py b/src/scrobbler/federation/publishing/base.py index 0e0c6a7..4b60e23 100644 --- a/src/scrobbler/federation/publishing/base.py +++ b/src/scrobbler/federation/publishing/base.py @@ -87,6 +87,7 @@ def publish( text: str, html: str, tags: tuple[str, ...] = DEFAULT_TAGS, + attachment: list[dict] = (), ) -> FederationPost | None: """Post `text`/`html` for the user, keyed by `kind:key`. @@ -116,6 +117,7 @@ def publish( to=to, cc=cc, tags=list(tags), + attachment=list(attachment), ) # activity.id is a Python-generated UUID (see activities.store), so it's already # usable below without a flush. diff --git a/src/scrobbler/federation/publishing/now_playing.py b/src/scrobbler/federation/publishing/now_playing.py index 6eeafdd..3052af3 100644 --- a/src/scrobbler/federation/publishing/now_playing.py +++ b/src/scrobbler/federation/publishing/now_playing.py @@ -19,7 +19,7 @@ from scrobbler.federation import activities, actors, followers, publishing, shar from scrobbler.federation import metrics as fed_metrics from scrobbler.federation.models import FederationNowPlaying, FederationPost, FederationSettings from scrobbler.federation.protocol import content, vocab -from scrobbler.services import accounts +from scrobbler.services import accounts, art from scrobbler.services.scrobbles import get_now_playing KIND = "now_playing" @@ -80,10 +80,36 @@ def _build_content(playing) -> tuple[str, str]: return text, html +def _attachment_for(playing) -> list[dict]: + """Cover art for the post, if we have an album and can resolve it. Cover Art + Archive's sized convenience endpoints (what art.lookup() resolves to) are always + JPEG, whatever the original upload was.""" + if not playing.album: + return [] + result = art.lookup(playing.artist, playing.album) + if result.status != "found": + return [] + return [ + { + "type": "Image", + "mediaType": "image/jpeg", + "url": result.image_url, + "name": f"Cover art for {playing.album}", + } + ] + + def _post_now_playing(user, playing, key: str, state: FederationNowPlaying, now: datetime) -> str: text, html = _build_content(playing) post = publishing.publish( - user.id, user.username, KIND, key, text=text, html=html, tags=("Scrobbler", "NowPlaying") + user.id, + user.username, + KIND, + key, + text=text, + html=html, + tags=("Scrobbler", "NowPlaying"), + attachment=_attachment_for(playing), ) if post is None: return "none" diff --git a/tests/test_federation_now_playing.py b/tests/test_federation_now_playing.py index 094e7e0..6d6f47c 100644 --- a/tests/test_federation_now_playing.py +++ b/tests/test_federation_now_playing.py @@ -8,18 +8,33 @@ from scrobbler.extensions import db from scrobbler.federation import sharing from scrobbler.federation.models import FederationActivity, FederationNowPlaying, FederationPost from scrobbler.federation.publishing import now_playing -from scrobbler.models import NowPlaying +from scrobbler.models import AlbumArt, NowPlaying from scrobbler.services.scrobbles import TrackInput, update_now_playing -def play(user, artist="Radiohead", track="Reckoner") -> datetime: +def play(user, artist="Radiohead", track="Reckoner", album=None) -> datetime: """Sets the track as playing (started_at = now) and returns that now, so tests always measure elapsed/throttle time relative to when it actually started, not a fixed constant that would drift from real test-execution time.""" - update_now_playing(user, TrackInput(artist=artist, track=track)) + update_now_playing(user, TrackInput(artist=artist, track=track, album=album)) return datetime.now(UTC) +def cache_art(artist: str, album: str, status: str, image_url: str | None = None) -> None: + """Primes the AlbumArt cache directly, so art.lookup() is a cache hit and never + makes a real network call during tests.""" + db.session.add( + AlbumArt( + artist=artist, + album=album, + status=status, + image_url=image_url, + checked_at=datetime.now(UTC), + ) + ) + db.session.commit() + + def stop_playing(user): """Expire (rather than delete) the row, matching how it naturally goes away.""" db.session.get(NowPlaying, user.id).expires_at = datetime.now(UTC) - timedelta(minutes=1) @@ -141,6 +156,44 @@ def test_post_sent_after_30_seconds(fed_ctx, posting_user): ] +def test_post_includes_album_art_when_known(fed_ctx, posting_user): + cache_art( + "Radiohead", + "In Rainbows", + "found", + image_url="https://coverartarchive.org/release-group/test/front-500", + ) + now = play(posting_user, album="In Rainbows") + now_playing.check_and_post(posting_user.id, now + timedelta(seconds=31)) + [post] = posts_for(posting_user.id) + activity = db.session.get(FederationActivity, post.activity_id) + assert activity.document["object"]["attachment"] == [ + { + "type": "Image", + "mediaType": "image/jpeg", + "url": "https://coverartarchive.org/release-group/test/front-500", + "name": "Cover art for In Rainbows", + } + ] + + +def test_post_has_no_attachment_without_an_album(fed_ctx, posting_user): + now = play(posting_user) # no album + now_playing.check_and_post(posting_user.id, now + timedelta(seconds=31)) + [post] = posts_for(posting_user.id) + activity = db.session.get(FederationActivity, post.activity_id) + assert "attachment" not in activity.document["object"] + + +def test_post_has_no_attachment_when_art_is_not_found(fed_ctx, posting_user): + cache_art("Radiohead", "Some Rare Bootleg", "not_found") + now = play(posting_user, album="Some Rare Bootleg") + now_playing.check_and_post(posting_user.id, now + timedelta(seconds=31)) + [post] = posts_for(posting_user.id) + activity = db.session.get(FederationActivity, post.activity_id) + assert "attachment" not in activity.document["object"] + + def test_post_throttled_within_30_minutes(fed_ctx, posting_user): now = play(posting_user, track="Reckoner") now_playing.check_and_post(posting_user.id, now + timedelta(seconds=31)) diff --git a/tests/test_federation_protocol.py b/tests/test_federation_protocol.py index 0890a48..6b6508d 100644 --- a/tests/test_federation_protocol.py +++ b/tests/test_federation_protocol.py @@ -182,6 +182,27 @@ def test_note(): assert doc["tag"] == [{"type": "Hashtag", "name": "#Scrobbler"}] assert doc["sensitive"] is False assert "@context" not in doc # carried by the wrapping Create instead + assert "attachment" not in doc # omitted entirely, not an empty list, when there's none + + +def test_note_with_attachment(): + image = { + "type": "Image", + "mediaType": "image/jpeg", + "url": f"{BASE}/art.jpg", + "name": "Cover art", + } + doc = vocab.note( + f"{BASE}/users/alice/posts/1", + actor_id=f"{BASE}/users/alice", + content_html="

Hello

", + published="2026-01-05T09:00:00Z", + url=f"{BASE}/post.html?id=1", + to=["FOLLOWERS"], + cc=[], + attachment=[image], + ) + assert doc["attachment"] == [image] def test_create_wraps_a_note_with_the_same_addressing():