Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6cd17d7586 | ||
|
|
83b27d7ba1 | ||
|
|
79193fbc8e | ||
|
|
2b984cca6e | ||
|
|
44abd70caa | ||
|
|
f106d68921 | ||
|
|
dfd2ef868b | ||
|
|
5bdeeddb0b | ||
|
|
7b169ea807 | ||
|
|
457e051828 |
No files matched your search
@@ -16,6 +16,13 @@ METRICS_PORT=9100
|
|||||||
# Set to allow importing history straight from Last.fm (https://www.last.fm/api/account/create).
|
# Set to allow importing history straight from Last.fm (https://www.last.fm/api/account/create).
|
||||||
LASTFM_API_KEY=
|
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=
|
||||||
|
# Where downloaded art is stored. docker compose points this at a shared volume; the
|
||||||
|
# default below is for running the api/worker directly (not in Docker).
|
||||||
|
ART_STORAGE_DIR=var/album-art
|
||||||
|
|
||||||
# docker compose host ports (defaults shown)
|
# docker compose host ports (defaults shown)
|
||||||
API_PORT=5050
|
API_PORT=5050
|
||||||
UI_PORT=8080
|
UI_PORT=8080
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ htmlcov/
|
|||||||
|
|
||||||
# Runtime
|
# Runtime
|
||||||
prometheus_multiproc/
|
prometheus_multiproc/
|
||||||
|
var/album-art/
|
||||||
|
|
||||||
# IDEs
|
# IDEs
|
||||||
.idea/
|
.idea/
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ server {
|
|||||||
try_files $uri $uri/ =404;
|
try_files $uri $uri/ =404;
|
||||||
# Files aren't fingerprinted, so always revalidate.
|
# Files aren't fingerprinted, so always revalidate.
|
||||||
add_header Cache-Control "no-cache";
|
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 X-Content-Type-Options nosniff always;
|
||||||
add_header Referrer-Policy same-origin always;
|
add_header Referrer-Policy same-origin always;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,6 +34,8 @@ services:
|
|||||||
WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2}
|
WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2}
|
||||||
FORWARDED_ALLOW_IPS: "*"
|
FORWARDED_ALLOW_IPS: "*"
|
||||||
LASTFM_API_KEY: ${LASTFM_API_KEY:-}
|
LASTFM_API_KEY: ${LASTFM_API_KEY:-}
|
||||||
|
MUSICBRAINZ_CONTACT: ${MUSICBRAINZ_CONTACT:-}
|
||||||
|
ART_STORAGE_DIR: ${ART_STORAGE_DIR:-/data/album-art}
|
||||||
FEDERATION_ENABLED: ${FEDERATION_ENABLED:-0}
|
FEDERATION_ENABLED: ${FEDERATION_ENABLED:-0}
|
||||||
FEDERATION_DOMAIN: ${FEDERATION_DOMAIN:-}
|
FEDERATION_DOMAIN: ${FEDERATION_DOMAIN:-}
|
||||||
FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-}
|
FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-}
|
||||||
@@ -42,6 +44,8 @@ services:
|
|||||||
- "${API_PORT:-5050}:8000"
|
- "${API_PORT:-5050}:8000"
|
||||||
expose:
|
expose:
|
||||||
- "9100" # metrics: internal network only
|
- "9100" # metrics: internal network only
|
||||||
|
volumes:
|
||||||
|
- album-art-data:/data/album-art
|
||||||
depends_on:
|
depends_on:
|
||||||
db:
|
db:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
@@ -57,6 +61,8 @@ services:
|
|||||||
DATABASE_URL: postgresql+psycopg://scrobbler:${POSTGRES_PASSWORD:-scrobbler}@db:5432/scrobbler
|
DATABASE_URL: postgresql+psycopg://scrobbler:${POSTGRES_PASSWORD:-scrobbler}@db:5432/scrobbler
|
||||||
SECRET_KEY: ${SECRET_KEY:-change-me}
|
SECRET_KEY: ${SECRET_KEY:-change-me}
|
||||||
LASTFM_API_KEY: ${LASTFM_API_KEY:-}
|
LASTFM_API_KEY: ${LASTFM_API_KEY:-}
|
||||||
|
MUSICBRAINZ_CONTACT: ${MUSICBRAINZ_CONTACT:-}
|
||||||
|
ART_STORAGE_DIR: ${ART_STORAGE_DIR:-/data/album-art}
|
||||||
FEDERATION_ENABLED: ${FEDERATION_ENABLED:-0}
|
FEDERATION_ENABLED: ${FEDERATION_ENABLED:-0}
|
||||||
FEDERATION_DOMAIN: ${FEDERATION_DOMAIN:-}
|
FEDERATION_DOMAIN: ${FEDERATION_DOMAIN:-}
|
||||||
FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-}
|
FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-}
|
||||||
@@ -64,6 +70,8 @@ services:
|
|||||||
RUN_MIGRATIONS: "0" # the api service applies them
|
RUN_MIGRATIONS: "0" # the api service applies them
|
||||||
expose:
|
expose:
|
||||||
- "9101" # metrics: internal network only
|
- "9101" # metrics: internal network only
|
||||||
|
volumes:
|
||||||
|
- album-art-data:/data/album-art
|
||||||
healthcheck:
|
healthcheck:
|
||||||
disable: true
|
disable: true
|
||||||
depends_on:
|
depends_on:
|
||||||
@@ -123,5 +131,6 @@ services:
|
|||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
db-data:
|
db-data:
|
||||||
|
album-art-data:
|
||||||
prometheus-data:
|
prometheus-data:
|
||||||
grafana-data:
|
grafana-data:
|
||||||
@@ -13,6 +13,8 @@ RUN uv sync --locked --no-dev --no-editable
|
|||||||
FROM python:3.13-slim
|
FROM python:3.13-slim
|
||||||
LABEL org.opencontainers.image.licenses="BSD-3-Clause"
|
LABEL org.opencontainers.image.licenses="BSD-3-Clause"
|
||||||
RUN useradd --system --uid 10001 --no-create-home scrobbler
|
RUN useradd --system --uid 10001 --no-create-home scrobbler
|
||||||
|
# Downloaded album art lives here, on a volume shared with the worker (which writes it).
|
||||||
|
RUN mkdir -p /data/album-art && chown scrobbler:scrobbler /data/album-art
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY --from=build /app/.venv /app/.venv
|
COPY --from=build /app/.venv /app/.venv
|
||||||
COPY gunicorn.conf.py docker/api-entrypoint.sh ./
|
COPY gunicorn.conf.py docker/api-entrypoint.sh ./
|
||||||
|
|||||||
+12
-2
@@ -16,8 +16,12 @@ Prometheus ◄── API :9100/metrics, postgres-exporter ──► Grafana
|
|||||||
|
|
||||||
- **`api`**: Flask under gunicorn. API-only; it serves no HTML pages.
|
- **`api`**: Flask under gunicorn. API-only; it serves no HTML pages.
|
||||||
- **`ui`**: nginx serving the static frontend (`frontend/`, no build step).
|
- **`ui`**: nginx serving the static frontend (`frontend/`, no build step).
|
||||||
- **`worker`**: `flask worker` — history imports and background tasks for optional
|
- **`worker`**: `flask worker` — history imports, resolving and downloading album art
|
||||||
modules (federation's deliveries, scheduled posts, and so on).
|
(MusicBrainz + Cover Art Archive), and background tasks for optional modules
|
||||||
|
(federation's deliveries, scheduled posts, and so on). This is the only service that
|
||||||
|
makes outbound calls to third-party APIs (Last.fm, MusicBrainz, Cover Art Archive, and
|
||||||
|
remote fediverse servers with federation on) — worth knowing if you're restricting
|
||||||
|
egress.
|
||||||
- **`db`**: PostgreSQL.
|
- **`db`**: PostgreSQL.
|
||||||
- With the `monitoring` profile: `prometheus`, `grafana`, `postgres-exporter`.
|
- With the `monitoring` profile: `prometheus`, `grafana`, `postgres-exporter`.
|
||||||
|
|
||||||
@@ -54,6 +58,8 @@ read **Putting it behind TLS** below — the quick start above serves plain HTTP
|
|||||||
| `WEB_CONCURRENCY` | api | `2` | gunicorn workers |
|
| `WEB_CONCURRENCY` | api | `2` | gunicorn workers |
|
||||||
| `RUN_MIGRATIONS` | api image | `1` | Apply database migrations on start |
|
| `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)) |
|
| `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, worker | `UI_BASE_URL` | Contact URL/email sent to MusicBrainz for album art lookups (no key needed, but they ask for one) |
|
||||||
|
| `ART_STORAGE_DIR` | api, worker | `var/album-art` | Where downloaded album art is stored; the worker writes it, the api serves it — both need access to the same directory (`docker compose` mounts a shared volume there) |
|
||||||
| `IMPORT_MAX_BYTES` | api | 200 MB | Largest export file accepted |
|
| `IMPORT_MAX_BYTES` | api | 200 MB | Largest export file accepted |
|
||||||
| `WORKER_METRICS_PORT` | worker | `9101` | The worker's Prometheus metrics port |
|
| `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 |
|
| `API_BASE_URL` | ui image | `http://localhost:5050` | Where the browser reaches the API — written into `config.js` and the CSP |
|
||||||
@@ -186,6 +192,10 @@ Restoring an older dump with federation on will leave followers pointed at posts
|
|||||||
longer exist and profile data that's gone stale — expected after any point-in-time
|
longer exist and profile data that's gone stale — expected after any point-in-time
|
||||||
restore, not a sign anything's broken.
|
restore, not a sign anything's broken.
|
||||||
|
|
||||||
|
The `album-art-data` volume is just a disposable cache of downloaded cover art — losing it
|
||||||
|
isn't a data-loss event, the worker simply re-downloads anything missing the next time it's
|
||||||
|
requested. No need to include it in backups.
|
||||||
|
|
||||||
## Upgrades
|
## Upgrades
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
|
|||||||
@@ -1503,6 +1503,73 @@
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
"/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"
|
||||||
|
},
|
||||||
|
"404": {
|
||||||
|
"description": "No cover art available yet",
|
||||||
|
"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": "Served from a local cache that a background worker task keeps filled; this endpoint\nnever makes a live MusicBrainz/Cover Art Archive call, so it can't be slowed down by\none. An album seen for the first time returns 404 until the worker resolves it,\ntypically within a few seconds - cache this response client-side and retry later.",
|
||||||
|
"tags": [
|
||||||
|
"Art"
|
||||||
|
],
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"bearerAuth": []
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
"/healthz": {
|
"/healthz": {
|
||||||
"get": {
|
"get": {
|
||||||
"responses": {
|
"responses": {
|
||||||
@@ -3374,6 +3441,10 @@
|
|||||||
"name": "Imports",
|
"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."
|
"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, resolved from MusicBrainz / Cover Art Archive by a background worker"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"name": "Health",
|
"name": "Health",
|
||||||
"description": "Liveness for load balancers and containers"
|
"description": "Liveness for load balancers and containers"
|
||||||
|
|||||||
@@ -625,6 +625,22 @@ input {
|
|||||||
color: var(--ink-soft);
|
color: var(--ink-soft);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Stack the track above a muted artist line and make the cell a link, like .ranking rows */
|
||||||
|
.log-stacked .by {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-stacked li a {
|
||||||
|
display: block;
|
||||||
|
color: inherit;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-stacked li a:hover,
|
||||||
|
.log-stacked li a:focus-visible {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
.log-day {
|
.log-day {
|
||||||
margin: 2rem 0 0.25rem;
|
margin: 2rem 0 0.25rem;
|
||||||
font-size: var(--step-0);
|
font-size: var(--step-0);
|
||||||
@@ -1063,3 +1079,73 @@ input {
|
|||||||
margin: 0;
|
margin: 0;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* The song page's glowing display gets an art thumbnail alongside its text, when there's one */
|
||||||
|
.display-with-art {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.display-with-art .display-body {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.display-art {
|
||||||
|
width: 4.5rem;
|
||||||
|
height: 4.5rem;
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- Album art ---------------------------------------------------------------- */
|
||||||
|
.art-thumb {
|
||||||
|
display: block;
|
||||||
|
border-radius: var(--radius-control);
|
||||||
|
object-fit: cover;
|
||||||
|
background: var(--paper-raised);
|
||||||
|
border: 1px solid var(--rule);
|
||||||
|
}
|
||||||
|
|
||||||
|
.art-thumb-empty {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* No artwork: a plain ring, echoing .brand-mark's small round "lamp" motif */
|
||||||
|
.art-thumb-empty::after {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
inset: 32%;
|
||||||
|
border-radius: 50%;
|
||||||
|
border: 2px solid var(--bar);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Most played > Albums: a thumbnail column ahead of the rank */
|
||||||
|
.ranking-art li {
|
||||||
|
grid-template-columns: 2.25rem 2rem minmax(0, 1fr) auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ranking-art .art-thumb {
|
||||||
|
width: 2.25rem;
|
||||||
|
height: 2.25rem;
|
||||||
|
align-self: center; /* .ranking li aligns its other cells to baseline, which suits text, not art */
|
||||||
|
}
|
||||||
|
|
||||||
|
.ranking-art .meter {
|
||||||
|
left: 5.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Recently played / History: a thumbnail column ahead of the time */
|
||||||
|
.log-art li {
|
||||||
|
grid-template-columns: 2.25rem 8rem minmax(0, 1fr);
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-art.log-clock li {
|
||||||
|
grid-template-columns: 2.25rem 3.5rem minmax(0, 1fr);
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-art .art-thumb {
|
||||||
|
width: 2.25rem;
|
||||||
|
height: 2.25rem;
|
||||||
|
align-self: center; /* .log li items default to stretch/start, which suits text, not art */
|
||||||
|
}
|
||||||
+2
-2
@@ -31,7 +31,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="charts">
|
<div class="charts">
|
||||||
<div><h3 class="muted">Artists</h3><ol class="ranking" id="top-artists"></ol></div>
|
<div><h3 class="muted">Artists</h3><ol class="ranking" id="top-artists"></ol></div>
|
||||||
<div><h3 class="muted">Albums</h3><ol class="ranking" id="top-albums"></ol></div>
|
<div><h3 class="muted">Albums</h3><ol class="ranking ranking-art" id="top-albums"></ol></div>
|
||||||
<div><h3 class="muted">Tracks</h3><ol class="ranking" id="top-tracks"></ol></div>
|
<div><h3 class="muted">Tracks</h3><ol class="ranking" id="top-tracks"></ol></div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
@@ -40,7 +40,7 @@
|
|||||||
<h2 id="recent-title">Recently played</h2>
|
<h2 id="recent-title">Recently played</h2>
|
||||||
<a href="history.html">Full history</a>
|
<a href="history.html">Full history</a>
|
||||||
</div>
|
</div>
|
||||||
<ol class="log" id="recent"></ol>
|
<ol class="log log-stacked log-art" id="recent"></ol>
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -40,6 +40,29 @@ export function redirectToLogin() {
|
|||||||
location.href = `login.html?next=${encodeURIComponent(safeNext(here + location.search))}`;
|
location.href = `login.html?next=${encodeURIComponent(safeNext(here + location.search))}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Fetches a binary resource (e.g. album art) with the same bearer-auth transport as api(),
|
||||||
|
// returning a blob: object URL, or null on any failure (including a 404 "no art" response) -
|
||||||
|
// the caller treats "missing" and "couldn't fetch" the same way: show a placeholder.
|
||||||
|
export async function fetchImage(path) {
|
||||||
|
const headers = {};
|
||||||
|
const token = getToken();
|
||||||
|
if (token) headers.Authorization = `Bearer ${token}`;
|
||||||
|
|
||||||
|
let response;
|
||||||
|
try {
|
||||||
|
response = await fetch(`${apiBase}/api/v1${path}`, { headers });
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (response.status === 401) {
|
||||||
|
setToken(null);
|
||||||
|
redirectToLogin();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (!response.ok) return null;
|
||||||
|
return URL.createObjectURL(await response.blob());
|
||||||
|
}
|
||||||
|
|
||||||
export async function api(path, { method = "GET", body, auth = true } = {}) {
|
export async function api(path, { method = "GET", body, auth = true } = {}) {
|
||||||
const headers = {};
|
const headers = {};
|
||||||
if (body !== undefined) headers["Content-Type"] = "application/json";
|
if (body !== undefined) headers["Content-Type"] = "application/json";
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
// A small thumbnail that starts as a placeholder and swaps itself for the real album art
|
||||||
|
// once (if) it resolves. Shared by every list/page that shows art.
|
||||||
|
|
||||||
|
import { fetchImage } from "./api.js";
|
||||||
|
import { h } from "./dom.js";
|
||||||
|
|
||||||
|
const cache = new Map(); // dedupes repeat/concurrent lookups for the same album within a page
|
||||||
|
|
||||||
|
export function artThumb(artist, album, extraClass) {
|
||||||
|
const classes = extraClass ? `art-thumb ${extraClass}` : "art-thumb";
|
||||||
|
const el = h("div", { class: `${classes} art-thumb-empty` });
|
||||||
|
if (!album) return el; // nothing to look up
|
||||||
|
|
||||||
|
const key = `${artist.toLowerCase()}␟${album.toLowerCase()}`;
|
||||||
|
if (!cache.has(key)) {
|
||||||
|
cache.set(
|
||||||
|
key,
|
||||||
|
fetchImage(`/art/album?artist=${encodeURIComponent(artist)}&album=${encodeURIComponent(album)}`),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
cache.get(key).then((url) => {
|
||||||
|
if (!url) return; // miss or failed fetch: leave the placeholder
|
||||||
|
// Not revoked: the same URL is shared by every thumbnail for this album on the page
|
||||||
|
// (see `cache` above), and this is a full-page-reload site, so the browser releases it
|
||||||
|
// on navigation anyway.
|
||||||
|
const img = h("img", { class: classes, alt: "", loading: "lazy" });
|
||||||
|
img.src = url;
|
||||||
|
el.replaceWith(img);
|
||||||
|
});
|
||||||
|
return el;
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { api } from "./api.js";
|
import { api } from "./api.js";
|
||||||
|
import { artThumb } from "./art.js";
|
||||||
import { errorBox, formatDuration, h, num, replace, timeAgo } from "./dom.js";
|
import { errorBox, formatDuration, h, num, replace, timeAgo } from "./dom.js";
|
||||||
import { signedInPage } from "./layout.js";
|
import { signedInPage } from "./layout.js";
|
||||||
import { spectrum } from "./spectrum.js";
|
import { spectrum } from "./spectrum.js";
|
||||||
@@ -157,16 +158,17 @@ async function loadTop(period) {
|
|||||||
api(`/me/top/tracks?period=${period}&limit=10`),
|
api(`/me/top/tracks?period=${period}&limit=10`),
|
||||||
]);
|
]);
|
||||||
renderRanking(document.getElementById("top-artists"), artists.items, false);
|
renderRanking(document.getElementById("top-artists"), artists.items, false);
|
||||||
renderRanking(document.getElementById("top-albums"), albums.items, true);
|
renderRanking(document.getElementById("top-albums"), albums.items, true, false, true);
|
||||||
renderRanking(document.getElementById("top-tracks"), tracks.items, true, true);
|
renderRanking(document.getElementById("top-tracks"), tracks.items, true, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderRanking(list, items, withArtist, linkToSong = false) {
|
function renderRanking(list, items, withArtist, linkToSong = false, withArt = false) {
|
||||||
if (!items.length) {
|
if (!items.length) {
|
||||||
replace(list, h("li", { class: "empty" }, "No plays in this period."));
|
replace(list, h("li", { class: "empty" }, "No plays in this period."));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const max = items[0].playcount;
|
const max = items[0].playcount;
|
||||||
|
const meterOffset = withArt ? "5.75rem" : "2.75rem";
|
||||||
replace(
|
replace(
|
||||||
list,
|
list,
|
||||||
items.map((item) => {
|
items.map((item) => {
|
||||||
@@ -177,13 +179,14 @@ function renderRanking(list, items, withArtist, linkToSong = false) {
|
|||||||
return h(
|
return h(
|
||||||
"li",
|
"li",
|
||||||
{},
|
{},
|
||||||
|
withArt ? artThumb(item.artist, item.name) : null,
|
||||||
h("span", { class: "rank" }, item.rank),
|
h("span", { class: "rank" }, item.rank),
|
||||||
name,
|
name,
|
||||||
h("span", { class: "plays" }, num(item.playcount)),
|
h("span", { class: "plays" }, num(item.playcount)),
|
||||||
h("span", {
|
h("span", {
|
||||||
class: "meter",
|
class: "meter",
|
||||||
"aria-hidden": "true",
|
"aria-hidden": "true",
|
||||||
style: `width: calc((100% - 2.75rem) * ${item.playcount / max})`,
|
style: `width: calc((100% - ${meterOffset}) * ${item.playcount / max})`,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}),
|
}),
|
||||||
@@ -261,8 +264,14 @@ async function loadRecent() {
|
|||||||
h(
|
h(
|
||||||
"li",
|
"li",
|
||||||
{},
|
{},
|
||||||
|
artThumb(s.album_artist || s.artist, s.album),
|
||||||
h("time", { datetime: s.played_at, title: new Date(s.played_at).toLocaleString() }, timeAgo(s.played_at)),
|
h("time", { datetime: s.played_at, title: new Date(s.played_at).toLocaleString() }, timeAgo(s.played_at)),
|
||||||
h("span", {}, h("span", { class: "track" }, s.track), h("span", { class: "by" }, ` by ${s.artist}`)),
|
h(
|
||||||
|
"a",
|
||||||
|
{ href: songHref(s.artist, s.track) },
|
||||||
|
h("span", { class: "track" }, s.track),
|
||||||
|
h("span", { class: "by" }, s.artist),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { api } from "./api.js";
|
import { api } from "./api.js";
|
||||||
|
import { artThumb } from "./art.js";
|
||||||
import { errorBox, formatDay, formatTime, h, num, replace } from "./dom.js";
|
import { errorBox, formatDay, formatTime, h, num, replace } from "./dom.js";
|
||||||
import { signedInPage } from "./layout.js";
|
import { signedInPage } from "./layout.js";
|
||||||
|
|
||||||
@@ -38,11 +39,12 @@ function render(result) {
|
|||||||
h("h2", { class: "log-day" }, formatDay(scrobbles[0].played_at)),
|
h("h2", { class: "log-day" }, formatDay(scrobbles[0].played_at)),
|
||||||
h(
|
h(
|
||||||
"ol",
|
"ol",
|
||||||
{ class: "log log-clock" },
|
{ class: "log log-clock log-art" },
|
||||||
scrobbles.map((s) =>
|
scrobbles.map((s) =>
|
||||||
h(
|
h(
|
||||||
"li",
|
"li",
|
||||||
{},
|
{},
|
||||||
|
artThumb(s.album_artist || s.artist, s.album),
|
||||||
h("time", { datetime: s.played_at }, formatTime(s.played_at)),
|
h("time", { datetime: s.played_at }, formatTime(s.played_at)),
|
||||||
h(
|
h(
|
||||||
"span",
|
"span",
|
||||||
|
|||||||
+6
-2
@@ -1,4 +1,5 @@
|
|||||||
import { api } from "./api.js";
|
import { api } from "./api.js";
|
||||||
|
import { artThumb } from "./art.js";
|
||||||
import { errorBox, formatDate, formatDay, formatDuration, formatTime, h, num, replace } from "./dom.js";
|
import { errorBox, formatDate, formatDay, formatDuration, formatTime, h, num, replace } from "./dom.js";
|
||||||
import { signedInPage } from "./layout.js";
|
import { signedInPage } from "./layout.js";
|
||||||
import { spectrum } from "./spectrum.js";
|
import { spectrum } from "./spectrum.js";
|
||||||
@@ -38,9 +39,9 @@ function render(result) {
|
|||||||
document.title = `${result.track} · Scrobbler`;
|
document.title = `${result.track} · Scrobbler`;
|
||||||
const m = result.metadata;
|
const m = result.metadata;
|
||||||
|
|
||||||
const display = h(
|
const body = h(
|
||||||
"div",
|
"div",
|
||||||
{ class: "display" },
|
{ class: "display-body" },
|
||||||
h("p", { class: "display-status" }, "Now viewing"),
|
h("p", { class: "display-status" }, "Now viewing"),
|
||||||
h("p", { class: "display-track" }, result.track),
|
h("p", { class: "display-track" }, result.track),
|
||||||
h(
|
h(
|
||||||
@@ -50,6 +51,9 @@ function render(result) {
|
|||||||
m.album ? [" from ", h("strong", {}, m.album)] : null,
|
m.album ? [" from ", h("strong", {}, m.album)] : null,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
const display = m.album
|
||||||
|
? h("div", { class: "display display-with-art" }, artThumb(m.album_artist || result.artist, m.album, "display-art"), body)
|
||||||
|
: h("div", { class: "display" }, body);
|
||||||
replace(panel, display, readouts(m), spectrum(result.counts, `Plays of ${result.track}`, "90 days"));
|
replace(panel, display, readouts(m), spectrum(result.counts, `Plays of ${result.track}`, "90 days"));
|
||||||
|
|
||||||
const row = (label, value) =>
|
const row = (label, value) =>
|
||||||
|
|||||||
@@ -42,11 +42,13 @@ def create_app(config_object=None):
|
|||||||
)
|
)
|
||||||
|
|
||||||
from scrobbler.cli import imports_cli, worker_command
|
from scrobbler.cli import imports_cli, worker_command
|
||||||
|
from scrobbler.services import art as art_service
|
||||||
from scrobbler.services import imports as import_service
|
from scrobbler.services import imports as import_service
|
||||||
|
|
||||||
app.cli.add_command(worker_command)
|
app.cli.add_command(worker_command)
|
||||||
app.cli.add_command(imports_cli)
|
app.cli.add_command(imports_cli)
|
||||||
import_service.register_worker_tasks(app)
|
import_service.register_worker_tasks(app)
|
||||||
|
art_service.register_worker_tasks(app)
|
||||||
|
|
||||||
from scrobbler.metrics import db as db_metrics
|
from scrobbler.metrics import db as db_metrics
|
||||||
|
|
||||||
|
|||||||
@@ -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(auth.blp, url_prefix="/api/v1/auth")
|
||||||
api.register_blueprint(apps.blp, url_prefix="/api/v1/apps")
|
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(stats.blp, url_prefix="/api/v1/me")
|
||||||
api.register_blueprint(tracks.blp, url_prefix="/api/v1/me/tracks")
|
api.register_blueprint(tracks.blp, url_prefix="/api/v1/me/tracks")
|
||||||
api.register_blueprint(imports.blp, url_prefix="/api/v1/imports")
|
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)
|
api.register_blueprint(health.blp)
|
||||||
|
|
||||||
from scrobbler.openapi import lastfm
|
from scrobbler.openapi import lastfm
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
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, resolved from MusicBrainz / Cover Art Archive by a background worker",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@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 available yet")
|
||||||
|
def album_art(args):
|
||||||
|
"""An album's cover art
|
||||||
|
|
||||||
|
Served from a local cache that a background worker task keeps filled; this endpoint
|
||||||
|
never makes a live MusicBrainz/Cover Art Archive call, so it can't be slowed down by
|
||||||
|
one. An album seen for the first time returns 404 until the worker resolves it,
|
||||||
|
typically within a few seconds - cache this response client-side and retry later.
|
||||||
|
"""
|
||||||
|
row = art.get_cached(args["artist"], args["album"])
|
||||||
|
if row is None:
|
||||||
|
art.want(args["artist"], args["album"])
|
||||||
|
abort(404, code="no_album_art", message="Not resolved yet")
|
||||||
|
image = art.read_file(row.id) if row.status == "found" else None
|
||||||
|
if image is None:
|
||||||
|
if row.status == "found":
|
||||||
|
art.requeue(row) # resolved before, but the file is missing - ask again
|
||||||
|
abort(404, code="no_album_art", message="No cover art found for this album")
|
||||||
|
response = Response(image, mimetype="image/jpeg")
|
||||||
|
response.headers["Cache-Control"] = "private, max-age=604800" # 7 days; art rarely changes
|
||||||
|
return response
|
||||||
@@ -54,6 +54,20 @@ class Config:
|
|||||||
LASTFM_API_KEY = os.environ.get("LASTFM_API_KEY", "")
|
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_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"))
|
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"))
|
||||||
|
# Downloaded art is kept here, named by the album_art row's id. Needs write access
|
||||||
|
# from the worker (which downloads it) and read access from the api (which serves it).
|
||||||
|
ART_STORAGE_DIR = os.environ.get("ART_STORAGE_DIR", "var/album-art")
|
||||||
|
|
||||||
IMPORT_MAX_BYTES = int(os.environ.get("IMPORT_MAX_BYTES", str(200 * 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
|
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.
|
# IMPORT_WORKER_METRICS_PORT is the pre-0.3 name, still honoured.
|
||||||
|
|||||||
@@ -250,10 +250,11 @@ def note(
|
|||||||
to: list[str],
|
to: list[str],
|
||||||
cc: list[str],
|
cc: list[str],
|
||||||
tags: list[str] = (),
|
tags: list[str] = (),
|
||||||
|
attachment: list[dict] = (),
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""A post (weekly summary or milestone). No `@context`: it's always embedded in the
|
"""A post (now playing, weekly summary or milestone). No `@context`: it's always
|
||||||
Create that carries the same addressing, as Mastodon does."""
|
embedded in the Create that carries the same addressing, as Mastodon does."""
|
||||||
return {
|
doc = {
|
||||||
"id": note_id,
|
"id": note_id,
|
||||||
"type": "Note",
|
"type": "Note",
|
||||||
"attributedTo": actor_id,
|
"attributedTo": actor_id,
|
||||||
@@ -266,6 +267,9 @@ def note(
|
|||||||
"tag": [hashtag(t) for t in tags],
|
"tag": [hashtag(t) for t in tags],
|
||||||
"sensitive": False,
|
"sensitive": False,
|
||||||
}
|
}
|
||||||
|
if attachment:
|
||||||
|
doc["attachment"] = list(attachment)
|
||||||
|
return doc
|
||||||
|
|
||||||
|
|
||||||
def create(activity_id: str, actor_id: str, obj: dict, *, to: list[str], cc: list[str]) -> dict:
|
def create(activity_id: str, actor_id: str, obj: dict, *, to: list[str], cc: list[str]) -> dict:
|
||||||
|
|||||||
@@ -87,6 +87,7 @@ def publish(
|
|||||||
text: str,
|
text: str,
|
||||||
html: str,
|
html: str,
|
||||||
tags: tuple[str, ...] = DEFAULT_TAGS,
|
tags: tuple[str, ...] = DEFAULT_TAGS,
|
||||||
|
attachment: list[dict] = (),
|
||||||
) -> FederationPost | None:
|
) -> FederationPost | None:
|
||||||
"""Post `text`/`html` for the user, keyed by `kind:key`.
|
"""Post `text`/`html` for the user, keyed by `kind:key`.
|
||||||
|
|
||||||
@@ -116,6 +117,7 @@ def publish(
|
|||||||
to=to,
|
to=to,
|
||||||
cc=cc,
|
cc=cc,
|
||||||
tags=list(tags),
|
tags=list(tags),
|
||||||
|
attachment=list(attachment),
|
||||||
)
|
)
|
||||||
# activity.id is a Python-generated UUID (see activities.store), so it's already
|
# activity.id is a Python-generated UUID (see activities.store), so it's already
|
||||||
# usable below without a flush.
|
# usable below without a flush.
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ from scrobbler.federation import activities, actors, followers, publishing, shar
|
|||||||
from scrobbler.federation import metrics as fed_metrics
|
from scrobbler.federation import metrics as fed_metrics
|
||||||
from scrobbler.federation.models import FederationNowPlaying, FederationPost, FederationSettings
|
from scrobbler.federation.models import FederationNowPlaying, FederationPost, FederationSettings
|
||||||
from scrobbler.federation.protocol import content, vocab
|
from scrobbler.federation.protocol import content, vocab
|
||||||
from scrobbler.services import accounts
|
from scrobbler.services import accounts, art
|
||||||
from scrobbler.services.scrobbles import get_now_playing
|
from scrobbler.services.scrobbles import get_now_playing
|
||||||
|
|
||||||
KIND = "now_playing"
|
KIND = "now_playing"
|
||||||
@@ -80,10 +80,36 @@ def _build_content(playing) -> tuple[str, str]:
|
|||||||
return text, html
|
return text, html
|
||||||
|
|
||||||
|
|
||||||
|
def _attachment_for(playing) -> list[dict]:
|
||||||
|
"""Cover art for the post, if we have an album and can resolve it. Cover Art
|
||||||
|
Archive's sized convenience endpoints (what art.lookup() resolves to) are always
|
||||||
|
JPEG, whatever the original upload was."""
|
||||||
|
if not playing.album:
|
||||||
|
return []
|
||||||
|
result = art.lookup(playing.artist, playing.album)
|
||||||
|
if result.status != "found":
|
||||||
|
return []
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"type": "Image",
|
||||||
|
"mediaType": "image/jpeg",
|
||||||
|
"url": result.image_url,
|
||||||
|
"name": f"Cover art for {playing.album}",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
def _post_now_playing(user, playing, key: str, state: FederationNowPlaying, now: datetime) -> str:
|
def _post_now_playing(user, playing, key: str, state: FederationNowPlaying, now: datetime) -> str:
|
||||||
text, html = _build_content(playing)
|
text, html = _build_content(playing)
|
||||||
post = publishing.publish(
|
post = publishing.publish(
|
||||||
user.id, user.username, KIND, key, text=text, html=html, tags=("Scrobbler", "NowPlaying")
|
user.id,
|
||||||
|
user.username,
|
||||||
|
KIND,
|
||||||
|
key,
|
||||||
|
text=text,
|
||||||
|
html=html,
|
||||||
|
tags=("Scrobbler", "NowPlaying"),
|
||||||
|
attachment=_attachment_for(playing),
|
||||||
)
|
)
|
||||||
if post is None:
|
if post is None:
|
||||||
return "none"
|
return "none"
|
||||||
|
|||||||
@@ -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 ###
|
||||||
@@ -157,3 +157,29 @@ class ImportJob(db.Model):
|
|||||||
started_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
started_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||||
finished_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))
|
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
|
||||||
|
),
|
||||||
|
)
|
||||||
@@ -155,6 +155,11 @@ class TrackDetailArgsSchema(PageArgsSchema):
|
|||||||
track = fields.String(required=True, validate=validate.Length(min=1, max=500))
|
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):
|
class TrackMetadataSchema(Schema):
|
||||||
album = fields.String(allow_none=True)
|
album = fields.String(allow_none=True)
|
||||||
album_artist = fields.String(allow_none=True)
|
album_artist = fields.String(allow_none=True)
|
||||||
|
|||||||
@@ -0,0 +1,307 @@
|
|||||||
|
"""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.
|
||||||
|
|
||||||
|
`lookup()` itself is still a live, synchronous resolution — fine for its one caller
|
||||||
|
(`federation/publishing/now_playing.py`, already running from a background worker task, not
|
||||||
|
a request). The web-facing `/api/v1/art/album` endpoint does NOT call `lookup()`: it only
|
||||||
|
ever reads via `get_cached()`/`read_file()`, both pure local reads with no network call, so
|
||||||
|
a page can never be slowed down by a MusicBrainz/Cover Art Archive round trip. A cache miss
|
||||||
|
there calls `want()` (a fast DB write, "please resolve this") instead, and a background
|
||||||
|
worker task (`resolve_one_pending()`, registered by `register_worker_tasks()`) does the
|
||||||
|
actual resolving plus downloading the image bytes to `ART_STORAGE_DIR`, completely
|
||||||
|
decoupled from any request.
|
||||||
|
"""
|
||||||
|
|
||||||
|
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 pathlib import Path
|
||||||
|
|
||||||
|
from flask import current_app
|
||||||
|
from sqlalchemy import func, or_, 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.
|
||||||
|
|
||||||
|
Cover Art Archive redirects to archive.org for the actual image, which is
|
||||||
|
occasionally slow — retried the same way as the MusicBrainz search, with a longer
|
||||||
|
per-attempt timeout to give that redirect room.
|
||||||
|
"""
|
||||||
|
coverart_url = current_app.config["COVERART_API_URL"]
|
||||||
|
url = f"{coverart_url}release-group/{release_group_mbid}/front-500"
|
||||||
|
retries = current_app.config["MUSICBRAINZ_RETRIES"]
|
||||||
|
for attempt in range(retries + 1):
|
||||||
|
request = urllib.request.Request(url, method="HEAD")
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(request, timeout=15):
|
||||||
|
return url
|
||||||
|
except urllib.error.HTTPError as err:
|
||||||
|
if err.code == 404:
|
||||||
|
return None
|
||||||
|
if attempt == retries or err.code < 500:
|
||||||
|
raise
|
||||||
|
except (urllib.error.URLError, TimeoutError):
|
||||||
|
if attempt == retries:
|
||||||
|
raise
|
||||||
|
time.sleep(min(10, 2**attempt))
|
||||||
|
raise TimeoutError("Cover Art Archive request exhausted its retries")
|
||||||
|
|
||||||
|
|
||||||
|
def get_cached(artist: str, album: str) -> AlbumArt | None:
|
||||||
|
"""Plain cache read by (artist, album). No network, no write."""
|
||||||
|
return db.session.scalar(
|
||||||
|
select(AlbumArt).where(
|
||||||
|
func.lower(AlbumArt.artist) == artist.lower(),
|
||||||
|
func.lower(AlbumArt.album) == album.lower(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve(artist: str, album: str) -> tuple[ArtResult, str | None, str | None]:
|
||||||
|
"""Live MusicBrainz + Cover Art Archive resolution, no caching involved. Returns
|
||||||
|
(result, release_group_mbid, error_code). Never raises."""
|
||||||
|
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"
|
||||||
|
return ArtResult(status, image_url), release_group_mbid, 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)
|
||||||
|
return ArtResult("error"), release_group_mbid, type(err).__name__
|
||||||
|
|
||||||
|
|
||||||
|
def _store(
|
||||||
|
artist: str,
|
||||||
|
album: str,
|
||||||
|
result: ArtResult,
|
||||||
|
release_group_mbid: str | None,
|
||||||
|
error_code: str | None,
|
||||||
|
) -> None:
|
||||||
|
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()
|
||||||
|
|
||||||
|
|
||||||
|
def lookup(artist: str, album: str) -> ArtResult:
|
||||||
|
"""Cached (artist, album) art resolution, resolving live on a cache miss. Never
|
||||||
|
raises. Used by ActivityPub posting, which already runs from a worker task - not
|
||||||
|
used by the web-facing endpoint, which must never block on a live lookup (see
|
||||||
|
get_cached()/want() below)."""
|
||||||
|
existing = get_cached(artist, album)
|
||||||
|
if existing is not None and not _stale(existing):
|
||||||
|
return ArtResult(existing.status, existing.image_url)
|
||||||
|
result, release_group_mbid, error_code = _resolve(artist, album)
|
||||||
|
_store(artist, album, result, release_group_mbid, error_code)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def want(artist: str, album: str) -> None:
|
||||||
|
"""Record that we'd like art for (artist, album), for the background worker to
|
||||||
|
resolve. A fast, network-free write; a no-op if a row already exists (any status)."""
|
||||||
|
stmt = insert(AlbumArt).values(
|
||||||
|
artist=artist, album=album, status="pending", checked_at=datetime.now(UTC)
|
||||||
|
)
|
||||||
|
stmt = stmt.on_conflict_do_nothing(
|
||||||
|
index_elements=[func.lower(AlbumArt.artist), func.lower(AlbumArt.album)]
|
||||||
|
)
|
||||||
|
db.session.execute(stmt)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def requeue(row: AlbumArt) -> None:
|
||||||
|
"""Asks the worker to (re)resolve a row - used when a 'found' row's file has gone
|
||||||
|
missing (e.g. one resolved before local file storage existed)."""
|
||||||
|
row.status = "pending"
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def _file_path(row_id: int) -> Path:
|
||||||
|
return Path(current_app.config["ART_STORAGE_DIR"]) / f"{row_id}.jpg"
|
||||||
|
|
||||||
|
|
||||||
|
def read_file(row_id: int) -> bytes | None:
|
||||||
|
"""The downloaded image bytes for a resolved row, or None if not downloaded."""
|
||||||
|
try:
|
||||||
|
return _file_path(row_id).read_bytes()
|
||||||
|
except FileNotFoundError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
# --- Worker --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _claim_pending() -> AlbumArt | None:
|
||||||
|
"""Atomically takes one row due for resolution (new, or a stale not_found/error)."""
|
||||||
|
not_found_cutoff = datetime.now(UTC) - timedelta(
|
||||||
|
days=current_app.config["ART_NOT_FOUND_RETRY_DAYS"]
|
||||||
|
)
|
||||||
|
error_cutoff = datetime.now(UTC) - timedelta(
|
||||||
|
seconds=current_app.config["ART_ERROR_RETRY_SECONDS"]
|
||||||
|
)
|
||||||
|
row = db.session.scalar(
|
||||||
|
select(AlbumArt)
|
||||||
|
.where(
|
||||||
|
or_(
|
||||||
|
AlbumArt.status == "pending",
|
||||||
|
(AlbumArt.status == "not_found") & (AlbumArt.checked_at < not_found_cutoff),
|
||||||
|
(AlbumArt.status == "error") & (AlbumArt.checked_at < error_cutoff),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.order_by(AlbumArt.checked_at)
|
||||||
|
.limit(1)
|
||||||
|
.with_for_update(skip_locked=True)
|
||||||
|
)
|
||||||
|
if row is None:
|
||||||
|
db.session.rollback()
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_one_pending() -> bool:
|
||||||
|
"""Worker task: resolve one row that's pending or due for a recheck, downloading
|
||||||
|
and saving its image bytes when found. Returns True if it processed a row (call
|
||||||
|
again immediately), False if there was nothing to do."""
|
||||||
|
row = _claim_pending()
|
||||||
|
if row is None:
|
||||||
|
return False
|
||||||
|
|
||||||
|
result, release_group_mbid, error_code = _resolve(row.artist, row.album)
|
||||||
|
if result.status == "found":
|
||||||
|
try:
|
||||||
|
image = fetch_image(result.image_url)
|
||||||
|
path = _file_path(row.id)
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
path.write_bytes(image.body)
|
||||||
|
except ArtFetchFailed as err:
|
||||||
|
log.warning("Album art download failed for %r/%r: %s", row.artist, row.album, err)
|
||||||
|
result, error_code = ArtResult("error"), "ArtFetchFailed"
|
||||||
|
|
||||||
|
row.status = result.status
|
||||||
|
row.image_url = result.image_url
|
||||||
|
row.release_group_mbid = release_group_mbid
|
||||||
|
row.error_code = error_code
|
||||||
|
row.checked_at = datetime.now(UTC)
|
||||||
|
db.session.commit()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def register_worker_tasks(app) -> None:
|
||||||
|
from scrobbler import worker
|
||||||
|
|
||||||
|
worker.register_task(app, "art", resolve_one_pending)
|
||||||
@@ -0,0 +1,371 @@
|
|||||||
|
import json
|
||||||
|
import pathlib
|
||||||
|
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 on HEAD
|
||||||
|
"Download Fail Album": "rg-dl-fail", # HEAD succeeds, but the GET download 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"]
|
||||||
|
|
||||||
|
if path == "/release-group/rg-dl-fail/front-500":
|
||||||
|
if method == "HEAD":
|
||||||
|
start_response("200 OK", [("Content-Type", "image/jpeg")])
|
||||||
|
return []
|
||||||
|
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, tmp_path):
|
||||||
|
keys = (
|
||||||
|
"MUSICBRAINZ_API_URL",
|
||||||
|
"COVERART_API_URL",
|
||||||
|
"MUSICBRAINZ_REQUEST_INTERVAL",
|
||||||
|
"MUSICBRAINZ_RETRIES",
|
||||||
|
"ART_STORAGE_DIR",
|
||||||
|
)
|
||||||
|
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,
|
||||||
|
ART_STORAGE_DIR=str(tmp_path),
|
||||||
|
)
|
||||||
|
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() (still live-resolving: used by ActivityPub posting, out of scope here) -----------
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
|
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_cached() / want() / requeue() / read_file() ----------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_cached_returns_none_for_unseen_album(art_config):
|
||||||
|
assert art.get_cached("Nobody", "Nothing") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_cached_is_case_insensitive(art_config):
|
||||||
|
insert("Radiohead", "In Rainbows", "found", image_url="https://example.com/a.jpg")
|
||||||
|
assert art.get_cached("radiohead", "in rainbows").image_url == "https://example.com/a.jpg"
|
||||||
|
|
||||||
|
|
||||||
|
def test_want_creates_a_pending_row(art_config):
|
||||||
|
art.want("New Artist", "New Album")
|
||||||
|
assert row("New Artist", "New Album").status == "pending"
|
||||||
|
|
||||||
|
|
||||||
|
def test_want_is_a_noop_if_a_row_already_exists(art_config):
|
||||||
|
insert("Radiohead", "In Rainbows", "found", image_url="https://example.com/a.jpg")
|
||||||
|
art.want("Radiohead", "In Rainbows")
|
||||||
|
assert row("Radiohead", "In Rainbows").status == "found" # untouched, not reset to pending
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_file_returns_none_when_not_downloaded(art_config):
|
||||||
|
assert art.read_file(999_999) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_file_returns_the_bytes(app, art_config):
|
||||||
|
path = pathlib.Path(app.config["ART_STORAGE_DIR"]) / "123.jpg"
|
||||||
|
path.write_bytes(b"hello")
|
||||||
|
assert art.read_file(123) == b"hello"
|
||||||
|
|
||||||
|
|
||||||
|
def test_requeue_marks_a_row_pending(art_config):
|
||||||
|
insert("Someone", "Old Album", "found", image_url="https://example.com/a.jpg")
|
||||||
|
art.requeue(row("Someone", "Old Album"))
|
||||||
|
assert row("Someone", "Old Album").status == "pending"
|
||||||
|
|
||||||
|
|
||||||
|
# --- resolve_one_pending() (the worker task) ------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_one_pending_resolves_and_downloads(art_config):
|
||||||
|
art.want("Radiohead", "In Rainbows")
|
||||||
|
assert art.resolve_one_pending() is True
|
||||||
|
cached = row("Radiohead", "In Rainbows")
|
||||||
|
assert cached.status == "found"
|
||||||
|
assert art.read_file(cached.id) == b"\xff\xd8\xff\xe0fake-jpeg-bytes"
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_one_pending_handles_not_found(art_config):
|
||||||
|
art.want("Nobody", "Nothing")
|
||||||
|
assert art.resolve_one_pending() is True
|
||||||
|
assert row("Nobody", "Nothing").status == "not_found"
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_one_pending_handles_upstream_error(art_config):
|
||||||
|
art.want("Someone", "Boom Album")
|
||||||
|
assert art.resolve_one_pending() is True
|
||||||
|
cached = row("Someone", "Boom Album")
|
||||||
|
assert cached.status == "error"
|
||||||
|
assert cached.error_code
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_one_pending_download_failure_is_cached_as_error(art_config):
|
||||||
|
art.want("Someone", "Download Fail Album")
|
||||||
|
assert art.resolve_one_pending() is True
|
||||||
|
cached = row("Someone", "Download Fail Album")
|
||||||
|
assert cached.status == "error" # not left "found" with no file on disk
|
||||||
|
assert art.read_file(cached.id) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_one_pending_returns_false_when_nothing_to_do(art_config):
|
||||||
|
assert art.resolve_one_pending() is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_one_pending_picks_up_stale_not_found(art_config):
|
||||||
|
insert("Radiohead", "In Rainbows", "not_found", days_ago=31)
|
||||||
|
assert art.resolve_one_pending() is True
|
||||||
|
assert row("Radiohead", "In Rainbows").status == "found"
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_one_pending_picks_up_stale_error(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()
|
||||||
|
assert art.resolve_one_pending() is True
|
||||||
|
assert row("Radiohead", "In Rainbows").status == "found"
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_one_pending_ignores_fresh_not_found(art_config):
|
||||||
|
insert("Radiohead", "In Rainbows", "not_found", days_ago=1)
|
||||||
|
assert art.resolve_one_pending() is False
|
||||||
|
|
||||||
|
|
||||||
|
# --- 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_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
|
||||||
|
|
||||||
|
|
||||||
|
def test_album_art_404s_and_queues_an_unseen_album(client, auth, art_config):
|
||||||
|
response = client.get("/api/v1/art/album?artist=New+Artist&album=New+Album", headers=auth)
|
||||||
|
assert response.status_code == 404
|
||||||
|
assert response.get_json()["error"]["code"] == "no_album_art"
|
||||||
|
assert row("New Artist", "New Album").status == "pending"
|
||||||
|
|
||||||
|
|
||||||
|
def test_album_art_never_calls_the_network(client, auth, app, art_config):
|
||||||
|
# Point at a port nothing listens on: the endpoint must still respond (fast, 404)
|
||||||
|
# without ever trying to reach it — proof it's a cache-only read.
|
||||||
|
app.config.update(
|
||||||
|
MUSICBRAINZ_API_URL="http://127.0.0.1:1/", COVERART_API_URL="http://127.0.0.1:1/"
|
||||||
|
)
|
||||||
|
response = client.get("/api/v1/art/album?artist=Another&album=Album", headers=auth)
|
||||||
|
assert response.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_album_art_404s_while_pending(client, auth, art_config):
|
||||||
|
art.want("Radiohead", "In Rainbows")
|
||||||
|
response = client.get("/api/v1/art/album?artist=Radiohead&album=In+Rainbows", headers=auth)
|
||||||
|
assert response.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_album_art_returns_the_image_once_resolved(client, auth, art_config):
|
||||||
|
art.want("Radiohead", "In Rainbows")
|
||||||
|
art.resolve_one_pending()
|
||||||
|
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_resolved_not_found(client, auth, art_config):
|
||||||
|
art.want("Nobody", "Nothing")
|
||||||
|
art.resolve_one_pending()
|
||||||
|
response = client.get("/api/v1/art/album?artist=Nobody&album=Nothing", headers=auth)
|
||||||
|
assert response.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_album_art_requeues_a_found_row_with_a_missing_file(client, auth, art_config):
|
||||||
|
insert("Legacy", "Album", "found", image_url="https://example.com/old.jpg")
|
||||||
|
response = client.get("/api/v1/art/album?artist=Legacy&album=Album", headers=auth)
|
||||||
|
assert response.status_code == 404
|
||||||
|
assert row("Legacy", "Album").status == "pending" # requeued for the worker to redo
|
||||||
@@ -8,18 +8,33 @@ from scrobbler.extensions import db
|
|||||||
from scrobbler.federation import sharing
|
from scrobbler.federation import sharing
|
||||||
from scrobbler.federation.models import FederationActivity, FederationNowPlaying, FederationPost
|
from scrobbler.federation.models import FederationActivity, FederationNowPlaying, FederationPost
|
||||||
from scrobbler.federation.publishing import now_playing
|
from scrobbler.federation.publishing import now_playing
|
||||||
from scrobbler.models import NowPlaying
|
from scrobbler.models import AlbumArt, NowPlaying
|
||||||
from scrobbler.services.scrobbles import TrackInput, update_now_playing
|
from scrobbler.services.scrobbles import TrackInput, update_now_playing
|
||||||
|
|
||||||
|
|
||||||
def play(user, artist="Radiohead", track="Reckoner") -> datetime:
|
def play(user, artist="Radiohead", track="Reckoner", album=None) -> datetime:
|
||||||
"""Sets the track as playing (started_at = now) and returns that now, so tests
|
"""Sets the track as playing (started_at = now) and returns that now, so tests
|
||||||
always measure elapsed/throttle time relative to when it actually started, not a
|
always measure elapsed/throttle time relative to when it actually started, not a
|
||||||
fixed constant that would drift from real test-execution time."""
|
fixed constant that would drift from real test-execution time."""
|
||||||
update_now_playing(user, TrackInput(artist=artist, track=track))
|
update_now_playing(user, TrackInput(artist=artist, track=track, album=album))
|
||||||
return datetime.now(UTC)
|
return datetime.now(UTC)
|
||||||
|
|
||||||
|
|
||||||
|
def cache_art(artist: str, album: str, status: str, image_url: str | None = None) -> None:
|
||||||
|
"""Primes the AlbumArt cache directly, so art.lookup() is a cache hit and never
|
||||||
|
makes a real network call during tests."""
|
||||||
|
db.session.add(
|
||||||
|
AlbumArt(
|
||||||
|
artist=artist,
|
||||||
|
album=album,
|
||||||
|
status=status,
|
||||||
|
image_url=image_url,
|
||||||
|
checked_at=datetime.now(UTC),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
|
||||||
def stop_playing(user):
|
def stop_playing(user):
|
||||||
"""Expire (rather than delete) the row, matching how it naturally goes away."""
|
"""Expire (rather than delete) the row, matching how it naturally goes away."""
|
||||||
db.session.get(NowPlaying, user.id).expires_at = datetime.now(UTC) - timedelta(minutes=1)
|
db.session.get(NowPlaying, user.id).expires_at = datetime.now(UTC) - timedelta(minutes=1)
|
||||||
@@ -141,6 +156,44 @@ def test_post_sent_after_30_seconds(fed_ctx, posting_user):
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_post_includes_album_art_when_known(fed_ctx, posting_user):
|
||||||
|
cache_art(
|
||||||
|
"Radiohead",
|
||||||
|
"In Rainbows",
|
||||||
|
"found",
|
||||||
|
image_url="https://coverartarchive.org/release-group/test/front-500",
|
||||||
|
)
|
||||||
|
now = play(posting_user, album="In Rainbows")
|
||||||
|
now_playing.check_and_post(posting_user.id, now + timedelta(seconds=31))
|
||||||
|
[post] = posts_for(posting_user.id)
|
||||||
|
activity = db.session.get(FederationActivity, post.activity_id)
|
||||||
|
assert activity.document["object"]["attachment"] == [
|
||||||
|
{
|
||||||
|
"type": "Image",
|
||||||
|
"mediaType": "image/jpeg",
|
||||||
|
"url": "https://coverartarchive.org/release-group/test/front-500",
|
||||||
|
"name": "Cover art for In Rainbows",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_post_has_no_attachment_without_an_album(fed_ctx, posting_user):
|
||||||
|
now = play(posting_user) # no album
|
||||||
|
now_playing.check_and_post(posting_user.id, now + timedelta(seconds=31))
|
||||||
|
[post] = posts_for(posting_user.id)
|
||||||
|
activity = db.session.get(FederationActivity, post.activity_id)
|
||||||
|
assert "attachment" not in activity.document["object"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_post_has_no_attachment_when_art_is_not_found(fed_ctx, posting_user):
|
||||||
|
cache_art("Radiohead", "Some Rare Bootleg", "not_found")
|
||||||
|
now = play(posting_user, album="Some Rare Bootleg")
|
||||||
|
now_playing.check_and_post(posting_user.id, now + timedelta(seconds=31))
|
||||||
|
[post] = posts_for(posting_user.id)
|
||||||
|
activity = db.session.get(FederationActivity, post.activity_id)
|
||||||
|
assert "attachment" not in activity.document["object"]
|
||||||
|
|
||||||
|
|
||||||
def test_post_throttled_within_30_minutes(fed_ctx, posting_user):
|
def test_post_throttled_within_30_minutes(fed_ctx, posting_user):
|
||||||
now = play(posting_user, track="Reckoner")
|
now = play(posting_user, track="Reckoner")
|
||||||
now_playing.check_and_post(posting_user.id, now + timedelta(seconds=31))
|
now_playing.check_and_post(posting_user.id, now + timedelta(seconds=31))
|
||||||
|
|||||||
@@ -182,6 +182,27 @@ def test_note():
|
|||||||
assert doc["tag"] == [{"type": "Hashtag", "name": "#Scrobbler"}]
|
assert doc["tag"] == [{"type": "Hashtag", "name": "#Scrobbler"}]
|
||||||
assert doc["sensitive"] is False
|
assert doc["sensitive"] is False
|
||||||
assert "@context" not in doc # carried by the wrapping Create instead
|
assert "@context" not in doc # carried by the wrapping Create instead
|
||||||
|
assert "attachment" not in doc # omitted entirely, not an empty list, when there's none
|
||||||
|
|
||||||
|
|
||||||
|
def test_note_with_attachment():
|
||||||
|
image = {
|
||||||
|
"type": "Image",
|
||||||
|
"mediaType": "image/jpeg",
|
||||||
|
"url": f"{BASE}/art.jpg",
|
||||||
|
"name": "Cover art",
|
||||||
|
}
|
||||||
|
doc = vocab.note(
|
||||||
|
f"{BASE}/users/alice/posts/1",
|
||||||
|
actor_id=f"{BASE}/users/alice",
|
||||||
|
content_html="<p>Hello</p>",
|
||||||
|
published="2026-01-05T09:00:00Z",
|
||||||
|
url=f"{BASE}/post.html?id=1",
|
||||||
|
to=["FOLLOWERS"],
|
||||||
|
cc=[],
|
||||||
|
attachment=[image],
|
||||||
|
)
|
||||||
|
assert doc["attachment"] == [image]
|
||||||
|
|
||||||
|
|
||||||
def test_create_wraps_a_note_with_the_same_addressing():
|
def test_create_wraps_a_note_with_the_same_addressing():
|
||||||
|
|||||||
Reference in new issue
Block a user