From 5bdeeddb0bfd23cc7e52d18241d4b8b19ab21756 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Tue, 6 Oct 2026 17:05:57 +0100 Subject: [PATCH] Add album art backend: MusicBrainz + Cover Art Archive, proxied and cached New GET /api/v1/art/album?artist=&album= resolves and streams an album's cover art. Lookups go through MusicBrainz release-group search then Cover Art Archive's release-group front-image endpoint, both free and keyless - no setup required by self-hosters. Results (hits, misses and errors) are cached in a new album_art table keyed case-insensitively on (artist, album), since Scrobble.mbid can't be trusted as a release identifier. The service layer separates resolving where the art is (lookup()) from fetching the bytes (fetch_image()) so a future move to storing the bytes ourselves only touches the latter. Also widens the UI's CSP (img-src) to allow blob: URLs, since the frontend will fetch art with the existing bearer-auth header and hand the browser a blob: object URL rather than hotlinking. Co-Authored-By: Claude Sonnet 5 --- .env.example | 4 + deploy/nginx/default.conf.template | 2 +- docker-compose.yml | 1 + docs/admin-guide.md | 1 + docs/openapi.json | 81 ++++++ src/scrobbler/api/__init__.py | 3 +- src/scrobbler/api/art.py | 42 ++++ src/scrobbler/config.py | 11 + .../versions/3ba21eb1ea0c_album_art_cache.py | 50 ++++ src/scrobbler/models.py | 26 ++ src/scrobbler/schemas/__init__.py | 5 + src/scrobbler/services/art.py | 169 +++++++++++++ tests/test_art.py | 234 ++++++++++++++++++ 13 files changed, 627 insertions(+), 2 deletions(-) create mode 100644 src/scrobbler/api/art.py create mode 100644 src/scrobbler/migrations/versions/3ba21eb1ea0c_album_art_cache.py create mode 100644 src/scrobbler/services/art.py create mode 100644 tests/test_art.py diff --git a/.env.example b/.env.example index 0d614b5..a96398c 100644 --- a/.env.example +++ b/.env.example @@ -16,6 +16,10 @@ METRICS_PORT=9100 # Set to allow importing history straight from Last.fm (https://www.last.fm/api/account/create). LASTFM_API_KEY= +# Album art (MusicBrainz + Cover Art Archive, both free and keyless — no setup required). +# MusicBrainz asks for a contact URL/email in requests; falls back to UI_BASE_URL if unset. +MUSICBRAINZ_CONTACT= + # docker compose host ports (defaults shown) API_PORT=5050 UI_PORT=8080 diff --git a/deploy/nginx/default.conf.template b/deploy/nginx/default.conf.template index b128334..a532fe2 100644 --- a/deploy/nginx/default.conf.template +++ b/deploy/nginx/default.conf.template @@ -18,7 +18,7 @@ server { try_files $uri $uri/ =404; # Files aren't fingerprinted, so always revalidate. add_header Cache-Control "no-cache"; - add_header Content-Security-Policy "default-src 'self'; connect-src 'self' ${API_BASE_URL}; img-src 'self' data:; style-src 'self'; font-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'" always; + add_header Content-Security-Policy "default-src 'self'; connect-src 'self' ${API_BASE_URL}; img-src 'self' data: blob:; style-src 'self'; font-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'" always; add_header X-Content-Type-Options nosniff always; add_header Referrer-Policy same-origin always; } diff --git a/docker-compose.yml b/docker-compose.yml index a36c6b8..19e316f 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -34,6 +34,7 @@ services: WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2} FORWARDED_ALLOW_IPS: "*" LASTFM_API_KEY: ${LASTFM_API_KEY:-} + MUSICBRAINZ_CONTACT: ${MUSICBRAINZ_CONTACT:-} FEDERATION_ENABLED: ${FEDERATION_ENABLED:-0} FEDERATION_DOMAIN: ${FEDERATION_DOMAIN:-} FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-} diff --git a/docs/admin-guide.md b/docs/admin-guide.md index c081244..8d56c41 100644 --- a/docs/admin-guide.md +++ b/docs/admin-guide.md @@ -54,6 +54,7 @@ read **Putting it behind TLS** below — the quick start above serves plain HTTP | `WEB_CONCURRENCY` | api | `2` | gunicorn workers | | `RUN_MIGRATIONS` | api image | `1` | Apply database migrations on start | | `LASTFM_API_KEY` | api, worker | *(unset)* | Enables importing straight from Last.fm ([get a key](https://www.last.fm/api/account/create)) | +| `MUSICBRAINZ_CONTACT` | api | `UI_BASE_URL` | Contact URL/email sent to MusicBrainz for album art lookups (no key needed, but they ask for one) | | `IMPORT_MAX_BYTES` | api | 200 MB | Largest export file accepted | | `WORKER_METRICS_PORT` | worker | `9101` | The worker's Prometheus metrics port | | `API_BASE_URL` | ui image | `http://localhost:5050` | Where the browser reaches the API — written into `config.js` and the CSP | diff --git a/docs/openapi.json b/docs/openapi.json index 1492953..314f43e 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -1503,6 +1503,83 @@ } ] }, + "/api/v1/art/album": { + "get": { + "parameters": [ + { + "in": "query", + "name": "artist", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 500 + }, + "required": true + }, + { + "in": "query", + "name": "album", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 500 + }, + "required": true + } + ], + "responses": { + "422": { + "$ref": "#/components/responses/UNPROCESSABLE_CONTENT" + }, + "502": { + "description": "MusicBrainz or Cover Art Archive is unreachable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "No cover art found for this album", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "200": { + "description": "The album's cover art" + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "An album's cover art", + "description": "Resolved via MusicBrainz + Cover Art Archive and cached; bytes are proxied on every\ncall, so cache this response client-side.", + "tags": [ + "Art" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, "/healthz": { "get": { "responses": { @@ -3374,6 +3451,10 @@ "name": "Imports", "description": "Import listening history from a Last.fm export file, or straight from Last.fm. Imports run in the background; poll a job to follow its progress." }, + { + "name": "Art", + "description": "Album art, proxied from MusicBrainz / Cover Art Archive" + }, { "name": "Health", "description": "Liveness for load balancers and containers" diff --git a/src/scrobbler/api/__init__.py b/src/scrobbler/api/__init__.py index a6cfd71..46b960f 100644 --- a/src/scrobbler/api/__init__.py +++ b/src/scrobbler/api/__init__.py @@ -48,7 +48,7 @@ def init_app(app: Flask) -> None: }, ) - from scrobbler.api import apps, auth, health, imports, sessions, stats, tokens, tracks + from scrobbler.api import apps, art, auth, 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") @@ -57,6 +57,7 @@ def init_app(app: Flask) -> None: api.register_blueprint(stats.blp, url_prefix="/api/v1/me") 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(health.blp) from scrobbler.openapi import lastfm diff --git a/src/scrobbler/api/art.py b/src/scrobbler/api/art.py new file mode 100644 index 0000000..56bbec0 --- /dev/null +++ b/src/scrobbler/api/art.py @@ -0,0 +1,42 @@ +from flask import Response +from flask_smorest import Blueprint, abort + +from scrobbler.api.decorators import authenticated +from scrobbler.schemas import AlbumArtArgsSchema, ErrorSchema +from scrobbler.services import art + +blp = Blueprint( + "Art", __name__, description="Album art, proxied from MusicBrainz / Cover Art Archive" +) + + +@blp.route("/album", methods=["GET"]) +@authenticated(blp) +@blp.arguments(AlbumArtArgsSchema, location="query") +@blp.response(200, content_type="image/jpeg", description="The album's cover art") +@blp.alt_response(404, schema=ErrorSchema, description="No cover art found for this album") +@blp.alt_response( + 502, schema=ErrorSchema, description="MusicBrainz or Cover Art Archive is unreachable" +) +def album_art(args): + """An album's cover art + + Resolved via MusicBrainz + Cover Art Archive and cached; bytes are proxied on every + call, so cache this response client-side. + """ + result = art.lookup(args["artist"], args["album"]) + if result.status == "not_found": + abort(404, code="no_album_art", message="No cover art found for this album") + if result.status == "error": + abort( + 502, + code="art_upstream_unavailable", + message="Couldn't reach MusicBrainz or Cover Art Archive", + ) + try: + image = art.fetch_image(result.image_url) + except art.ArtFetchFailed: + abort(502, code="art_upstream_unavailable", message="Couldn't reach Cover Art Archive") + response = Response(image.body, mimetype=image.content_type) + response.headers["Cache-Control"] = "private, max-age=604800" # 7 days; art rarely changes + return response diff --git a/src/scrobbler/config.py b/src/scrobbler/config.py index b16a5d0..49a5edb 100644 --- a/src/scrobbler/config.py +++ b/src/scrobbler/config.py @@ -54,6 +54,17 @@ class Config: LASTFM_API_KEY = os.environ.get("LASTFM_API_KEY", "") LASTFM_API_URL = os.environ.get("LASTFM_API_URL", "https://ws.audioscrobbler.com/2.0/") LASTFM_REQUEST_INTERVAL = float(os.environ.get("LASTFM_REQUEST_INTERVAL", "0.25")) + + # Album art: MusicBrainz release-group search + Cover Art Archive, both free and keyless. + MUSICBRAINZ_API_URL = os.environ.get("MUSICBRAINZ_API_URL", "https://musicbrainz.org/ws/2/") + COVERART_API_URL = os.environ.get("COVERART_API_URL", "https://coverartarchive.org/") + # MusicBrainz requires a descriptive contact in the User-Agent or it throttles/blocks us. + MUSICBRAINZ_CONTACT = os.environ.get("MUSICBRAINZ_CONTACT", "") or UI_BASE_URL + MUSICBRAINZ_REQUEST_INTERVAL = float(os.environ.get("MUSICBRAINZ_REQUEST_INTERVAL", "1.0")) + MUSICBRAINZ_RETRIES = int(os.environ.get("MUSICBRAINZ_RETRIES", "2")) + ART_NOT_FOUND_RETRY_DAYS = int(os.environ.get("ART_NOT_FOUND_RETRY_DAYS", "30")) + ART_ERROR_RETRY_SECONDS = int(os.environ.get("ART_ERROR_RETRY_SECONDS", "3600")) + 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 # IMPORT_WORKER_METRICS_PORT is the pre-0.3 name, still honoured. diff --git a/src/scrobbler/migrations/versions/3ba21eb1ea0c_album_art_cache.py b/src/scrobbler/migrations/versions/3ba21eb1ea0c_album_art_cache.py new file mode 100644 index 0000000..f1c364b --- /dev/null +++ b/src/scrobbler/migrations/versions/3ba21eb1ea0c_album_art_cache.py @@ -0,0 +1,50 @@ +"""album art cache + +Revision ID: 3ba21eb1ea0c +Revises: e7fb730bac15 +Create Date: 2026-10-06 16:58:58.755196 + +""" + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = "3ba21eb1ea0c" +down_revision = "e7fb730bac15" +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table( + "album_art", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("artist", sa.Text(), nullable=False), + sa.Column("album", sa.Text(), nullable=False), + sa.Column("status", sa.String(length=16), nullable=False), + sa.Column("image_url", sa.Text(), nullable=True), + sa.Column("release_group_mbid", sa.String(length=36), nullable=True), + sa.Column("error_code", sa.String(length=64), nullable=True), + sa.Column("checked_at", sa.DateTime(timezone=True), nullable=False), + sa.PrimaryKeyConstraint("id"), + ) + with op.batch_alter_table("album_art", schema=None) as batch_op: + batch_op.create_index( + "uq_album_art_artist_album_lower", + [sa.literal_column("lower(artist)"), sa.literal_column("lower(album)")], + unique=True, + ) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table("album_art", schema=None) as batch_op: + batch_op.drop_index("uq_album_art_artist_album_lower") + + op.drop_table("album_art") + # ### end Alembic commands ### diff --git a/src/scrobbler/models.py b/src/scrobbler/models.py index a6a48d2..7f90ed0 100644 --- a/src/scrobbler/models.py +++ b/src/scrobbler/models.py @@ -157,3 +157,29 @@ class ImportJob(db.Model): started_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) heartbeat_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + + +class AlbumArt(db.Model): + """Cached MusicBrainz + Cover Art Archive lookup for one (artist, album). + + Global, not per-user: this is data about the real-world release, not a user's own data. + A row always exists once looked up — a miss or an error is cached too, so repeat requests + for an album with no art skip the upstream calls until due for a recheck. + """ + + __tablename__ = "album_art" + + id: Mapped[int] = mapped_column(primary_key=True) + artist: Mapped[str] = mapped_column(Text) + album: Mapped[str] = mapped_column(Text) + status: Mapped[str] = mapped_column(String(16)) # found, not_found or error + image_url: Mapped[str | None] = mapped_column(Text) # set iff status == "found" + release_group_mbid: Mapped[str | None] = mapped_column(String(36)) + error_code: Mapped[str | None] = mapped_column(String(64)) # set iff status == "error" + checked_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + + __table_args__ = ( + Index( + "uq_album_art_artist_album_lower", func.lower(artist), func.lower(album), unique=True + ), + ) diff --git a/src/scrobbler/schemas/__init__.py b/src/scrobbler/schemas/__init__.py index f999661..67a098c 100644 --- a/src/scrobbler/schemas/__init__.py +++ b/src/scrobbler/schemas/__init__.py @@ -155,6 +155,11 @@ class TrackDetailArgsSchema(PageArgsSchema): track = fields.String(required=True, validate=validate.Length(min=1, max=500)) +class AlbumArtArgsSchema(Schema): + artist = fields.String(required=True, validate=validate.Length(min=1, max=500)) + album = fields.String(required=True, validate=validate.Length(min=1, max=500)) + + class TrackMetadataSchema(Schema): album = fields.String(allow_none=True) album_artist = fields.String(allow_none=True) diff --git a/src/scrobbler/services/art.py b/src/scrobbler/services/art.py new file mode 100644 index 0000000..e0bd76b --- /dev/null +++ b/src/scrobbler/services/art.py @@ -0,0 +1,169 @@ +"""Album art: MusicBrainz release-group search + Cover Art Archive, both free and keyless. + +Every (artist, album) lookup is cached in `AlbumArt` — a miss or an error is cached too, so +repeat requests for an album we can't find art for don't keep hammering the upstream APIs. +`lookup()` resolves *where* the art is (and never raises); `fetch_image()` streams the bytes +from there. They're kept separate so that storing the bytes ourselves later only needs to +change `fetch_image()`, not the caching/lookup logic. +""" + +import json +import logging +import re +import time +import urllib.error +import urllib.parse +import urllib.request +from dataclasses import dataclass +from datetime import UTC, datetime, timedelta + +from flask import current_app +from sqlalchemy import func, select +from sqlalchemy.dialects.postgresql import insert + +from scrobbler.extensions import db +from scrobbler.models import AlbumArt + +log = logging.getLogger(__name__) + +# Lucene special characters MusicBrainz's search syntax requires escaping. +_LUCENE_SPECIAL = re.compile(r'([+\-&|!(){}\[\]^"~*?:\\/])') + + +def _escape(value: str) -> str: + return _LUCENE_SPECIAL.sub(r"\\\1", value) + + +@dataclass +class ArtResult: + status: str # "found", "not_found" or "error" + image_url: str | None = None + + +@dataclass +class ImageBytes: + body: bytes + content_type: str + + +class ArtFetchFailed(Exception): + """The resolved image URL couldn't be fetched.""" + + +def _user_agent() -> str: + from scrobbler import __version__ + + contact = current_app.config["MUSICBRAINZ_CONTACT"] + return f"Scrobbler/{__version__} ( {contact} )" + + +_last_musicbrainz_call = 0.0 + + +def _throttled_request(url: str, method: str = "GET") -> urllib.request.Request: + global _last_musicbrainz_call + interval = current_app.config["MUSICBRAINZ_REQUEST_INTERVAL"] + wait = interval - (time.monotonic() - _last_musicbrainz_call) + if wait > 0: + time.sleep(wait) + _last_musicbrainz_call = time.monotonic() + return urllib.request.Request(url, method=method, headers={"User-Agent": _user_agent()}) + + +def _stale(row: AlbumArt) -> bool: + if row.status == "found": + return False + now = datetime.now(UTC) + if row.status == "error": + threshold = timedelta(seconds=current_app.config["ART_ERROR_RETRY_SECONDS"]) + else: + threshold = timedelta(days=current_app.config["ART_NOT_FOUND_RETRY_DAYS"]) + return now - row.checked_at > threshold + + +def _find_release_group(artist: str, album: str) -> str | None: + """A matching release-group's MBID, or None if MusicBrainz has no match.""" + api_url = current_app.config["MUSICBRAINZ_API_URL"] + query = f'releasegroup:"{_escape(album)}" AND artist:"{_escape(artist)}"' + params = urllib.parse.urlencode({"query": query, "fmt": "json", "limit": "5"}) + retries = current_app.config["MUSICBRAINZ_RETRIES"] + for attempt in range(retries + 1): + request = _throttled_request(f"{api_url}release-group/?{params}") + try: + with urllib.request.urlopen(request, timeout=10) as response: + body = json.load(response) + except urllib.error.HTTPError as err: + if attempt == retries or err.code < 500: + raise + except (urllib.error.URLError, TimeoutError): + if attempt == retries: + raise + else: + groups = body.get("release-groups") or [] + return groups[0]["id"] if groups else None + time.sleep(min(10, 2**attempt)) + raise TimeoutError("MusicBrainz request exhausted its retries") + + +def _cover_art_url(release_group_mbid: str) -> str | None: + """The release-group's front cover URL, or None if Cover Art Archive has none.""" + coverart_url = current_app.config["COVERART_API_URL"] + url = f"{coverart_url}release-group/{release_group_mbid}/front-500" + request = urllib.request.Request(url, method="HEAD") + try: + with urllib.request.urlopen(request, timeout=10): + return url + except urllib.error.HTTPError as err: + if err.code == 404: + return None + raise + + +def lookup(artist: str, album: str) -> ArtResult: + """Cached (artist, album) art resolution. Never raises.""" + existing = db.session.scalar( + select(AlbumArt).where( + func.lower(AlbumArt.artist) == artist.lower(), + func.lower(AlbumArt.album) == album.lower(), + ) + ) + if existing is not None and not _stale(existing): + return ArtResult(existing.status, existing.image_url) + + release_group_mbid = None + try: + release_group_mbid = _find_release_group(artist, album) + image_url = _cover_art_url(release_group_mbid) if release_group_mbid else None + status = "found" if image_url else "not_found" + result = ArtResult(status, image_url) + error_code = None + except Exception as err: # noqa: BLE001 - any upstream failure degrades to a cached "error" + log.warning("Album art lookup failed for %r/%r: %s", artist, album, err) + result = ArtResult("error") + error_code = type(err).__name__ + + values = { + "artist": artist, + "album": album, + "status": result.status, + "image_url": result.image_url, + "release_group_mbid": release_group_mbid, + "error_code": error_code, + "checked_at": datetime.now(UTC), + } + stmt = insert(AlbumArt).values(**values) + stmt = stmt.on_conflict_do_update( + index_elements=[func.lower(AlbumArt.artist), func.lower(AlbumArt.album)], set_=values + ) + db.session.execute(stmt) + db.session.commit() + return result + + +def fetch_image(image_url: str) -> ImageBytes: + """Streams the bytes from image_url. Raises ArtFetchFailed on any problem.""" + try: + with urllib.request.urlopen(image_url, timeout=10) as response: + return ImageBytes(response.read(), response.headers.get("Content-Type", "image/jpeg")) + except (urllib.error.URLError, TimeoutError) as err: + raise ArtFetchFailed(str(err)) from err diff --git a/tests/test_art.py b/tests/test_art.py new file mode 100644 index 0000000..491041d --- /dev/null +++ b/tests/test_art.py @@ -0,0 +1,234 @@ +import json +import threading +import urllib.parse +from datetime import UTC, datetime, timedelta + +import pytest +from werkzeug.serving import make_server + +from scrobbler.extensions import db +from scrobbler.models import AlbumArt +from scrobbler.services import art + +# Canned release-group matches, keyed by a substring of the Lucene search query we send. +_RELEASE_GROUPS = { + "In Rainbows": "rg-found", # has art + "No Art Album": "rg-no-art", # MB match, but Cover Art Archive has nothing + "Boom Album": "rg-boom", # MB match, but Cover Art Archive 500s +} + + +def _fake_musicbrainz_caa(environ, start_response): + method, path = environ["REQUEST_METHOD"], environ["PATH_INFO"] + + if path == "/release-group/" and method == "GET": + query = urllib.parse.parse_qs(environ.get("QUERY_STRING", ""))["query"][0] + if "Query Boom" in query: + start_response("500 Internal Server Error", [("Content-Type", "text/plain")]) + return [b"boom"] + match = next((v for k, v in _RELEASE_GROUPS.items() if k in query), None) + groups = [{"id": match}] if match else [] + body = json.dumps({"release-groups": groups}).encode() + start_response( + "200 OK", [("Content-Type", "application/json"), ("Content-Length", str(len(body)))] + ) + return [body] + + if path == "/release-group/rg-found/front-500": + body = b"\xff\xd8\xff\xe0fake-jpeg-bytes" + headers = [("Content-Type", "image/jpeg"), ("Content-Length", str(len(body)))] + start_response("200 OK", headers) + return [] if method == "HEAD" else [body] + + if path == "/release-group/rg-boom/front-500": + start_response("500 Internal Server Error", [("Content-Type", "text/plain")]) + return [b"boom"] + + start_response("404 Not Found", [("Content-Type", "text/plain")]) + return [b"not found"] + + +@pytest.fixture(scope="module") +def fake_art_api(): + server = make_server("127.0.0.1", 0, _fake_musicbrainz_caa, threaded=True) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + yield f"http://127.0.0.1:{server.server_port}/" + server.shutdown() + + +@pytest.fixture +def art_config(app, fake_art_api): + keys = ( + "MUSICBRAINZ_API_URL", + "COVERART_API_URL", + "MUSICBRAINZ_REQUEST_INTERVAL", + "MUSICBRAINZ_RETRIES", + ) + saved = {k: app.config[k] for k in keys} + app.config.update( + MUSICBRAINZ_API_URL=fake_art_api, + COVERART_API_URL=fake_art_api, + MUSICBRAINZ_REQUEST_INTERVAL=0, + MUSICBRAINZ_RETRIES=0, + ) + yield + app.config.update(saved) + + +def row(artist, album): + return db.session.scalar( + db.select(AlbumArt).where( + db.func.lower(AlbumArt.artist) == artist.lower(), + db.func.lower(AlbumArt.album) == album.lower(), + ) + ) + + +def insert(artist, album, status, days_ago=0.0, image_url=None): + db.session.add( + AlbumArt( + artist=artist, + album=album, + status=status, + image_url=image_url, + checked_at=datetime.now(UTC) - timedelta(days=days_ago), + ) + ) + db.session.commit() + + +# --- lookup() ------------------------------------------------------------------------------ + + +def test_lookup_finds_art(art_config): + result = art.lookup("Radiohead", "In Rainbows") + assert result.status == "found" + assert result.image_url.endswith("/release-group/rg-found/front-500") + assert row("Radiohead", "In Rainbows").status == "found" + + +def test_lookup_no_musicbrainz_match_is_not_found(art_config): + result = art.lookup("Nobody", "Nothing At All") + assert result == art.ArtResult("not_found") + + +def test_lookup_musicbrainz_match_but_no_cover_art_is_not_found(art_config): + result = art.lookup("Someone", "No Art Album") + assert result == art.ArtResult("not_found") + + +def test_lookup_upstream_error_is_cached_not_raised(app, art_config): + result = art.lookup("Someone", "Boom Album") + assert result.status == "error" + assert row("Someone", "Boom Album").error_code + + +def test_lookup_search_error_is_cached_not_raised(app, art_config): + result = art.lookup("Someone", "Query Boom") + assert result.status == "error" + + +def test_lookup_is_case_insensitive_and_cached(app, art_config): + art.lookup("Radiohead", "In Rainbows") + # Point at a port nothing listens on: if the different-cased call weren't a cache hit on + # the same row, it would fail to reach the network and come back as "error". + app.config.update( + MUSICBRAINZ_API_URL="http://127.0.0.1:1/", COVERART_API_URL="http://127.0.0.1:1/" + ) + result = art.lookup("radiohead", "in rainbows") + assert result.status == "found" + + +def test_lookup_fresh_cache_hit_skips_the_network(app, art_config, fake_art_api): + insert("Fresh Artist", "Fresh Album", "not_found", days_ago=0) + # If this weren't a cache hit, the (nonexistent) search term would still return "not_found" + # from the live fake server too — so instead prove no network call happened by pointing at + # a port nothing listens on and confirming the result is still served from the cache. + app.config.update( + MUSICBRAINZ_API_URL="http://127.0.0.1:1/", COVERART_API_URL="http://127.0.0.1:1/" + ) + result = art.lookup("Fresh Artist", "Fresh Album") + assert result.status == "not_found" + + +def test_stale_not_found_row_is_rechecked(app, art_config): + insert("Radiohead", "In Rainbows", "not_found", days_ago=31) + result = art.lookup("Radiohead", "In Rainbows") + assert result.status == "found" # the live fake server actually has art for this album + + +def test_fresh_not_found_row_is_not_rechecked(app, art_config): + insert("Radiohead", "In Rainbows", "not_found", days_ago=1) + result = art.lookup("Radiohead", "In Rainbows") + assert result.status == "not_found" # cache hit, even though the live server has art + + +def test_stale_error_row_is_rechecked(app, art_config): + db.session.add( + AlbumArt( + artist="Radiohead", + album="In Rainbows", + status="error", + error_code="TimeoutError", + checked_at=datetime.now(UTC) - timedelta(hours=2), + ) + ) + db.session.commit() + result = art.lookup("Radiohead", "In Rainbows") + assert result.status == "found" + + +def test_found_row_is_never_rechecked(app, art_config): + insert( + "Someone", "No Art Album", "found", days_ago=9999, image_url="https://example.com/old.jpg" + ) + result = art.lookup("Someone", "No Art Album") + assert result.image_url == "https://example.com/old.jpg" + + +# --- fetch_image() --------------------------------------------------------------------------- + + +def test_fetch_image_streams_the_bytes(art_config): + result = art.lookup("Radiohead", "In Rainbows") + image = art.fetch_image(result.image_url) + assert image.body == b"\xff\xd8\xff\xe0fake-jpeg-bytes" + assert image.content_type == "image/jpeg" + + +def test_fetch_image_raises_on_failure(art_config): + with pytest.raises(art.ArtFetchFailed): + art.fetch_image("http://127.0.0.1:1/nope.jpg") + + +# --- GET /api/v1/art/album --------------------------------------------------------------------- + + +def test_album_art_requires_auth(client): + assert client.get("/api/v1/art/album?artist=A&album=B").status_code == 401 + + +def test_album_art_returns_the_image(client, auth, art_config): + response = client.get("/api/v1/art/album?artist=Radiohead&album=In+Rainbows", headers=auth) + assert response.status_code == 200 + assert response.data == b"\xff\xd8\xff\xe0fake-jpeg-bytes" + assert response.content_type == "image/jpeg" + assert response.headers["Cache-Control"] == "private, max-age=604800" + + +def test_album_art_404s_when_not_found(client, auth, art_config): + response = client.get("/api/v1/art/album?artist=Nobody&album=Nothing", headers=auth) + assert response.status_code == 404 + assert response.get_json()["error"]["code"] == "no_album_art" + + +def test_album_art_502s_on_upstream_error(client, auth, art_config): + response = client.get("/api/v1/art/album?artist=Someone&album=Boom+Album", headers=auth) + assert response.status_code == 502 + assert response.get_json()["error"]["code"] == "art_upstream_unavailable" + + +def test_album_art_requires_artist_and_album(client, auth): + assert client.get("/api/v1/art/album?artist=A", headers=auth).status_code == 422 + assert client.get("/api/v1/art/album?album=B", headers=auth).status_code == 422