Page the outbox and serve individual posts (phase 3, step 7)
CI / validate-monitoring (push) Successful in 8s
CI / federation-interop (push) Successful in 1m1s
CI / lint (push) Successful in 1m10s
CI / test (push) Successful in 2m47s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 5s

GET /users/<u>/outbox is now a real OrderedCollection pointing at
paged OrderedCollectionPages of 20 Creates, newest first - public and
unlisted posts only, since it's unauthenticated. Adds
publishing.outbox_page() for the query and publishing.find_by_note_id()
to look a post up by its Note's id (the two ActivityPub ids a post has
- the wrapping Create's and the embedded Note's - were already
generated independently in publish(); finding by the Note's id reuses
the existing JSONB-path query pattern already established by
activities.undo_block(), rather than adding a new column just for this
lookup).

GET /users/<u>/posts/<uuid> serves that Note for public and unlisted
posts; followers-only and deleted posts 404 (they reach followers by
delivery instead); a browser without an ActivityPub Accept is
redirected to the UI post page unconditionally, before any lookup,
matching actor()'s existing reasoning that a 404-vs-302 difference
must never be usable to probe which posts exist.

Documents both endpoints in federation/openapi.py and regenerates
docs/openapi.json (test_every_api_route_is_documented already enforces
this on every new federation route, so it can't wait for the docs
step at the end of the phase).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
This commit is contained in:
mattandClaude Sonnet 5 committed 2026-09-26 13:37:38 +01:00
1 parent 6fd028d108
commit d4f3607eef
6 files changed
+308 -11

No files matched your search

+77 -2
View File
@@ -2543,11 +2543,11 @@
"ActivityPub"
],
"summary": "Outbox",
"description": "The user's published activities.",
"description": "The user's public and unlisted posts (followers-only posts are never listed here, since this endpoint isn't authenticated). Without `page`, an OrderedCollection pointing at the first page; with it, an OrderedCollectionPage of up to 20 `Create`s, newest first.",
"operationId": "federation_outbox",
"responses": {
"200": {
"description": "OrderedCollection",
"description": "OrderedCollection or OrderedCollectionPage",
"content": {
"application/activity+json": {
"schema": {
@@ -2568,6 +2568,15 @@
"schema": {
"type": "string"
}
},
{
"name": "page",
"in": "query",
"required": false,
"schema": {
"type": "integer",
"minimum": 1
}
}
]
},
@@ -2583,6 +2592,72 @@
}
]
},
"/users/{username}/posts/{post_uuid}": {
"get": {
"tags": [
"ActivityPub"
],
"summary": "Post",
"description": "One public or unlisted post's `Note`, when asked for ActivityPub JSON; browsers are redirected to the web UI's post page. Followers-only and deleted posts answer 404 here (they're delivered directly to followers instead).",
"operationId": "federation_post_note",
"responses": {
"200": {
"description": "Note",
"content": {
"application/activity+json": {
"schema": {
"type": "object"
}
}
}
},
"302": {
"description": "Redirect to the post page (non-ActivityPub Accept)"
},
"404": {
"description": "Not found, not listed, or deleted"
}
},
"parameters": [
{
"name": "username",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "post_uuid",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
]
},
"parameters": [
{
"in": "path",
"name": "username",
"required": true,
"schema": {
"type": "string",
"minLength": 1
}
},
{
"in": "path",
"name": "post_uuid",
"required": true,
"schema": {
"type": "string",
"minLength": 1
}
}
]
},
"/users/{username}/followers": {
"get": {
"tags": [
+36 -3
View File
@@ -93,9 +93,42 @@ _OPERATIONS = {
"federation.outbox": (
"get",
"Outbox",
"The user's published activities.",
[_USERNAME],
{"200": {"description": "OrderedCollection", "content": _AP}, "404": _NOT_FOUND},
"The user's public and unlisted posts (followers-only posts are never listed "
"here, since this endpoint isn't authenticated). Without `page`, an "
"OrderedCollection pointing at the first page; with it, an OrderedCollectionPage "
"of up to 20 `Create`s, newest first.",
[
_USERNAME,
{
"name": "page",
"in": "query",
"required": False,
"schema": {"type": "integer", "minimum": 1},
},
],
{
"200": {
"description": "OrderedCollection or OrderedCollectionPage",
"content": _AP,
},
"404": _NOT_FOUND,
},
),
"federation.post_note": (
"get",
"Post",
"One public or unlisted post's `Note`, when asked for ActivityPub JSON; browsers "
"are redirected to the web UI's post page. Followers-only and deleted posts "
"answer 404 here (they're delivered directly to followers instead).",
[
_USERNAME,
{"name": "post_uuid", "in": "path", "required": True, "schema": {"type": "string"}},
],
{
"200": {"description": "Note", "content": _AP},
"302": {"description": "Redirect to the post page (non-ActivityPub Accept)"},
"404": {"description": "Not found, not listed, or deleted"},
},
),
"federation.followers": (
"get",
@@ -3,6 +3,24 @@ later now-playing. Shared machinery — idempotent publishing, addressing, fan-o
deletion — lives in base.py.
"""
from scrobbler.federation.publishing.base import delete_all_for, delete_post, has_post, publish
from scrobbler.federation.publishing.base import (
LISTED_VISIBILITIES,
OUTBOX_PAGE_SIZE,
delete_all_for,
delete_post,
find_by_note_id,
has_post,
outbox_page,
publish,
)
__all__ = ["delete_all_for", "delete_post", "has_post", "publish"]
__all__ = [
"LISTED_VISIBILITIES",
"OUTBOX_PAGE_SIZE",
"delete_all_for",
"delete_post",
"find_by_note_id",
"has_post",
"outbox_page",
"publish",
]
@@ -18,12 +18,54 @@ from scrobbler.federation.models import FederationActivity, FederationPost
from scrobbler.federation.protocol import addressing, vocab
DEFAULT_TAGS = ("Scrobbler",)
OUTBOX_PAGE_SIZE = 20
LISTED_VISIBILITIES = ("public", "unlisted") # followers-only posts aren't listed unauthenticated
def _now() -> datetime:
return datetime.now(UTC)
def _listed(user_id: int):
return (
FederationPost.user_id == user_id,
FederationPost.deleted_at.is_(None),
FederationPost.visibility.in_(LISTED_VISIBILITIES),
)
def outbox_page(
user_id: int, page: int, per_page: int = OUTBOX_PAGE_SIZE
) -> tuple[list[dict], int]:
"""Create documents for a user's outbox: public and unlisted posts only, newest
first, paged. `page` is 1-based."""
conditions = _listed(user_id)
total = db.session.scalar(
db.select(db.func.count()).select_from(FederationPost).filter(*conditions)
)
rows = db.session.scalars(
db.select(FederationActivity)
.join(FederationPost, FederationPost.activity_id == FederationActivity.id)
.filter(*conditions)
.order_by(FederationActivity.created_at.desc())
.limit(per_page)
.offset((page - 1) * per_page)
).all()
return [row.document for row in rows], total
def find_by_note_id(user_id: int, note_id: str) -> FederationPost | None:
"""The post whose Note has this id (the URL served at /users/<u>/posts/<uuid>)."""
return db.session.scalar(
db.select(FederationPost)
.join(FederationActivity, FederationActivity.id == FederationPost.activity_id)
.filter(
FederationPost.user_id == user_id,
FederationActivity.document["object"]["id"].as_string() == note_id,
)
)
def has_post(user_id: int, kind: str, key: str) -> bool:
"""Whether a post with this (user, kind, key) already exists (posted or since
deleted). Lets a caller skip expensive work — computing stats, say — before deciding
+46 -2
View File
@@ -8,7 +8,7 @@ from flask import Blueprint, Response, current_app, redirect, request
from scrobbler.extensions import db
from scrobbler.federation import followers as follower_state
from scrobbler.federation import inbox, keys, sharing
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
@@ -155,7 +155,51 @@ def _collection(username: str, which: str, items: list | None, total: int = 0):
@bp.get("/users/<username>/outbox")
def outbox(username: str):
return _collection(username, "outbox", [])
found = sharing.shared_user(username)
if found is None:
return _not_found("actor")
urls = _urls(found[0].username)
page_param = request.args.get("page")
if page_param is None:
total = publishing.outbox_page(found[0].id, page=1)[1]
return _json(vocab.ordered_collection(urls.outbox, total, first=f"{urls.outbox}?page=1"))
try:
page = max(int(page_param), 1)
except ValueError:
page = 1
per_page = publishing.OUTBOX_PAGE_SIZE
items, total = publishing.outbox_page(found[0].id, page, per_page=per_page)
next_page = f"{urls.outbox}?page={page + 1}" if page * per_page < total else None
prev_page = f"{urls.outbox}?page={page - 1}" if page > 1 else None
return _json(
vocab.ordered_collection_page(
f"{urls.outbox}?page={page}",
part_of=urls.outbox,
items=items,
next_page=next_page,
prev_page=prev_page,
)
)
@bp.get("/users/<username>/posts/<post_uuid>")
def post_note(username: str, post_uuid: str):
if not media.wants_activitypub(request.headers.get("Accept")):
# Same reasoning as actor(): redirect everyone, so the response can't be used to
# probe which posts exist.
return redirect(ids.post_page_url(username, post_uuid), code=302)
found = sharing.shared_user(username)
if found is None:
return _not_found("post")
post = publishing.find_by_note_id(found[0].id, ids.note_url(username, post_uuid))
if (
post is None
or post.deleted_at is not None
or post.visibility not in publishing.LISTED_VISIBILITIES
):
return _not_found("post")
return _json(post.activity.document["object"], cache=60)
@bp.get("/users/<username>/followers")
+87 -2
View File
@@ -3,6 +3,9 @@ from urllib.parse import urlsplit
import pytest
from scrobbler.extensions import db
from scrobbler.federation import publishing, sharing
AP = {"Accept": "application/activity+json"}
BASE = "https://scrobble.test"
@@ -79,15 +82,97 @@ def test_browsers_are_sent_to_the_profile_page(fed_client, sharing_user, usernam
def test_collections(fed_client, sharing_user):
outbox = fed_client.get("/users/alice/outbox", headers=AP).get_json()
assert (outbox["type"], outbox["totalItems"], outbox["orderedItems"]) == (
assert (outbox["type"], outbox["totalItems"], outbox["first"]) == (
"OrderedCollection",
0,
[],
f"{BASE}/users/alice/outbox?page=1",
)
assert "orderedItems" not in outbox # paged: points at the first page instead
followers = fed_client.get("/users/alice/followers", headers=AP).get_json()
assert followers["totalItems"] == 0 and "orderedItems" not in followers
def test_outbox_paging_lists_public_and_unlisted_but_not_followers_only(
fed_client, fed_ctx, sharing_user
):
sharing.update(sharing_user.id, {"visibility": "public"})
publishing.publish(sharing_user.id, "alice", "weekly", "a", text="first", html="<p>first</p>")
sharing.update(sharing_user.id, {"visibility": "unlisted"})
publishing.publish(sharing_user.id, "alice", "weekly", "b", text="second", html="<p>second</p>")
sharing.update(sharing_user.id, {"visibility": "followers"})
publishing.publish(sharing_user.id, "alice", "weekly", "c", text="third", html="<p>third</p>")
root = fed_client.get("/users/alice/outbox", headers=AP).get_json()
assert root["totalItems"] == 2 # the followers-only one isn't counted here
page = fed_client.get("/users/alice/outbox?page=1", headers=AP).get_json()
assert page["type"] == "OrderedCollectionPage"
assert page["partOf"] == f"{BASE}/users/alice/outbox"
# Newest first: "second" (unlisted) was published after "first" (public).
assert [item["object"]["content"] for item in page["orderedItems"]] == [
"<p>second</p>",
"<p>first</p>",
]
assert "next" not in page
assert "prev" not in page
def test_outbox_paging_links(fed_client, fed_ctx, sharing_user, monkeypatch):
monkeypatch.setattr(publishing, "OUTBOX_PAGE_SIZE", 1)
sharing.update(sharing_user.id, {"visibility": "public"})
for key in ("a", "b"):
publishing.publish(sharing_user.id, "alice", "weekly", key, text="t", html="<p>t</p>")
first = fed_client.get("/users/alice/outbox?page=1", headers=AP).get_json()
assert len(first["orderedItems"]) == 1
assert first["next"] == f"{BASE}/users/alice/outbox?page=2"
assert "prev" not in first
second = fed_client.get("/users/alice/outbox?page=2", headers=AP).get_json()
assert len(second["orderedItems"]) == 1
assert "next" not in second
assert second["prev"] == f"{BASE}/users/alice/outbox?page=1"
def test_outbox_missing_user_is_not_found(fed_client, fed_ctx):
assert fed_client.get("/users/nobody/outbox", headers=AP).status_code == 404
assert fed_client.get("/users/nobody/outbox?page=1", headers=AP).status_code == 404
def test_post_note_serves_a_public_note(fed_client, fed_ctx, sharing_user):
sharing.update(sharing_user.id, {"visibility": "public"})
post = publishing.publish(sharing_user.id, "alice", "weekly", "a", text="t", html="<p>t</p>")
note_uuid = post.activity.document["object"]["id"].rsplit("/", 1)[-1]
response = fed_client.get(f"/users/alice/posts/{note_uuid}", headers=AP)
assert response.status_code == 200
doc = response.get_json()
assert (doc["type"], doc["content"]) == ("Note", "<p>t</p>")
def test_post_note_404s_for_followers_only_deleted_or_unknown(fed_client, fed_ctx, sharing_user):
post = publishing.publish(sharing_user.id, "alice", "weekly", "a", text="t", html="<p>t</p>")
note_uuid = post.activity.document["object"]["id"].rsplit("/", 1)[-1]
# followers-only (the default): not listed to an unauthenticated fetch
assert fed_client.get(f"/users/alice/posts/{note_uuid}", headers=AP).status_code == 404
sharing.update(post.user_id, {"visibility": "public"})
publishing.delete_post(post.user_id, "alice", post)
db.session.commit()
assert fed_client.get(f"/users/alice/posts/{note_uuid}", headers=AP).status_code == 404
assert fed_client.get("/users/alice/posts/not-a-real-uuid", headers=AP).status_code == 404
assert fed_client.get("/users/nobody/posts/not-a-real-uuid", headers=AP).status_code == 404
def test_post_note_browser_is_redirected_to_the_ui_page(fed_client, fed_ctx, sharing_user):
post = publishing.publish(sharing_user.id, "alice", "weekly", "a", text="t", html="<p>t</p>")
note_uuid = post.activity.document["object"]["id"].rsplit("/", 1)[-1]
response = fed_client.get(f"/users/alice/posts/{note_uuid}", headers={"Accept": "text/html"})
assert response.status_code == 302
assert response.headers["Location"] == f"http://localhost:8080/post.html?id={note_uuid}"
def test_nodeinfo(fed_client, sharing_user):
link = fed_client.get("/.well-known/nodeinfo").get_json()["links"][0]
assert link["href"] == f"{BASE}/nodeinfo/2.1"