Let users pick their Gravatar as their profile image (SCR-1)
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 13s
CI / federation-interop (push) Successful in 1m42s
CI / test (push) Successful in 5m46s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / trigger-deploy (push) Skipped
CI / notify (push) Successful in 7s

Opt-in per user and gated by AVATAR_GRAVATAR_ENABLED. The server fetches the image by
the SHA-256 of the account email and caches it with the uploads, so browsers never
contact Gravatar.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
mattandClaude Sonnet 5.5 committed 2026-10-13 11:41:32 +01:00
1 parent c55a6596d0
commit 9243fe4d3f
8 files changed
+328 -4

No files matched your search

+27 -1
View File
@@ -9,7 +9,10 @@ from scrobbler.services import avatars
blp = Blueprint(
"Avatar",
__name__,
description="Your profile image: upload one, or remove it.",
description=(
"Your profile image: upload one, use your Gravatar (if this server allows it), "
"or remove it."
),
)
@@ -59,6 +62,29 @@ def upload_avatar(files):
return g.user
@blp.route("/gravatar", methods=["POST"])
@authenticated(blp)
@blp.response(200, UserSchema)
@blp.alt_response(404, schema=ErrorSchema, description="Gravatar is off, or has no image for you")
@blp.alt_response(502, schema=ErrorSchema, description="Gravatar couldn't be reached")
def use_gravatar():
"""Use your Gravatar as your profile image
The server fetches the image for your account email from Gravatar (sending it a hash
of the address) and keeps a copy. Call again to refresh it. Only available when the
server's admin has enabled it; see `gravatar_enabled` on `/auth/me`.
"""
try:
avatars.use_gravatar(g.user)
except avatars.GravatarDisabled:
abort(404, code="gravatar_disabled", message="This server doesn't use Gravatar.")
except avatars.GravatarMissing:
abort(404, code="no_gravatar", message="Gravatar has no image for your email address.")
except avatars.GravatarUnavailable:
abort(502, code="gravatar_unavailable", message="Gravatar couldn't be reached.")
return g.user
@blp.route("", methods=["DELETE"])
@authenticated(blp)
@blp.response(204)
+8
View File
@@ -75,6 +75,14 @@ class Config:
# Profile images live in an "avatars" folder inside ART_STORAGE_DIR. This is the
# largest one a user may upload.
AVATAR_UPLOAD_MAX_BYTES = int(os.environ.get("AVATAR_UPLOAD_MAX_BYTES", str(2 * 1024 * 1024)))
# Lets users pick their Gravatar as their profile image. Off by default: using one
# sends a hash of the user's email address to Gravatar (from this server, not their browser).
AVATAR_GRAVATAR_ENABLED = os.environ.get("AVATAR_GRAVATAR_ENABLED", "").lower() in (
"1",
"true",
"yes",
)
GRAVATAR_URL = os.environ.get("GRAVATAR_URL", "https://gravatar.com/avatar/")
IMPORT_MAX_BYTES = int(os.environ.get("IMPORT_MAX_BYTES", str(200 * 1024 * 1024)))
MAX_CONTENT_LENGTH = IMPORT_MAX_BYTES + 1024 * 1024 # uploads are the largest requests
+11 -1
View File
@@ -204,9 +204,19 @@ avatar_upload_bytes = Histogram(
"Size of accepted profile image uploads",
buckets=(5_000, 10_000, 25_000, 50_000, 100_000, 250_000, 500_000, 1_000_000, 2_000_000),
)
avatar_gravatar_fetches_total = Counter(
"scrobbler_avatar_gravatar_fetches_total",
"Gravatar fetches: ok, none (no Gravatar for the email), bad_type, too_large or error",
["result"],
)
avatar_gravatar_seconds = Histogram(
"scrobbler_avatar_gravatar_seconds",
"Latency of one Gravatar fetch",
buckets=(0.1, 0.25, 0.5, 1, 2.5, 5, 10),
)
avatar_actions_total = Counter(
"scrobbler_avatar_actions_total",
"Profile image changes: uploaded, removed",
"Profile image changes: uploaded, gravatar, removed",
["action"],
)
+8
View File
@@ -1,6 +1,7 @@
"""Marshmallow schemas for the /api/v1 JSON API. They drive both request
validation and the generated OpenAPI document."""
from flask import current_app
from flask_smorest.fields import Upload
from marshmallow import Schema, ValidationError, fields, validate, validates_schema
@@ -31,6 +32,13 @@ class UserSchema(Schema):
avatar_updated_at = fields.DateTime(
dump_only=True, allow_none=True, metadata={"description": "When it last changed"}
)
gravatar_enabled = fields.Method(
"_gravatar_enabled",
metadata={"type": "boolean", "description": "Whether this server offers Gravatar"},
)
def _gravatar_enabled(self, _user) -> bool:
return bool(current_app.config["AVATAR_GRAVATAR_ENABLED"])
class RegisterSchema(Schema):
+78 -1
View File
@@ -6,8 +6,12 @@ row records where the image came from and its content type; that is the source o
for whether there is one.
"""
import hashlib
import os
import tempfile
import time
import urllib.error
import urllib.request
from datetime import UTC, datetime
from pathlib import Path
@@ -18,7 +22,34 @@ from scrobbler.extensions import db
from scrobbler.models import User
from scrobbler.services.art import IMAGE_TYPES, UnsupportedImage, sniff_image_type
__all__ = ["IMAGE_TYPES", "UnsupportedImage", "read", "remove", "save", "sniff_image_type"]
__all__ = [
"IMAGE_TYPES",
"GravatarDisabled",
"GravatarMissing",
"GravatarUnavailable",
"UnsupportedImage",
"read",
"remove",
"save",
"sniff_image_type",
"use_gravatar",
]
GRAVATAR_SIZE = 256 # px; plenty for a header icon or a profile page
GRAVATAR_MAX_BYTES = 1024 * 1024
GRAVATAR_TIMEOUT = 5 # seconds - this runs inside a web request
class GravatarDisabled(Exception):
"""The admin hasn't turned Gravatar on."""
class GravatarMissing(Exception):
"""Gravatar has no image for the user's email address."""
class GravatarUnavailable(Exception):
"""Gravatar couldn't be reached, or sent something unusable."""
def _path(user_id: int) -> Path:
@@ -71,3 +102,49 @@ def remove(user: User) -> bool:
_path(user.id).unlink(missing_ok=True)
metrics.avatar_actions_total.labels("removed").inc()
return True
def gravatar_url(email: str) -> str:
"""Where Gravatar serves this address's image; d=404 asks for an error, not a stock
picture, when it has none. Gravatar keys on the SHA-256 of the trimmed, lower-cased email."""
digest = hashlib.sha256(email.strip().lower().encode()).hexdigest()
base = current_app.config["GRAVATAR_URL"]
return f"{base}{digest}?s={GRAVATAR_SIZE}&d=404"
def _fetch_gravatar(email: str) -> bytes:
start = time.perf_counter()
try:
with urllib.request.urlopen(gravatar_url(email), timeout=GRAVATAR_TIMEOUT) as response:
data = response.read(GRAVATAR_MAX_BYTES + 1)
except urllib.error.HTTPError as err:
if err.code == 404:
metrics.avatar_gravatar_fetches_total.labels("none").inc()
raise GravatarMissing from err
metrics.avatar_gravatar_fetches_total.labels("error").inc()
raise GravatarUnavailable(str(err)) from err
except (urllib.error.URLError, TimeoutError) as err:
metrics.avatar_gravatar_fetches_total.labels("error").inc()
raise GravatarUnavailable(str(err)) from err
finally:
metrics.avatar_gravatar_seconds.observe(time.perf_counter() - start)
if len(data) > GRAVATAR_MAX_BYTES:
metrics.avatar_gravatar_fetches_total.labels("too_large").inc()
raise GravatarUnavailable("image too large")
return data
def use_gravatar(user: User) -> None:
"""Fetch the Gravatar for the user's email and make it their image (also how it's
refreshed). Raises GravatarDisabled, GravatarMissing or GravatarUnavailable, leaving
any current image alone. The bytes are kept on disk, so browsers never talk to Gravatar."""
if not current_app.config["AVATAR_GRAVATAR_ENABLED"]:
raise GravatarDisabled
data = _fetch_gravatar(user.email)
try:
content_type = sniff_image_type(data)
except UnsupportedImage as err:
metrics.avatar_gravatar_fetches_total.labels("bad_type").inc()
raise GravatarUnavailable("not an image") from err
save(user, data, content_type, "gravatar")
metrics.avatar_gravatar_fetches_total.labels("ok").inc()