From c38e2e392a1e3a90e06ac4087550df6512f88b40 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Sat, 26 Sep 2026 17:03:04 +0100 Subject: [PATCH] Update(Person) vocabulary and the live now-playing actor field (phase 4, step 2) vocab.update() wraps a document as an Update, addressed explicitly (unlike undo(), which derives `to` from the undone activity - an actor document has no `to` of its own). New actors.py builds the actor document body, shared by GET /users/ (live) and the coming Update(Person) push (throttled) so both render the same shape without web.py depending on the worker-side module or vice versa. now_playing_field() reads core's get_now_playing() directly - never federation's own throttled push state - so a fetch always shows the truth, whatever the last proactive push said. GET /users/ now includes a "Now playing" PropertyValue attachment whenever something unexpired is playing, and omits it otherwise. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- src/scrobbler/federation/actors.py | 37 ++++++++++++++++++++++ src/scrobbler/federation/protocol/vocab.py | 13 ++++++++ src/scrobbler/federation/web.py | 15 ++------- tests/test_federation_actors.py | 36 +++++++++++++++++++++ tests/test_federation_protocol.py | 9 ++++++ tests/test_federation_web.py | 11 +++++++ 6 files changed, 108 insertions(+), 13 deletions(-) create mode 100644 src/scrobbler/federation/actors.py create mode 100644 tests/test_federation_actors.py diff --git a/src/scrobbler/federation/actors.py b/src/scrobbler/federation/actors.py new file mode 100644 index 0000000..f7d332d --- /dev/null +++ b/src/scrobbler/federation/actors.py @@ -0,0 +1,37 @@ +"""Building a user's actor document: shared by the live `GET /users/` route and the +now-playing `Update(Person)` push, so both render the same shape. + +The now-playing field is always computed live from the core `now_playing` table, never +from federation's own throttled push state (`federation_now_playing`) - a fetch should +never lie, even if the last proactive Update was a few minutes ago. +""" + +from scrobbler.federation import keys +from scrobbler.federation.protocol import vocab +from scrobbler.services.scrobbles import get_now_playing + +NOW_PLAYING_FIELD = "Now playing" + + +def now_playing_field(user) -> list[tuple[str, str]]: + """The actor's now-playing `PropertyValue` field. Empty when nothing's playing + (`get_now_playing` already excludes expired tracks).""" + playing = get_now_playing(user) + if playing is None: + return [] + return [(NOW_PLAYING_FIELD, f"{playing.track} by {playing.artist}")] + + +def build_document(urls: vocab.ActorUrls, user, settings) -> dict: + return vocab.person( + urls, + username=user.username, + name=settings.display_name or user.username, + summary=settings.bio, + public_key_pem=keys.key_for(user.id).public_key_pem, + manually_approves_followers=settings.manually_approves_followers, + discoverable=settings.discoverable, + indexable=settings.indexable, + published=settings.created_at.isoformat().replace("+00:00", "Z"), + fields=now_playing_field(user), + ) diff --git a/src/scrobbler/federation/protocol/vocab.py b/src/scrobbler/federation/protocol/vocab.py index 6705804..d712f07 100644 --- a/src/scrobbler/federation/protocol/vocab.py +++ b/src/scrobbler/federation/protocol/vocab.py @@ -221,6 +221,19 @@ def undo(activity_id: str, actor_id: str, undone: dict) -> dict: } +def update(activity_id: str, actor_id: str, obj: dict, *, to: list[str]) -> dict: + """Tells already-following servers something about the actor changed (their now + playing field, here), so they don't have to re-fetch it to notice.""" + return { + "@context": AS_CONTEXT, + "id": activity_id, + "type": "Update", + "actor": actor_id, + "object": obj, + "to": list(to), + } + + def hashtag(name: str) -> dict: """A Hashtag tag, e.g. #Scrobbler. No href: we don't serve tag pages, and Mastodon still recognises and indexes the tag from `name` alone.""" diff --git a/src/scrobbler/federation/web.py b/src/scrobbler/federation/web.py index d55d8a2..3f0e8c5 100644 --- a/src/scrobbler/federation/web.py +++ b/src/scrobbler/federation/web.py @@ -7,8 +7,8 @@ import json from flask import Blueprint, Response, current_app, redirect, request from scrobbler.extensions import db +from scrobbler.federation import actors, ids, inbox, keys, publishing, sharing from scrobbler.federation import followers as follower_state -from scrobbler.federation import ids, inbox, keys, publishing, sharing from scrobbler.federation import metrics as fed_metrics from scrobbler.federation.models import FederationActivity from scrobbler.federation.protocol import hostmeta, media, nodeinfo, vocab, webfinger @@ -130,18 +130,7 @@ def actor(username: str): return _json(doc, cache=0) user, settings = found _found("actor") - urls = _urls(user.username) - doc = vocab.person( - urls, - username=user.username, - name=settings.display_name or user.username, - summary=settings.bio, - public_key_pem=keys.key_for(user.id).public_key_pem, - manually_approves_followers=settings.manually_approves_followers, - discoverable=settings.discoverable, - indexable=settings.indexable, - published=settings.created_at.isoformat().replace("+00:00", "Z"), - ) + doc = actors.build_document(_urls(user.username), user, settings) return _json(doc) diff --git a/tests/test_federation_actors.py b/tests/test_federation_actors.py new file mode 100644 index 0000000..013a108 --- /dev/null +++ b/tests/test_federation_actors.py @@ -0,0 +1,36 @@ +"""Actor document building (actors.py): shared by the live GET /users/ route and the +now-playing Update(Person) push.""" + +from scrobbler.federation import actors, sharing +from scrobbler.federation.protocol import vocab +from scrobbler.services.scrobbles import TrackInput, update_now_playing + +URLS = vocab.actor_urls( + "https://scrobble.test", "alice", "https://scrobble.test/profile.html?u=alice" +) + + +def test_now_playing_field_is_empty_when_nothing_is_playing(fed_ctx, user): + assert actors.now_playing_field(user) == [] + + +def test_now_playing_field_shows_the_current_track(fed_ctx, user): + update_now_playing(user, TrackInput(artist="Radiohead", track="Reckoner")) + assert actors.now_playing_field(user) == [("Now playing", "Reckoner by Radiohead")] + + +def test_build_document_includes_the_now_playing_field(fed_ctx, user): + sharing.update(user.id, {"enabled": True, "display_name": "Alice", "bio": "Hi."}) + update_now_playing(user, TrackInput(artist="Radiohead", track="Reckoner")) + settings = sharing.settings_for(user.id) + doc = actors.build_document(URLS, user, settings) + assert doc["attachment"] == [ + {"type": "PropertyValue", "name": "Now playing", "value": "Reckoner by Radiohead"} + ] + + +def test_build_document_has_no_now_playing_field_when_idle(fed_ctx, user): + sharing.update(user.id, {"enabled": True}) + settings = sharing.settings_for(user.id) + doc = actors.build_document(URLS, user, settings) + assert doc["attachment"] == [] diff --git a/tests/test_federation_protocol.py b/tests/test_federation_protocol.py index 8030e31..0890a48 100644 --- a/tests/test_federation_protocol.py +++ b/tests/test_federation_protocol.py @@ -209,6 +209,15 @@ def test_delete_is_a_tombstone(): assert (doc["to"], doc["cc"]) == (["FOLLOWERS"], ["PUBLIC"]) +def test_update_wraps_the_actor_document(): + actor_doc = {"id": "actor", "type": "Person", "attachment": []} + doc = vocab.update("activity-id", "actor", actor_doc, to=["FOLLOWERS"]) + assert (doc["type"], doc["id"], doc["actor"]) == ("Update", "activity-id", "actor") + assert doc["object"] == actor_doc + assert doc["to"] == ["FOLLOWERS"] + assert doc["@context"] == vocab.AS_CONTEXT + + def test_nodeinfo(): assert nodeinfo.discovery(BASE)["links"][0]["href"] == f"{BASE}/nodeinfo/2.1" doc = nodeinfo.document(version="0.2.0", users_total=3, open_registrations=True) diff --git a/tests/test_federation_web.py b/tests/test_federation_web.py index 71b596c..32c6d90 100644 --- a/tests/test_federation_web.py +++ b/tests/test_federation_web.py @@ -66,6 +66,17 @@ def test_actor_document(fed_client, sharing_user): assert doc["manuallyApprovesFollowers"] is False # the user's setting (off by default) assert (doc["discoverable"], doc["indexable"]) == (False, False) assert doc["url"] == "http://localhost:8080/profile.html?u=alice" + assert doc["attachment"] == [] # nothing playing + + +def test_actor_document_shows_now_playing_live(fed_client, fed_ctx, sharing_user): + from scrobbler.services.scrobbles import TrackInput, update_now_playing + + update_now_playing(sharing_user, TrackInput(artist="Radiohead", track="Reckoner")) + doc = fed_client.get("/users/alice", headers=AP).get_json() + assert doc["attachment"] == [ + {"type": "PropertyValue", "name": "Now playing", "value": "Reckoner by Radiohead"} + ] def test_ids_come_from_config_not_the_request(fed_client, sharing_user):