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

+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")