Add uploaded profile images (SCR-1)
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 16s
CI / federation-interop (push) Successful in 1m40s
CI / test (push) Successful in 4m48s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / trigger-deploy (push) Skipped
CI / notify (push) Successful in 5s

Users can upload, fetch and remove a profile image at /api/v1/me/avatar. The
bytes live in an avatars folder inside ART_STORAGE_DIR; the users row records the
source and content type. Adds metrics, AVATAR_UPLOAD_MAX_BYTES and the regenerated
OpenAPI document.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
mattandClaude Sonnet 5.5 committed 2026-10-13 11:39:43 +01:00
1 parent 81e0b0cf42
commit c55a6596d0
11 files changed
+555 -1

No files matched your search

+13 -1
View File
@@ -48,7 +48,18 @@ def init_app(app: Flask) -> None:
},
)
from scrobbler.api import apps, art, auth, health, imports, sessions, stats, tokens, tracks
from scrobbler.api import (
apps,
art,
auth,
avatar,
health,
imports,
sessions,
stats,
tokens,
tracks,
)
api.register_blueprint(auth.blp, url_prefix="/api/v1/auth")
api.register_blueprint(apps.blp, url_prefix="/api/v1/apps")
@@ -58,6 +69,7 @@ def init_app(app: Flask) -> None:
api.register_blueprint(tracks.blp, url_prefix="/api/v1/me/tracks")
api.register_blueprint(imports.blp, url_prefix="/api/v1/imports")
api.register_blueprint(art.blp, url_prefix="/api/v1/art")
api.register_blueprint(avatar.blp, url_prefix="/api/v1/me/avatar")
api.register_blueprint(health.blp)
from scrobbler.openapi import lastfm
+69
View File
@@ -0,0 +1,69 @@
from flask import Response, current_app, g, request
from flask_smorest import Blueprint, abort
from scrobbler import metrics
from scrobbler.api.decorators import authenticated
from scrobbler.schemas import AvatarUploadSchema, ErrorSchema, UserSchema
from scrobbler.services import avatars
blp = Blueprint(
"Avatar",
__name__,
description="Your profile image: upload one, or remove it.",
)
@blp.route("", methods=["GET"])
@authenticated(blp)
@blp.response(200, content_type="image/jpeg", description="Your profile image (JPEG, PNG or WebP)")
@blp.alt_response(404, schema=ErrorSchema, description="You have no profile image")
def get_avatar():
"""Your profile image"""
data = avatars.read(g.user)
if data is None:
abort(404, code="no_avatar", message="You have no profile image")
response = Response(data, mimetype=g.user.avatar_content_type or "image/jpeg")
response.headers["Cache-Control"] = "private, no-cache" # revalidate: it can change
response.add_etag()
return response.make_conditional(request)
@blp.route("", methods=["PUT"])
@authenticated(blp)
@blp.arguments(AvatarUploadSchema, location="files")
@blp.response(200, UserSchema)
@blp.alt_response(400, schema=ErrorSchema, description="Empty file")
@blp.alt_response(413, schema=ErrorSchema, description="Image too large")
@blp.alt_response(415, schema=ErrorSchema, description="Not a JPEG, PNG or WebP image")
def upload_avatar(files):
"""Upload a profile image
Replaces your current one, whatever its source.
"""
limit = current_app.config["AVATAR_UPLOAD_MAX_BYTES"]
data = files["file"].read(limit + 1)
if not data:
metrics.avatar_uploads_total.labels("empty").inc()
abort(400, code="empty_file", message="That file is empty.")
if len(data) > limit:
metrics.avatar_uploads_total.labels("too_large").inc()
abort(413, code="file_too_large", message="That image is larger than this server accepts.")
try:
content_type = avatars.sniff_image_type(data)
except avatars.UnsupportedImage:
metrics.avatar_uploads_total.labels("bad_type").inc()
abort(415, code="unsupported_image", message="Upload a JPEG, PNG or WebP image.")
avatars.save(g.user, data, content_type, "upload")
metrics.avatar_uploads_total.labels("ok").inc()
metrics.avatar_upload_bytes.observe(len(data))
return g.user
@blp.route("", methods=["DELETE"])
@authenticated(blp)
@blp.response(204)
@blp.alt_response(404, schema=ErrorSchema, description="You have no profile image")
def delete_avatar():
"""Remove your profile image"""
if not avatars.remove(g.user):
abort(404, code="no_avatar", message="You have no profile image")
+3
View File
@@ -72,6 +72,9 @@ class Config:
ART_STORAGE_DIR = os.environ.get("ART_STORAGE_DIR", "var/album-art")
# Largest image a user may upload as their own album art.
ART_UPLOAD_MAX_BYTES = int(os.environ.get("ART_UPLOAD_MAX_BYTES", str(5 * 1024 * 1024)))
# 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)))
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
+17
View File
@@ -193,6 +193,23 @@ art_override_worker_seconds = Histogram(
buckets=(0.25, 0.5, 1, 2.5, 5, 10, 20, 40, 80),
)
# Profile images
avatar_uploads_total = Counter(
"scrobbler_avatar_uploads_total",
"Profile image upload attempts: ok, empty, too_large or bad_type",
["result"],
)
avatar_upload_bytes = Histogram(
"scrobbler_avatar_upload_bytes",
"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_actions_total = Counter(
"scrobbler_avatar_actions_total",
"Profile image changes: uploaded, removed",
["action"],
)
# Database
db_query_duration_seconds = Histogram(
"scrobbler_db_query_duration_seconds",
@@ -0,0 +1,34 @@
"""user avatar
Revision ID: b3e8a5d1f720
Revises: c7d2f08a19e4
Create Date: 2026-10-13 09:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "b3e8a5d1f720"
down_revision = "c7d2f08a19e4"
branch_labels = None
depends_on = None
def upgrade():
op.add_column(
"users",
sa.Column("avatar_source", sa.String(length=16), server_default="none", nullable=False),
)
op.add_column("users", sa.Column("avatar_content_type", sa.String(length=32), nullable=True))
op.add_column(
"users", sa.Column("avatar_updated_at", sa.DateTime(timezone=True), nullable=True)
)
def downgrade():
op.drop_column("users", "avatar_updated_at")
op.drop_column("users", "avatar_content_type")
op.drop_column("users", "avatar_source")
+9
View File
@@ -28,9 +28,18 @@ class User(db.Model):
email: Mapped[str] = mapped_column(String(255))
password_hash: Mapped[str] = mapped_column(String(255))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
# The profile image: none, upload or gravatar. Any image's bytes sit on disk (see
# services/avatars.py); these columns just say whether there is one, and what it is.
avatar_source: Mapped[str] = mapped_column(String(16), default="none", server_default="none")
avatar_content_type: Mapped[str | None] = mapped_column(String(32))
avatar_updated_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
__table_args__ = (Index("uq_users_username_lower", func.lower(username), unique=True),)
@property
def has_avatar(self) -> bool:
return self.avatar_source != "none"
class ApiApp(db.Model):
"""A client application; scrobblers authenticate with its key and secret."""
+15
View File
@@ -20,6 +20,17 @@ class UserSchema(Schema):
username = fields.String(dump_only=True, metadata={"example": "alice"})
email = fields.String(dump_only=True, metadata={"example": "alice@example.com"})
created_at = fields.DateTime(dump_only=True)
has_avatar = fields.Boolean(
dump_only=True, metadata={"description": "Whether you have a profile image"}
)
avatar_source = fields.String(
dump_only=True,
validate=validate.OneOf(["none", "upload", "gravatar"]),
metadata={"description": "Where your profile image comes from"},
)
avatar_updated_at = fields.DateTime(
dump_only=True, allow_none=True, metadata={"description": "When it last changed"}
)
class RegisterSchema(Schema):
@@ -164,6 +175,10 @@ class AlbumArtUploadSchema(Schema):
file = Upload(required=True, metadata={"description": "A JPEG, PNG or WebP image"})
class AvatarUploadSchema(Schema):
file = Upload(required=True, metadata={"description": "A JPEG, PNG or WebP image"})
class AlbumArtCorrectionSchema(AlbumArtArgsSchema):
search_artist = fields.String(
validate=validate.Length(min=1, max=500),
+73
View File
@@ -0,0 +1,73 @@
"""Profile images.
The bytes live on disk, in an "avatars" folder inside ART_STORAGE_DIR (so they share its
volume and its backups), one file per user named by user id with no extension. The users
row records where the image came from and its content type; that is the source of truth
for whether there is one.
"""
import os
import tempfile
from datetime import UTC, datetime
from pathlib import Path
from flask import current_app
from scrobbler import metrics
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"]
def _path(user_id: int) -> Path:
return Path(current_app.config["ART_STORAGE_DIR"]) / "avatars" / str(user_id)
def read(user: User) -> bytes | None:
"""The user's image bytes, or None if they have none (or the file has gone missing)."""
if not user.has_avatar:
return None
try:
return _path(user.id).read_bytes()
except FileNotFoundError:
return None
def _write(user_id: int, data: bytes) -> None:
"""Writes via a temp file and a rename, so a reader never sees half an image."""
path = _path(user_id)
path.parent.mkdir(parents=True, exist_ok=True)
fd, temp = tempfile.mkstemp(dir=path.parent, prefix=f".{user_id}.")
try:
with os.fdopen(fd, "wb") as file:
file.write(data)
os.replace(temp, path)
except BaseException:
Path(temp).unlink(missing_ok=True)
raise
def save(user: User, data: bytes, content_type: str, source: str) -> None:
"""Make `data` the user's image. The caller has already validated it. The file is
written first, so a failure leaves the previous image (and row) intact."""
_write(user.id, data)
user.avatar_source = source
user.avatar_content_type = content_type
user.avatar_updated_at = datetime.now(UTC)
db.session.commit()
metrics.avatar_actions_total.labels("uploaded" if source == "upload" else source).inc()
def remove(user: User) -> bool:
"""Drops the user's image. False if they didn't have one."""
if not user.has_avatar:
return False
user.avatar_source = "none"
user.avatar_content_type = None
user.avatar_updated_at = datetime.now(UTC)
db.session.commit()
_path(user.id).unlink(missing_ok=True)
metrics.avatar_actions_total.labels("removed").inc()
return True