diff --git a/docs/openapi.json b/docs/openapi.json index 384128a..a648cf5 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -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" diff --git a/src/scrobbler/federation/actors.py b/src/scrobbler/federation/actors.py index 5e5fc07..6263288 100644 --- a/src/scrobbler/federation/actors.py +++ b/src/scrobbler/federation/actors.py @@ -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), ) diff --git a/src/scrobbler/federation/api.py b/src/scrobbler/federation/api.py index 30f7342..a8b8211 100644 --- a/src/scrobbler/federation/api.py +++ b/src/scrobbler/federation/api.py @@ -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//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//posts/", methods=["GET"]) @blp.response(200, PublicPostSchema) @blp.alt_response(404, schema=ErrorSchema, description="Not found, not public, or deleted") diff --git a/src/scrobbler/federation/metrics.py b/src/scrobbler/federation/metrics.py index a58ce4c..7fd1ddc 100644 --- a/src/scrobbler/federation/metrics.py +++ b/src/scrobbler/federation/metrics.py @@ -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( diff --git a/src/scrobbler/federation/models.py b/src/scrobbler/federation/models.py index e01904e..f2ee658 100644 --- a/src/scrobbler/federation/models.py +++ b/src/scrobbler/federation/models.py @@ -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) diff --git a/src/scrobbler/federation/protocol/vocab.py b/src/scrobbler/federation/protocol/vocab.py index ed2a7f4..99e3561 100644 --- a/src/scrobbler/federation/protocol/vocab.py +++ b/src/scrobbler/federation/protocol/vocab.py @@ -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 diff --git a/src/scrobbler/federation/schemas.py b/src/scrobbler/federation/schemas.py index c4dfba7..8827b13 100644 --- a/src/scrobbler/federation/schemas.py +++ b/src/scrobbler/federation/schemas.py @@ -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() diff --git a/src/scrobbler/federation/sharing.py b/src/scrobbler/federation/sharing.py index fe811c7..75701d9 100644 --- a/src/scrobbler/federation/sharing.py +++ b/src/scrobbler/federation/sharing.py @@ -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) diff --git a/src/scrobbler/federation/web.py b/src/scrobbler/federation/web.py index 3f0e8c5..7c4d7b9 100644 --- a/src/scrobbler/federation/web.py +++ b/src/scrobbler/federation/web.py @@ -134,6 +134,15 @@ def actor(username: str): return _json(doc) +@bp.get("/users//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: diff --git a/src/scrobbler/migrations/versions/e5a91c3d7b08_federation_share_avatar.py b/src/scrobbler/migrations/versions/e5a91c3d7b08_federation_share_avatar.py new file mode 100644 index 0000000..3aa7609 --- /dev/null +++ b/src/scrobbler/migrations/versions/e5a91c3d7b08_federation_share_avatar.py @@ -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") diff --git a/tests/test_federation_api.py b/tests/test_federation_api.py index ba10649..9dd690a 100644 --- a/tests/test_federation_api.py +++ b/tests/test_federation_api.py @@ -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", } diff --git a/tests/test_federation_avatar.py b/tests/test_federation_avatar.py new file mode 100644 index 0000000..7016b26 --- /dev/null +++ b/tests/test_federation_avatar.py @@ -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