Sharing settings API, public profiles and ActivityPub docs (phase 1, step 4)
CI / validate-monitoring (push) Successful in 7s
CI / lint (push) Successful in 12s
CI / test (push) Successful in 1m5s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 5s

- /api/v1/federation/settings (GET, PATCH): sharing on/off, visibility
  (followers-only default), follow approval, discoverable/indexable,
  display name and bio, plus the read-only handle and URLs
- /api/v1/federation/profiles/<name>: public profile for the UI page,
  only for users sharing
- ActivityPub endpoints documented under an ActivityPub tag
- docs/openapi.json is now exported with every optional module on
  (python -m scrobbler.openapi.export); the drift test and route checks
  cover both a federation-off and a federation-on app
- Boundary: federation may use scrobbler.api.get_api to register its
  blueprint; the checker proves other scrobbler.api modules stay off
  limits

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
This commit is contained in:
mattandClaude Opus 5.5 committed 2026-09-25 20:26:33 +01:00
1 parent ce39e8f865
commit 0b10469514
11 files changed
+1175 -11

No files matched your search

+1
View File
@@ -12,6 +12,7 @@ or switched off without touching anything else. Design: `docs/design/activitypub
Signature schemes, vocabulary and document formats live there.
3. **The rest of this package uses only the core's public surface**:
- `scrobbler.__version__`
- `scrobbler.api.get_api` (to register federation's API blueprint and document its paths)
- `scrobbler.events`
- `scrobbler.extensions` (`db`)
- `scrobbler.worker`
+5 -1
View File
@@ -28,6 +28,10 @@ def init_app(app: Flask) -> None:
return
log.info("federation enabled: handles @user@%s, actors at %s", config.domain, config.base_url)
from scrobbler.federation import web
from scrobbler.api import get_api
from scrobbler.federation import api, openapi, web
app.register_blueprint(web.bp)
core_api = get_api(app)
core_api.register_blueprint(api.blp, url_prefix="/api/v1/federation")
openapi.register(app, core_api)
+93
View File
@@ -0,0 +1,93 @@
"""/api/v1/federation: sharing settings for the web UI, and public profiles."""
from flask import current_app, g
from flask_smorest import Blueprint, abort
from scrobbler.api.decorators import authenticated
from scrobbler.federation import metrics as fed_metrics
from scrobbler.federation import sharing
from scrobbler.federation.schemas import (
PublicProfileSchema,
SharingSettingsSchema,
SharingSettingsUpdateSchema,
)
from scrobbler.schemas import ErrorSchema
blp = Blueprint(
"Federation",
__name__,
description=(
"Sharing listening on the fediverse (ActivityPub). These endpoints only exist when "
"the server has federation enabled; a 404 means it doesn't."
),
)
def _identity(username: str) -> dict:
config = current_app.extensions["federation"]
return {
"handle": f"@{username}@{config.domain}",
"actor_url": f"{config.base_url}/users/{username}",
"profile_url": f"{current_app.config['UI_BASE_URL']}/profile.html?u={username}",
}
def _settings_body(user, settings) -> dict:
return {
**{field: getattr(settings, field) for field in sharing.EDITABLE},
**_identity(user.username),
"followers": 0,
}
@blp.route("/settings", methods=["GET"])
@authenticated(blp)
@blp.response(200, SharingSettingsSchema)
def get_settings():
"""Your sharing settings
Sharing is off and posts are followers-only until you change them.
"""
return _settings_body(g.user, sharing.settings_for(g.user.id))
@blp.route("/settings", methods=["PATCH"])
@authenticated(blp)
@blp.arguments(SharingSettingsUpdateSchema)
@blp.response(200, SharingSettingsSchema)
@blp.alt_response(422, schema=ErrorSchema, description="Invalid settings")
def update_settings(changes):
"""Change your sharing settings
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.
"""
try:
settings, toggled = sharing.update(g.user.id, changes)
except ValueError as err:
abort(422, code="invalid_settings", message=str(err))
if toggled is not None:
fed_metrics.sharing_changes_total.labels(change="enabled" if toggled else "disabled").inc()
return _settings_body(g.user, settings)
@blp.route("/profiles/<string:username>", methods=["GET"])
@blp.response(200, PublicProfileSchema)
@blp.alt_response(404, schema=ErrorSchema, description="No one sharing with that name")
def public_profile(username):
"""A public fediverse profile
For the web UI's profile page. Only users who share are visible.
"""
found = sharing.shared_user(username)
if found is None:
fed_metrics.lookups_total.labels(kind="profile", result="not_found").inc()
abort(404, code="not_found", message="No one here shares their listening under that name.")
fed_metrics.lookups_total.labels(kind="profile", result="found").inc()
user, settings = found
return {
"username": user.username,
"display_name": settings.display_name or user.username,
"bio": settings.bio,
**{k: v for k, v in _identity(user.username).items() if k != "profile_url"},
}
+156
View File
@@ -0,0 +1,156 @@
"""OpenAPI descriptions of the ActivityPub endpoints (served on the UI's domain)."""
from flask import Flask
from flask_smorest import Api
TAG = "ActivityPub"
_AP = {"application/activity+json": {"schema": {"type": "object"}}}
_NOT_FOUND = {"description": "Unknown, or not sharing (the two are indistinguishable)"}
_USERNAME = {"name": "username", "in": "path", "required": True, "schema": {"type": "string"}}
# endpoint -> (method, summary, description, extra parameters, responses)
_OPERATIONS = {
"federation.webfinger_lookup": (
"get",
"WebFinger",
"Resolves `acct:user@domain` (or an actor URL) to the user's actor. Only users "
"sharing their listening can be found.",
[
{
"name": "resource",
"in": "query",
"required": True,
"schema": {"type": "string"},
"example": "acct:alice@scrobble.example",
}
],
{
"200": {
"description": "JRD",
"content": {"application/jrd+json": {"schema": {"type": "object"}}},
},
"400": {"description": "Not a resource on this server"},
"404": _NOT_FOUND,
},
),
"federation.host_meta": (
"get",
"host-meta",
"XRD pointing at WebFinger (RFC 6415).",
[],
{
"200": {
"description": "XRD",
"content": {"application/xrd+xml": {"schema": {"type": "string"}}},
}
},
),
"federation.nodeinfo_discovery": (
"get",
"NodeInfo discovery",
"Links to the NodeInfo 2.1 document.",
[],
{
"200": {
"description": "Links",
"content": {"application/json": {"schema": {"type": "object"}}},
}
},
),
"federation.nodeinfo_document": (
"get",
"NodeInfo 2.1",
"Software name and version, protocols, and users sharing.",
[],
{
"200": {
"description": "NodeInfo",
"content": {"application/json": {"schema": {"type": "object"}}},
}
},
),
"federation.actor": (
"get",
"Actor",
"A user's `Person` actor when asked for ActivityPub JSON; browsers are redirected to "
"the web UI's profile page.",
[_USERNAME],
{
"200": {"description": "Person", "content": _AP},
"302": {"description": "Redirect to the profile page (non-ActivityPub Accept)"},
"404": _NOT_FOUND,
},
),
"federation.outbox": (
"get",
"Outbox",
"The user's published activities.",
[_USERNAME],
{"200": {"description": "OrderedCollection", "content": _AP}, "404": _NOT_FOUND},
),
"federation.followers": (
"get",
"Followers",
"Follower count (members aren't listed).",
[_USERNAME],
{"200": {"description": "OrderedCollection", "content": _AP}, "404": _NOT_FOUND},
),
"federation.following": (
"get",
"Following",
"Accounts the user follows.",
[_USERNAME],
{"200": {"description": "OrderedCollection", "content": _AP}, "404": _NOT_FOUND},
),
"federation.instance_actor": (
"get",
"Instance actor",
"The server's `Application` actor.",
[],
{"200": {"description": "Application", "content": _AP}},
),
"federation.instance_outbox": (
"get",
"Instance outbox",
"Always empty.",
[],
{"200": {"description": "OrderedCollection", "content": _AP}},
),
"federation.user_inbox": (
"post",
"User inbox",
"Receives activities for one user (signed deliveries).",
[_USERNAME],
{
"202": {"description": "Accepted"},
"404": _NOT_FOUND,
"413": {"description": "Too large"},
},
),
"federation.shared_inbox": (
"post",
"Shared inbox",
"Receives activities for any user on this server.",
[],
{"202": {"description": "Accepted"}, "413": {"description": "Too large"}},
),
}
def register(app: Flask, api: Api) -> None:
api.spec.tag({"name": TAG, "description": "Fediverse endpoints, served on the web UI's domain"})
rules = {rule.endpoint: rule for rule in app.url_map.iter_rules()}
for endpoint, (method, summary, description, parameters, responses) in _OPERATIONS.items():
operation = {
"tags": [TAG],
"summary": summary,
"description": description,
"operationId": endpoint.replace(".", "_"),
"responses": responses,
}
if parameters:
operation["parameters"] = parameters
if method == "post":
operation["requestBody"] = {"content": _AP}
api.spec.path(rule=rules[endpoint], operations={method: operation})
+40
View File
@@ -0,0 +1,40 @@
from marshmallow import Schema, fields, validate
from scrobbler.federation.models import VISIBILITIES
class SharingSettingsSchema(Schema):
enabled = fields.Boolean(metadata={"description": "Share listening on the fediverse"})
visibility = fields.String(
validate=validate.OneOf(VISIBILITIES),
metadata={
"description": (
"Who sees posts: `followers` (default), `unlisted` (anyone visiting the "
"profile, not public timelines) or `public`. Followers-only is only as private "
"as who may follow: see `manually_approves_followers`."
)
},
)
manually_approves_followers = fields.Boolean()
discoverable = fields.Boolean(metadata={"description": "May appear in profile directories"})
indexable = fields.Boolean(metadata={"description": "Posts may be indexed for search"})
display_name = fields.String(allow_none=True, validate=validate.Length(max=100))
bio = fields.String(allow_none=True, validate=validate.Length(max=500))
handle = fields.String(dump_only=True, metadata={"example": "@alice@scrobble.example"})
actor_url = fields.String(dump_only=True)
profile_url = fields.String(dump_only=True)
followers = fields.Integer(
dump_only=True, metadata={"description": "0 until following arrives"}
)
class PublicProfileSchema(Schema):
username = fields.String()
display_name = fields.String()
bio = fields.String(allow_none=True)
handle = fields.String(metadata={"example": "@alice@scrobble.example"})
actor_url = fields.String()
class SharingSettingsUpdateSchema(SharingSettingsSchema):
"""Any subset of the editable settings (read-only fields are rejected)."""