Let users share their profile image with the fediverse (SCR-1)
CI / validate-monitoring (push) Successful in 9s
CI / lint (push) Successful in 13s
CI / federation-interop (push) Successful in 1m44s
CI / test (push) Failing after 6m30s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / trigger-deploy (push) Skipped
CI / notify (push) Successful in 6s

A share_avatar switch (off by default) in the sharing settings publishes the image as
the actor's icon and on the public profile page, via a public avatar endpoint.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
mattandClaude Sonnet 5.5 committed 2026-10-13 11:43:55 +01:00
1 parent 9243fe4d3f
commit 016fc707d1
12 files changed
+286 -3

No files matched your search

+50
View File
@@ -2940,6 +2940,44 @@
}
]
},
"/api/v1/federation/profiles/{username}/avatar": {
"get": {
"responses": {
"404": {
"description": "No image shared under that name",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"200": {
"description": "The profile image (JPEG, PNG or WebP)"
},
"default": {
"$ref": "#/components/responses/DEFAULT_ERROR"
}
},
"summary": "A public profile image",
"description": "For the web UI's profile page. Only served when the user shares and has chosen to\nshare their image.",
"tags": [
"Federation"
]
},
"parameters": [
{
"in": "path",
"name": "username",
"required": true,
"schema": {
"type": "string",
"minLength": 1
}
}
]
},
"/api/v1/federation/profiles/{username}/posts/{post_uuid}": {
"get": {
"responses": {
@@ -5526,6 +5564,10 @@
],
"description": "`off` (default): nothing. `profile`: a \"Now playing\" field on your profile, refreshed at most every 5 minutes and cleared when you stop. `posts`: the profile field, plus a post for each track played 30+ seconds, at most one every 30 minutes, replacing the last one."
},
"share_avatar": {
"type": "boolean",
"description": "Show your profile image on your public profile and send it to other servers as your picture. Off by default; has no effect if you have no image."
},
"handle": {
"type": "string",
"readOnly": true,
@@ -5615,6 +5657,10 @@
],
"description": "`off` (default): nothing. `profile`: a \"Now playing\" field on your profile, refreshed at most every 5 minutes and cleared when you stop. `posts`: the profile field, plus a post for each track played 30+ seconds, at most one every 30 minutes, replacing the last one."
},
"share_avatar": {
"type": "boolean",
"description": "Show your profile image on your public profile and send it to other servers as your picture. Off by default; has no effect if you have no image."
},
"handle": {
"type": "string",
"readOnly": true,
@@ -5705,6 +5751,10 @@
],
"description": "\"Track by Artist\", or null"
},
"has_avatar": {
"type": "boolean",
"description": "Whether there's a profile image at `/profiles/{username}/avatar`"
},
"handle": {
"type": "string",
"example": "@alice@scrobble.example"
+10
View File
@@ -34,6 +34,15 @@ def now_playing_field(user, settings) -> list[tuple[str, str]]:
return [(NOW_PLAYING_FIELD, text)] if text else []
def avatar_icon(urls: vocab.ActorUrls, user, settings) -> tuple[str, str] | None:
"""The actor's picture: only if they've chosen to share one. The URL carries the
image's age so other servers, which cache by URL, fetch a changed picture."""
if not settings.share_avatar or not user.has_avatar:
return None
version = int(user.avatar_updated_at.timestamp()) if user.avatar_updated_at else 0
return f"{urls.avatar}?v={version}", user.avatar_content_type or "image/jpeg"
def build_document(urls: vocab.ActorUrls, user, settings) -> dict:
return vocab.person(
urls,
@@ -46,4 +55,5 @@ def build_document(urls: vocab.ActorUrls, user, settings) -> dict:
indexable=settings.indexable,
published=settings.created_at.isoformat().replace("+00:00", "Z"),
fields=now_playing_field(user, settings),
icon=avatar_icon(urls, user, settings),
)
+18
View File
@@ -178,10 +178,28 @@ def public_profile(username):
"now_playing": actors.now_playing_text(user)
if settings.now_playing_mode != "off"
else None,
"has_avatar": settings.share_avatar and user.has_avatar,
**{k: v for k, v in _identity(user.username).items() if k != "profile_url"},
}
@blp.route("/profiles/<string:username>/avatar", methods=["GET"])
@blp.response(200, content_type="image/jpeg", description="The profile image (JPEG, PNG or WebP)")
@blp.alt_response(404, schema=ErrorSchema, description="No image shared under that name")
def public_avatar(username):
"""A public profile image
For the web UI's profile page. Only served when the user shares and has chosen to
share their image.
"""
found = sharing.shared_avatar(username)
if found is None:
fed_metrics.lookups_total.labels(kind="avatar", result="not_found").inc()
abort(404, code="not_found", message="No shared profile image under that name.")
fed_metrics.lookups_total.labels(kind="avatar", result="found").inc()
return sharing.avatar_response(*found)
@blp.route("/profiles/<string:username>/posts/<string:post_uuid>", methods=["GET"])
@blp.response(200, PublicPostSchema)
@blp.alt_response(404, schema=ErrorSchema, description="Not found, not public, or deleted")
+1 -1
View File
@@ -4,7 +4,7 @@ from prometheus_client import Counter, Gauge, Histogram
lookups_total = Counter(
"scrobbler_federation_lookups_total",
"Fediverse lookups answered: WebFinger, actor, NodeInfo, profile",
"Fediverse lookups answered: WebFinger, actor, NodeInfo, profile, avatar",
["kind", "result"],
)
sharing_changes_total = Counter(
+3
View File
@@ -41,6 +41,9 @@ class FederationSettings(db.Model):
indexable: Mapped[bool] = mapped_column(Boolean, default=False)
display_name: Mapped[str | None] = mapped_column(String(100))
bio: Mapped[str | None] = mapped_column(Text)
# Offer the user's profile image to other servers (as the actor's icon) and on the
# public profile page. Off until they say so.
share_avatar: Mapped[bool] = mapped_column(Boolean, default=False)
# An IANA zone name (validated with zoneinfo), used to decide when a Monday starts.
timezone: Mapped[str] = mapped_column(String(64), default="UTC")
post_weekly_summary: Mapped[bool] = mapped_column(Boolean, default=True)
+7 -1
View File
@@ -35,6 +35,7 @@ class ActorUrls:
shared_inbox: str
key_id: str
profile_page: str
avatar: str
def actor_urls(base_url: str, username: str, profile_page: str) -> ActorUrls:
@@ -49,6 +50,7 @@ def actor_urls(base_url: str, username: str, profile_page: str) -> ActorUrls:
shared_inbox=f"{base_url}/inbox",
key_id=f"{actor}#main-key",
profile_page=profile_page,
avatar=f"{actor}/avatar",
)
@@ -79,8 +81,10 @@ def person(
indexable: bool,
published: str | None = None,
fields: list[tuple[str, str]] = (),
icon: tuple[str, str] | None = None,
) -> dict:
"""A user's actor document. `fields` are (name, plain-text value) profile fields."""
"""A user's actor document. `fields` are (name, plain-text value) profile fields;
`icon` is the profile picture's (url, media type)."""
doc = {
"@context": ACTOR_CONTEXT,
"id": urls.id,
@@ -106,6 +110,8 @@ def person(
}
if published:
doc["published"] = published
if icon:
doc["icon"] = {"type": "Image", "url": icon[0], "mediaType": icon[1]}
return doc
+11
View File
@@ -55,6 +55,14 @@ class SharingSettingsSchema(Schema):
)
},
)
share_avatar = fields.Boolean(
metadata={
"description": (
"Show your profile image on your public profile and send it to other "
"servers as your picture. Off by default; has no effect if you have no image."
)
}
)
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)
@@ -71,6 +79,9 @@ class PublicProfileSchema(Schema):
now_playing = fields.String(
allow_none=True, metadata={"description": '"Track by Artist", or null'}
)
has_avatar = fields.Boolean(
metadata={"description": "Whether there's a profile image at `/profiles/{username}/avatar`"}
)
handle = fields.String(metadata={"example": "@alice@scrobble.example"})
actor_url = fields.String()
+26 -1
View File
@@ -1,10 +1,12 @@
"""Per-user sharing settings: whether a user federates, and how."""
from flask import Response, request
from scrobbler.extensions import db
from scrobbler.federation import keys
from scrobbler.federation.models import NOW_PLAYING_MODES, VISIBILITIES, FederationSettings
from scrobbler.federation.protocol.schedule import is_valid_timezone
from scrobbler.services import accounts
from scrobbler.services import accounts, avatars
EDITABLE = (
"enabled",
@@ -18,6 +20,7 @@ EDITABLE = (
"post_weekly_summary",
"post_milestones",
"now_playing_mode",
"share_avatar",
)
@@ -38,6 +41,7 @@ def settings_for(user_id: int) -> FederationSettings:
post_weekly_summary=True,
post_milestones=True,
now_playing_mode="off",
share_avatar=False,
)
return settings
@@ -81,6 +85,27 @@ def shared_user(username: str):
return user, settings
def shared_avatar(username: str):
"""(user, image bytes) for a sharing user who has chosen to share their profile image
and has one, else None - indistinguishable from 'no such user', like shared_user."""
found = shared_user(username)
if found is None:
return None
user, settings = found
if not settings.share_avatar:
return None
data = avatars.read(user)
return None if data is None else (user, data)
def avatar_response(user, data: bytes):
"""The public image response: cacheable by anyone, but briefly, as it can change."""
response = Response(data, mimetype=user.avatar_content_type or "image/jpeg")
response.headers["Cache-Control"] = "public, max-age=300"
response.add_etag()
return response.make_conditional(request)
def sharing_count() -> int:
return db.session.scalar(
db.select(db.func.count()).select_from(FederationSettings).filter_by(enabled=True)
+9
View File
@@ -134,6 +134,15 @@ def actor(username: str):
return _json(doc)
@bp.get("/users/<username>/avatar")
def actor_avatar(username: str):
found = sharing.shared_avatar(username)
if found is None:
return _not_found("avatar")
_found("avatar")
return sharing.avatar_response(*found)
def _collection(username: str, which: str, items: list | None, total: int = 0):
found = sharing.shared_user(username)
if found is None:
@@ -0,0 +1,29 @@
"""federation share avatar
Revision ID: e5a91c3d7b08
Revises: 2533b727da79
Create Date: 2026-10-13 10:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "e5a91c3d7b08"
down_revision = "2533b727da79"
branch_labels = None
depends_on = None
def upgrade():
with op.batch_alter_table("federation_settings", schema=None) as batch_op:
batch_op.add_column(
sa.Column("share_avatar", sa.Boolean(), nullable=False, server_default=sa.false())
)
def downgrade():
with op.batch_alter_table("federation_settings", schema=None) as batch_op:
batch_op.drop_column("share_avatar")
+1
View File
@@ -127,6 +127,7 @@ def test_public_profile(fed_client, sharing_user, make_user):
"display_name": "Alice",
"bio": "Listening.",
"now_playing": None,
"has_avatar": False,
"handle": "@alice@scrobble.test",
"actor_url": "https://scrobble.test/users/alice",
}
+121
View File
@@ -0,0 +1,121 @@
import io
import pytest
from scrobbler.federation import sharing
from scrobbler.services import avatars
from scrobbler.services.accounts import issue_ui_token
AP = {"Accept": "application/activity+json"}
JPEG = b"\xff\xd8\xff\xe0fake-jpeg"
API = "/api/v1/federation/profiles/alice"
@pytest.fixture
def storage(fed_app, tmp_path):
saved = fed_app.config["ART_STORAGE_DIR"]
fed_app.config["ART_STORAGE_DIR"] = str(tmp_path)
yield tmp_path
fed_app.config["ART_STORAGE_DIR"] = saved
@pytest.fixture
def avatar_user(sharing_user, storage):
"""The sharing user, with a profile image that they haven't chosen to share yet."""
avatars.save(sharing_user, JPEG, "image/jpeg", "upload")
return sharing_user
@pytest.fixture
def shared(avatar_user):
sharing.update(avatar_user.id, {"share_avatar": True})
return avatar_user
def actor(fed_client):
return fed_client.get("/users/alice", headers=AP).get_json()
def test_sharing_the_avatar_is_off_by_default(fed_client, fed_ctx, user):
auth = {"Authorization": f"Bearer {issue_ui_token(user)}"}
settings = fed_client.get("/api/v1/federation/settings", headers=auth).get_json()
assert settings["share_avatar"] is False
changed = fed_client.patch(
"/api/v1/federation/settings", json={"share_avatar": True}, headers=auth
)
assert changed.get_json()["share_avatar"] is True
def test_nothing_is_public_until_the_user_opts_in(fed_client, avatar_user):
assert fed_client.get(API).get_json()["has_avatar"] is False
assert fed_client.get(f"{API}/avatar").status_code == 404
assert fed_client.get("/users/alice/avatar").status_code == 404
assert "icon" not in actor(fed_client)
def test_opted_in_avatar_is_served_publicly(fed_client, shared, metric_delta):
found = metric_delta("scrobbler_federation_lookups_total", kind="avatar", result="found")
assert fed_client.get(API).get_json()["has_avatar"] is True
for path in (f"{API}/avatar", "/users/alice/avatar"):
response = fed_client.get(path) # no credentials
assert (response.status_code, response.data, response.mimetype) == (
200,
JPEG,
"image/jpeg",
)
assert response.headers["Cache-Control"] == "public, max-age=300"
assert found.delta == 2
tag = fed_client.get("/users/alice/avatar").headers["ETag"]
assert fed_client.get("/users/alice/avatar", headers={"If-None-Match": tag}).status_code == 304
def test_actor_gets_an_icon_that_changes_with_the_image(fed_client, shared):
icon = actor(fed_client)["icon"]
assert icon["type"] == "Image"
assert icon["mediaType"] == "image/jpeg"
version = int(shared.avatar_updated_at.timestamp())
assert icon["url"] == f"https://scrobble.test/users/alice/avatar?v={version}"
def test_no_icon_without_an_image(fed_client, sharing_user, storage):
sharing.update(sharing_user.id, {"share_avatar": True})
assert "icon" not in actor(fed_client)
assert fed_client.get(API).get_json()["has_avatar"] is False
assert fed_client.get("/users/alice/avatar").status_code == 404
def test_removing_the_image_withdraws_it(fed_client, shared):
avatars.remove(shared)
assert fed_client.get("/users/alice/avatar").status_code == 404
assert "icon" not in actor(fed_client)
def test_not_sharing_at_all_hides_the_avatar_too(fed_client, shared, make_user):
sharing.update(shared.id, {"enabled": False})
assert fed_client.get(f"{API}/avatar").status_code == 404
assert fed_client.get("/users/alice/avatar").status_code == 404
# ...and looks the same as someone who doesn't exist.
assert fed_client.get("/users/nobody/avatar").data == fed_client.get("/users/alice/avatar").data
def test_unknown_users_have_no_avatar(fed_client, fed_ctx):
assert fed_client.get("/api/v1/federation/profiles/nobody/avatar").status_code == 404
def test_the_file_going_missing_is_a_404_not_an_error(fed_client, shared, storage):
(storage / "avatars" / str(shared.id)).unlink()
assert fed_client.get("/users/alice/avatar").status_code == 404
assert "icon" in actor(fed_client) # the row still says there is one; only the fetch fails
def test_upload_through_the_api_is_what_gets_shared(fed_client, fed_ctx, sharing_user, storage):
auth = {"Authorization": f"Bearer {issue_ui_token(sharing_user)}"}
sharing.update(sharing_user.id, {"share_avatar": True})
uploaded = fed_client.put(
"/api/v1/me/avatar",
headers=auth,
data={"file": (io.BytesIO(JPEG), "me.jpg")},
content_type="multipart/form-data",
)
assert uploaded.status_code == 200
assert fed_client.get("/users/alice/avatar").data == JPEG