diff --git a/docs/openapi.json b/docs/openapi.json index 1ecff2a..1753f4a 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -1942,7 +1942,7 @@ } }, "summary": "Change your sharing settings", - "description": "Turning sharing on makes you findable as your handle. Your handle can't change once\npeople follow you. Visibility changes apply to new posts only. Turning sharing off\nremoves all your followers (each is told).", + "description": "Turning sharing on makes you findable as your handle. Your handle can't change once\npeople follow you. Visibility changes apply to new posts only. Turning sharing off\ndeletes your posts and removes all your followers (each is told).", "tags": [ "Federation" ], diff --git a/src/scrobbler/federation/activities.py b/src/scrobbler/federation/activities.py index e1adbc7..296bd0c 100644 --- a/src/scrobbler/federation/activities.py +++ b/src/scrobbler/federation/activities.py @@ -13,8 +13,11 @@ from scrobbler.federation.models import ( from scrobbler.federation.protocol import vocab -def _store(user_id: int, document_for, public: bool = False) -> FederationActivity: - """Create an activity. `document_for(activity_url)` builds its JSON.""" +def store(user_id: int, document_for, public: bool = False) -> FederationActivity: + """Create an activity. `document_for(activity_url)` builds its JSON. + + Public: used both for our own narrow activity types below (Accept, Reject, Block, + Undo) and, from publishing/base.py, for Create/Delete of posts.""" activity_uuid = str(uuid.uuid4()) document = document_for(ids.activity_url(activity_uuid)) activity = FederationActivity( @@ -38,7 +41,7 @@ def queue(activity: FederationActivity, inboxes: list[str]) -> list[FederationDe def accept_follow(username: str, follower: FederationFollower) -> FederationActivity: - activity = _store( + activity = store( follower.user_id, lambda url: vocab.accept(url, ids.actor_id(username), follower.follow_activity), ) @@ -47,7 +50,7 @@ def accept_follow(username: str, follower: FederationFollower) -> FederationActi def reject_follow(username: str, follower: FederationFollower) -> FederationActivity: - activity = _store( + activity = store( follower.user_id, lambda url: vocab.reject(url, ids.actor_id(username), follower.follow_activity), ) @@ -59,13 +62,13 @@ def reject_follow_activity( user_id: int, username: str, follow: dict, actor: FederationRemoteActor ) -> FederationActivity: """Reject a Follow that never became a follower (e.g. from a blocked account).""" - activity = _store(user_id, lambda url: vocab.reject(url, ids.actor_id(username), follow)) + activity = store(user_id, lambda url: vocab.reject(url, ids.actor_id(username), follow)) queue(activity, [actor.inbox]) return activity def block(user_id: int, username: str, actor: FederationRemoteActor) -> FederationActivity: - activity = _store(user_id, lambda url: vocab.block(url, ids.actor_id(username), actor.uri)) + activity = store(user_id, lambda url: vocab.block(url, ids.actor_id(username), actor.uri)) queue(activity, [actor.inbox]) return activity @@ -82,7 +85,7 @@ def undo_block( ).first() if block_activity is None: return None - activity = _store( + activity = store( user_id, lambda url: vocab.undo(url, ids.actor_id(username), block_activity.document) ) queue(activity, [actor.inbox]) diff --git a/src/scrobbler/federation/api.py b/src/scrobbler/federation/api.py index e6283d4..a3504b5 100644 --- a/src/scrobbler/federation/api.py +++ b/src/scrobbler/federation/api.py @@ -5,7 +5,7 @@ from flask_smorest import Blueprint, abort from scrobbler.api.decorators import authenticated from scrobbler.extensions import db -from scrobbler.federation import activities, sharing +from scrobbler.federation import activities, publishing, sharing from scrobbler.federation import followers as follower_state from scrobbler.federation import metrics as fed_metrics from scrobbler.federation.models import FederationBlock, FederationFollower @@ -69,7 +69,7 @@ def update_settings(changes): Turning sharing on makes you findable as your handle. Your handle can't change once people follow you. Visibility changes apply to new posts only. Turning sharing off - removes all your followers (each is told). + deletes your posts and removes all your followers (each is told). """ try: settings, toggled = sharing.update(g.user.id, changes) @@ -78,7 +78,9 @@ def update_settings(changes): if toggled is not None: fed_metrics.sharing_changes_total.labels(change="enabled" if toggled else "disabled").inc() if toggled is False: - # Tell every follower (a Reject each), then forget them + # Delete every live post first: reject_all removes the followers that + # accepted_inboxes() needs to know where to send the Deletes. + publishing.delete_all_for(g.user.id, g.user.username) follower_state.reject_all(g.user.id, g.user.username) db.session.commit() return _settings_body(g.user, settings) diff --git a/src/scrobbler/federation/followers.py b/src/scrobbler/federation/followers.py index 4e9a05c..0e18c84 100644 --- a/src/scrobbler/federation/followers.py +++ b/src/scrobbler/federation/followers.py @@ -139,3 +139,12 @@ def counts(user_id: int) -> dict[str, int]: ).all() found = dict(rows) return {"accepted": found.get("accepted", 0), "pending": found.get("pending", 0)} + + +def accepted_inboxes(user_id: int) -> list[str]: + """Delivery inbox (their shared one, or their own) of every accepted follower, for + fanning out a post. Pending followers are excluded: they haven't been let in yet.""" + accepted = db.session.scalars( + db.select(FederationFollower).filter_by(user_id=user_id, state="accepted") + ).all() + return [follower.actor.delivery_inbox for follower in accepted] diff --git a/src/scrobbler/federation/ids.py b/src/scrobbler/federation/ids.py index 8fa139d..c49ed0a 100644 --- a/src/scrobbler/federation/ids.py +++ b/src/scrobbler/federation/ids.py @@ -11,6 +11,10 @@ def actor_id(username: str) -> str: return f"{base_url()}/users/{username}" +def followers_url(username: str) -> str: + return f"{actor_id(username)}/followers" + + def key_id(username: str) -> str: return f"{actor_id(username)}#main-key" @@ -27,6 +31,16 @@ def activity_url(activity_uuid: str) -> str: return f"{base_url()}/activities/{activity_uuid}" +def note_url(username: str, post_uuid: str) -> str: + """The Note's ActivityPub id (served at /users//posts/).""" + return f"{actor_id(username)}/posts/{post_uuid}" + + +def post_page_url(username: str, post_uuid: str) -> str: + """Where a browser following the Note's `url` lands, in the web UI.""" + return f"{current_app.config['UI_BASE_URL']}/post.html?id={post_uuid}" + + def username_from_actor_id(uri: str | None) -> str | None: """`/users/` -> name; None for anything else.""" prefix = f"{base_url()}/users/" diff --git a/src/scrobbler/federation/publishing/__init__.py b/src/scrobbler/federation/publishing/__init__.py new file mode 100644 index 0000000..61f04d5 --- /dev/null +++ b/src/scrobbler/federation/publishing/__init__.py @@ -0,0 +1,8 @@ +"""Posts to followers: weekly summaries (weekly.py) and milestones (milestones.py), and +later now-playing. Shared machinery — idempotent publishing, addressing, fan-out and +deletion — lives in base.py. +""" + +from scrobbler.federation.publishing.base import delete_all_for, delete_post, publish + +__all__ = ["delete_all_for", "delete_post", "publish"] diff --git a/src/scrobbler/federation/publishing/base.py b/src/scrobbler/federation/publishing/base.py new file mode 100644 index 0000000..9bd1118 --- /dev/null +++ b/src/scrobbler/federation/publishing/base.py @@ -0,0 +1,129 @@ +"""Publishing posts: building and storing the Note/Create, fanning out to accepted +followers, and deleting. + +Each post kind (weekly.py, milestones.py, and later now-playing) decides *when* to post +and builds the text; this module handles what every post shares: idempotence (one row +per (user, key), enforced by federation_posts' unique constraint), addressing from the +user's current visibility, storage, delivery and deletion. +""" + +import uuid +from datetime import UTC, datetime + +from sqlalchemy.exc import IntegrityError + +from scrobbler.extensions import db +from scrobbler.federation import activities, followers, ids, sharing +from scrobbler.federation.models import FederationActivity, FederationPost +from scrobbler.federation.protocol import addressing, vocab + +DEFAULT_TAGS = ("Scrobbler",) + + +def _now() -> datetime: + return datetime.now(UTC) + + +def publish( + user_id: int, + username: str, + kind: str, + key: str, + *, + text: str, + html: str, + tags: tuple[str, ...] = DEFAULT_TAGS, +) -> FederationPost | None: + """Post `text`/`html` for the user, keyed by `kind:key`. + + Idempotent: a second call with the same (user, kind, key) is a no-op, including when + two worker passes race each other (caught as a duplicate-key error, not raised). + Returns None, without posting, if the user isn't sharing or the key already exists. + """ + settings = sharing.settings_for(user_id) + if not settings.enabled: + return None + full_key = f"{kind}:{key}" + already = db.session.scalar( + db.select(FederationPost.id).filter_by(user_id=user_id, key=full_key) + ) + if already: + return None + + published = _now().isoformat().replace("+00:00", "Z") + post_uuid = str(uuid.uuid4()) + to, cc = addressing.address(settings.visibility, ids.followers_url(username)) + note_doc = vocab.note( + ids.note_url(username, post_uuid), + actor_id=ids.actor_id(username), + content_html=html, + published=published, + url=ids.post_page_url(username, post_uuid), + to=to, + cc=cc, + tags=list(tags), + ) + # activity.id is a Python-generated UUID (see activities.store), so it's already + # usable below without a flush. + activity = activities.store( + user_id, + lambda url: vocab.create(url, ids.actor_id(username), note_doc, to=to, cc=cc), + public=addressing.is_public_or_unlisted(settings.visibility), + ) + post = FederationPost( + user_id=user_id, + kind=kind, + key=full_key, + activity_id=activity.id, + visibility=settings.visibility, + content_text=text, + content_html=html, + ) + db.session.add(post) + inboxes = followers.accepted_inboxes(user_id) + if inboxes: + activities.queue(activity, inboxes) + try: + db.session.commit() + except IntegrityError: # posted with this key by a concurrent pass + db.session.rollback() + return None + return post + + +def delete_post(user_id: int, username: str, post: FederationPost) -> FederationActivity | None: + """Delete one post: sends Delete to the same inboxes the Create went to, and + tombstones the row (kept, so its key can never be reused). The caller commits. + None if it's already deleted.""" + if post.deleted_at is not None: + return None + return _delete(user_id, username, post) + + +def delete_all_for(user_id: int, username: str) -> int: + """Sharing switched off: delete every live post before the Rejects go out (call this + before followers.reject_all — it needs accepted_inboxes() to still have somewhere to + send the Deletes). The caller commits. Returns how many were deleted.""" + posts = db.session.scalars( + db.select(FederationPost).filter_by(user_id=user_id, deleted_at=None) + ).all() + for post in posts: + _delete(user_id, username, post) + return len(posts) + + +def _delete(user_id: int, username: str, post: FederationPost) -> FederationActivity: + # The post's own visibility at the time it was posted, not the user's current + # setting: a Delete has to reach whoever could have seen the Create. + note_id = post.activity.document["object"]["id"] + to, cc = addressing.address(post.visibility, ids.followers_url(username)) + activity = activities.store( + user_id, + lambda url: vocab.delete(url, ids.actor_id(username), note_id, to=to, cc=cc), + public=addressing.is_public_or_unlisted(post.visibility), + ) + inboxes = followers.accepted_inboxes(user_id) + if inboxes: + activities.queue(activity, inboxes) + post.deleted_at = _now() + return activity diff --git a/src/scrobbler/federation/sharing.py b/src/scrobbler/federation/sharing.py index b0b16ab..2e274f5 100644 --- a/src/scrobbler/federation/sharing.py +++ b/src/scrobbler/federation/sharing.py @@ -20,6 +20,8 @@ def settings_for(user_id: int) -> FederationSettings: """The user's settings; unsaved defaults if they've never changed them.""" settings = db.session.get(FederationSettings, user_id) if settings is None: + # Not added to the session: the model's column defaults apply on INSERT, not + # here, so every field a caller might read has to be set explicitly. settings = FederationSettings( user_id=user_id, enabled=False, @@ -27,6 +29,9 @@ def settings_for(user_id: int) -> FederationSettings: manually_approves_followers=False, discoverable=False, indexable=False, + timezone="UTC", + post_weekly_summary=True, + post_milestones=True, ) return settings diff --git a/tests/test_federation_keys_sharing.py b/tests/test_federation_keys_sharing.py index 2950a2b..bb08b15 100644 --- a/tests/test_federation_keys_sharing.py +++ b/tests/test_federation_keys_sharing.py @@ -15,6 +15,17 @@ def test_defaults_are_private(fed_ctx, user): assert sharing.shared_user("alice") is None +def test_unsaved_defaults_have_every_field_populated(fed_ctx, user): + """settings_for() builds a transient object when a user has never saved settings; its + column defaults apply only on INSERT, so every field has to be set by hand.""" + settings = sharing.settings_for(user.id) + assert (settings.timezone, settings.post_weekly_summary, settings.post_milestones) == ( + "UTC", + True, + True, + ) + + def test_enabling_creates_a_key_pair_that_signs(fed_ctx, user): _, toggled = sharing.update(user.id, {"enabled": True}) assert toggled is True diff --git a/tests/test_federation_publishing.py b/tests/test_federation_publishing.py new file mode 100644 index 0000000..e2a6351 --- /dev/null +++ b/tests/test_federation_publishing.py @@ -0,0 +1,216 @@ +"""Publishing core: idempotent posting, addressing, fan-out and deletion.""" + +import pytest + +from federation_helpers import RemoteAccount +from scrobbler.extensions import db +from scrobbler.federation import followers as follower_state +from scrobbler.federation import inbox, publishing, sharing +from scrobbler.federation.models import FederationActivity, FederationDelivery, FederationPost + + +def all_activities(): + return db.session.scalars( + db.select(FederationActivity).order_by(FederationActivity.created_at) + ).all() + + +def deliveries_for(activity_id): + return db.session.scalars( + db.select(FederationDelivery).filter_by(activity_id=activity_id) + ).all() + + +def approved_follower(fed_client, remote, sharing_user, name): + """A remote account following sharing_user, already accepted.""" + account = RemoteAccount(remote, name) + remote.routes[f"/users/{name}/inbox"] = (202, {}, b"") + account.deliver(fed_client, account.follow()) + while inbox.work_once(): + pass + db.session.expire_all() + return account + + +def test_publish_creates_a_post_and_a_create_activity(fed_ctx, user): + sharing.update(user.id, {"enabled": True}) + post = publishing.publish( + user.id, "alice", "weekly", "2026-W01", text="312 plays", html="

312 plays

" + ) + assert post is not None + assert (post.kind, post.key, post.content_text) == ("weekly", "weekly:2026-W01", "312 plays") + assert post.visibility == "followers" + assert post.deleted_at is None + + [activity] = all_activities() + assert activity.id == post.activity_id + assert activity.activity_type == "Create" + assert activity.document["object"]["type"] == "Note" + assert activity.document["object"]["content"] == "

312 plays

" + assert activity.document["object"]["contentMap"] == {"en": "

312 plays

"} + assert activity.document["object"]["tag"] == [{"type": "Hashtag", "name": "#Scrobbler"}] + assert activity.public is False # followers-only, the default + + +def test_publish_is_idempotent(fed_ctx, user): + sharing.update(user.id, {"enabled": True}) + first = publishing.publish(user.id, "alice", "weekly", "2026-W01", text="a", html="a") + second = publishing.publish(user.id, "alice", "weekly", "2026-W01", text="b", html="b") + assert first is not None + assert second is None + assert db.session.scalar(db.select(db.func.count()).select_from(FederationPost)) == 1 + # The first call's content wins; a later call never overwrites it + assert db.session.get(FederationPost, first.id).content_text == "a" + + +def test_publish_keys_are_scoped_to_kind_and_user(fed_ctx, user, make_user): + sharing.update(user.id, {"enabled": True}) + same_key_different_kind = publishing.publish( + user.id, "alice", "milestone", "2026-W01", text="x", html="x" + ) + assert publishing.publish(user.id, "alice", "weekly", "2026-W01", text="y", html="y") + assert same_key_different_kind is not None # "weekly:2026-W01" != "milestone:2026-W01" + + other = make_user(username="bob") + sharing.update(other.id, {"enabled": True}) + assert publishing.publish(other.id, "bob", "weekly", "2026-W01", text="z", html="z") + assert db.session.scalar(db.select(db.func.count()).select_from(FederationPost)) == 3 + + +def test_publish_refuses_when_not_sharing(fed_ctx, user): + assert publishing.publish(user.id, "alice", "weekly", "2026-W01", text="x", html="x") is None + sharing.update(user.id, {"enabled": True}) + sharing.update(user.id, {"enabled": False}) + assert publishing.publish(user.id, "alice", "weekly", "2026-W02", text="x", html="x") is None + assert db.session.scalar(db.select(db.func.count()).select_from(FederationPost)) == 0 + + +@pytest.mark.parametrize( + ("visibility", "to", "cc"), + [ + ("followers", "FOLLOWERS", []), + ("unlisted", "FOLLOWERS", "PUBLIC"), + ("public", "PUBLIC", "FOLLOWERS"), + ], +) +def test_publish_addresses_by_the_users_visibility(fed_ctx, user, visibility, to, cc): + from scrobbler.federation.protocol.vocab import PUBLIC + + sharing.update(user.id, {"enabled": True, "visibility": visibility}) + post = publishing.publish(user.id, "alice", "weekly", "2026-W01", text="x", html="

x

") + activity = db.session.get(FederationActivity, post.activity_id) + expected_to = [PUBLIC] if to == "PUBLIC" else ["https://scrobble.test/users/alice/followers"] + expected_cc = ( + [] + if cc == [] + else [PUBLIC] + if cc == "PUBLIC" + else ["https://scrobble.test/users/alice/followers"] + ) + assert activity.document["to"] == expected_to + assert activity.document["cc"] == expected_cc + assert activity.document["object"]["to"] == expected_to # the Note matches the Create + assert activity.document["object"]["cc"] == expected_cc + assert activity.public is (visibility != "followers") + + +def test_publish_fans_out_only_to_accepted_followers(fed_client, remote, sharing_user): + bob = approved_follower(fed_client, remote, sharing_user, "bob") + # A pending request: not yet let in, so it shouldn't receive posts + sharing.update(sharing_user.id, {"manually_approves_followers": True}) + carol = RemoteAccount(remote, "carol") + remote.routes["/users/carol/inbox"] = (202, {}, b"") + carol.deliver(fed_client, carol.follow()) + while inbox.work_once(): + pass + db.session.expire_all() + assert follower_state.counts(sharing_user.id) == {"accepted": 1, "pending": 1} + + post = publishing.publish(sharing_user.id, "alice", "weekly", "2026-W01", text="x", html="x") + deliveries = deliveries_for(post.activity_id) + assert [d.inbox for d in deliveries] == [bob.server.url("/inbox")] + + +def test_publish_with_no_followers_still_creates_the_post(fed_ctx, user): + sharing.update(user.id, {"enabled": True}) + post = publishing.publish(user.id, "alice", "weekly", "2026-W01", text="x", html="x") + assert post is not None + assert deliveries_for(post.activity_id) == [] + + +def test_delete_post_sends_delete_and_tombstones(fed_client, remote, sharing_user): + bob = approved_follower(fed_client, remote, sharing_user, "bob") + post = publishing.publish( + sharing_user.id, "alice", "weekly", "2026-W01", text="x", html="

x

" + ) + note_id = db.session.get(FederationActivity, post.activity_id).document["object"]["id"] + activity = publishing.delete_post(sharing_user.id, "alice", post) + db.session.commit() + + assert activity is not None + assert activity.activity_type == "Delete" + assert activity.document["object"] == {"id": note_id, "type": "Tombstone"} + assert db.session.get(FederationPost, post.id).deleted_at is not None + assert [d.inbox for d in deliveries_for(activity.id)] == [bob.server.url("/inbox")] + + +def test_deleting_an_already_deleted_post_is_a_noop(fed_ctx, user): + sharing.update(user.id, {"enabled": True}) + post = publishing.publish(user.id, "alice", "weekly", "2026-W01", text="x", html="x") + first = publishing.delete_post(user.id, "alice", post) + db.session.commit() + second = publishing.delete_post(user.id, "alice", post) + assert first is not None + assert second is None + assert len([a for a in all_activities() if a.activity_type == "Delete"]) == 1 + + +def test_delete_uses_the_posts_own_visibility_not_the_current_setting(fed_ctx, user): + from scrobbler.federation.protocol.vocab import PUBLIC + + sharing.update(user.id, {"enabled": True, "visibility": "public"}) + post = publishing.publish(user.id, "alice", "weekly", "2026-W01", text="x", html="x") + sharing.update(user.id, {"visibility": "followers"}) # changed after posting + activity = publishing.delete_post(user.id, "alice", post) + assert activity.document["to"] == [PUBLIC] # still addressed as it was posted + + +def test_delete_all_for_deletes_every_live_post(fed_ctx, user): + sharing.update(user.id, {"enabled": True}) + a = publishing.publish(user.id, "alice", "weekly", "2026-W01", text="a", html="a") + b = publishing.publish(user.id, "alice", "milestone", "scrobbles:1000", text="b", html="b") + already_deleted = publishing.publish(user.id, "alice", "weekly", "2026-W02", text="c", html="c") + publishing.delete_post(user.id, "alice", already_deleted) + db.session.commit() + + count = publishing.delete_all_for(user.id, "alice") + db.session.commit() + + assert count == 2 # not the one already deleted + assert db.session.get(FederationPost, a.id).deleted_at is not None + assert db.session.get(FederationPost, b.id).deleted_at is not None + # 3 Deletes total: one from the already_deleted post above, plus a and b just now + assert len([act for act in all_activities() if act.activity_type == "Delete"]) == 3 + + +def test_turning_sharing_off_deletes_posts_before_rejecting(fed_client, remote, sharing_user): + bob = approved_follower(fed_client, remote, sharing_user, "bob") + from scrobbler.services.accounts import issue_ui_token + + auth = {"Authorization": f"Bearer {issue_ui_token(sharing_user)}"} + publishing.publish(sharing_user.id, "alice", "weekly", "2026-W01", text="x", html="x") + db.session.commit() + + response = fed_client.patch( + "/api/v1/federation/settings", json={"enabled": False}, headers=auth + ) + assert response.status_code == 200 + types = [a.activity_type for a in all_activities()] + assert types.count("Delete") == 1 + assert types.count("Reject") == 1 + assert types.index("Delete") < types.index("Reject") # Delete queued before the Reject + + [post] = db.session.scalars(db.select(FederationPost)).all() + assert post.deleted_at is not None + delete_activity = next(a for a in all_activities() if a.activity_type == "Delete") + assert [d.inbox for d in deliveries_for(delete_activity.id)] == [bob.server.url("/inbox")]