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

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