16 Commits
Author SHA1 Message Date
matt 81e0b0cf42 Merge feature/scrobbled-branding into main
CI / notify (push) Successful in 6s
CI / lint (push) Successful in 17s
CI / test (push) Successful in 5m21s
CI / validate-monitoring (push) Successful in 12s
CI / federation-interop (push) Successful in 1m20s
CI / images (push) Successful in 41s
CI / assets (push) Successful in 10s
CI / python-package (push) Successful in 17s
CI / trigger-deploy (push) Successful in 2s
2026-10-12 21:28:46 +01:00
mattandClaude Sonnet 5.5 6649cbbcae Use the outlined Scrobbled wordmark and add the artwork licence
The design repo now ships a finished wordmark, so the header uses it (one file
per colour scheme) instead of live Bricolage text, and the font is dropped.
The artwork is all rights reserved, so it gets its own licence file.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-12 21:27:53 +01:00
mattandClaude Sonnet 5.5 65ee13fa65 Rename the product Scrobbled
Display name only: UI, docs, API title, dashboards, hashtag and User-Agent.
Identifiers (package, metrics, env vars, SCROBBLER_CONFIG) are unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-12 21:21:55 +01:00
mattandClaude Sonnet 5.5 9e4218f11b Add the Scrobbled logo, favicons and wordmark typeface to the web UI
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-12 21:18:46 +01:00
matt aadb1c6def Merge feature/album-art-by-mbid into main
CI / notify (push) Successful in 5s
CI / lint (push) Successful in 16s
CI / test (push) Successful in 5m46s
CI / validate-monitoring (push) Successful in 9s
CI / federation-interop (push) Successful in 1m40s
CI / images (push) Successful in 42s
CI / assets (push) Successful in 10s
CI / python-package (push) Successful in 18s
CI / trigger-deploy (push) Successful in 2s
2026-10-06 23:41:18 +01:00
mattandClaude Sonnet 5.5 2c4c42a42b Find album art by MusicBrainz ID (SCR-6)
CI / lint (push) Successful in 16s
CI / federation-interop (push) Successful in 1m20s
CI / validate-monitoring (push) Successful in 21s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / test (push) Successful in 5m50s
CI / trigger-deploy (push) Skipped
CI / notify (push) Successful in 9s
Corrections accept a release MBID as well as a release-group MBID, and the
worker uses a scrobble's recording MBID to find the release-group before falling
back to the text search. Counts matched/missed recording lookups.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-06 23:37:54 +01:00
mattandClaude Sonnet 5.5 ad383b602e Configurable logging for the API and worker (SCR-5)
CI / notify (push) Successful in 6s
CI / lint (push) Successful in 18s
CI / test (push) Successful in 5m26s
CI / validate-monitoring (push) Successful in 15s
CI / federation-interop (push) Successful in 1m17s
CI / images (push) Successful in 33s
CI / assets (push) Successful in 9s
CI / python-package (push) Successful in 18s
CI / trigger-deploy (push) Successful in 3s
Shared LOG_LEVEL/LOG_FORMAT (text or json) set up in create_app, per-task
activity and duration logs in the worker, and more context on delivery,
inbox and import failures. Alembic's fileConfig no longer disables loggers.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-06 23:30:54 +01:00
mattandClaude Sonnet 5.5 65cd610468 Isolate concurrent federation interop runs (SCR-4)
CI / validate-monitoring (push) Successful in 16s
CI / lint (push) Successful in 17s
CI / federation-interop (push) Successful in 1m40s
CI / test (push) Successful in 5m23s
CI / python-package (push) Skipped
CI / assets (push) Successful in 13s
CI / images (push) Successful in 31s
CI / trigger-deploy (push) Skipped
CI / notify (push) Successful in 5s
Let Docker allocate each run's network subnet instead of deriving a /24 from
the run number, trust private ranges in GoToSocial, and tag/clean up api and ui
images per run so overlapping runs (e.g. main push plus tag) cannot collide.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-06 23:12:41 +01:00
mattandClaude Sonnet 5.5 735556bf21 Merge feature/album-art-overrides into main
CI / test (push) Successful in 3m48s
CI / lint (push) Successful in 19s
CI / validate-monitoring (push) Successful in 14s
CI / federation-interop (push) Successful in 1m36s
CI / python-package (push) Successful in 16s
CI / images (push) Successful in 29s
CI / trigger-deploy (push) Successful in 2s
CI / assets (push) Successful in 1m22s
CI / notify (push) Successful in 6s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QHPkt2v797pphGCFKfTFmv
2026-10-06 22:58:11 +01:00
mattandClaude Sonnet 5.5 524b78a075 Document user-uploaded album art in the admin guide
CI / lint (push) Successful in 16s
CI / federation-interop (push) Successful in 1m11s
CI / validate-monitoring (push) Successful in 10s
CI / test (push) Successful in 3m55s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / trigger-deploy (push) Skipped
CI / notify (push) Successful in 5s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QHPkt2v797pphGCFKfTFmv
2026-10-06 22:31:28 +01:00
mattandClaude Sonnet 5.5 9c84a64d4e Add album art page for uploading, retrying and correcting missing art
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QHPkt2v797pphGCFKfTFmv
2026-10-06 22:27:58 +01:00
mattandClaude Sonnet 5.5 bee83cb9f3 Add manual album art panels, usage stats and alerts
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QHPkt2v797pphGCFKfTFmv
2026-10-06 22:27:18 +01:00
mattandClaude Sonnet 5.5 87edaafe19 Add album art upload, correction, retry, delete and failures endpoints
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QHPkt2v797pphGCFKfTFmv
2026-10-06 22:26:46 +01:00
mattandClaude Sonnet 5.5 a887865f05 Add per-user art overrides: service, worker corrections and metrics
Uploads and queued corrections are stored per user and take precedence over the
global cache; the worker resolves corrections (by MusicBrainz release-group or
corrected search text) ahead of the global queue. Adds upload/correction metrics
and DB gauges for overrides and the unresolved-album backlog.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QHPkt2v797pphGCFKfTFmv
2026-10-06 22:25:05 +01:00
mattandClaude Sonnet 5.5 d0b8e1ed22 Add per-user album art override model and migration
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QHPkt2v797pphGCFKfTFmv
2026-10-06 22:22:26 +01:00
mattandClaude Sonnet 5.5 48fba1e0e2 Add album art observability metrics, dashboard and alerts
CI / lint (push) Successful in 18s
CI / validate-monitoring (push) Successful in 13s
CI / federation-interop (push) Successful in 1m36s
CI / test (push) Successful in 3m37s
CI / python-package (push) Successful in 13s
CI / trigger-deploy (push) Successful in 3s
CI / notify (push) Successful in 5s
CI / assets (push) Successful in 8s
CI / images (push) Successful in 1m37s
Endpoint result counters, worker resolution/latency/image-size metrics,
per-upstream latency and error counters, cache-status and oldest-pending
gauges, an Album Art Grafana dashboard, and backlog/upstream-error alerts.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QHPkt2v797pphGCFKfTFmv
2026-10-06 21:56:18 +01:00
101 changed files with 4187 additions and 209 deletions

No files matched your search

+7
View File
@@ -10,6 +10,10 @@ CORS_ORIGINS=http://localhost:8080
# Where Last.fm clients are redirected to approve desktop auth tokens.
UI_BASE_URL=http://localhost:8080
# Logging: level (DEBUG, INFO, WARNING, ERROR) and format ("text", or "json" for log aggregators).
LOG_LEVEL=INFO
LOG_FORMAT=text
# Prometheus metrics are served on a separate port.
METRICS_PORT=9100
@@ -22,6 +26,9 @@ 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
# Largest image a user may upload as their own album art (bytes). Uploaded art is
# stored in ART_STORAGE_DIR too, so back that directory up.
ART_UPLOAD_MAX_BYTES=5242880
# docker compose host ports (defaults shown)
API_PORT=5050
+5 -6
View File
@@ -78,20 +78,19 @@ jobs:
run: for f in deploy/grafana/dashboards/*.json; do python3 -m json.tool "$f" > /dev/null; done
federation-interop:
# A real GoToSocial server follows a Scrobbler user (see scripts/interop/run.sh).
# A real GoToSocial server follows a Scrobbled user (see scripts/interop/run.sh).
# Not for pull requests from forks: it runs containers on the runner's Docker.
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v4
- name: Scrobbler <-> GoToSocial
- name: Scrobbled <-> GoToSocial
env:
# Own compose project, network and image tags, so concurrent runs can't collide
INTEROP_PROJECT: interop-${{ github.run_id }}
run: |
# A subnet of its own, so concurrent runs can't collide
export INTEROP_SUBNET="172.30.$(( ${{ github.run_number }} % 200 + 20 )).0/24"
scripts/interop/run.sh
SCROBBLER_IMAGE_TAG: interop-${{ github.run_id }}
run: scripts/interop/run.sh
# ---- Publishing (main and v* tags only) -------------------------------------
+30
View File
@@ -0,0 +1,30 @@
# Artwork licence
Copyright (c) 2026 Matthew Daubney. All rights reserved.
This applies to the Scrobbled logo and everything derived from it: the record and
tonearm mark, the wordmark and the icon files. In this repository that is
`frontend/img/`, `frontend/favicon.*`, `frontend/apple-touch-icon.png`,
`frontend/icon-*.png` and the mark drawn by `.brand-mark` in the web UI. The rest
of the repository is under [LICENSE](LICENSE).
## Permitted use
You may use the Scrobbled name and logo, unmodified, to refer to the Scrobbled
product. For example, in an article, review, tutorial, integration listing or
"works with Scrobbled" mention.
When you do:
- Use the files as supplied. Scaling is fine. Don't recolour, redraw, crop,
distort, animate or combine them with other marks.
- Don't use the logo in a way that suggests Scrobbled made, endorsed or
sponsors your product, service or organisation.
- Don't use the logo, or anything confusingly similar, as the name or logo of
your own product, app or business.
## Everything else
Any other use needs written permission first. That includes modifying the
artwork, selling it or merchandise bearing it, and using it as part of another
brand. To ask, contact Matthew Daubney.
+3 -2
View File
@@ -1,4 +1,4 @@
# Scrobbler
# Scrobbled
A self-hosted music scrobbling service. It speaks the **Last.fm (Audioscrobbler 2.0) API**,
so players and scrobblers that let you set a custom Last.fm server can use it unchanged.
@@ -40,4 +40,5 @@ configuration reference and production notes.
## Licence
BSD 3-Clause; see [LICENSE](LICENSE). The fonts vendored in `frontend/fonts/` are under
the SIL Open Font License 1.1.
the SIL Open Font License 1.1. The Scrobbled logo, wordmark and icons are not BSD-licensed:
they are all rights reserved, see [LICENSE-ARTWORK.md](LICENSE-ARTWORK.md).
File diff suppressed because it is too large. Load diff
+3 -3
View File
@@ -1,7 +1,7 @@
{
"uid": "scrobbler-api-overview",
"title": "Scrobbler: API overview",
"description": "Rate, errors and duration for every endpoint of the Scrobbler API.",
"title": "Scrobbled: API overview",
"description": "Rate, errors and duration for every endpoint of the Scrobbled API.",
"tags": [
"scrobbler"
],
@@ -57,7 +57,7 @@
"scrobbler"
],
"asDropdown": true,
"title": "Scrobbler",
"title": "Scrobbled",
"includeVars": false
}
],
+2 -2
View File
@@ -1,6 +1,6 @@
{
"uid": "scrobbler-database",
"title": "Scrobbler: Database",
"title": "Scrobbled: Database",
"description": "Query latency and pool use from the app's side; Postgres health from postgres-exporter.",
"tags": [
"scrobbler"
@@ -28,7 +28,7 @@
"scrobbler"
],
"asDropdown": true,
"title": "Scrobbler",
"title": "Scrobbled",
"includeVars": false
}
],
+2 -2
View File
@@ -1,6 +1,6 @@
{
"uid": "scrobbler-federation",
"title": "Scrobbler: Federation",
"title": "Scrobbled: Federation",
"description": "ActivityPub: how the fediverse finds and talks to users sharing their listening. Empty unless FEDERATION_ENABLED is on.",
"tags": [
"scrobbler"
@@ -28,7 +28,7 @@
"scrobbler"
],
"asDropdown": true,
"title": "Scrobbler",
"title": "Scrobbled",
"includeVars": false
}
],
+2 -2
View File
@@ -1,6 +1,6 @@
{
"uid": "scrobbler-lastfm",
"title": "Scrobbler: Last.fm API",
"title": "Scrobbled: Last.fm API",
"description": "The Last.fm-compatible /2.0/ API: which methods clients call, what fails, and what happens to scrobbles.",
"tags": [
"scrobbler"
@@ -57,7 +57,7 @@
"scrobbler"
],
"asDropdown": true,
"title": "Scrobbler",
"title": "Scrobbled",
"includeVars": false
}
],
+127 -2
View File
@@ -1,6 +1,6 @@
{
"uid": "scrobbler-usage",
"title": "Scrobbler: Usage",
"title": "Scrobbled: Usage",
"description": "Who is using the service and how much they're listening.",
"tags": [
"scrobbler"
@@ -28,7 +28,7 @@
"scrobbler"
],
"asDropdown": true,
"title": "Scrobbler",
"title": "Scrobbled",
"includeVars": false
}
],
@@ -989,6 +989,131 @@
"w": 12,
"h": 8
}
},
{
"type": "row",
"title": "Album art",
"id": 21,
"collapsed": false,
"gridPos": {
"x": 0,
"y": 54,
"w": 24,
"h": 1
},
"panels": []
},
{
"type": "stat",
"title": "Albums needing manual art",
"description": "Not found or errored in the shared cache, and not fixed by any user. See the Album Art dashboard.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "max(scrobbler_art_unresolved_albums)",
"legendFormat": "__auto",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"decimals": 0,
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "text",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"reduceOptions": {
"calcs": [
"lastNotNull"
],
"fields": "",
"values": false
},
"colorMode": "value",
"graphMode": "area",
"textMode": "auto",
"justifyMode": "auto"
},
"id": 22,
"gridPos": {
"x": 0,
"y": 55,
"w": 6,
"h": 5
}
},
{
"type": "stat",
"title": "Pending art corrections",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "max(scrobbler_art_overrides{kind=\"correction\",status=\"pending\"})",
"legendFormat": "__auto",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"decimals": 0,
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "text",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"reduceOptions": {
"calcs": [
"lastNotNull"
],
"fields": "",
"values": false
},
"colorMode": "value",
"graphMode": "area",
"textMode": "auto",
"justifyMode": "auto"
},
"id": 23,
"gridPos": {
"x": 6,
"y": 55,
"w": 6,
"h": 5
}
}
]
}
@@ -1,7 +1,7 @@
apiVersion: 1
providers:
- name: scrobbler
folder: Scrobbler
folder: Scrobbled
type: file
allowUiUpdates: true
options:
+6 -7
View File
@@ -1,9 +1,9 @@
# Federation interop test: Scrobbler and a real GoToSocial server on one private network.
# Federation interop test: Scrobbled and a real GoToSocial server on one private network.
#
# docker compose -f docker-compose.yml -f deploy/interop/docker-compose.interop.yml up -d --build
# ...create the GoToSocial user (see scripts/interop/run.sh), then run the driver.
#
# TEST ONLY: GoToSocial runs over plain HTTP and skips TLS verification; Scrobbler is
# TEST ONLY: GoToSocial runs over plain HTTP and skips TLS verification; Scrobbled is
# served over HTTPS by a Caddy proxy with a throwaway certificate, and its "insecure
# testing" switch lets it reach GoToSocial over HTTP on this private network. All on the
# reserved .test domain. Never use these settings anywhere else.
@@ -18,11 +18,10 @@ x-federation: &federation
FEDERATION_INSECURE_TESTING: "1"
UI_BASE_URL: https://scrobble.test
# Docker picks the network's subnet, so concurrent runs can't collide on one. GoToSocial
# is therefore told to trust any private range rather than one specific /24.
networks:
fedi:
ipam:
config:
- subnet: ${INTEROP_SUBNET:-172.30.0.0/24}
services:
db:
@@ -63,9 +62,9 @@ services:
GTS_PORT: "80"
GTS_DB_TYPE: sqlite
GTS_DB_ADDRESS: /gotosocial/storage/sqlite.db
GTS_HTTP_CLIENT_ALLOW_IPS: ${INTEROP_SUBNET:-172.30.0.0/24} # let it reach Scrobbler on this network
GTS_HTTP_CLIENT_ALLOW_IPS: ${INTEROP_PRIVATE_RANGES:-10.0.0.0/8,172.16.0.0/12,192.168.0.0/16} # let it reach Scrobbled on this network
GTS_HTTP_CLIENT_TLS_INSECURE_SKIP_VERIFY: "true" # Caddy's throwaway certificate
GTS_TRUSTED_PROXIES: ${INTEROP_SUBNET:-172.30.0.0/24}
GTS_TRUSTED_PROXIES: ${INTEROP_PRIVATE_RANGES:-10.0.0.0/8,172.16.0.0/12,192.168.0.0/16}
GTS_ACCOUNTS_REGISTRATION_OPEN: "false"
GTS_LOG_LEVEL: ${GTS_LOG_LEVEL:-info}
sysctls:
+38 -1
View File
@@ -6,7 +6,7 @@ groups:
for: 2m
labels: {severity: critical}
annotations:
summary: Scrobbler API metrics endpoint is down
summary: Scrobbled API metrics endpoint is down
description: Prometheus hasn't been able to scrape {{ $labels.instance }} for 2 minutes.
- alert: HighErrorRate
@@ -107,6 +107,43 @@ groups:
summary: More than 20% of incoming fediverse signatures are failing
description: Check the Federation dashboard for the reason (e.g. a clock problem shows as 'expired').
- alert: AlbumArtBacklog
expr: max(scrobbler_art_oldest_pending_seconds) > 900
for: 10m
labels: {severity: warning}
annotations:
summary: Album art requests have been waiting over 15 minutes
description: The worker is probably stopped, or MusicBrainz / Cover Art Archive is failing.
- alert: AlbumArtUpstreamErrors
expr: |
sum by (service) (rate(scrobbler_art_upstream_errors_total[15m]))
/ sum by (service) (rate(scrobbler_art_upstream_seconds_count[15m])) > 0.5
for: 15m
labels: {severity: warning}
annotations:
summary: Over half of {{ $labels.service }} album art calls are failing
description: Failed lookups are cached as errors and retried later; check the upstream's status.
- alert: AlbumArtCorrectionBacklog
expr: max(scrobbler_art_override_oldest_pending_seconds) > 900
for: 10m
labels: {severity: warning}
annotations:
summary: A manual album art correction has been waiting over 15 minutes
description: The worker is probably stopped, or MusicBrainz / Cover Art Archive is failing.
- alert: AlbumArtUploadRejections
expr: |
sum(rate(scrobbler_art_uploads_total{result!="ok"}[30m]))
/ sum(rate(scrobbler_art_uploads_total[30m])) > 0.5
and sum(rate(scrobbler_art_uploads_total[30m])) > 0.002
for: 30m
labels: {severity: warning}
annotations:
summary: Most album art uploads are being rejected
description: Check the Album Art dashboard for the reason (too_large suggests ART_UPLOAD_MAX_BYTES or a proxy limit; bad_type a client sending the wrong format).
- alert: PostgresDown
expr: pg_up == 0
for: 2m
+4
View File
@@ -33,6 +33,8 @@ services:
UI_BASE_URL: ${UI_BASE_URL:-http://localhost:8080}
WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2}
FORWARDED_ALLOW_IPS: "*"
LOG_LEVEL: ${LOG_LEVEL:-INFO}
LOG_FORMAT: ${LOG_FORMAT:-text}
LASTFM_API_KEY: ${LASTFM_API_KEY:-}
MUSICBRAINZ_CONTACT: ${MUSICBRAINZ_CONTACT:-}
ART_STORAGE_DIR: ${ART_STORAGE_DIR:-/data/album-art}
@@ -68,6 +70,8 @@ services:
FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-}
FEDERATION_KEY_SECRET: ${FEDERATION_KEY_SECRET:-}
RUN_MIGRATIONS: "0" # the api service applies them
LOG_LEVEL: ${LOG_LEVEL:-INFO}
LOG_FORMAT: ${LOG_FORMAT:-text}
expose:
- "9101" # metrics: internal network only
volumes:
+1 -1
View File
@@ -1,4 +1,4 @@
# Scrobbler API: gunicorn serving the Flask app, metrics on :9100.
# Scrobbled API: gunicorn serving the Flask app, metrics on :9100.
FROM ghcr.io/astral-sh/uv:0.7.21 AS uv
FROM python:3.13-slim AS build
+1 -1
View File
@@ -1,4 +1,4 @@
# Scrobbler web UI: static files served by nginx.
# Scrobbled web UI: static files served by nginx.
FROM nginx:1.29-alpine
LABEL org.opencontainers.image.licenses="BSD-3-Clause"
ENV API_BASE_URL=http://localhost:5050
+18 -13
View File
@@ -1,9 +1,9 @@
# Admin guide
Running a real Scrobbler instance: architecture, installation, configuration, TLS,
Running a real Scrobbled instance: architecture, installation, configuration, TLS,
fediverse sharing, monitoring, backups, upgrades and troubleshooting. If you're using an
instance someone else runs, see the [user guide](user-guide.md) instead. If you're
working on Scrobbler's own code, see [setup.md](setup.md).
working on Scrobbled's own code, see [setup.md](setup.md).
## Architecture
@@ -25,7 +25,7 @@ Prometheus ◄── API :9100/metrics, postgres-exporter ──► Grafana
- **`db`**: PostgreSQL.
- With the `monitoring` profile: `prometheus`, `grafana`, `postgres-exporter`.
Everything Scrobbler needs to run is in these five services plus optional monitoring —
Everything Scrobbled needs to run is in these five services plus optional monitoring —
there's no separate cache, queue or search service to operate.
## Installing
@@ -42,7 +42,7 @@ Published images: `pkgs.daubney.dev/scrobbler/scrobbler-api` and
`pkgs.daubney.dev/scrobbler/scrobbler-ui`, tagged `main` (latest push to `main`),
`sha-<commit>`, and `<version>`/`latest` for tagged releases.
This is enough for evaluating Scrobbler. Before putting it in front of real users, also
This is enough for evaluating Scrobbled. Before putting it in front of real users, also
read **Putting it behind TLS** below — the quick start above serves plain HTTP only.
## Configuration
@@ -54,12 +54,15 @@ read **Putting it behind TLS** below — the quick start above serves plain HTTP
| `CORS_ORIGINS` | api | `http://localhost:8080` | Comma-separated origins allowed to call `/api/v1`: wherever browsers actually load the UI from |
| `UI_BASE_URL` | api | `http://localhost:8080` | Where `/api/auth/` sends users to approve desktop sign-ins, and (with federation on) the public identity users are found under |
| `OPENAPI_DOCS_ENABLED` | api | `1` | Set to `0` to hide `/api/docs` and `/api/redoc` |
| `LOG_LEVEL` | api, worker | `INFO` | `DEBUG`, `INFO`, `WARNING` or `ERROR`. The worker logs each task pass that did work at `INFO` (with its duration); idle polls show at `DEBUG` |
| `LOG_FORMAT` | api, worker | `text` | `json` writes one JSON object per line (with `task` and `duration_ms` fields for worker tasks), for log aggregators |
| `METRICS_PORT` | api | `9100` | Prometheus metrics port — keep it off the public network |
| `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, 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) |
| `ART_UPLOAD_MAX_BYTES` | api | 5 MB | Largest image a user may upload as their own album art. A reverse proxy in front of the api needs a body limit at least this large |
| `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 |
@@ -106,7 +109,7 @@ the web UI — see the [user guide](user-guide.md#sharing-on-the-fediverse).
## Putting it behind TLS
Scrobbler itself only speaks plain HTTP; something in front of it needs to terminate
Scrobbled itself only speaks plain HTTP; something in front of it needs to terminate
TLS. Any reverse proxy works — nginx, Caddy, or a tunnel like Cloudflare Tunnel for
testing without a public IP (see `docs/design/activitypub-phase4.md` for how the
project's own manual federation test used one).
@@ -163,7 +166,7 @@ registered/active/currently-listening users. Labels never contain usernames, API
track names.
With `--profile monitoring`, Grafana (`GRAFANA_ADMIN_PASSWORD`) provisions a
**Scrobbler** folder with dashboards for API overview, Last.fm API, usage, database and
**Scrobbled** folder with dashboards for API overview, Last.fm API, usage, database and
(with federation on) federation. Alert rules live in `deploy/prometheus/alerts.yml` —
evaluated by Prometheus and visible in Grafana, but nothing routes them anywhere without
Alertmanager.
@@ -192,9 +195,11 @@ 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
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.
The `album-art-data` volume holds two kinds of file. Cover art the worker downloaded is a
disposable cache — it's simply re-downloaded the next time it's requested. Images users
**upload** (and the art from their manual corrections) live under `user/` in the same
volume and can't be re-created, so include the volume in your backups. The database rows
that point at them are in `user_album_art`; restore the two together.
## Upgrades
@@ -225,7 +230,7 @@ how to run it locally before tagging.
## Troubleshooting
**The web UI loads but can't reach the API ("Can't reach the Scrobbler API at …" or
**The web UI loads but can't reach the API ("Can't reach the Scrobbled API at …" or
requests failing silently).** Almost always `CORS_ORIGINS` on the `api` service not
listing the exact origin the browser loads the UI from (scheme and host both have to
match — `https://scrobble.example` is not the same origin as `http://scrobble.example`
@@ -264,10 +269,10 @@ curl -H 'Accept: application/jrd+json' \
```
If that's correct, the fix is time (or trying a smaller/different instance to confirm
it's not a Scrobbler-side problem) — there's nothing to change on the server.
it's not a Scrobbled-side problem) — there's nothing to change on the server.
**A legacy scrobbler client (e.g. VLC's built-in scrobbler) fails to connect at all.**
Scrobbler implements the Last.fm 2.0 API only, not the legacy 1.2 Audioscrobbler
Scrobbled implements the Last.fm 2.0 API only, not the legacy 1.2 Audioscrobbler
handshake (`hs=true&p=1.2&...`). Clients that only speak 1.2 can't be pointed at
Scrobbler regardless of configuration — point users at a client with 2.0 support
Scrobbled regardless of configuration — point users at a client with 2.0 support
instead.
+6 -6
View File
@@ -5,12 +5,12 @@
Where this differed from the plan:
- **httpcore instead of httpx.** httpcore is the transport layer underneath httpx, and it publicly supports the custom network backend that connecting to a pre-checked address needs.
- **No in-process test with two Scrobbler instances.** Scrobbler can't initiate follows yet, so one instance has nothing to send the other. Scripted remote accounts over real HTTP cover the same paths, and GoToSocial is the real second server.
- **No in-process test with two Scrobbled instances.** Scrobbled can't initiate follows yet, so one instance has nothing to send the other. Scripted remote accounts over real HTTP cover the same paths, and GoToSocial is the real second server.
- **Undo of a Block.** Unblocking needed it: GoToSocial otherwise keeps the block.
This implements phase 2 of [activitypub.md](activitypub.md), building on [phase 1](activitypub-phase1.md).
**Outcome:** people on Mastodon, GoToSocial and similar servers can follow a user who shares. Follows are accepted automatically, or wait for the user's approval if they've turned it on. The user sees their followers and can approve, decline, remove or block them. Scrobbler signs everything it sends and checks the signature on everything it receives. Posts come in phase 3; this phase makes the relationship work end to end.
**Outcome:** people on Mastodon, GoToSocial and similar servers can follow a user who shares. Follows are accepted automatically, or wait for the user's approval if they've turned it on. The user sees their followers and can approve, decline, remove or block them. Scrobbled signs everything it sends and checks the signature on everything it receives. Posts come in phase 3; this phase makes the relationship work end to end.
Everything below is inside `scrobbler.federation`, and the boundary tests keep holding. Federation off still means nothing is registered.
@@ -56,7 +56,7 @@ Everything below is inside `scrobbler.federation`, and the boundary tests keep h
- At most 3 redirects, each checked the same way.
- Response bodies are capped at 1 MB.
- Timeouts: 10s to connect and 20s to read.
- A `User-Agent` of `Scrobbler/<version> (+<base url>)`.
- A `User-Agent` of `Scrobbled/<version> (+<base url>)`.
- `signed_get(url, as_actor)`, which signs with the instance actor by default so "authorized fetch" servers answer; and `signed_post(inbox, activity, as_user)`.
- **`FEDERATION_INSECURE_TESTING=1`** is **for automated tests only**. It allows `http://` and private addresses. It's refused unless the domain ends in `.test` (a reserved top-level domain) and logs a warning every minute while on. It exists so CI can federate with GoToSocial on a private Docker network.
- **`remote.py`**: the remote-actor cache.
@@ -178,12 +178,12 @@ Everything below is inside `scrobbler.federation`, and the boundary tests keep h
- bad signatures rejected with the right reason
- a blocked domain
- turning sharing off
- **A real peer in CI**: a new `federation-interop` job runs Scrobbler (API, worker and UI) and a GoToSocial container on one Docker network. The hosts are `scrobble.test` and `gts.test`, over HTTP, with each side's test-only settings. A script:
- **A real peer in CI**: a new `federation-interop` job runs Scrobbled (API, worker and UI) and a GoToSocial container on one Docker network. The hosts are `scrobble.test` and `gts.test`, over HTTP, with each side's test-only settings. A script:
1. creates a GoToSocial user with its admin CLI,
2. gets a user token by driving GoToSocial's sign-in and OAuth screens with plain HTTP (this part gets a short spike first, since GoToSocial has no password grant),
3. follows `@alice@scrobble.test`, and checks it's accepted,
4. unfollows, and checks it's gone,
5. with manual approval on, checks the request waits until approved through Scrobbler's API.
5. with manual approval on, checks the request waits until approved through Scrobbled's API.
The job posts to ntfy like every other job. It doesn't run on pull requests from forks.
- **Manual pass before merging**: follow and unfollow from a real Mastodon account through a tunnel.
@@ -210,5 +210,5 @@ Everything below is inside `scrobbler.federation`, and the boundary tests keep h
- **Licences**:
- `httpx` is BSD-3-Clause and `cryptography` is Apache-2.0/BSD.
- GoToSocial is AGPL, but it runs only as a separate container in CI to test against. Nothing of it is linked into, or shipped with, Scrobbler, so it has no effect on Scrobbler's licence.
- GoToSocial is AGPL, but it runs only as a separate container in CI to test against. Nothing of it is linked into, or shipped with, Scrobbled, so it has no effect on Scrobbled's licence.
- **Scale**: this is the biggest phase, and signatures plus safe outbound HTTP are where the risk lies. They come first and have the most thorough tests.
+4 -4
View File
@@ -46,7 +46,7 @@ Everything is in `scrobbler.federation` except one small addition to the core st
- `id`, `attributedTo`, `content` (HTML) plus `contentMap` (`{"en": …}`)
- `published`, `url` (the UI post page)
- `to` and `cc` from the visibility setting
- `tag` (`Hashtag` objects: `#Scrobbler`, and `#NowPlaying` in phase 4)
- `tag` (`Hashtag` objects: `#Scrobbled`, and `#NowPlaying` in phase 4)
- `sensitive: false`
- **`create(...)`**: `Create` wrapping the Note, with the same addressing.
- **`delete(...)`**: `Delete` whose object is a `Tombstone` of the Note (the same shape Mastodon sends).
@@ -85,7 +85,7 @@ Everything is in `scrobbler.federation` except one small addition to the core st
> **My week in music: 312 plays**
> Top artists: 1. Radiohead (48) 2. Björk (31) 3. Portishead (22)
> Most played: *Reckoner* by Radiohead (12 plays)
> #Scrobbler
> #Scrobbled
**Milestones** (`publishing/milestones.py`, worker task `federation.milestones`):
@@ -99,7 +99,7 @@ Everything is in `scrobbler.federation` except one small addition to the core st
- **No retroactive posts:**
- When a user **turns sharing on**, every threshold they've already passed is marked `posted=false`.
- When an **import finishes** (`import_finished`), the same happens: imported history moves the baseline silently. Imported plays therefore never trigger milestone posts, even if a live scrobble crosses a line soon after.
- Example: *"10,000 plays on Scrobbler 🎉"* or *"Björk just joined my all-time top 10 (at #7)"*.
- Example: *"10,000 plays on Scrobbled 🎉"* or *"Björk just joined my all-time top 10 (at #7)"*.
## 6. Endpoints (served on the UI domain, documented in OpenAPI)
@@ -188,5 +188,5 @@ Everything is in `scrobbler.federation` except one small addition to the core st
| Milestone thresholds | Plays: 1k, 5k, 10k, then every 25k. An artist's plays: 100, 500, 1k. New artist in the all-time top 10 |
| Posts per milestone check | At most one (the most notable) |
| Post language | English only for now (`contentMap.en`) |
| Hashtag | `#Scrobbler` on every post |
| Hashtag | `#Scrobbled` on every post |
| Deleting individual posts | Allowed, from the web UI |
+3 -3
View File
@@ -26,7 +26,7 @@ Everything is in `scrobbler.federation`, using the core's existing `services.scr
## 1. Settings and data (migration on the `federation` branch)
- **`federation_settings` gains `now_playing_mode`**: `off` (default), `profile`, or `posts`. Validated the same way `visibility` is.
- **`federation_now_playing`**, one row per user, the state of what Scrobbler has last told the fediverse (as opposed to `now_playing` in core, which is what's actually playing):
- **`federation_now_playing`**, one row per user, the state of what Scrobbled has last told the fediverse (as opposed to `now_playing` in core, which is what's actually playing):
- `profile_key` (nullable) and `profile_updated_at` (nullable): what the last `Update(Person)` said, and when it was sent
- `post_key` (nullable) and `post_posted_at` (nullable): the key of the last now-playing post, and when
@@ -36,7 +36,7 @@ Everything is in `scrobbler.federation`, using the core's existing `services.scr
- **`update(activity_id, actor_id, actor_object)`**: wraps a document as an `Update`, addressed the same way `undo()` already does (mirrors its shape).
- **`person(...)` already takes `fields`** (phase 1): a "Now playing" field is just one more `(name, value)` pair, `"Track by Artist"`.
- Now-playing posts reuse the existing `note()`/`create()` builders from phase 3, tagged `#NowPlaying` in addition to `#Scrobbler` (already anticipated in the phase 3 plan's vocabulary notes).
- Now-playing posts reuse the existing `note()`/`create()` builders from phase 3, tagged `#NowPlaying` in addition to `#Scrobbled` (already anticipated in the phase 3 plan's vocabulary notes).
## 3. Live actor vs. pushed updates
@@ -114,4 +114,4 @@ No event receiver, no pending-checks queue: unlike milestones, now playing doesn
| Minimum played before a post | 30 seconds |
| Deleting the previous now-playing post | Always, when a new one goes out |
| Worker poll interval | 30 seconds |
| Hashtags | `#Scrobbler` and `#NowPlaying` |
| Hashtags | `#Scrobbled` and `#NowPlaying` |
+12 -12
View File
@@ -4,17 +4,17 @@ Status: **proposal, for review.** Nothing here is built yet. The decisions still
## Summary
Let a user turn their Scrobbler account into a fediverse account, for example `@alice@scrobble.example`, that people on Mastodon, GoToSocial, Misskey and similar servers can follow. Followers see three kinds of post:
Let a user turn their Scrobbled account into a fediverse account, for example `@alice@scrobble.example`, that people on Mastodon, GoToSocial, Misskey and similar servers can follow. Followers see three kinds of post:
- a **weekly listening summary**
- **milestones** (for example "10,000th scrobble")
- **what the user is playing now**
The first version is **outbound only**: Scrobbler publishes, and it accepts and manages followers. Following other people and showing their listening in the UI is a possible later phase (see [Later](#later-following-and-listen-activities)). The data model is designed so it can be added without rework.
The first version is **outbound only**: Scrobbled publishes, and it accepts and manages followers. Following other people and showing their listening in the UI is a possible later phase (see [Later](#later-following-and-listen-activities)). The data model is designed so it can be added without rework.
Federation is **off for everyone until they turn it on**. Until then a user can't be found by WebFinger and nothing about them is published.
**Decided:** we write the protocol layer ourselves, on `cryptography` plus the Flask, SQLAlchemy and worker setup we already have (about 1,500 lines, in the four phases below). Scrobbler is BSD-licensed, and the ready-made Python library is AGPL (see [Build or buy](#build-or-buy)).
**Decided:** we write the protocol layer ourselves, on `cryptography` plus the Flask, SQLAlchemy and worker setup we already have (about 1,500 lines, in the four phases below). Scrobbled is BSD-licensed, and the ready-made Python library is AGPL (see [Build or buy](#build-or-buy)).
All of it lives in **one self-contained package, `scrobbler.federation`**, behind a narrow interface. It can then be changed, replaced or switched off without touching the rest of the app, and changes to the specs (signature schemes, vocabulary, FEPs) stay inside it. See [Module structure](#module-structure).
@@ -35,7 +35,7 @@ All of it lives in **one self-contained package, `scrobbler.federation`**, behin
## How it fits the current system
```
Mastodon, GoToSocial, … Scrobbler
Mastodon, GoToSocial, … Scrobbled
────────────────────────────────────────────────────────────────────────────
GET /.well-known/webfinger?resource=acct:… ─► API (only for opted-in users)
GET /users/alice (Accept: activity+json) ─► API actor document
@@ -53,7 +53,7 @@ POST /users/alice/inbox or /inbox ─► API verify signature, reco
## Module structure
Everything to do with ActivityPub lives in `src/scrobbler/federation/`. The rest of Scrobbler knows only two things about it: how to switch it on, and a handful of domain events. Replacing the implementation (with another library, or a rewrite when the specs move on) means replacing this package; nothing else changes.
Everything to do with ActivityPub lives in `src/scrobbler/federation/`. The rest of Scrobbled knows only two things about it: how to switch it on, and a handful of domain events. Replacing the implementation (with another library, or a rewrite when the specs move on) means replacing this package; nothing else changes.
```
src/scrobbler/
@@ -222,7 +222,7 @@ Serve `/.well-known/nodeinfo` and `/nodeinfo/2.1`, giving the software name `scr
## What gets posted
Posts are `Note` objects inside `Create` activities: Mastodon shows `Note` as a normal status, while other types are squashed into a title and link. The HTML uses only tags Mastodon keeps (`p`, `a`, `br`, `strong`, `em`, `ul`, `ol`, `li`), and all track and artist text is escaped. Each post also gets hashtags (`#NowPlaying`, `#Scrobbler`) as `Hashtag` tags. Visibility follows the user's setting, which defaults to **followers only**:
Posts are `Note` objects inside `Create` activities: Mastodon shows `Note` as a normal status, while other types are squashed into a title and link. The HTML uses only tags Mastodon keeps (`p`, `a`, `br`, `strong`, `em`, `ul`, `ol`, `li`), and all track and artist text is escaped. Each post also gets hashtags (`#NowPlaying`, `#Scrobbled`) as `Hashtag` tags. Visibility follows the user's setting, which defaults to **followers only**:
| Setting | `to` | `cc` |
|---|---|---|
@@ -248,7 +248,7 @@ Example:
> **This week: 312 scrobbles**
> Top artists: 1. Radiohead (48) 2. Björk (31) 3. Portishead (22)
> Top track: *Reckoner* by Radiohead (12 plays)
> #Scrobbler
> #Scrobbled
### Milestones
@@ -279,7 +279,7 @@ A new post for every track would flood followers' timelines. There are two optio
| Maturity | New code, but the scope is narrow | Active, but young (0.3.x, one maintainer) | The most complete framework |
| Effort | About 1,500 lines, mostly signatures, inbox and delivery | Less code, but we'd adapt its storage and flow to ours | A new service to run and monitor |
**Decided: write it ourselves.** Scrobbler is BSD-3-Clause licensed. Using Pubby inside the app would make the running program subject to the AGPL, which defeats the point of a permissive licence. Fedify is excellent, but it would split the backend across two languages. The protocol surface we need is small (four activity types in and three out), so writing it ourselves is the least total cost. It also keeps ActivityPub on the same metrics, dashboards and tests as everything else, and it can all live in the one replaceable module described above.
**Decided: write it ourselves.** Scrobbled is BSD-3-Clause licensed. Using Pubby inside the app would make the running program subject to the AGPL, which defeats the point of a permissive licence. Fedify is excellent, but it would split the backend across two languages. The protocol surface we need is small (four activity types in and three out), so writing it ourselves is the least total cost. It also keeps ActivityPub on the same metrics, dashboards and tests as everything else, and it can all live in the one replaceable module described above.
New dependency: `cryptography` (Apache-2.0 or BSD), for keys and signatures.
@@ -335,8 +335,8 @@ Everything goes on the existing Prometheus and Grafana setup:
- inbox state transitions
- delivery retry schedule
- visibility addressing
- **In-process federation**: two Scrobbler instances in one test process following each other.
- **A real peer in CI**: a [GoToSocial](https://gotosocial.org) container, which is a single binary with SQLite. It follows a Scrobbler user and we assert that it receives the `Accept` and the posts. That's much lighter than running Mastodon in CI.
- **In-process federation**: two Scrobbled instances in one test process following each other.
- **A real peer in CI**: a [GoToSocial](https://gotosocial.org) container, which is a single binary with SQLite. It follows a Scrobbled user and we assert that it receives the `Accept` and the posts. That's much lighter than running Mastodon in CI.
- **Manual pass before release** (done, over a `cloudflared` tunnel - see [phase 4](activitypub-phase4.md)):
- follow from a real Mastodon account
- check the profile, posts, profile-field updates and unfollowing
@@ -363,8 +363,8 @@ Each phase can be released on its own, with its migration, docs, OpenAPI updates
This is the "profiles plus friends' listening" option, deliberately left out of v1:
- Users follow other Scrobbler users, or any actor that publishes listens, and see a friends feed in the UI.
- **Wire format**: ActivityStreams has a `Listen` activity type. Funkwhale already federates `Listen` activities whose object is a `Track`. We'd send the same thing to followers on Scrobbler and Funkwhale servers only. Mastodon ignores activity types it doesn't know, and a stream of `Listen`s isn't something people want in their timelines anyway.
- Users follow other Scrobbled users, or any actor that publishes listens, and see a friends feed in the UI.
- **Wire format**: ActivityStreams has a `Listen` activity type. Funkwhale already federates `Listen` activities whose object is a `Track`. We'd send the same thing to followers on Scrobbled and Funkwhale servers only. Mastodon ignores activity types it doesn't know, and a stream of `Listen`s isn't something people want in their timelines anyway.
- **Changes needed**: an outbound `Follow` flow, storing received listens, a feed UI, and moderation of incoming content.
- **Account migration** (`Move` and `alsoKnownAs`) would come with this, so users can change handle or domain without losing followers.
+523 -4
View File
@@ -1,7 +1,7 @@
{
"info": {
"description": "Two APIs: `/2.0/` is Last.fm (Audioscrobbler 2.0) compatible, for players and scrobblers; `/api/v1/` is the JSON API used by the web UI.",
"title": "Scrobbler API",
"title": "Scrobbled API",
"version": "v1"
},
"paths": {
@@ -1542,7 +1542,7 @@
}
},
"200": {
"description": "The album's cover art"
"description": "The album's cover art (JPEG, PNG or WebP)"
},
"401": {
"description": "Not authenticated",
@@ -1559,7 +1559,358 @@
}
},
"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.",
"description": "Your own uploaded or corrected art comes first. Otherwise it's served from a local\ncache that a background worker task keeps filled; this endpoint never makes a live\nMusicBrainz/Cover Art Archive call, so it can't be slowed down by one. An album seen\nfor the first time returns 404 until the worker resolves it, typically within a few\nseconds - cache this response client-side and retry later.",
"tags": [
"Art"
],
"security": [
{
"bearerAuth": []
}
]
},
"post": {
"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"
},
"415": {
"description": "Not a JPEG, PNG or WebP image",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"413": {
"description": "Image too large",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"400": {
"description": "Empty file",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"201": {
"description": "Created",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/AlbumArtOverride"
}
}
}
},
"401": {
"description": "Not authenticated",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"default": {
"$ref": "#/components/responses/DEFAULT_ERROR"
}
},
"requestBody": {
"required": true,
"content": {
"multipart/form-data": {
"schema": {
"$ref": "#/components/schemas/AlbumArtUpload"
}
}
}
},
"summary": "Upload your own art for an album",
"description": "Replaces any earlier upload or correction of yours for this album. Only you see it.",
"tags": [
"Art"
],
"security": [
{
"bearerAuth": []
}
]
},
"delete": {
"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": "You have no art of your own for this album",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"204": {
"description": "No Content"
},
"401": {
"description": "Not authenticated",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"default": {
"$ref": "#/components/responses/DEFAULT_ERROR"
}
},
"summary": "Remove your own art for an album",
"description": "The album goes back to the shared lookup result, if there is one.",
"tags": [
"Art"
],
"security": [
{
"bearerAuth": []
}
]
}
},
"/api/v1/art/album/correction": {
"put": {
"responses": {
"422": {
"$ref": "#/components/responses/UNPROCESSABLE_CONTENT"
},
"202": {
"description": "Accepted",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/AlbumArtOverride"
}
}
}
},
"401": {
"description": "Not authenticated",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"default": {
"$ref": "#/components/responses/DEFAULT_ERROR"
}
},
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/AlbumArtCorrection"
}
}
}
},
"summary": "Correct a failed lookup",
"description": "Queues a new lookup with different search text, or straight from a MusicBrainz\nrelease-group or release ID. The background worker resolves it; poll the failures list, or just\nfetch the art later. Replaces any earlier upload or correction of yours.",
"tags": [
"Art"
],
"security": [
{
"bearerAuth": []
}
]
}
},
"/api/v1/art/album/retry": {
"post": {
"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"
},
"409": {
"description": "Nothing to retry",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"202": {
"description": "Accepted"
},
"401": {
"description": "Not authenticated",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"default": {
"$ref": "#/components/responses/DEFAULT_ERROR"
}
},
"summary": "Look an album up again",
"description": "Re-queues the shared lookup for an album whose search found nothing or failed.",
"tags": [
"Art"
],
"security": [
{
"bearerAuth": []
}
]
}
},
"/api/v1/art/failures": {
"get": {
"parameters": [
{
"in": "query",
"name": "page",
"schema": {
"type": "integer",
"default": 1,
"minimum": 1
},
"required": false
},
{
"in": "query",
"name": "limit",
"schema": {
"type": "integer",
"default": 50,
"minimum": 1,
"maximum": 200
},
"required": false
}
],
"responses": {
"422": {
"$ref": "#/components/responses/UNPROCESSABLE_CONTENT"
},
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/AlbumArtFailuresPage"
}
}
}
},
"401": {
"description": "Not authenticated",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"default": {
"$ref": "#/components/responses/DEFAULT_ERROR"
}
},
"summary": "Albums of yours without art",
"description": "Albums you've scrobbled whose lookup found nothing or failed, plus ones where your\nown correction didn't work, most-scrobbled first. Albums you've fixed drop off.",
"tags": [
"Art"
],
@@ -3443,7 +3794,7 @@
},
{
"name": "Art",
"description": "Album art, resolved from MusicBrainz / Cover Art Archive by a background worker"
"description": "Album art, resolved from MusicBrainz / Cover Art Archive by a background worker. You can also upload your own art, or correct a failed lookup; those only change what you see."
},
{
"name": "Health",
@@ -4135,6 +4486,174 @@
],
"additionalProperties": false
},
"AlbumArtUpload": {
"type": "object",
"properties": {
"file": {
"description": "A JPEG, PNG or WebP image",
"type": "string",
"format": "binary"
}
},
"required": [
"file"
],
"additionalProperties": false
},
"AlbumArtOverride": {
"type": "object",
"properties": {
"kind": {
"type": "string",
"description": "upload or correction"
},
"status": {
"type": "string",
"description": "pending, found or error"
},
"error_code": {
"type": [
"string",
"null"
]
},
"search_artist": {
"type": [
"string",
"null"
]
},
"search_album": {
"type": [
"string",
"null"
]
},
"release_group_mbid": {
"type": [
"string",
"null"
]
},
"release_mbid": {
"type": [
"string",
"null"
]
}
},
"additionalProperties": false
},
"AlbumArtCorrection": {
"type": "object",
"properties": {
"artist": {
"type": "string",
"minLength": 1,
"maxLength": 500
},
"album": {
"type": "string",
"minLength": 1,
"maxLength": 500
},
"search_artist": {
"type": "string",
"minLength": 1,
"maxLength": 500,
"description": "Artist text to search MusicBrainz for, if it differs"
},
"search_album": {
"type": "string",
"minLength": 1,
"maxLength": 500,
"description": "Album text to search MusicBrainz for, if it differs"
},
"release_group_mbid": {
"type": "string",
"format": "uuid",
"description": "A MusicBrainz release-group ID; skips the search"
},
"release_mbid": {
"type": "string",
"format": "uuid",
"description": "A MusicBrainz release ID, as an alternative to a release-group ID; skips the search"
}
},
"required": [
"album",
"artist"
],
"additionalProperties": false
},
"AlbumArtFailure": {
"type": "object",
"properties": {
"artist": {
"type": "string"
},
"album": {
"type": "string"
},
"scrobbles": {
"type": "integer",
"description": "Your scrobbles of this album"
},
"status": {
"type": "string",
"description": "The shared lookup: pending, not_found or error"
},
"error_code": {
"type": [
"string",
"null"
]
},
"checked_at": {
"type": [
"string",
"null"
],
"format": "date-time"
},
"override": {
"description": "Your own fix, if any",
"anyOf": [
{
"$ref": "#/components/schemas/AlbumArtOverride"
},
{
"type": "null"
}
]
}
},
"additionalProperties": false
},
"AlbumArtFailuresPage": {
"type": "object",
"properties": {
"page": {
"type": "integer"
},
"per_page": {
"type": "integer"
},
"total": {
"type": "integer"
},
"total_pages": {
"type": "integer"
},
"items": {
"type": "array",
"items": {
"$ref": "#/components/schemas/AlbumArtFailure"
}
}
},
"additionalProperties": false
},
"Health": {
"type": "object",
"properties": {
+2 -2
View File
@@ -1,4 +1,4 @@
# Working on Scrobbler
# Working on Scrobbled
Setting up a local development environment. For running a real instance, see the
[admin guide](admin-guide.md). For what the service does, see the
@@ -67,7 +67,7 @@ route is missing its bearer-auth declaration.
- `uv run python scripts/generate_traffic.py --minutes 5` — sends a realistic mix of
scrobbles and errors, so the Grafana dashboards have something to show.
- `scripts/interop/run.sh` — runs Scrobbler against a real GoToSocial server on a private
- `scripts/interop/run.sh` — runs Scrobbled against a real GoToSocial server on a private
network and checks the whole federation follow/post/now-playing life cycle end to end.
CI runs this on every push; run it locally the same way before changing anything in
`scrobbler.federation`.
+2 -2
View File
@@ -1,6 +1,6 @@
# User guide
What Scrobbler does once you're signed in: connecting a player, importing your old
What Scrobbled does once you're signed in: connecting a player, importing your old
history, and sharing your listening on the fediverse. If you're setting up or running an
instance rather than using one, see the [admin guide](admin-guide.md) instead.
@@ -18,7 +18,7 @@ In the player's scrobbling settings, choose a custom or self-hosted Last.fm serv
- **API URL**: `https://your-host/2.0/`
- **API key and shared secret**: from an app on the **Apps** page
- **Username and password**: your Scrobbler account
- **Username and password**: your Scrobbled account
Two sign-in flows are supported, and most players use one or the other automatically:
Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

+6 -2
View File
@@ -3,8 +3,12 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Allow access · Scrobbler</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
<title>Allow access · Scrobbled</title>
<link rel="icon" href="favicon.ico" sizes="48x48">
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="manifest" href="site.webmanifest">
<meta name="theme-color" content="#1F1C28">
<link rel="stylesheet" href="css/style.css">
<script src="config.js"></script>
<script type="module" src="js/approve.js"></script>
+6 -2
View File
@@ -3,8 +3,12 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Apps · Scrobbler</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
<title>Apps · Scrobbled</title>
<link rel="icon" href="favicon.ico" sizes="48x48">
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="manifest" href="site.webmanifest">
<meta name="theme-color" content="#1F1C28">
<link rel="stylesheet" href="css/style.css">
<script src="config.js"></script>
<script type="module" src="js/apps.js"></script>
+26
View File
@@ -0,0 +1,26 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Album art · Scrobbled</title>
<link rel="icon" href="favicon.ico" sizes="48x48">
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="manifest" href="site.webmanifest">
<meta name="theme-color" content="#1F1C28">
<link rel="stylesheet" href="css/style.css">
<script src="config.js"></script>
<script type="module" src="js/art-failures.js"></script>
</head>
<body>
<header class="site-header" id="site-header"></header>
<main id="main">
<h1 class="page-title">Album art</h1>
<p class="lede" id="art-summary">Albums you've scrobbled that have no cover art.</p>
<div id="messages" aria-live="polite"></div>
<ul class="rows art-rows" id="albums"></ul>
<nav class="pager" aria-label="Pages" id="pager"></nav>
</main>
</body>
</html>
+1 -1
View File
@@ -1,4 +1,4 @@
// Where the Scrobbler API lives. The UI container rewrites this file from the
// Where the Scrobbled API lives. The UI container rewrites this file from the
// API_BASE_URL environment variable at start-up; edit it by hand otherwise.
window.SCROBBLER_CONFIG = {
apiBaseUrl: "http://localhost:5050",
+44 -9
View File
@@ -152,18 +152,32 @@ code {
display: inline-flex;
align-items: center;
gap: 0.6rem;
font-weight: 700;
font-size: var(--step-1);
text-decoration: none;
}
/* A small round "power" lamp */
/* The Scrobbled mark: a record with the tonearm resting on it */
.brand-mark {
width: 0.7rem;
height: 0.7rem;
border-radius: 50%;
background: var(--glow);
box-shadow: 0 0 0 3px var(--panel), 0 0 10px 1px color-mix(in srgb, var(--glow) 60%, transparent);
width: 2rem;
height: 2rem;
background: url("../img/scrobbled-mark-simple.svg") center / contain no-repeat;
}
/* The outlined wordmark; the name is in the link's visually-hidden text. The "b" is
lime on dark and violet on light, so there is one file per theme. */
.brand-word {
width: 5.3rem;
height: 1.4rem;
background: url("../img/scrobbled-wordmark-on-light.svg") center / contain no-repeat;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) .brand-word {
background-image: url("../img/scrobbled-wordmark-on-dark.svg");
}
}
:root[data-theme="dark"] .brand-word {
background-image: url("../img/scrobbled-wordmark-on-dark.svg");
}
.site-header nav ul {
@@ -1111,7 +1125,7 @@ input {
position: relative;
}
/* No artwork: a plain ring, echoing .brand-mark's small round "lamp" motif */
/* No artwork: a plain ring, echoing the record in .brand-mark */
.art-thumb-empty::after {
content: "";
position: absolute;
@@ -1149,3 +1163,24 @@ input {
height: 2.25rem;
align-self: center; /* .log li items default to stretch/start, which suits text, not art */
}
/* ---- Album art: fixing missing art ---------------------------------------------- */
.art-row {
display: grid;
grid-template-columns: 4rem minmax(0, 1fr);
gap: 1rem;
align-items: start;
}
.art-thumb-lg {
width: 4rem;
height: 4rem;
}
.art-row-body .muted {
margin: 0.35rem 0 0.75rem;
}
.art-correction {
margin-top: 1rem;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

+7
View File
@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-6 8 196 196" width="512" height="512"><circle cx="88" cy="112" r="76" fill="#15131A" stroke="#F4F1EA" stroke-width="9"/>
<circle cx="88" cy="112" r="28" fill="#8B6CFF"/>
<path d="M168 32 L144 78" fill="none" stroke="#000000" stroke-width="14" stroke-linecap="round"/>
<circle cx="168" cy="32" r="14" fill="#F4F1EA" stroke="#000000" stroke-width="2.4"/>
<path d="M168 32 L144 78" fill="none" stroke="#F4F1EA" stroke-width="10" stroke-linecap="round"/>
<path d="M144 78 L126 108 L114 96" fill="none" stroke="#C8F560" stroke-width="15" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 639 B

+6 -2
View File
@@ -3,8 +3,12 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Followers · Scrobbler</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
<title>Followers · Scrobbled</title>
<link rel="icon" href="favicon.ico" sizes="48x48">
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="manifest" href="site.webmanifest">
<meta name="theme-color" content="#1F1C28">
<link rel="stylesheet" href="css/style.css">
<script src="config.js"></script>
<script type="module" src="js/followers.js"></script>
+6 -2
View File
@@ -3,8 +3,12 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>History · Scrobbler</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
<title>History · Scrobbled</title>
<link rel="icon" href="favicon.ico" sizes="48x48">
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="manifest" href="site.webmanifest">
<meta name="theme-color" content="#1F1C28">
<link rel="stylesheet" href="css/style.css">
<script src="config.js"></script>
<script type="module" src="js/history.js"></script>
Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

+7
View File
@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-6 8 196 196" width="512" height="512"><circle cx="88" cy="112" r="76" fill="#15131A" stroke="#F4F1EA" stroke-width="9"/>
<circle cx="88" cy="112" r="28" fill="#8B6CFF"/>
<path d="M168 32 L144 78" fill="none" stroke="#000000" stroke-width="14" stroke-linecap="round"/>
<circle cx="168" cy="32" r="14" fill="#F4F1EA" stroke="#000000" stroke-width="2.4"/>
<path d="M168 32 L144 78" fill="none" stroke="#F4F1EA" stroke-width="10" stroke-linecap="round"/>
<path d="M144 78 L126 108 L114 96" fill="none" stroke="#C8F560" stroke-width="15" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 639 B

+10
View File
@@ -0,0 +1,10 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-6 8 196 196" width="512" height="512"><circle cx="88" cy="112" r="78" fill="#15131A" stroke="#F4F1EA" stroke-width="5"/>
<circle cx="88" cy="112" r="60" fill="none" stroke="#F4F1EA" stroke-width="2" stroke-opacity="0.4"/>
<circle cx="88" cy="112" r="46" fill="none" stroke="#F4F1EA" stroke-width="2" stroke-opacity="0.28"/>
<circle cx="88" cy="112" r="24" fill="#8B6CFF"/>
<circle cx="88" cy="112" r="4" fill="#15131A"/>
<path d="M168 32 L144 78" fill="none" stroke="#000000" stroke-width="9" stroke-linecap="round"/>
<circle cx="168" cy="32" r="12" fill="#F4F1EA" stroke="#000000" stroke-width="1.6"/>
<path d="M168 32 L144 78" fill="none" stroke="#F4F1EA" stroke-width="7" stroke-linecap="round"/>
<path d="M144 78 L128 108 L119 99" fill="none" stroke="#C8F560" stroke-width="11" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 888 B

@@ -0,0 +1,11 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-35.0 -111.0 554.7 146.0" width="555" height="146" role="img" aria-label="scrobbled">
<path d="M27.8 1.4Q22.5 1.4 18.2 0.45Q13.9 -0.5 10.7 -2.3Q7.5 -4.1 5.45 -6.65Q3.4 -9.2 2.6 -12.3L14.6 -17.6Q15.3 -15.9 17.05 -14.15Q18.8 -12.4 21.75 -11.3Q24.7 -10.2 28.9 -10.2Q32.9 -10.2 35.15 -11.35Q37.4 -12.5 37.4 -14.7Q37.4 -16.3 36.15 -17.25Q34.9 -18.2 32.4 -18.95Q29.9 -19.7 26.2 -20.4Q22.4 -21.2 18.5 -22.25Q14.6 -23.3 11.2 -25.15Q7.8 -27 5.75 -30.05Q3.7 -33.1 3.7 -37.8Q3.7 -42.7 6.3 -46.35Q8.9 -50 14.05 -52.1Q19.2 -54.2 26.6 -54.2Q33.2 -54.2 38.2 -52.5Q43.2 -50.8 46.55 -47.65Q49.9 -44.5 51.2 -40.1L38.3 -35.5Q37.8 -37.7 36.25 -39.3Q34.7 -40.9 32.35 -41.75Q30 -42.6 26.8 -42.6Q22.9 -42.6 20.75 -41.4Q18.6 -40.2 18.6 -38.2Q18.6 -36.6 20.05 -35.55Q21.5 -34.5 24.2 -33.8Q26.9 -33.1 30.6 -32.3Q34.5 -31.5 38.35 -30.45Q42.2 -29.4 45.35 -27.65Q48.5 -25.9 50.35 -23.05Q52.2 -20.2 52.2 -15.7Q52.2 -10.4 49.4 -6.55Q46.6 -2.7 41.15 -0.65Q35.7 1.4 27.8 1.4Z" fill="#F4F1EA"/>
<path d="M84.6 1.4Q77.8 1.4 72.6 -0.5Q67.4 -2.4 63.9 -5.95Q60.4 -9.5 58.55 -14.5Q56.7 -19.5 56.7 -25.7Q56.7 -32.1 58.55 -37.3Q60.4 -42.5 63.9 -46.3Q67.4 -50.1 72.5 -52.15Q77.6 -54.2 84.2 -54.2Q90.8 -54.2 95.6 -52.1Q100.4 -50 103.45 -46.2Q106.5 -42.4 107.6 -37.4L92.7 -32.4Q92.4 -35.7 91.1 -37.8Q89.8 -39.9 87.75 -40.85Q85.7 -41.8 83.3 -41.8Q80.8 -41.8 78.9 -40.8Q77 -39.8 75.7 -37.8Q74.4 -35.8 73.7 -32.95Q73 -30.1 73 -26.4Q73 -21.1 74.35 -17.55Q75.7 -14 78.35 -12.2Q81 -10.4 84.8 -10.4Q88.7 -10.4 90.9 -12Q93.1 -13.6 94.1 -15.95Q95.1 -18.3 95.3 -20.6L109.3 -17.5Q108.9 -13.8 107.35 -10.35Q105.8 -6.9 102.8 -4.25Q99.8 -1.6 95.35 -0.1Q90.9 1.4 84.6 1.4Z" fill="#F4F1EA"/>
<path d="M114.8 0V-24.5V-52.8H128L128.3 -34.9H130.3Q131 -41.9 132.95 -46.05Q134.9 -50.2 138.55 -52.1Q142.2 -54 147.6 -54Q148.4 -54 149.4 -53.95Q150.4 -53.9 151.7 -53.7L151.1 -36.5Q149.5 -37.3 147.65 -37.55Q145.8 -37.8 144.4 -37.8Q140.5 -37.8 137.65 -36.3Q134.8 -34.8 133.15 -31.7Q131.5 -28.6 131 -23.9V0Z" fill="#F4F1EA"/>
<path d="M181.7 1.4Q173.7 1.4 167.55 -1.7Q161.4 -4.8 157.9 -11Q154.4 -17.2 154.4 -26.5Q154.4 -35.8 157.9 -41.95Q161.4 -48.1 167.6 -51.15Q173.8 -54.2 181.8 -54.2Q189.8 -54.2 196 -51.1Q202.2 -48 205.7 -41.85Q209.2 -35.7 209.2 -26.4Q209.2 -16.9 205.6 -10.7Q202 -4.5 195.75 -1.55Q189.5 1.4 181.7 1.4ZM182.2 -10.3Q185.8 -10.3 188.2 -11.95Q190.6 -13.6 191.8 -17Q193 -20.4 193 -25.4Q193 -30.7 191.7 -34.35Q190.4 -38 187.85 -39.95Q185.3 -41.9 181.3 -41.9Q177.9 -41.9 175.45 -40.25Q173 -38.6 171.8 -35.2Q170.6 -31.8 170.6 -26.7Q170.6 -18.5 173.65 -14.4Q176.7 -10.3 182.2 -10.3Z" fill="#F4F1EA"/>
<path d="M250 1.4Q245 1.4 241.25 -0.5Q237.5 -2.4 235.15 -6.2Q232.8 -10 232 -15.6H230.1L229.8 0H216.6V-25.9V-72H232.7V-54.5Q232.7 -52.1 232.35 -49.45Q232 -46.8 231.45 -43.9Q230.9 -41 230.3 -37.7H232.6Q234 -43.1 236.3 -46.7Q238.6 -50.3 242.05 -52.15Q245.5 -54 250.2 -54Q256.8 -54 261.65 -50.6Q266.5 -47.2 269.2 -40.95Q271.9 -34.7 271.9 -26Q271.9 -17.6 269.25 -11.45Q266.6 -5.3 261.7 -1.95Q256.8 1.4 250 1.4ZM244 -11.6Q247.3 -11.6 249.8 -13.45Q252.3 -15.3 253.65 -18.65Q255 -22 255 -26.5Q255 -31.1 253.7 -34.35Q252.4 -37.6 250.05 -39.4Q247.7 -41.2 244.4 -41.2Q242.2 -41.2 240.35 -40.4Q238.5 -39.6 237.1 -38.2Q235.7 -36.8 234.7 -35.05Q233.7 -33.3 233.2 -31.35Q232.7 -29.4 232.7 -27.5V-25.4Q232.7 -23.3 233.3 -20.9Q233.9 -18.5 235.25 -16.4Q236.6 -14.3 238.75 -12.95Q240.9 -11.6 244 -11.6Z" fill="#C8F560"/>
<path d="M312.8 1.4Q307.8 1.4 304.05 -0.5Q300.3 -2.4 297.95 -6.2Q295.6 -10 294.8 -15.6H292.9L292.6 0H279.4V-25.9V-72H295.5V-54.5Q295.5 -52.1 295.15 -49.45Q294.8 -46.8 294.25 -43.9Q293.7 -41 293.1 -37.7H295.4Q296.8 -43.1 299.1 -46.7Q301.4 -50.3 304.85 -52.15Q308.3 -54 313 -54Q319.6 -54 324.45 -50.6Q329.3 -47.2 332 -40.95Q334.7 -34.7 334.7 -26Q334.7 -17.6 332.05 -11.45Q329.4 -5.3 324.5 -1.95Q319.6 1.4 312.8 1.4ZM306.8 -11.6Q310.1 -11.6 312.6 -13.45Q315.1 -15.3 316.45 -18.65Q317.8 -22 317.8 -26.5Q317.8 -31.1 316.5 -34.35Q315.2 -37.6 312.85 -39.4Q310.5 -41.2 307.2 -41.2Q305 -41.2 303.15 -40.4Q301.3 -39.6 299.9 -38.2Q298.5 -36.8 297.5 -35.05Q296.5 -33.3 296 -31.35Q295.5 -29.4 295.5 -27.5V-25.4Q295.5 -23.3 296.1 -20.9Q296.7 -18.5 298.05 -16.4Q299.4 -14.3 301.55 -12.95Q303.7 -11.6 306.8 -11.6Z" fill="#F4F1EA"/>
<path d="M342.2 0V-72H358V0Z" fill="#F4F1EA"/>
<path d="M393.6 1.4Q387 1.4 381.8 -0.35Q376.6 -2.1 372.95 -5.5Q369.3 -8.9 367.4 -13.9Q365.5 -18.9 365.5 -25.4Q365.5 -31.7 367.35 -37Q369.2 -42.3 372.65 -46.15Q376.1 -50 381.15 -52.1Q386.2 -54.2 392.5 -54.2Q398.9 -54.2 403.75 -52.15Q408.6 -50.1 411.75 -46.1Q414.9 -42.1 416.4 -36.35Q417.9 -30.6 417.4 -23.2L376.1 -22.9V-31.3L408.2 -31.6L402.5 -27.7Q403.2 -32.7 401.9 -35.85Q400.6 -39 398.1 -40.45Q395.6 -41.9 392.7 -41.9Q389.2 -41.9 386.55 -40Q383.9 -38.1 382.4 -34.5Q380.9 -30.9 380.9 -25.7Q380.9 -17.5 384.45 -13.8Q388 -10.1 393.5 -10.1Q396.2 -10.1 398 -10.85Q399.8 -11.6 400.95 -12.75Q402.1 -13.9 402.75 -15.3Q403.4 -16.7 403.8 -18L417.8 -15Q417 -11.3 415.25 -8.3Q413.5 -5.3 410.55 -3.1Q407.6 -0.9 403.45 0.25Q399.3 1.4 393.6 1.4Z" fill="#F4F1EA"/>
<path d="M445.3 1.4Q438.7 1.4 433.75 -1.95Q428.8 -5.3 426 -11.55Q423.2 -17.8 423.2 -26.5Q423.2 -34.5 425.6 -40.7Q428 -46.9 432.75 -50.45Q437.5 -54 444.5 -54Q449.5 -54 452.95 -52.2Q456.4 -50.4 458.7 -46.8Q461 -43.2 462.4 -37.7H464.9Q464.2 -41.1 463.6 -44.15Q463 -47.2 462.65 -49.85Q462.3 -52.5 462.3 -54.5V-72H478.5V-25.8V0H465.3L465.1 -15.6H462.9Q461.8 -9.6 459.45 -5.85Q457.1 -2.1 453.55 -0.35Q450 1.4 445.3 1.4ZM451.1 -11.6Q454.2 -11.6 456.35 -12.95Q458.5 -14.3 459.8 -16.4Q461.1 -18.5 461.7 -20.9Q462.3 -23.3 462.3 -25.4V-27.5Q462.3 -29.4 461.8 -31.3Q461.3 -33.2 460.35 -35Q459.4 -36.8 458 -38.2Q456.6 -39.6 454.75 -40.4Q452.9 -41.2 450.7 -41.2Q447.4 -41.2 445.05 -39.4Q442.7 -37.6 441.45 -34.3Q440.2 -31 440.2 -26.5Q440.2 -22 441.5 -18.65Q442.8 -15.3 445.3 -13.45Q447.8 -11.6 451.1 -11.6Z" fill="#F4F1EA"/>
</svg>

After

Width:  |  Height:  |  Size: 5.7 KiB

@@ -0,0 +1,11 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-35.0 -111.0 554.7 146.0" width="555" height="146" role="img" aria-label="scrobbled">
<path d="M27.8 1.4Q22.5 1.4 18.2 0.45Q13.9 -0.5 10.7 -2.3Q7.5 -4.1 5.45 -6.65Q3.4 -9.2 2.6 -12.3L14.6 -17.6Q15.3 -15.9 17.05 -14.15Q18.8 -12.4 21.75 -11.3Q24.7 -10.2 28.9 -10.2Q32.9 -10.2 35.15 -11.35Q37.4 -12.5 37.4 -14.7Q37.4 -16.3 36.15 -17.25Q34.9 -18.2 32.4 -18.95Q29.9 -19.7 26.2 -20.4Q22.4 -21.2 18.5 -22.25Q14.6 -23.3 11.2 -25.15Q7.8 -27 5.75 -30.05Q3.7 -33.1 3.7 -37.8Q3.7 -42.7 6.3 -46.35Q8.9 -50 14.05 -52.1Q19.2 -54.2 26.6 -54.2Q33.2 -54.2 38.2 -52.5Q43.2 -50.8 46.55 -47.65Q49.9 -44.5 51.2 -40.1L38.3 -35.5Q37.8 -37.7 36.25 -39.3Q34.7 -40.9 32.35 -41.75Q30 -42.6 26.8 -42.6Q22.9 -42.6 20.75 -41.4Q18.6 -40.2 18.6 -38.2Q18.6 -36.6 20.05 -35.55Q21.5 -34.5 24.2 -33.8Q26.9 -33.1 30.6 -32.3Q34.5 -31.5 38.35 -30.45Q42.2 -29.4 45.35 -27.65Q48.5 -25.9 50.35 -23.05Q52.2 -20.2 52.2 -15.7Q52.2 -10.4 49.4 -6.55Q46.6 -2.7 41.15 -0.65Q35.7 1.4 27.8 1.4Z" fill="#15131A"/>
<path d="M84.6 1.4Q77.8 1.4 72.6 -0.5Q67.4 -2.4 63.9 -5.95Q60.4 -9.5 58.55 -14.5Q56.7 -19.5 56.7 -25.7Q56.7 -32.1 58.55 -37.3Q60.4 -42.5 63.9 -46.3Q67.4 -50.1 72.5 -52.15Q77.6 -54.2 84.2 -54.2Q90.8 -54.2 95.6 -52.1Q100.4 -50 103.45 -46.2Q106.5 -42.4 107.6 -37.4L92.7 -32.4Q92.4 -35.7 91.1 -37.8Q89.8 -39.9 87.75 -40.85Q85.7 -41.8 83.3 -41.8Q80.8 -41.8 78.9 -40.8Q77 -39.8 75.7 -37.8Q74.4 -35.8 73.7 -32.95Q73 -30.1 73 -26.4Q73 -21.1 74.35 -17.55Q75.7 -14 78.35 -12.2Q81 -10.4 84.8 -10.4Q88.7 -10.4 90.9 -12Q93.1 -13.6 94.1 -15.95Q95.1 -18.3 95.3 -20.6L109.3 -17.5Q108.9 -13.8 107.35 -10.35Q105.8 -6.9 102.8 -4.25Q99.8 -1.6 95.35 -0.1Q90.9 1.4 84.6 1.4Z" fill="#15131A"/>
<path d="M114.8 0V-24.5V-52.8H128L128.3 -34.9H130.3Q131 -41.9 132.95 -46.05Q134.9 -50.2 138.55 -52.1Q142.2 -54 147.6 -54Q148.4 -54 149.4 -53.95Q150.4 -53.9 151.7 -53.7L151.1 -36.5Q149.5 -37.3 147.65 -37.55Q145.8 -37.8 144.4 -37.8Q140.5 -37.8 137.65 -36.3Q134.8 -34.8 133.15 -31.7Q131.5 -28.6 131 -23.9V0Z" fill="#15131A"/>
<path d="M181.7 1.4Q173.7 1.4 167.55 -1.7Q161.4 -4.8 157.9 -11Q154.4 -17.2 154.4 -26.5Q154.4 -35.8 157.9 -41.95Q161.4 -48.1 167.6 -51.15Q173.8 -54.2 181.8 -54.2Q189.8 -54.2 196 -51.1Q202.2 -48 205.7 -41.85Q209.2 -35.7 209.2 -26.4Q209.2 -16.9 205.6 -10.7Q202 -4.5 195.75 -1.55Q189.5 1.4 181.7 1.4ZM182.2 -10.3Q185.8 -10.3 188.2 -11.95Q190.6 -13.6 191.8 -17Q193 -20.4 193 -25.4Q193 -30.7 191.7 -34.35Q190.4 -38 187.85 -39.95Q185.3 -41.9 181.3 -41.9Q177.9 -41.9 175.45 -40.25Q173 -38.6 171.8 -35.2Q170.6 -31.8 170.6 -26.7Q170.6 -18.5 173.65 -14.4Q176.7 -10.3 182.2 -10.3Z" fill="#15131A"/>
<path d="M250 1.4Q245 1.4 241.25 -0.5Q237.5 -2.4 235.15 -6.2Q232.8 -10 232 -15.6H230.1L229.8 0H216.6V-25.9V-72H232.7V-54.5Q232.7 -52.1 232.35 -49.45Q232 -46.8 231.45 -43.9Q230.9 -41 230.3 -37.7H232.6Q234 -43.1 236.3 -46.7Q238.6 -50.3 242.05 -52.15Q245.5 -54 250.2 -54Q256.8 -54 261.65 -50.6Q266.5 -47.2 269.2 -40.95Q271.9 -34.7 271.9 -26Q271.9 -17.6 269.25 -11.45Q266.6 -5.3 261.7 -1.95Q256.8 1.4 250 1.4ZM244 -11.6Q247.3 -11.6 249.8 -13.45Q252.3 -15.3 253.65 -18.65Q255 -22 255 -26.5Q255 -31.1 253.7 -34.35Q252.4 -37.6 250.05 -39.4Q247.7 -41.2 244.4 -41.2Q242.2 -41.2 240.35 -40.4Q238.5 -39.6 237.1 -38.2Q235.7 -36.8 234.7 -35.05Q233.7 -33.3 233.2 -31.35Q232.7 -29.4 232.7 -27.5V-25.4Q232.7 -23.3 233.3 -20.9Q233.9 -18.5 235.25 -16.4Q236.6 -14.3 238.75 -12.95Q240.9 -11.6 244 -11.6Z" fill="#8B6CFF"/>
<path d="M312.8 1.4Q307.8 1.4 304.05 -0.5Q300.3 -2.4 297.95 -6.2Q295.6 -10 294.8 -15.6H292.9L292.6 0H279.4V-25.9V-72H295.5V-54.5Q295.5 -52.1 295.15 -49.45Q294.8 -46.8 294.25 -43.9Q293.7 -41 293.1 -37.7H295.4Q296.8 -43.1 299.1 -46.7Q301.4 -50.3 304.85 -52.15Q308.3 -54 313 -54Q319.6 -54 324.45 -50.6Q329.3 -47.2 332 -40.95Q334.7 -34.7 334.7 -26Q334.7 -17.6 332.05 -11.45Q329.4 -5.3 324.5 -1.95Q319.6 1.4 312.8 1.4ZM306.8 -11.6Q310.1 -11.6 312.6 -13.45Q315.1 -15.3 316.45 -18.65Q317.8 -22 317.8 -26.5Q317.8 -31.1 316.5 -34.35Q315.2 -37.6 312.85 -39.4Q310.5 -41.2 307.2 -41.2Q305 -41.2 303.15 -40.4Q301.3 -39.6 299.9 -38.2Q298.5 -36.8 297.5 -35.05Q296.5 -33.3 296 -31.35Q295.5 -29.4 295.5 -27.5V-25.4Q295.5 -23.3 296.1 -20.9Q296.7 -18.5 298.05 -16.4Q299.4 -14.3 301.55 -12.95Q303.7 -11.6 306.8 -11.6Z" fill="#15131A"/>
<path d="M342.2 0V-72H358V0Z" fill="#15131A"/>
<path d="M393.6 1.4Q387 1.4 381.8 -0.35Q376.6 -2.1 372.95 -5.5Q369.3 -8.9 367.4 -13.9Q365.5 -18.9 365.5 -25.4Q365.5 -31.7 367.35 -37Q369.2 -42.3 372.65 -46.15Q376.1 -50 381.15 -52.1Q386.2 -54.2 392.5 -54.2Q398.9 -54.2 403.75 -52.15Q408.6 -50.1 411.75 -46.1Q414.9 -42.1 416.4 -36.35Q417.9 -30.6 417.4 -23.2L376.1 -22.9V-31.3L408.2 -31.6L402.5 -27.7Q403.2 -32.7 401.9 -35.85Q400.6 -39 398.1 -40.45Q395.6 -41.9 392.7 -41.9Q389.2 -41.9 386.55 -40Q383.9 -38.1 382.4 -34.5Q380.9 -30.9 380.9 -25.7Q380.9 -17.5 384.45 -13.8Q388 -10.1 393.5 -10.1Q396.2 -10.1 398 -10.85Q399.8 -11.6 400.95 -12.75Q402.1 -13.9 402.75 -15.3Q403.4 -16.7 403.8 -18L417.8 -15Q417 -11.3 415.25 -8.3Q413.5 -5.3 410.55 -3.1Q407.6 -0.9 403.45 0.25Q399.3 1.4 393.6 1.4Z" fill="#15131A"/>
<path d="M445.3 1.4Q438.7 1.4 433.75 -1.95Q428.8 -5.3 426 -11.55Q423.2 -17.8 423.2 -26.5Q423.2 -34.5 425.6 -40.7Q428 -46.9 432.75 -50.45Q437.5 -54 444.5 -54Q449.5 -54 452.95 -52.2Q456.4 -50.4 458.7 -46.8Q461 -43.2 462.4 -37.7H464.9Q464.2 -41.1 463.6 -44.15Q463 -47.2 462.65 -49.85Q462.3 -52.5 462.3 -54.5V-72H478.5V-25.8V0H465.3L465.1 -15.6H462.9Q461.8 -9.6 459.45 -5.85Q457.1 -2.1 453.55 -0.35Q450 1.4 445.3 1.4ZM451.1 -11.6Q454.2 -11.6 456.35 -12.95Q458.5 -14.3 459.8 -16.4Q461.1 -18.5 461.7 -20.9Q462.3 -23.3 462.3 -25.4V-27.5Q462.3 -29.4 461.8 -31.3Q461.3 -33.2 460.35 -35Q459.4 -36.8 458 -38.2Q456.6 -39.6 454.75 -40.4Q452.9 -41.2 450.7 -41.2Q447.4 -41.2 445.05 -39.4Q442.7 -37.6 441.45 -34.3Q440.2 -31 440.2 -26.5Q440.2 -22 441.5 -18.65Q442.8 -15.3 445.3 -13.45Q447.8 -11.6 451.1 -11.6Z" fill="#15131A"/>
</svg>

After

Width:  |  Height:  |  Size: 5.7 KiB

+6 -2
View File
@@ -3,8 +3,12 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Import · Scrobbler</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
<title>Import · Scrobbled</title>
<link rel="icon" href="favicon.ico" sizes="48x48">
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="manifest" href="site.webmanifest">
<meta name="theme-color" content="#1F1C28">
<link rel="stylesheet" href="css/style.css">
<script src="config.js"></script>
<script type="module" src="js/import.js"></script>
+6 -2
View File
@@ -3,8 +3,12 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Overview · Scrobbler</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
<title>Overview · Scrobbled</title>
<link rel="icon" href="favicon.ico" sizes="48x48">
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="manifest" href="site.webmanifest">
<meta name="theme-color" content="#1F1C28">
<link rel="stylesheet" href="css/style.css">
<script src="config.js"></script>
<script type="module" src="js/dashboard.js"></script>
+6 -6
View File
@@ -1,4 +1,4 @@
// Thin client for the Scrobbler /api/v1 JSON API.
// Thin client for the Scrobbled /api/v1 JSON API.
const TOKEN_KEY = "scrobbler.token";
@@ -77,7 +77,7 @@ export async function api(path, { method = "GET", body, auth = true } = {}) {
body: body === undefined ? undefined : JSON.stringify(body),
});
} catch {
throw new ApiError(0, "network", `Can't reach the Scrobbler API at ${apiBase}. Check that it's running.`);
throw new ApiError(0, "network", `Can't reach the Scrobbled API at ${apiBase}. Check that it's running.`);
}
if (response.status === 401 && auth) {
@@ -102,7 +102,7 @@ export async function api(path, { method = "GET", body, auth = true } = {}) {
// Turn webargs validation details into a single readable sentence.
export function describeError(error) {
const fields = error.details?.json ?? error.details?.query;
const fields = error.details?.json ?? error.details?.query ?? error.details?.files;
if (fields) {
return Object.entries(fields)
.map(([field, messages]) => `${field}: ${[].concat(messages).join(" ")}`)
@@ -112,17 +112,17 @@ export function describeError(error) {
}
// Multipart upload with progress (fetch can't report upload progress).
export function upload(path, formData, onProgress) {
export function upload(path, formData, onProgress, method = "POST") {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("POST", `${apiBase}/api/v1${path}`);
xhr.open(method, `${apiBase}/api/v1${path}`);
const token = getToken();
if (token) xhr.setRequestHeader("Authorization", `Bearer ${token}`);
xhr.upload.addEventListener("progress", (event) => {
if (event.lengthComputable) onProgress?.(event.loaded / event.total);
});
xhr.addEventListener("error", () =>
reject(new ApiError(0, "network", `Can't reach the Scrobbler API at ${apiBase}. Check that it's running.`)),
reject(new ApiError(0, "network", `Can't reach the Scrobbled API at ${apiBase}. Check that it's running.`)),
);
xhr.addEventListener("load", () => {
let data = null;
+1 -1
View File
@@ -113,7 +113,7 @@ function renderSetup() {
h("dt", {}, "Username"),
h("dd", {}, h("code", {}, user.username)),
h("dt", {}, "Password"),
h("dd", {}, "Your Scrobbler password"),
h("dd", {}, "Your Scrobbled password"),
h("dt", {}, "Key and secret"),
h("dd", {}, "From one of the apps above"),
h("dt", {}, "API reference"),
+178
View File
@@ -0,0 +1,178 @@
import { api, describeError, upload } from "./api.js";
import { artThumb, forgetArt } from "./art.js";
import { errorBox, h, num, replace } from "./dom.js";
import { signedInPage } from "./layout.js";
const PER_PAGE = 25;
const list = document.getElementById("albums");
const messages = document.getElementById("messages");
const pager = document.getElementById("pager");
const page = Math.max(1, Number.parseInt(new URLSearchParams(location.search).get("page"), 10) || 1);
await signedInPage("art.html");
await refresh();
async function refresh() {
try {
render(await api(`/art/failures?page=${page}&limit=${PER_PAGE}`));
} catch (error) {
replace(list, h("li", {}, errorBox(error.message)));
}
}
function render(result) {
document.getElementById("art-summary").textContent = result.total
? `${num(result.total)} of your albums have no cover art, most-played first. Upload a picture, retry the lookup, or correct what it searches for.`
: "Every album you've scrobbled has cover art, or is still being looked up.";
if (!result.items.length) {
replace(list);
} else {
replace(list, result.items.map(albumRow));
}
replace(
pager,
result.page > 1 ? h("a", { class: "button button-quiet", href: `?page=${result.page - 1}` }, "Previous") : h("span"),
result.page < result.total_pages
? h("a", { class: "button button-quiet", href: `?page=${result.page + 1}` }, "Next")
: h("span"),
);
}
function statusText(item) {
const own = item.override;
if (own?.status === "pending") return "Your correction is waiting to be looked up.";
if (own?.status === "error") {
return own.error_code === "NotFound"
? "Your correction didn't find any art."
: `Your correction failed (${own.error_code ?? "unknown error"}).`;
}
if (item.status === "error") return `The lookup failed (${item.error_code ?? "unknown error"}). It will be tried again.`;
if (item.status === "not_found") return "No cover art was found for this album.";
return "Waiting to be looked up.";
}
function say(notice) {
replace(messages, notice);
}
function albumRow(item) {
const { artist, album } = item;
const query = `artist=${encodeURIComponent(artist)}&album=${encodeURIComponent(album)}`;
const fileInput = h("input", { type: "file", accept: "image/jpeg,image/png,image/webp", hidden: true });
const correction = correctionForm(item, query);
const buttons = h("div", { class: "button-row" });
const busy = (on) => buttons.querySelectorAll("button").forEach((b) => (b.disabled = on));
async function act(work, done) {
busy(true);
replace(messages);
try {
await work();
say(h("p", { class: "notice notice-ok", role: "status" }, done));
forgetArt(artist, album);
await refresh();
} catch (error) {
say(errorBox(describeError(error)));
} finally {
busy(false);
}
}
fileInput.addEventListener("change", () => {
const file = fileInput.files[0];
if (!file) return;
const data = new FormData();
data.append("file", file);
act(() => upload(`/art/album?${query}`, data), `Uploaded art for ${album}.`);
fileInput.value = "";
});
replace(
buttons,
h("button", { type: "button", class: "button", onclick: () => fileInput.click() }, "Upload art"),
h(
"button",
{
type: "button",
class: "button button-quiet",
onclick: () => act(() => api(`/art/album/retry?${query}`, { method: "POST" }), `Looking up ${album} again.`),
},
"Retry lookup",
),
h(
"button",
{ type: "button", class: "button button-quiet", onclick: () => (correction.hidden = !correction.hidden) },
"Correct search",
),
item.override
? h(
"button",
{
type: "button",
class: "button button-quiet",
onclick: () => act(() => api(`/art/album?${query}`, { method: "DELETE" }), `Removed your correction for ${album}.`),
},
"Remove mine",
)
: null,
);
correction.addEventListener("submit", (event) => {
event.preventDefault();
const body = { artist, album };
const { search_artist, search_album, release_group_mbid, release_mbid } = correction.elements;
if (search_artist.value.trim()) body.search_artist = search_artist.value.trim();
if (search_album.value.trim()) body.search_album = search_album.value.trim();
if (release_group_mbid.value.trim()) body.release_group_mbid = release_group_mbid.value.trim();
if (release_mbid.value.trim()) body.release_mbid = release_mbid.value.trim();
act(() => api("/art/album/correction", { method: "PUT", body }), `Queued a corrected lookup for ${album}.`);
});
return h(
"li",
{ class: "art-row" },
artThumb(artist, album, "art-thumb-lg"),
h(
"div",
{ class: "art-row-body" },
h("span", { class: "row-title" }, album),
h("span", { class: "by" }, ` by ${artist}`),
h("p", { class: "muted" }, `${num(item.scrobbles)} ${item.scrobbles === 1 ? "scrobble" : "scrobbles"} · ${statusText(item)}`),
buttons,
fileInput,
correction,
),
);
}
function correctionForm(item, query) {
const own = item.override ?? {};
const field = (name, label, value, hint, extra = {}) =>
h(
"div",
{ class: "field" },
h("label", { for: `${name}-${query}` }, label),
h("input", { id: `${name}-${query}`, name, type: "text", value: value ?? "", autocomplete: "off", ...extra }),
hint ? h("p", { class: "hint" }, hint) : null,
);
return h(
"form",
{ class: "stacked-form art-correction", hidden: true },
field("search_artist", "Search for artist", own.search_artist ?? item.artist),
field("search_album", "Search for album", own.search_album ?? item.album),
field(
"release_group_mbid",
"MusicBrainz release-group ID (optional)",
own.release_group_mbid,
"If you know it, paste the ID from the album's MusicBrainz page. It skips the search.",
{ placeholder: "00000000-0000-0000-0000-000000000000", pattern: "[0-9a-fA-F-]{36}" },
),
field(
"release_mbid",
"MusicBrainz release ID (optional)",
own.release_mbid,
"Or a specific release's ID, if that's the one you have. Use either this or the release-group ID.",
{ placeholder: "00000000-0000-0000-0000-000000000000", pattern: "[0-9a-fA-F-]{36}" },
),
h("button", { type: "submit", class: "button" }, "Look it up"),
);
}
+9 -1
View File
@@ -6,12 +6,20 @@ import { h } from "./dom.js";
const cache = new Map(); // dedupes repeat/concurrent lookups for the same album within a page
const keyFor = (artist, album) => `${artist.toLowerCase()}␟${album.toLowerCase()}`;
// Forget a looked-up album (after the user uploads or corrects its art) so the next
// artThumb() for it asks the server again instead of reusing the stale answer.
export function forgetArt(artist, album) {
cache.delete(keyFor(artist, album));
}
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()}`;
const key = keyFor(artist, album);
if (!cache.has(key)) {
cache.set(
key,
+8 -1
View File
@@ -6,6 +6,7 @@ import { h, replace } from "./dom.js";
const NAV = [
["index.html", "Overview"],
["history.html", "History"],
["art.html", "Album art"],
["apps.html", "Apps"],
["sessions.html", "Sessions"],
["import.html", "Import"],
@@ -37,7 +38,13 @@ export function publicPage() {
}
function brand() {
return h("a", { class: "brand", href: "index.html" }, h("span", { class: "brand-mark", "aria-hidden": "true" }), "Scrobbler");
return h(
"a",
{ class: "brand", href: "index.html" },
h("span", { class: "brand-mark", "aria-hidden": "true" }),
h("span", { class: "brand-word", "aria-hidden": "true" }),
h("span", { class: "visually-hidden" }, "Scrobbled"),
);
}
function nav(active) {
+1 -1
View File
@@ -15,7 +15,7 @@ try {
`/federation/profiles/${encodeURIComponent(username)}/posts/${encodeURIComponent(postId)}`,
{ auth: false },
);
document.title = `${post.display_name} · Scrobbler`;
document.title = `${post.display_name} · Scrobbled`;
replace(
root,
h(
+1 -1
View File
@@ -10,7 +10,7 @@ publicPage();
try {
const profile = await api(`/federation/profiles/${encodeURIComponent(username)}`, { auth: false });
document.title = `${profile.display_name} · Scrobbler`;
document.title = `${profile.display_name} · Scrobbled`;
const copy = h("button", { type: "button", class: "button button-quiet" }, "Copy handle");
copy.addEventListener("click", async () => {
try {
+1 -1
View File
@@ -36,7 +36,7 @@ if (!artist || !track) {
}
function render(result) {
document.title = `${result.track} · Scrobbler`;
document.title = `${result.track} · Scrobbled`;
const m = result.metadata;
const body = h(
+6 -2
View File
@@ -3,8 +3,12 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sign in · Scrobbler</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
<title>Sign in · Scrobbled</title>
<link rel="icon" href="favicon.ico" sizes="48x48">
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="manifest" href="site.webmanifest">
<meta name="theme-color" content="#1F1C28">
<link rel="stylesheet" href="css/style.css">
<script src="config.js"></script>
<script type="module" src="js/login.js"></script>
+6 -2
View File
@@ -3,8 +3,12 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Post · Scrobbler</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
<title>Post · Scrobbled</title>
<link rel="icon" href="favicon.ico" sizes="48x48">
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="manifest" href="site.webmanifest">
<meta name="theme-color" content="#1F1C28">
<link rel="stylesheet" href="css/style.css">
<script src="config.js"></script>
<script type="module" src="js/post.js"></script>
+6 -2
View File
@@ -3,8 +3,12 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Posts · Scrobbler</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
<title>Posts · Scrobbled</title>
<link rel="icon" href="favicon.ico" sizes="48x48">
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="manifest" href="site.webmanifest">
<meta name="theme-color" content="#1F1C28">
<link rel="stylesheet" href="css/style.css">
<script src="config.js"></script>
<script type="module" src="js/posts.js"></script>
+6 -2
View File
@@ -3,8 +3,12 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Profile · Scrobbler</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
<title>Profile · Scrobbled</title>
<link rel="icon" href="favicon.ico" sizes="48x48">
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="manifest" href="site.webmanifest">
<meta name="theme-color" content="#1F1C28">
<link rel="stylesheet" href="css/style.css">
<script src="config.js"></script>
<script type="module" src="js/profile.js"></script>
+6 -2
View File
@@ -3,8 +3,12 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Create an account · Scrobbler</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
<title>Create an account · Scrobbled</title>
<link rel="icon" href="favicon.ico" sizes="48x48">
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="manifest" href="site.webmanifest">
<meta name="theme-color" content="#1F1C28">
<link rel="stylesheet" href="css/style.css">
<script src="config.js"></script>
<script type="module" src="js/register.js"></script>
+7 -3
View File
@@ -3,8 +3,12 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sessions · Scrobbler</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
<title>Sessions · Scrobbled</title>
<link rel="icon" href="favicon.ico" sizes="48x48">
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="manifest" href="site.webmanifest">
<meta name="theme-color" content="#1F1C28">
<link rel="stylesheet" href="css/style.css">
<script src="config.js"></script>
<script type="module" src="js/sessions.js"></script>
@@ -13,7 +17,7 @@
<header class="site-header" id="site-header"></header>
<main id="main">
<h1 class="page-title">Sessions</h1>
<p class="lede">Players you've signed in to Scrobbler. Revoking one signs it out straight away; it has to sign in again before it can scrobble.</p>
<p class="lede">Players you've signed in to Scrobbled. Revoking one signs it out straight away; it has to sign in again before it can scrobble.</p>
<div id="messages"></div>
<ul class="rows" id="sessions"></ul>
</main>
+6 -2
View File
@@ -3,8 +3,12 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sharing · Scrobbler</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
<title>Sharing · Scrobbled</title>
<link rel="icon" href="favicon.ico" sizes="48x48">
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="manifest" href="site.webmanifest">
<meta name="theme-color" content="#1F1C28">
<link rel="stylesheet" href="css/style.css">
<script src="config.js"></script>
<script type="module" src="js/sharing.js"></script>
+25
View File
@@ -0,0 +1,25 @@
{
"name": "Scrobbled",
"short_name": "Scrobbled",
"icons": [
{
"src": "icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "icon-512.png",
"sizes": "512x512",
"type": "image/png"
},
{
"src": "icon-maskable-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
],
"theme_color": "#1F1C28",
"background_color": "#1F1C28",
"display": "standalone"
}
+6 -2
View File
@@ -3,8 +3,12 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Song · Scrobbler</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
<title>Song · Scrobbled</title>
<link rel="icon" href="favicon.ico" sizes="48x48">
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="manifest" href="site.webmanifest">
<meta name="theme-color" content="#1F1C28">
<link rel="stylesheet" href="css/style.css">
<script src="config.js"></script>
<script type="module" src="js/song.js"></script>
+10
View File
@@ -11,11 +11,21 @@ wsgi_app = "scrobbler:create_app()"
bind = os.environ.get("BIND", "0.0.0.0:8000")
workers = int(os.environ.get("WEB_CONCURRENCY", "2"))
accesslog = "-"
loglevel = os.environ.get("LOG_LEVEL", "INFO").lower()
forwarded_allow_ips = os.environ.get("FORWARDED_ALLOW_IPS", "127.0.0.1")
# gunicorn 26's control socket lives in $HOME, which the container user doesn't have.
control_socket_disable = True
def post_fork(server, worker):
# Gunicorn's own messages go through the app's handler too, so the format is uniform.
import logging
gunicorn_error = logging.getLogger("gunicorn.error")
gunicorn_error.handlers.clear()
gunicorn_error.propagate = True
def on_starting(server):
# Stale files from a previous run would double-count.
shutil.rmtree(MULTIPROC_DIR, ignore_errors=True)
+1 -1
View File
@@ -1,4 +1,4 @@
"""Send realistic traffic to a running Scrobbler, e.g. to see the Grafana dashboards move.
"""Send realistic traffic to a running Scrobbled, e.g. to see the Grafana dashboards move.
uv run python scripts/generate_traffic.py --api http://localhost:5050 --minutes 5
+2 -2
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env bash
# docker compose for the federation interop stack (Scrobbler + GoToSocial).
# docker compose for the federation interop stack (Scrobbled + GoToSocial).
set -euo pipefail
root="$(cd "$(dirname "$0")/../.." && pwd)"
# INTEROP_PROJECT and INTEROP_SUBNET let concurrent runs (e.g. in CI) stay apart.
# INTEROP_PROJECT (with a distinct SCROBBLER_IMAGE_TAG) lets concurrent runs (e.g. in CI) stay apart.
exec docker compose -p "${INTEROP_PROJECT:-scrobbler-interop}" \
-f "$root/docker-compose.yml" -f "$root/deploy/interop/docker-compose.interop.yml" "$@"
+15 -15
View File
@@ -1,4 +1,4 @@
"""Federation interop test: a real GoToSocial account follows a Scrobbler user.
"""Federation interop test: a real GoToSocial account follows a Scrobbled user.
Runs inside the interop compose network (see deploy/interop/). Standard library only.
Exits non-zero, with a description, on the first thing that doesn't work.
@@ -164,7 +164,7 @@ def wait_for(description, check, timeout=60):
fail(f"timed out waiting for: {description}")
class Scrobbler:
class Scrobbled:
def __init__(self, username="alice", password="interop-password-1"):
status, body = api(
"POST",
@@ -185,7 +185,7 @@ class Scrobbler:
},
)
if status not in (200, 201):
fail(f"signing in to Scrobbler: {status} {body}")
fail(f"signing in to Scrobbled: {status} {body}")
self.token = body["token"]
def settings(self, **changes):
@@ -193,7 +193,7 @@ class Scrobbler:
"PATCH", f"{SCROBBLER_API}/federation/settings", self.token, body=changes
)
if status != 200:
fail(f"changing Scrobbler settings: {status} {body}")
fail(f"changing Scrobbled settings: {status} {body}")
return body
def followers(self, state=None):
@@ -275,8 +275,8 @@ def main():
step("Getting a GoToSocial access token")
gts = GoToSocial(gotosocial_token())
step("Alice starts sharing on Scrobbler")
alice = Scrobbler()
step("Alice starts sharing on Scrobbled")
alice = Scrobbled()
alice.settings(
enabled=True,
display_name="Alice Interop",
@@ -294,14 +294,14 @@ def main():
step("Follow: GoToSocial sees it accepted (our signed Accept verified)")
gts.follow(account_id)
wait_for("GoToSocial to be following", lambda: gts.relationship(account_id)["following"])
followers = wait_for("Scrobbler to list the follower", lambda: alice.followers("accepted"))
print(f" Scrobbler follower: {followers[0]['handle']}")
followers = wait_for("Scrobbled to list the follower", lambda: alice.followers("accepted"))
print(f" Scrobbled follower: {followers[0]['handle']}")
if followers[0]["handle"] != "@gtsuser@gts.test":
fail(f"unexpected follower {followers[0]['handle']}")
step("Unfollow: Scrobbler drops the follower (their signed Undo verified)")
step("Unfollow: Scrobbled drops the follower (their signed Undo verified)")
gts.unfollow(account_id)
wait_for("Scrobbler to drop the follower", lambda: not alice.followers())
wait_for("Scrobbled to drop the follower", lambda: not alice.followers())
step("Manual approval: the follow waits as a request")
alice.settings(manually_approves_followers=True)
@@ -309,7 +309,7 @@ def main():
wait_for(
"GoToSocial to show a pending request", lambda: gts.relationship(account_id)["requested"]
)
pending = wait_for("Scrobbler to list the request", lambda: alice.followers("pending"))
pending = wait_for("Scrobbled to list the request", lambda: alice.followers("pending"))
if gts.relationship(account_id)["following"]:
fail("following before being approved")
@@ -317,7 +317,7 @@ def main():
alice.act(pending[0]["id"], "approve")
wait_for("GoToSocial to be following", lambda: gts.relationship(account_id)["following"])
step("Remove the follower: Scrobbler drops them and sends a Reject")
step("Remove the follower: Scrobbled drops them and sends a Reject")
alice.act(alice.followers()[0]["id"], "remove")
if alice.followers():
fail("the follower is still listed after removal")
@@ -338,7 +338,7 @@ def main():
step("Block a follower: GoToSocial drops the follow (it honours Block)")
gts.follow(account_id)
pending = wait_for("Scrobbler to list the request", lambda: alice.followers("pending"))
pending = wait_for("Scrobbled to list the request", lambda: alice.followers("pending"))
alice.act(pending[0]["id"], "approve")
wait_for("GoToSocial to be following", lambda: gts.relationship(account_id)["following"])
alice.act(alice.followers()[0]["id"], "block")
@@ -358,7 +358,7 @@ def main():
step("Decline a request: GoToSocial's request is withdrawn")
gts.follow(account_id)
pending = wait_for("Scrobbler to list the request", lambda: alice.followers("pending"))
pending = wait_for("Scrobbled to list the request", lambda: alice.followers("pending"))
alice.act(pending[0]["id"], "decline")
wait_for(
"GoToSocial's request to go away",
@@ -385,7 +385,7 @@ def check_posts():
profile field GoToSocial has cached is updated by the periodic push."""
step("Getting a GoToSocial access token")
gts = GoToSocial(gotosocial_token())
alice = Scrobbler() # register-or-login: the same account main() set up
alice = Scrobbled() # register-or-login: the same account main() set up
account = gts.resolve("@alice@scrobble.test")
account_id = account["id"]
if not gts.relationship(account_id)["following"]:
+10 -3
View File
@@ -6,11 +6,18 @@ here="$(cd "$(dirname "$0")" && pwd)"
compose="$here/compose.sh"
keep=0; [ "${1:-}" = "--keep" ] && keep=1
cleanup() { [ "$keep" = 1 ] || "$compose" down -v --remove-orphans >/dev/null 2>&1; }
cleanup() {
[ "$keep" = 1 ] && return 0
"$compose" down -v --remove-orphans --rmi local >/dev/null 2>&1
# Per-run api/ui images (tagged with SCROBBLER_IMAGE_TAG) would otherwise pile up
[ -n "${SCROBBLER_IMAGE_TAG:-}" ] && "$compose" config --images 2>/dev/null \
| grep ":${SCROBBLER_IMAGE_TAG}$" | xargs -r docker rmi >/dev/null 2>&1
return 0
}
trap cleanup EXIT
"$compose" down -v --remove-orphans >/dev/null 2>&1
echo "==> Building and starting Scrobbler + GoToSocial"
echo "==> Building and starting Scrobbled + GoToSocial"
"$compose" up -d --build --wait db api ui worker tls gotosocial || { "$compose" ps; exit 1; }
echo "==> Waiting for GoToSocial"
@@ -25,7 +32,7 @@ echo "==> Creating the GoToSocial test user"
"$compose" exec -T gotosocial /gotosocial/gotosocial admin account confirm --username gtsuser >/dev/null
diagnose() {
echo "==> Scrobbler federation state"
echo "==> Scrobbled federation state"
"$compose" exec -T db psql -U scrobbler -d scrobbler -c \
"select activity_type, status, reason, attempts from federation_inbox order by id" -c \
"select a.activity_type, d.status, d.attempts, d.last_status, left(d.last_error, 200) as error
+4
View File
@@ -19,6 +19,10 @@ def create_app(config_object=None):
app = Flask(__name__, static_folder=None) # API only: the UI is hosted separately
app.config.from_object(config_object or Config)
from scrobbler.logsetup import configure_logging
configure_logging(app.config["LOG_LEVEL"], app.config["LOG_FORMAT"])
db.init_app(app)
migrate.init_app(app, db, directory=_migrations_dir())
http_metrics.init_app(app)
+147 -8
View File
@@ -1,39 +1,178 @@
from flask import Response
import math
from flask import Response, current_app, g, request
from flask_smorest import Blueprint, abort
from scrobbler import metrics
from scrobbler.api.decorators import authenticated
from scrobbler.schemas import AlbumArtArgsSchema, ErrorSchema
from scrobbler.schemas import (
AlbumArtArgsSchema,
AlbumArtCorrectionSchema,
AlbumArtFailuresPageSchema,
AlbumArtOverrideSchema,
AlbumArtUploadSchema,
ErrorSchema,
PageArgsSchema,
)
from scrobbler.services import art
blp = Blueprint(
"Art",
__name__,
description="Album art, resolved from MusicBrainz / Cover Art Archive by a background worker",
description=(
"Album art, resolved from MusicBrainz / Cover Art Archive by a background worker. "
"You can also upload your own art, or correct a failed lookup; those only change "
"what you see."
),
)
@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.response(
200, content_type="image/jpeg", description="The album's cover art (JPEG, PNG or WebP)"
)
@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.
Your own uploaded or corrected art comes first. Otherwise it's 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.
"""
own = art.get_override(g.user.id, args["artist"], args["album"])
if own is not None and own.status == "found":
data = art.read_override_file(own)
if data is not None:
metrics.art_requests_total.labels("override").inc()
response = Response(data, mimetype=own.content_type or "image/jpeg")
response.headers["Cache-Control"] = "private, no-cache" # revalidate: it can change
response.add_etag()
return response.make_conditional(request)
row = art.get_cached(args["artist"], args["album"])
if row is None:
art.want(args["artist"], args["album"])
metrics.art_requests_total.labels("queued").inc()
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
result = "file_missing"
else:
result = "pending" if row.status == "pending" else "unavailable"
metrics.art_requests_total.labels(result).inc()
abort(404, code="no_album_art", message="No cover art found for this album")
metrics.art_requests_total.labels("served").inc()
response = Response(image, mimetype="image/jpeg")
response.headers["Cache-Control"] = "private, max-age=604800" # 7 days; art rarely changes
return response
@blp.route("/album", methods=["POST"])
@authenticated(blp)
@blp.arguments(AlbumArtUploadSchema, location="files")
@blp.arguments(AlbumArtArgsSchema, location="query")
@blp.response(201, AlbumArtOverrideSchema)
@blp.alt_response(400, schema=ErrorSchema, description="Empty file")
@blp.alt_response(413, schema=ErrorSchema, description="Image too large")
@blp.alt_response(415, schema=ErrorSchema, description="Not a JPEG, PNG or WebP image")
def upload_art(files, args):
"""Upload your own art for an album
Replaces any earlier upload or correction of yours for this album. Only you see it.
"""
limit = current_app.config["ART_UPLOAD_MAX_BYTES"]
data = files["file"].read(limit + 1)
if not data:
metrics.art_uploads_total.labels("empty").inc()
abort(400, code="empty_file", message="That file is empty.")
if len(data) > limit:
metrics.art_uploads_total.labels("too_large").inc()
abort(413, code="file_too_large", message="That image is larger than this server accepts.")
try:
content_type = art.sniff_image_type(data)
except art.UnsupportedImage:
metrics.art_uploads_total.labels("bad_type").inc()
abort(415, code="unsupported_image", message="Upload a JPEG, PNG or WebP image.")
art.save_upload(g.user.id, args["artist"], args["album"], data, content_type)
metrics.art_uploads_total.labels("ok").inc()
metrics.art_upload_bytes.observe(len(data))
return art.get_override(g.user.id, args["artist"], args["album"])
@blp.route("/album", methods=["DELETE"])
@authenticated(blp)
@blp.arguments(AlbumArtArgsSchema, location="query")
@blp.response(204)
@blp.alt_response(404, schema=ErrorSchema, description="You have no art of your own for this album")
def delete_override(args):
"""Remove your own art for an album
The album goes back to the shared lookup result, if there is one.
"""
if not art.delete_override(g.user.id, args["artist"], args["album"]):
abort(404, code="not_found", message="You have no art of your own for this album")
@blp.route("/album/correction", methods=["PUT"])
@authenticated(blp)
@blp.arguments(AlbumArtCorrectionSchema)
@blp.response(202, AlbumArtOverrideSchema)
def correct_art(body):
"""Correct a failed lookup
Queues a new lookup with different search text, or straight from a MusicBrainz
release-group or release ID. The background worker resolves it; poll the failures list, or just
fetch the art later. Replaces any earlier upload or correction of yours.
"""
mbid = body.get("release_group_mbid")
release_mbid = body.get("release_mbid")
art.request_correction(
g.user.id,
body["artist"],
body["album"],
body.get("search_artist"),
body.get("search_album"),
str(mbid) if mbid else None,
str(release_mbid) if release_mbid else None,
)
return art.get_override(g.user.id, body["artist"], body["album"])
@blp.route("/album/retry", methods=["POST"])
@authenticated(blp)
@blp.arguments(AlbumArtArgsSchema, location="query")
@blp.response(202)
@blp.alt_response(409, schema=ErrorSchema, description="Nothing to retry")
def retry_art(args):
"""Look an album up again
Re-queues the shared lookup for an album whose search found nothing or failed.
"""
if not art.retry(args["artist"], args["album"]):
abort(409, code="nothing_to_retry", message="This album's art is found or already queued")
@blp.route("/failures", methods=["GET"])
@authenticated(blp)
@blp.arguments(PageArgsSchema, location="query")
@blp.response(200, AlbumArtFailuresPageSchema)
def failures(args):
"""Albums of yours without art
Albums you've scrobbled whose lookup found nothing or failed, plus ones where your
own correction didn't work, most-scrobbled first. Albums you've fixed drop off.
"""
items, total = art.list_failures(g.user.id, args["page"], args["limit"])
return {
"items": items,
"page": args["page"],
"per_page": args["limit"],
"total": total,
"total_pages": math.ceil(total / args["limit"]),
}
-1
View File
@@ -8,7 +8,6 @@ from flask.cli import AppGroup, with_appcontext
def _run_worker(once: bool, poll: float, serve_metrics: bool) -> None:
from scrobbler import worker
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
if serve_metrics:
from scrobbler.metrics.server import start_metrics_server
+8 -1
View File
@@ -20,13 +20,16 @@ class Config:
CORS_ORIGINS = _csv(os.environ.get("CORS_ORIGINS", "http://localhost:8080"))
UI_BASE_URL = os.environ.get("UI_BASE_URL", "http://localhost:8080").rstrip("/")
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()
LOG_FORMAT = os.environ.get("LOG_FORMAT", "text").lower() # "text" or "json"
METRICS_PORT = int(os.environ.get("METRICS_PORT", "9100"))
# Start the metrics HTTP server from create_app (dev server). Under gunicorn the
# server is started by gunicorn.conf.py instead, so this stays off there.
START_METRICS_SERVER = os.environ.get("START_METRICS_SERVER", "0") == "1"
# OpenAPI document and docs (flask-smorest)
API_TITLE = "Scrobbler API"
API_TITLE = "Scrobbled API"
API_VERSION = "v1"
OPENAPI_VERSION = "3.1.0"
OPENAPI_URL_PREFIX = "/api"
@@ -67,6 +70,8 @@ class Config:
# 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")
# Largest image a user may upload as their own album art.
ART_UPLOAD_MAX_BYTES = int(os.environ.get("ART_UPLOAD_MAX_BYTES", str(5 * 1024 * 1024)))
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
@@ -90,6 +95,8 @@ class TestConfig(Config):
"postgresql+psycopg://scrobbler:scrobbler@localhost:5432/scrobbler_test",
)
START_METRICS_SERVER = False
LOG_LEVEL = "INFO"
LOG_FORMAT = "text"
# Tests never inherit optional features or URLs from a developer's .env or
# environment; tests that need them turn them on, or override them, explicitly.
LASTFM_API_KEY = ""
+1 -1
View File
@@ -112,7 +112,7 @@ for users with it on, every 30 seconds). All are registered only when federation
## Interop
`scripts/interop/run.sh` runs Scrobbler against a real GoToSocial server on a private
`scripts/interop/run.sh` runs Scrobbled against a real GoToSocial server on a private
`.test` network. `scripts/interop/gotosocial_interop.py` checks the whole follow life
cycle, then `run.sh` seeds a scrobble and a now-playing track, runs
`flask federation post-weekly --now` directly in the `api` container, and runs the
+1 -1
View File
@@ -1,6 +1,6 @@
"""ActivityPub federation: optional, self-contained, replaceable.
The rest of Scrobbler only calls `init_app(app)` (from `create_app`) and sends domain
The rest of Scrobbled only calls `init_app(app)` (from `create_app`) and sends domain
events (`scrobbler.events`). Everything else about federation lives in this package;
see README.md here and docs/design/activitypub.md.
+16 -1
View File
@@ -68,6 +68,13 @@ def _retry_or_abandon(delivery: FederationDelivery, error: str, status: int | No
delivery.last_status, delivery.last_error = status, error[:1000]
if _now() - delivery.created_at >= GIVE_UP_AFTER:
delivery.status = "abandoned"
log.warning(
"delivery %s to %s abandoned after %s attempts: %s",
delivery.id,
delivery.inbox,
delivery.attempts,
error[:200],
)
return "abandoned"
delay = (
RETRY_DELAYS[delivery.attempts - 1]
@@ -75,6 +82,14 @@ def _retry_or_abandon(delivery: FederationDelivery, error: str, status: int | No
else LATER_DELAY
)
delivery.next_attempt_at = _now() + delay
log.warning(
"delivery %s to %s failed (attempt %s), retrying in %s: %s",
delivery.id,
delivery.inbox,
delivery.attempts,
delay,
error[:200],
)
return "retry"
@@ -135,7 +150,7 @@ def _deliver_in_context(app, delivery_id: int) -> str:
try:
return deliver(delivery_id)
except Exception:
log.exception("delivery %s failed unexpectedly", delivery_id)
log.exception("delivery %s failed unexpectedly (will be retried)", delivery_id)
db.session.rollback()
return "retry" # the lease expires and it becomes due again
finally:
+7 -1
View File
@@ -224,7 +224,13 @@ def process(item: FederationInboxItem) -> None:
db.session.rollback()
transient = isinstance(err, FetchError) and err.reason == "network"
if not transient:
log.exception("inbox item %s failed", item.id)
log.exception(
"inbox item %s (%s) failed on attempt %s of %s",
item.id,
item.activity_type,
item.attempts,
MAX_ATTEMPTS,
)
if item.attempts < MAX_ATTEMPTS:
_finish(item, "queued", f"retrying: {err}"[:255], done=False)
return
+1 -1
View File
@@ -19,7 +19,7 @@ def client() -> Client:
config = current_app.extensions["federation"]
existing = Client(
user_agent=f"Scrobbler/{__version__} (+{config.base_url})",
user_agent=f"Scrobbled/{__version__} (+{config.base_url})",
insecure_testing=config.insecure_testing,
)
current_app.extensions["federation_client"] = existing
@@ -2,6 +2,6 @@
NodeInfo documents, HTTP signature schemes.
Rule: nothing in this package imports Flask, SQLAlchemy, Werkzeug or any other part of
Scrobbler; only the standard library and `cryptography`. Spec changes land here and are
Scrobbled; only the standard library and `cryptography`. Spec changes land here and are
tested with spec test vectors alone. (Enforced by tests/test_federation_boundary.py.)
"""
+1 -1
View File
@@ -7,7 +7,7 @@ line of a post is its own paragraph.
import html
HASHTAG = "Scrobbler"
HASHTAG = "Scrobbled"
def escape(text: str) -> str:
+1 -1
View File
@@ -235,7 +235,7 @@ def update(activity_id: str, actor_id: str, obj: dict, *, to: list[str]) -> dict
def hashtag(name: str) -> dict:
"""A Hashtag tag, e.g. #Scrobbler. No href: we don't serve tag pages, and Mastodon
"""A Hashtag tag, e.g. #Scrobbled. No href: we don't serve tag pages, and Mastodon
still recognises and indexes the tag from `name` alone."""
return {"type": "Hashtag", "name": f"#{name}"}
+1 -1
View File
@@ -18,7 +18,7 @@ from scrobbler.federation import metrics as fed_metrics
from scrobbler.federation.models import FederationActivity, FederationPost
from scrobbler.federation.protocol import addressing, vocab
DEFAULT_TAGS = ("Scrobbler",)
DEFAULT_TAGS = ("Scrobbled",)
OUTBOX_PAGE_SIZE = 20
LISTED_VISIBILITIES = ("public", "unlisted") # followers-only posts aren't listed unauthenticated
@@ -108,7 +108,7 @@ def _post_now_playing(user, playing, key: str, state: FederationNowPlaying, now:
key,
text=text,
html=html,
tags=("Scrobbler", "NowPlaying"),
tags=("Scrobbled", "NowPlaying"),
attachment=_attachment_for(playing),
)
if post is None:
+44
View File
@@ -0,0 +1,44 @@
"""Logging set-up shared by the API and the worker (`LOG_LEVEL`, `LOG_FORMAT`).
`text` is human-readable; `json` is one object per line for log aggregators. Fields passed
as `extra=` to a log call (e.g. `task`, `duration_ms`) appear as keys in the JSON output.
"""
import json
import logging
import sys
from datetime import UTC, datetime
TEXT_FORMAT = "%(asctime)s %(levelname)s %(name)s %(message)s"
# Attributes every LogRecord has; anything else on a record came from `extra=`.
_STANDARD = set(logging.makeLogRecord({}).__dict__) | {"message", "asctime", "taskName"}
_HANDLER_FLAG = "_scrobbler_handler"
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
entry = {
"time": datetime.fromtimestamp(record.created, UTC).isoformat(timespec="milliseconds"),
"level": record.levelname,
"logger": record.name,
"message": record.getMessage(),
}
entry.update((k, v) for k, v in record.__dict__.items() if k not in _STANDARD)
if record.exc_info:
entry["exception"] = self.formatException(record.exc_info)
return json.dumps(entry, default=str)
def configure_logging(level: str = "INFO", fmt: str = "text") -> None:
"""Point the root logger at stderr. Safe to call repeatedly (it replaces its own
handler); an unknown level falls back to INFO."""
root = logging.getLogger()
for handler in [h for h in root.handlers if getattr(h, _HANDLER_FLAG, False)]:
root.removeHandler(handler)
handler = logging.StreamHandler(sys.stderr)
setattr(handler, _HANDLER_FLAG, True)
handler.setFormatter(JsonFormatter() if fmt == "json" else logging.Formatter(TEXT_FORMAT))
root.addHandler(handler)
resolved = logging.getLevelName(str(level).upper())
root.setLevel(resolved if isinstance(resolved, int) else logging.INFO)
+76
View File
@@ -122,6 +122,77 @@ worker_tasks_total = Counter(
["task", "outcome"],
)
# Album art (endpoint + background resolver)
art_requests_total = Counter(
"scrobbler_art_requests_total",
"Album art endpoint responses: served, queued (first sighting), pending (still "
"resolving), unavailable (no art found), file_missing (re-queued)",
["result"],
)
art_resolutions_total = Counter(
"scrobbler_art_resolutions_total",
"Album art resolutions by outcome (found, not_found, error) and caller (worker, inline)",
["source", "result"],
)
art_upstream_seconds = Histogram(
"scrobbler_art_upstream_seconds",
"Latency of one album art upstream call, by service (musicbrainz, coverart, download)",
["service", "outcome"],
buckets=(0.1, 0.25, 0.5, 1, 2.5, 5, 10, 20, 40),
)
art_upstream_errors_total = Counter(
"scrobbler_art_upstream_errors_total",
"Failed album art upstream calls, by service and exception class",
["service", "error"],
)
art_worker_resolve_seconds = Histogram(
"scrobbler_art_worker_resolve_seconds",
"Time for the worker to resolve and download one album's art",
buckets=(0.25, 0.5, 1, 2.5, 5, 10, 20, 40, 80),
)
art_image_bytes = Histogram(
"scrobbler_art_image_bytes",
"Size of downloaded album art images",
buckets=(5_000, 10_000, 25_000, 50_000, 100_000, 250_000, 500_000, 1_000_000),
)
# Album art: per-user uploads and corrections
art_uploads_total = Counter(
"scrobbler_art_uploads_total",
"Album art upload attempts: ok, empty, too_large or bad_type",
["result"],
)
art_upload_bytes = Histogram(
"scrobbler_art_upload_bytes",
"Size of accepted album art uploads",
buckets=(5_000, 10_000, 25_000, 50_000, 100_000, 250_000, 500_000, 1_000_000, 5_000_000),
)
art_override_actions_total = Counter(
"scrobbler_art_override_actions_total",
"Manual album art actions: correction_requested, retry_requested, override_deleted",
["action"],
)
art_mbid_lookups_total = Counter(
"scrobbler_art_mbid_lookups_total",
"Album art lookups that tried a scrobble's recording MBID, by result (matched, missed)",
["result"],
)
art_correction_resolutions_total = Counter(
"scrobbler_art_correction_resolutions_total",
"Worker outcome of a manual correction, by input (mbid, release_mbid or search) and result",
["input", "result"],
)
art_correction_wait_seconds = Histogram(
"scrobbler_art_correction_wait_seconds",
"Time from a correction being requested to the worker finishing it",
buckets=(1, 5, 15, 30, 60, 300, 900, 3600, 6 * 3600),
)
art_override_worker_seconds = Histogram(
"scrobbler_art_override_worker_seconds",
"Time for the worker to resolve and download one corrected album's art",
buckets=(0.25, 0.5, 1, 2.5, 5, 10, 20, 40, 80),
)
# Database
db_query_duration_seconds = Histogram(
"scrobbler_db_query_duration_seconds",
@@ -150,4 +221,9 @@ COLLECTED = {
"active_users": "scrobbler_active_users",
"now_playing_active": "scrobbler_now_playing_active",
"import_jobs": "scrobbler_import_jobs",
"art_cache": "scrobbler_art_cache",
"art_oldest_pending": "scrobbler_art_oldest_pending_seconds",
"art_overrides": "scrobbler_art_overrides",
"art_override_oldest_pending": "scrobbler_art_override_oldest_pending_seconds",
"art_unresolved": "scrobbler_art_unresolved_albums",
}
+69
View File
@@ -12,6 +12,9 @@ from sqlalchemy.pool import NullPool
from scrobbler.metrics import COLLECTED
ART_STATUSES = ("pending", "found", "not_found", "error")
ART_OVERRIDE_KINDS = ("upload", "correction")
ART_OVERRIDE_STATUSES = ("pending", "found", "error")
ACTIVE_WINDOWS = {"1h": "1 hour", "24h": "24 hours", "7d": "7 days"}
@@ -46,11 +49,48 @@ class DatabaseStatsCollector(Collector):
)
).all()
)
art_cache = dict(
conn.execute(text("SELECT status, count(*) FROM album_art GROUP BY status")).all()
)
oldest_pending = conn.execute(
text(
"SELECT coalesce(extract(epoch FROM now() - min(checked_at)), 0) "
"FROM album_art WHERE status = 'pending'"
)
).scalar_one()
overrides = {
(kind, status): count
for kind, status, count in conn.execute(
text("SELECT kind, status, count(*) FROM user_album_art GROUP BY kind, status")
).all()
}
override_oldest = conn.execute(
text(
"SELECT coalesce(extract(epoch FROM now() - min(updated_at)), 0) "
"FROM user_album_art WHERE status = 'pending'"
)
).scalar_one()
unresolved = conn.execute(
text(
"SELECT count(*) FROM album_art a WHERE a.status IN ('not_found', 'error') "
"AND NOT EXISTS (SELECT 1 FROM user_album_art u WHERE u.status = 'found' "
"AND lower(u.artist) = lower(a.artist) AND lower(u.album) = lower(a.album))"
)
).scalar_one()
return {
"users": users,
"active": active,
"now_playing": now_playing,
"import_jobs": {s: import_jobs.get(s, 0) for s in ("pending", "running")},
"art_cache": {s: art_cache.get(s, 0) for s in ART_STATUSES},
"art_oldest_pending": float(oldest_pending),
"art_overrides": {
(kind, status): overrides.get((kind, status), 0)
for kind in ART_OVERRIDE_KINDS
for status in ART_OVERRIDE_STATUSES
},
"art_override_oldest_pending": float(override_oldest),
"art_unresolved": unresolved,
}
def values(self) -> dict | None:
@@ -85,3 +125,32 @@ class DatabaseStatsCollector(Collector):
for status, count in values["import_jobs"].items():
jobs.add_metric([status], count)
yield jobs
art = GaugeMetricFamily(
COLLECTED["art_cache"], "Album art cache rows by status", labels=["status"]
)
for status, count in values["art_cache"].items():
art.add_metric([status], count)
yield art
yield GaugeMetricFamily(
COLLECTED["art_oldest_pending"],
"Age of the longest-waiting album art request (0 if none pending)",
value=values["art_oldest_pending"],
)
overrides = GaugeMetricFamily(
COLLECTED["art_overrides"],
"User album art overrides by kind and status",
labels=["kind", "status"],
)
for (kind, status), count in values["art_overrides"].items():
overrides.add_metric([kind, status], count)
yield overrides
yield GaugeMetricFamily(
COLLECTED["art_override_oldest_pending"],
"Age of the longest-waiting manual art correction (0 if none pending)",
value=values["art_override_oldest_pending"],
)
yield GaugeMetricFamily(
COLLECTED["art_unresolved"],
"Albums with no art that no user has fixed",
value=values["art_unresolved"],
)
+1 -1
View File
@@ -11,7 +11,7 @@ config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
fileConfig(config.config_file_name, disable_existing_loggers=False)
logger = logging.getLogger('alembic.env')
@@ -0,0 +1,51 @@
"""user album art
Revision ID: a41c9e2d7b53
Revises: 3ba21eb1ea0c
Create Date: 2026-10-06 21:40:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "a41c9e2d7b53"
down_revision = "3ba21eb1ea0c"
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
"user_album_art",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("user_id", sa.Integer(), nullable=False),
sa.Column("artist", sa.Text(), nullable=False),
sa.Column("album", sa.Text(), nullable=False),
sa.Column("kind", sa.String(length=16), nullable=False),
sa.Column("status", sa.String(length=16), nullable=False),
sa.Column("search_artist", sa.Text(), nullable=True),
sa.Column("search_album", sa.Text(), nullable=True),
sa.Column("release_group_mbid", sa.String(length=36), nullable=True),
sa.Column("content_type", sa.String(length=32), nullable=True),
sa.Column("error_code", sa.String(length=64), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
sa.PrimaryKeyConstraint("id"),
)
with op.batch_alter_table("user_album_art", schema=None) as batch_op:
batch_op.create_index(
"uq_user_album_art_user_artist_album_lower",
["user_id", sa.literal_column("lower(artist)"), sa.literal_column("lower(album)")],
unique=True,
)
def downgrade():
with op.batch_alter_table("user_album_art", schema=None) as batch_op:
batch_op.drop_index("uq_user_album_art_user_artist_album_lower")
op.drop_table("user_album_art")
@@ -0,0 +1,25 @@
"""user album art release mbid
Revision ID: c7d2f08a19e4
Revises: a41c9e2d7b53
Create Date: 2026-10-06 23:10:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "c7d2f08a19e4"
down_revision = "a41c9e2d7b53"
branch_labels = None
depends_on = None
def upgrade():
op.add_column("user_album_art", sa.Column("release_mbid", sa.String(length=36), nullable=True))
def downgrade():
op.drop_column("user_album_art", "release_mbid")
+37
View File
@@ -183,3 +183,40 @@ class AlbumArt(db.Model):
"uq_album_art_artist_album_lower", func.lower(artist), func.lower(album), unique=True
),
)
class UserAlbumArt(db.Model):
"""One user's own art for (artist, album): an uploaded image, or a manual correction.
Takes precedence over the global `AlbumArt` cache for that user only. A correction
(a different search text and/or a MusicBrainz release-group ID) is resolved by the
worker, never by the request that asked for it; an upload is `found` immediately.
The image bytes live on disk, named by this row's id.
"""
__tablename__ = "user_album_art"
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
artist: Mapped[str] = mapped_column(Text)
album: Mapped[str] = mapped_column(Text)
kind: Mapped[str] = mapped_column(String(16)) # upload or correction
status: Mapped[str] = mapped_column(String(16)) # pending, found or error
search_artist: Mapped[str | None] = mapped_column(Text) # correction inputs
search_album: Mapped[str | None] = mapped_column(Text)
release_group_mbid: Mapped[str | None] = mapped_column(String(36))
release_mbid: Mapped[str | None] = mapped_column(String(36)) # alternative to the group ID
content_type: Mapped[str | None] = mapped_column(String(32)) # set iff status == "found"
error_code: Mapped[str | None] = mapped_column(String(64)) # set iff status == "error"
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
__table_args__ = (
Index(
"uq_user_album_art_user_artist_album_lower",
user_id,
func.lower(artist),
func.lower(album),
unique=True,
),
)
+63 -1
View File
@@ -2,7 +2,7 @@
validation and the generated OpenAPI document."""
from flask_smorest.fields import Upload
from marshmallow import Schema, fields, validate
from marshmallow import Schema, ValidationError, fields, validate, validates_schema
class ErrorDetailSchema(Schema):
@@ -160,6 +160,68 @@ class AlbumArtArgsSchema(Schema):
album = fields.String(required=True, validate=validate.Length(min=1, max=500))
class AlbumArtUploadSchema(Schema):
file = Upload(required=True, metadata={"description": "A JPEG, PNG or WebP image"})
class AlbumArtCorrectionSchema(AlbumArtArgsSchema):
search_artist = fields.String(
validate=validate.Length(min=1, max=500),
metadata={"description": "Artist text to search MusicBrainz for, if it differs"},
)
search_album = fields.String(
validate=validate.Length(min=1, max=500),
metadata={"description": "Album text to search MusicBrainz for, if it differs"},
)
release_group_mbid = fields.UUID(
metadata={"description": "A MusicBrainz release-group ID; skips the search"}
)
release_mbid = fields.UUID(
metadata={
"description": "A MusicBrainz release ID, as an alternative to a release-group ID; "
"skips the search"
}
)
@validates_schema
def _needs_a_correction(self, data, **kwargs):
ids = ("release_group_mbid", "release_mbid")
if not any(k in data for k in ("search_artist", "search_album", *ids)):
raise ValidationError(
"Give a search_artist, search_album, release_group_mbid or release_mbid"
)
if all(k in data for k in ids):
raise ValidationError("Give a release_group_mbid or a release_mbid, not both")
class AlbumArtOverrideSchema(Schema):
kind = fields.String(metadata={"description": "upload or correction"})
status = fields.String(metadata={"description": "pending, found or error"})
error_code = fields.String(allow_none=True)
search_artist = fields.String(allow_none=True)
search_album = fields.String(allow_none=True)
release_group_mbid = fields.String(allow_none=True)
release_mbid = fields.String(allow_none=True)
class AlbumArtFailureSchema(Schema):
artist = fields.String()
album = fields.String()
scrobbles = fields.Integer(metadata={"description": "Your scrobbles of this album"})
status = fields.String(
metadata={"description": "The shared lookup: pending, not_found or error"}
)
error_code = fields.String(allow_none=True)
checked_at = fields.DateTime(allow_none=True)
override = fields.Nested(
AlbumArtOverrideSchema, allow_none=True, metadata={"description": "Your own fix, if any"}
)
class AlbumArtFailuresPageSchema(PageMetaSchema):
items = fields.List(fields.Nested(AlbumArtFailureSchema))
class TrackMetadataSchema(Schema):
album = fields.String(allow_none=True)
album_artist = fields.String(allow_none=True)
+381 -22
View File
@@ -1,5 +1,9 @@
"""Album art: MusicBrainz release-group search + Cover Art Archive, both free and keyless.
A scrobble's MBID (the recording) is tried first when we have one for the album: it names
the release-group exactly, where the text search can only guess. Without one, or without a
matching release, the text search is used as before.
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
@@ -23,19 +27,37 @@ import time
import urllib.error
import urllib.parse
import urllib.request
from contextlib import contextmanager
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 import and_, delete, func, or_, select
from sqlalchemy.dialects.postgresql import insert
from scrobbler import metrics
from scrobbler.extensions import db
from scrobbler.models import AlbumArt
from scrobbler.models import AlbumArt, Scrobble, UserAlbumArt
log = logging.getLogger(__name__)
@contextmanager
def _upstream_call(service: str):
"""Times one upstream call and counts its failures (the error is re-raised)."""
start = time.perf_counter()
outcome = "ok"
try:
yield
except Exception as err:
outcome = "error"
metrics.art_upstream_errors_total.labels(service, type(err).__name__).inc()
raise
finally:
metrics.art_upstream_seconds.labels(service, outcome).observe(time.perf_counter() - start)
# Lucene special characters MusicBrainz's search syntax requires escaping.
_LUCENE_SPECIAL = re.compile(r'([+\-&|!(){}\[\]^"~*?:\\/])')
@@ -64,7 +86,7 @@ def _user_agent() -> str:
from scrobbler import __version__
contact = current_app.config["MUSICBRAINZ_CONTACT"]
return f"Scrobbler/{__version__} ( {contact} )"
return f"Scrobbled/{__version__} ( {contact} )"
_last_musicbrainz_call = 0.0
@@ -91,44 +113,82 @@ def _stale(row: AlbumArt) -> bool:
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."""
def _musicbrainz_get(path: str, params: dict[str, str], missing_ok: bool = False) -> dict | None:
"""GET a MusicBrainz JSON document, retrying server errors and timeouts. With
`missing_ok`, a 404 returns None; other client errors and exhausted retries raise."""
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"})
query = urllib.parse.urlencode({**params, "fmt": "json"})
retries = current_app.config["MUSICBRAINZ_RETRIES"]
for attempt in range(retries + 1):
request = _throttled_request(f"{api_url}release-group/?{params}")
request = _throttled_request(f"{api_url}{path}?{query}")
try:
with urllib.request.urlopen(request, timeout=10) as response:
body = json.load(response)
with (
_upstream_call("musicbrainz"),
urllib.request.urlopen(request, timeout=10) as response,
):
return json.load(response)
except urllib.error.HTTPError as err:
if missing_ok and err.code == 404:
return None
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.
def _find_release_group(artist: str, album: str) -> str | None:
"""A matching release-group's MBID, or None if MusicBrainz has no match."""
query = f'releasegroup:"{_escape(album)}" AND artist:"{_escape(artist)}"'
body = _musicbrainz_get("release-group/", {"query": query, "limit": "5"}) or {}
groups = body.get("release-groups") or []
return groups[0]["id"] if groups else None
def _release_group_of_recording(recording_mbid: str, album: str) -> str | None:
"""The release-group of the recording's release titled `album`, or None if MusicBrainz
doesn't know the recording or none of its releases has that title."""
body = _musicbrainz_get(
f"recording/{recording_mbid}", {"inc": "releases+release-groups"}, missing_ok=True
)
for release in (body or {}).get("releases") or []:
group = release.get("release-group") or {}
if (release.get("title") or "").casefold() == album.casefold() and group.get("id"):
return group["id"]
return None
def _scrobbled_recording_mbid(artist: str, album: str) -> str | None:
"""A recording MBID some scrobble of this album carried (the newest), if any."""
return db.session.scalar(
select(Scrobble.mbid)
.where(
func.lower(Scrobble.artist) == artist.lower(),
func.lower(Scrobble.album) == album.lower(),
Scrobble.mbid.is_not(None),
)
.order_by(Scrobble.played_at.desc())
.limit(1)
)
def _cover_art_url(mbid: str, entity: str = "release-group") -> str | None:
"""The release-group's (or release'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"
url = f"{coverart_url}{entity}/{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):
with _upstream_call("coverart"), urllib.request.urlopen(request, timeout=15):
return url
except urllib.error.HTTPError as err:
if err.code == 404:
@@ -152,12 +212,19 @@ def get_cached(artist: str, album: str) -> AlbumArt | None:
)
def _resolve(artist: str, album: str) -> tuple[ArtResult, str | None, str | None]:
def _resolve(
artist: str, album: str, use_scrobble_mbid: bool = True
) -> 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)
if use_scrobble_mbid and (recording := _scrobbled_recording_mbid(artist, album)):
release_group_mbid = _release_group_of_recording(recording, album)
outcome = "matched" if release_group_mbid else "missed"
metrics.art_mbid_lookups_total.labels(outcome).inc()
if release_group_mbid is None:
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
@@ -199,6 +266,7 @@ def lookup(artist: str, album: str) -> ArtResult:
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)
metrics.art_resolutions_total.labels("inline", result.status).inc()
_store(artist, album, result, release_group_mbid, error_code)
return result
@@ -238,12 +306,224 @@ def read_file(row_id: int) -> bytes | 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:
with _upstream_call("download"), 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
# --- Per-user overrides --------------------------------------------------------------
#
# A user's own art for an album (an upload, or a manual correction the worker resolves)
# beats the global cache for that user only. Like the rest of the web path, nothing here
# touches the network: a correction is just a queued row.
IMAGE_TYPES = {"image/jpeg", "image/png", "image/webp"}
class UnsupportedImage(Exception):
"""The bytes aren't a JPEG, PNG or WebP image."""
def sniff_image_type(data: bytes) -> str:
"""The image's content type from its magic bytes. Raises UnsupportedImage."""
if data.startswith(b"\xff\xd8\xff"):
return "image/jpeg"
if data.startswith(b"\x89PNG\r\n\x1a\n"):
return "image/png"
if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
return "image/webp"
raise UnsupportedImage
def _override_path(row_id: int) -> Path:
return Path(current_app.config["ART_STORAGE_DIR"]) / "user" / str(row_id)
def _override_key(user_id: int, artist: str, album: str):
return and_(
UserAlbumArt.user_id == user_id,
func.lower(UserAlbumArt.artist) == artist.lower(),
func.lower(UserAlbumArt.album) == album.lower(),
)
def get_override(user_id: int, artist: str, album: str) -> UserAlbumArt | None:
return db.session.scalar(select(UserAlbumArt).where(_override_key(user_id, artist, album)))
def read_override_file(row: UserAlbumArt) -> bytes | None:
try:
return _override_path(row.id).read_bytes()
except FileNotFoundError:
return None
def _upsert_override(user_id: int, artist: str, album: str, **values) -> int:
now = datetime.now(UTC)
stmt = insert(UserAlbumArt).values(
user_id=user_id, artist=artist, album=album, created_at=now, updated_at=now, **values
)
stmt = stmt.on_conflict_do_update(
index_elements=[
UserAlbumArt.user_id,
func.lower(UserAlbumArt.artist),
func.lower(UserAlbumArt.album),
],
set_={**values, "updated_at": now},
).returning(UserAlbumArt.id)
row_id = db.session.execute(stmt).scalar_one()
db.session.commit()
return row_id
def save_upload(user_id: int, artist: str, album: str, data: bytes, content_type: str) -> None:
"""Store an uploaded image as the user's art. The caller has already validated it."""
path_id = _upsert_override(
user_id,
artist,
album,
kind="upload",
status="found",
content_type=content_type,
search_artist=None,
search_album=None,
release_group_mbid=None,
error_code=None,
)
path = _override_path(path_id)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
def request_correction(
user_id: int,
artist: str,
album: str,
search_artist: str | None,
search_album: str | None,
release_group_mbid: str | None,
release_mbid: str | None = None,
) -> None:
"""Queue a corrected lookup (different search text, or a known MusicBrainz
release-group or release) for the worker. A fast, network-free write."""
_upsert_override(
user_id,
artist,
album,
kind="correction",
status="pending",
content_type=None,
search_artist=search_artist,
search_album=search_album,
release_group_mbid=release_group_mbid,
release_mbid=release_mbid,
error_code=None,
)
metrics.art_override_actions_total.labels("correction_requested").inc()
def delete_override(user_id: int, artist: str, album: str) -> bool:
"""Drops the user's override (and its image). False if there wasn't one."""
row = get_override(user_id, artist, album)
if row is None:
return False
row_id = row.id
db.session.execute(delete(UserAlbumArt).where(UserAlbumArt.id == row_id))
db.session.commit()
_override_path(row_id).unlink(missing_ok=True)
metrics.art_override_actions_total.labels("override_deleted").inc()
return True
def retry(artist: str, album: str) -> bool:
"""Ask the worker to look an album up again from scratch. False if there's nothing
to retry (it's already found, or already waiting)."""
row = get_cached(artist, album)
if row is None:
want(artist, album)
elif row.status in ("not_found", "error"):
requeue(row)
else:
return False
metrics.art_override_actions_total.labels("retry_requested").inc()
return True
def list_failures(user_id: int, page: int, limit: int) -> tuple[list[dict], int]:
"""One page of the user's scrobbled albums that have no art (the lookup failed) or
whose manual correction hasn't worked, most-scrobbled first. Returns (items, total)."""
albums = (
select(
func.min(Scrobble.artist).label("artist"),
func.min(Scrobble.album).label("album"),
func.count().label("scrobbles"),
)
.where(Scrobble.user_id == user_id, Scrobble.album.is_not(None), Scrobble.album != "")
.group_by(func.lower(Scrobble.artist), func.lower(Scrobble.album))
.subquery()
)
query = (
select(albums.c.artist, albums.c.album, albums.c.scrobbles, AlbumArt, UserAlbumArt)
.select_from(albums)
.outerjoin(
AlbumArt,
and_(
func.lower(AlbumArt.artist) == func.lower(albums.c.artist),
func.lower(AlbumArt.album) == func.lower(albums.c.album),
),
)
.outerjoin(
UserAlbumArt,
and_(
UserAlbumArt.user_id == user_id,
func.lower(UserAlbumArt.artist) == func.lower(albums.c.artist),
func.lower(UserAlbumArt.album) == func.lower(albums.c.album),
),
)
.where(
or_(
UserAlbumArt.status.in_(("pending", "error")),
and_(
UserAlbumArt.id.is_(None),
AlbumArt.status.in_(("not_found", "error")),
),
)
)
)
total = db.session.scalar(select(func.count()).select_from(query.subquery()))
rows = db.session.execute(
query.order_by(albums.c.scrobbles.desc(), albums.c.artist, albums.c.album)
.limit(limit)
.offset((page - 1) * limit)
).all()
items = [
{
"artist": artist,
"album": album,
"scrobbles": scrobbles,
"status": cached.status if cached else "pending",
"error_code": cached.error_code if cached else None,
"checked_at": cached.checked_at if cached else None,
"override": (
{
"kind": override.kind,
"status": override.status,
"error_code": override.error_code,
"search_artist": override.search_artist,
"search_album": override.search_album,
"release_group_mbid": override.release_group_mbid,
"release_mbid": override.release_mbid,
}
if override
else None
),
}
for artist, album, scrobbles, cached, override in rows
]
return items, total
# --- Worker --------------------------------------------------------------------------
@@ -273,14 +553,89 @@ def _claim_pending() -> AlbumArt | None:
return row
def _claim_correction() -> UserAlbumArt | None:
row = db.session.scalar(
select(UserAlbumArt)
.where(UserAlbumArt.status == "pending")
.order_by(UserAlbumArt.updated_at)
.limit(1)
.with_for_update(skip_locked=True)
)
if row is None:
db.session.rollback()
return row
def _resolve_correction(row: UserAlbumArt) -> tuple[ArtResult, str | None]:
"""Live resolution of a user's correction: a known release-group or release goes
straight to Cover Art Archive, otherwise the (corrected) text is searched. Never raises."""
if not (row.release_group_mbid or row.release_mbid):
result, _, error_code = _resolve(
row.search_artist or row.artist,
row.search_album or row.album,
use_scrobble_mbid=False, # the user gave different text: don't second-guess it
)
return result, error_code
try:
if row.release_mbid:
image_url = _cover_art_url(row.release_mbid, "release")
else:
image_url = _cover_art_url(row.release_group_mbid)
except Exception as err: # noqa: BLE001 - any upstream failure is recorded on the row
log.warning("Corrected art lookup failed for %r/%r: %s", row.artist, row.album, err)
return ArtResult("error"), type(err).__name__
return ArtResult("found" if image_url else "not_found", image_url), None
def resolve_one_correction() -> bool:
"""Resolve one user's pending manual correction, saving the image on success.
Returns True if it processed one."""
row = _claim_correction()
if row is None:
return False
start = time.perf_counter()
source = "release_mbid" if row.release_mbid else "mbid" if row.release_group_mbid else "search"
result, error_code = _resolve_correction(row)
content_type = None
if result.status == "found":
try:
image = fetch_image(result.image_url)
content_type = image.content_type.split(";")[0].strip()
if content_type not in IMAGE_TYPES:
content_type = "image/jpeg"
path = _override_path(row.id)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(image.body)
except ArtFetchFailed as err:
log.warning("Corrected art download failed for %r/%r: %s", row.artist, row.album, err)
result, error_code = ArtResult("error"), "ArtFetchFailed"
elif result.status == "not_found":
error_code = "NotFound"
metrics.art_correction_resolutions_total.labels(source, result.status).inc()
metrics.art_resolutions_total.labels("override", result.status).inc()
now = datetime.now(UTC)
metrics.art_correction_wait_seconds.observe((now - row.updated_at).total_seconds())
row.status = "found" if result.status == "found" else "error"
row.content_type = content_type
row.error_code = error_code
row.updated_at = now
db.session.commit()
metrics.art_override_worker_seconds.observe(time.perf_counter() - start)
return True
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."""
and saving its image bytes when found. A user's manual correction goes first.
Returns True if it processed a row (call again immediately), False if there was
nothing to do."""
if resolve_one_correction():
return True
row = _claim_pending()
if row is None:
return False
start = time.perf_counter()
result, release_group_mbid, error_code = _resolve(row.artist, row.album)
if result.status == "found":
try:
@@ -288,16 +643,20 @@ def resolve_one_pending() -> bool:
path = _file_path(row.id)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(image.body)
metrics.art_image_bytes.observe(len(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"
metrics.art_resolutions_total.labels("worker", result.status).inc()
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()
metrics.art_worker_resolve_seconds.observe(time.perf_counter() - start)
log.info("album art for %r/%r: %s", row.artist, row.album, result.status)
return True
+1 -1
View File
@@ -549,7 +549,7 @@ def process_job(job: ImportJob) -> None:
db.session.rollback()
_finish(job, "failed", err.message)
except Exception:
log.exception("import job %s failed", job.id)
log.exception("import job %s (%s) for user %s failed", job.id, job.source, job.user_id)
db.session.rollback()
_finish(
job, "failed", "The import failed unexpectedly. Try again, or check the server logs."
+28 -2
View File
@@ -50,18 +50,44 @@ def registered(app: Flask | None = None) -> list[str]:
def _call(task: _Task) -> bool:
started = time.monotonic()
try:
worked = bool(task.fn())
result = task.fn()
except Exception:
log.exception("worker task %s failed", task.name)
log.exception(
"worker task %s failed after %.0f ms",
task.name,
_elapsed_ms(started),
extra={"task": task.name, "outcome": "error", "duration_ms": _elapsed_ms(started)},
)
db.session.rollback()
metrics.worker_tasks_total.labels(task=task.name, outcome="error").inc()
return False
worked = bool(result)
if worked or task.every is not None:
metrics.worker_tasks_total.labels(task=task.name, outcome="worked").inc()
duration = _elapsed_ms(started)
# Queue tasks are polled every couple of seconds, so only passes that did work are
# worth an INFO line; periodic tasks say so only when they report work (a truthy result).
log.log(
logging.INFO if worked else logging.DEBUG,
"worker task %s %s in %.0f ms",
task.name,
"worked" if worked else "ran (nothing to do)",
duration,
extra={
"task": task.name,
"outcome": "worked" if worked else "idle",
"duration_ms": duration,
},
)
return worked
def _elapsed_ms(started: float) -> float:
return round((time.monotonic() - started) * 1000, 1)
def run_once() -> bool:
"""One pass: due periodic tasks, then each queue task once. True if any queue
task did work (so there may be more waiting)."""
+484 -3
View File
@@ -1,6 +1,8 @@
import io
import json
import pathlib
import threading
import time
import urllib.parse
from datetime import UTC, datetime, timedelta
@@ -8,8 +10,11 @@ import pytest
from werkzeug.serving import make_server
from scrobbler.extensions import db
from scrobbler.models import AlbumArt
from scrobbler.services import art
from scrobbler.models import AlbumArt, UserAlbumArt
from scrobbler.services import art, scrobbles
from scrobbler.services.scrobbles import TrackInput
FOUND_MBID = "11111111-1111-1111-1111-111111111111" # a real-looking id the fake has art for
# Canned release-group matches, keyed by a substring of the Lucene search query we send.
_RELEASE_GROUPS = {
@@ -20,6 +25,18 @@ _RELEASE_GROUPS = {
}
# Canned recordings (a scrobble's MBID) and the releases MusicBrainz lists them on.
RECORDING_MBID = "22222222-2222-2222-2222-222222222222"
UNMATCHED_RECORDING_MBID = "33333333-3333-3333-3333-333333333333"
_RECORDINGS = {
RECORDING_MBID: [
{"title": "Some Compilation", "release-group": {"id": "rg-other"}},
{"title": "Mbid Album", "release-group": {"id": "rg-found"}},
],
UNMATCHED_RECORDING_MBID: [{"title": "Another Album", "release-group": {"id": "rg-other"}}],
}
def _fake_musicbrainz_caa(environ, start_response):
method, path = environ["REQUEST_METHOD"], environ["PATH_INFO"]
@@ -36,7 +53,23 @@ def _fake_musicbrainz_caa(environ, start_response):
)
return [body]
if path == "/release-group/rg-found/front-500":
if path.startswith("/recording/"):
recording = path.rsplit("/", 1)[1]
releases = _RECORDINGS.get(recording)
if releases is None:
start_response("404 Not Found", [("Content-Type", "text/plain")])
return [b"not found"]
body = json.dumps({"releases": releases}).encode()
start_response(
"200 OK", [("Content-Type", "application/json"), ("Content-Length", str(len(body)))]
)
return [body]
if path in (
"/release-group/rg-found/front-500",
f"/release-group/{FOUND_MBID}/front-500",
f"/release/{FOUND_MBID}/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)
@@ -369,3 +402,451 @@ def test_album_art_requeues_a_found_row_with_a_missing_file(client, auth, art_co
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
# --- metrics ------------------------------------------------------------------------------
def test_worker_counts_resolutions_and_times_upstreams(art_config, metric_delta):
found = metric_delta("scrobbler_art_resolutions_total", source="worker", result="found")
resolve = metric_delta("scrobbler_art_worker_resolve_seconds_count")
image = metric_delta("scrobbler_art_image_bytes_count")
musicbrainz = metric_delta(
"scrobbler_art_upstream_seconds_count", service="musicbrainz", outcome="ok"
)
download = metric_delta(
"scrobbler_art_upstream_seconds_count", service="download", outcome="ok"
)
art.want("Radiohead", "In Rainbows")
art.resolve_one_pending()
assert (found.delta, resolve.delta, image.delta) == (1, 1, 1)
assert musicbrainz.delta == 1
assert download.delta == 1
def test_worker_counts_download_failure_as_one_error(art_config, metric_delta):
errors = metric_delta("scrobbler_art_resolutions_total", source="worker", result="error")
found = metric_delta("scrobbler_art_resolutions_total", source="worker", result="found")
failed = metric_delta(
"scrobbler_art_upstream_errors_total", service="download", error="HTTPError"
)
art.want("Someone", "Download Fail Album")
art.resolve_one_pending()
assert (errors.delta, found.delta) == (1, 0)
assert failed.delta == 1
def test_endpoint_counts_queued_pending_and_unavailable(client, auth, art_config, metric_delta):
queued = metric_delta("scrobbler_art_requests_total", result="queued")
pending = metric_delta("scrobbler_art_requests_total", result="pending")
unavailable = metric_delta("scrobbler_art_requests_total", result="unavailable")
url = "/api/v1/art/album?artist=Nobody&album=Nothing"
client.get(url, headers=auth)
client.get(url, headers=auth)
art.resolve_one_pending()
client.get(url, headers=auth)
assert (queued.delta, pending.delta, unavailable.delta) == (1, 1, 1)
def test_endpoint_counts_served(client, auth, art_config, metric_delta):
served = metric_delta("scrobbler_art_requests_total", result="served")
url = "/api/v1/art/album?artist=Radiohead&album=In+Rainbows"
client.get(url, headers=auth)
art.resolve_one_pending()
assert client.get(url, headers=auth).status_code == 200
assert served.delta == 1
# --- per-user overrides (service + worker) ----------------------------------------------
BASE = int(time.time()) - 3600
JPEG = b"\xff\xd8\xff\xe0my-own-art"
def override(user, artist, album):
return art.get_override(user.id, artist, album)
def scrobble_album(user, artist, album, count=1, base=None):
scrobbles.submit_scrobbles(
user,
None,
[
TrackInput(artist=artist, track=f"t{i}", album=album, timestamp=(base or BASE) + i)
for i in range(count)
],
)
def test_sniff_image_type():
assert art.sniff_image_type(JPEG) == "image/jpeg"
assert art.sniff_image_type(b"\x89PNG\r\n\x1a\n....") == "image/png"
assert art.sniff_image_type(b"RIFF\x00\x00\x00\x00WEBPVP8 ") == "image/webp"
with pytest.raises(art.UnsupportedImage):
art.sniff_image_type(b"GIF89a")
def test_save_upload_stores_the_file_and_replaces_it(art_config, user):
art.save_upload(user.id, "Nobody", "Nothing", JPEG, "image/jpeg")
first = override(user, "nobody", "NOTHING") # case-insensitive
assert (first.kind, first.status, first.content_type) == ("upload", "found", "image/jpeg")
assert art.read_override_file(first) == JPEG
art.save_upload(user.id, "Nobody", "Nothing", b"\x89PNG\r\n\x1a\nnew", "image/png")
second = override(user, "Nobody", "Nothing")
assert second.id == first.id
assert art.read_override_file(second).endswith(b"new")
assert second.content_type == "image/png"
def test_overrides_are_per_user(art_config, user, make_user):
other = make_user(username="mallory")
art.save_upload(user.id, "Nobody", "Nothing", JPEG, "image/jpeg")
assert override(other, "Nobody", "Nothing") is None
def test_delete_override_removes_row_and_file(art_config, user):
art.save_upload(user.id, "Nobody", "Nothing", JPEG, "image/jpeg")
row_id = override(user, "Nobody", "Nothing").id
assert art.delete_override(user.id, "Nobody", "Nothing") is True
assert override(user, "Nobody", "Nothing") is None
assert not art._override_path(row_id).exists()
assert art.delete_override(user.id, "Nobody", "Nothing") is False
def test_retry_requeues_failures_only(art_config):
insert("A", "Failed", "not_found")
insert("A", "Fine", "found")
assert art.retry("A", "Failed") is True
assert row("A", "Failed").status == "pending"
assert art.retry("A", "Fine") is False
assert art.retry("Brand", "New") is True
assert row("Brand", "New").status == "pending"
def test_correction_by_mbid_is_resolved_by_the_worker(art_config, user, metric_delta):
resolved = metric_delta(
"scrobbler_art_correction_resolutions_total", input="mbid", result="found"
)
wait = metric_delta("scrobbler_art_correction_wait_seconds_count")
art.request_correction(user.id, "Radiohead", "Inrainbows", None, None, "rg-found")
assert override(user, "Radiohead", "Inrainbows").status == "pending"
assert art.resolve_one_pending() is True
fixed = override(user, "Radiohead", "Inrainbows")
assert (fixed.status, fixed.content_type) == ("found", "image/jpeg")
assert art.read_override_file(fixed) == b"\xff\xd8\xff\xe0fake-jpeg-bytes"
assert (resolved.delta, wait.delta) == (1, 1)
def test_correction_by_search_text_is_resolved_by_the_worker(art_config, user, metric_delta):
resolved = metric_delta(
"scrobbler_art_correction_resolutions_total", input="search", result="found"
)
art.request_correction(user.id, "Radiohead", "Inrainbows", "Radiohead", "In Rainbows", None)
art.resolve_one_pending()
assert override(user, "Radiohead", "Inrainbows").status == "found"
assert resolved.delta == 1
def test_correction_that_finds_nothing_is_an_error_on_the_override(art_config, user, metric_delta):
nothing = metric_delta(
"scrobbler_art_correction_resolutions_total", input="search", result="not_found"
)
art.request_correction(user.id, "Nobody", "Nothing", "Nobody", "Still Nothing", None)
art.resolve_one_pending()
failed = override(user, "Nobody", "Nothing")
assert (failed.status, failed.error_code) == ("error", "NotFound")
assert nothing.delta == 1
def test_correction_with_a_failing_upstream_records_the_error(art_config, user):
art.request_correction(user.id, "Someone", "Boom", None, None, "rg-boom")
art.resolve_one_pending()
failed = override(user, "Someone", "Boom")
assert (failed.status, failed.error_code) == ("error", "HTTPError")
def test_worker_resolves_corrections_before_the_global_queue(art_config, user):
art.want("Radiohead", "In Rainbows")
art.request_correction(user.id, "X", "Y", None, None, "rg-found")
art.resolve_one_pending()
assert override(user, "X", "Y").status == "found"
assert row("Radiohead", "In Rainbows").status == "pending"
def test_failures_lists_only_the_users_failed_albums(art_config, user, make_user):
other = make_user(username="mallory")
scrobble_album(user, "A", "Missing", count=3)
scrobble_album(user, "A", "Fine", count=1)
scrobble_album(user, "A", "Unlooked", count=1)
scrobble_album(other, "B", "Theirs", count=1)
insert("A", "Missing", "not_found")
insert("A", "Fine", "found")
insert("B", "Theirs", "error")
items, total = art.list_failures(user.id, 1, 50)
assert total == 1
assert [(i["artist"], i["album"], i["scrobbles"], i["status"]) for i in items] == [
("A", "Missing", 3, "not_found")
]
assert items[0]["override"] is None
def test_failures_drops_fixed_albums_and_keeps_failed_corrections(art_config, user):
scrobble_album(user, "A", "Uploaded")
scrobble_album(user, "A", "Wrong", base=BASE + 500)
insert("A", "Uploaded", "not_found")
insert("A", "Wrong", "not_found")
art.save_upload(user.id, "A", "Uploaded", JPEG, "image/jpeg")
art.request_correction(user.id, "A", "Wrong", None, None, "rg-boom")
art.resolve_one_pending()
items, total = art.list_failures(user.id, 1, 50)
assert total == 1
assert items[0]["album"] == "Wrong"
assert (items[0]["override"]["status"], items[0]["override"]["kind"]) == ("error", "correction")
def test_failures_paginates_most_scrobbled_first(art_config, user):
for i, count in enumerate((1, 3, 2)):
scrobble_album(user, "A", f"Album {i}", count=count, base=BASE + i * 100)
insert("A", f"Album {i}", "not_found")
items, total = art.list_failures(user.id, 1, 2)
assert (total, [i["album"] for i in items]) == (3, ["Album 1", "Album 2"])
items, _ = art.list_failures(user.id, 2, 2)
assert [i["album"] for i in items] == ["Album 0"]
# --- per-user override endpoints -----------------------------------------------------------
ALBUM = "artist=Nobody&album=Nothing"
def upload(client, auth, data=JPEG, name="cover.jpg", query=ALBUM):
return client.post(
f"/api/v1/art/album?{query}",
headers=auth,
data={"file": (io.BytesIO(data), name)},
content_type="multipart/form-data",
)
def test_upload_requires_auth(client):
assert client.post(f"/api/v1/art/album?{ALBUM}").status_code == 401
def test_upload_then_get_serves_the_users_image(client, auth, art_config, metric_delta):
ok = metric_delta("scrobbler_art_uploads_total", result="ok")
size = metric_delta("scrobbler_art_upload_bytes_count")
served = metric_delta("scrobbler_art_requests_total", result="override")
response = upload(client, auth)
assert response.status_code == 201
assert response.get_json()["status"] == "found"
image = client.get(f"/api/v1/art/album?{ALBUM}", headers=auth)
assert image.status_code == 200
assert image.data == JPEG
assert image.mimetype == "image/jpeg"
assert image.headers["Cache-Control"] == "private, no-cache"
assert (ok.delta, size.delta, served.delta) == (1, 1, 1)
def test_override_response_supports_conditional_requests(client, auth, art_config):
upload(client, auth)
first = client.get(f"/api/v1/art/album?{ALBUM}", headers=auth)
again = client.get(
f"/api/v1/art/album?{ALBUM}", headers={**auth, "If-None-Match": first.headers["ETag"]}
)
assert again.status_code == 304
def test_upload_keeps_the_png_content_type(client, auth, art_config):
upload(client, auth, data=b"\x89PNG\r\n\x1a\nxxxx", name="c.png")
assert client.get(f"/api/v1/art/album?{ALBUM}", headers=auth).mimetype == "image/png"
def test_upload_beats_the_shared_cache(client, auth, art_config):
insert("Nobody", "Nothing", "not_found")
upload(client, auth)
assert client.get(f"/api/v1/art/album?{ALBUM}", headers=auth).data == JPEG
def test_upload_is_only_visible_to_its_owner(client, auth, art_config, make_user):
from scrobbler.services.accounts import issue_ui_token
upload(client, auth)
token = issue_ui_token(make_user(username="mallory"))
other = client.get(f"/api/v1/art/album?{ALBUM}", headers={"Authorization": f"Bearer {token}"})
assert other.status_code == 404
@pytest.mark.parametrize(
("data", "status", "result"),
[(b"", 400, "empty"), (b"GIF89a....", 415, "bad_type"), (JPEG + b"x" * 100, 413, "too_large")],
)
def test_upload_rejects_bad_files(
client, auth, app, art_config, metric_delta, data, status, result
):
app.config["ART_UPLOAD_MAX_BYTES"] = 50
try:
counted = metric_delta("scrobbler_art_uploads_total", result=result)
assert upload(client, auth, data=data).status_code == status
assert counted.delta == 1
assert override_row() is None
finally:
app.config["ART_UPLOAD_MAX_BYTES"] = 5 * 1024 * 1024
def override_row():
return db.session.scalar(db.select(UserAlbumArt))
def test_upload_requires_artist_and_album(client, auth, art_config):
assert upload(client, auth, query="artist=A").status_code == 422
def test_delete_override_reverts_to_the_shared_cache(client, auth, art_config, metric_delta):
deleted = metric_delta("scrobbler_art_override_actions_total", action="override_deleted")
upload(client, auth)
assert client.delete(f"/api/v1/art/album?{ALBUM}", headers=auth).status_code == 204
assert client.get(f"/api/v1/art/album?{ALBUM}", headers=auth).status_code == 404
assert client.delete(f"/api/v1/art/album?{ALBUM}", headers=auth).status_code == 404
assert deleted.delta == 1
def test_correction_is_queued_without_touching_the_network(
client, auth, app, art_config, metric_delta
):
app.config.update(
MUSICBRAINZ_API_URL="http://127.0.0.1:1/", COVERART_API_URL="http://127.0.0.1:1/"
)
queued = metric_delta("scrobbler_art_override_actions_total", action="correction_requested")
response = client.put(
"/api/v1/art/album/correction",
headers=auth,
json={"artist": "Radiohead", "album": "Inrainbows", "search_album": "In Rainbows"},
)
assert response.status_code == 202
body = response.get_json()
assert (body["kind"], body["status"], body["search_album"]) == (
"correction",
"pending",
"In Rainbows",
)
assert queued.delta == 1
def test_correction_then_worker_then_get(client, auth, art_config):
url = "/api/v1/art/album?artist=Radiohead&album=Inrainbows"
client.put(
"/api/v1/art/album/correction",
headers=auth,
json={"artist": "Radiohead", "album": "Inrainbows", "release_group_mbid": FOUND_MBID},
)
assert client.get(url, headers=auth).status_code == 404 # not resolved yet
art.resolve_one_pending()
assert client.get(url, headers=auth).data == b"\xff\xd8\xff\xe0fake-jpeg-bytes"
def test_correction_needs_something_to_correct_and_a_valid_mbid(client, auth):
url = "/api/v1/art/album/correction"
assert client.put(url, headers=auth, json={"artist": "A", "album": "B"}).status_code == 422
bad = {"artist": "A", "album": "B", "release_group_mbid": "nope"}
assert client.put(url, headers=auth, json=bad).status_code == 422
def test_retry_requeues_a_failed_lookup(client, auth, art_config, metric_delta):
retried = metric_delta("scrobbler_art_override_actions_total", action="retry_requested")
insert("Nobody", "Nothing", "not_found")
assert client.post(f"/api/v1/art/album/retry?{ALBUM}", headers=auth).status_code == 202
assert row("Nobody", "Nothing").status == "pending"
assert client.post(f"/api/v1/art/album/retry?{ALBUM}", headers=auth).status_code == 409
assert retried.delta == 1
def test_failures_endpoint(client, auth, art_config, user):
scrobble_album(user, "Nobody", "Nothing", count=2)
insert("Nobody", "Nothing", "not_found")
body = client.get("/api/v1/art/failures", headers=auth).get_json()
assert (body["total"], body["total_pages"], body["page"]) == (1, 1, 1)
assert body["items"][0]["album"] == "Nothing"
assert body["items"][0]["scrobbles"] == 2
assert body["items"][0]["override"] is None
upload(client, auth)
assert client.get("/api/v1/art/failures", headers=auth).get_json()["items"] == []
def test_failures_requires_auth(client):
assert client.get("/api/v1/art/failures").status_code == 401
def scrobble_with_mbid(user, artist, track, album, mbid):
scrobbles.submit_scrobbles(
user, None, [TrackInput(artist, track, album=album, mbid=mbid, timestamp=int(time.time()))]
)
def test_scrobble_mbid_finds_the_release_group_without_a_text_match(art_config, user, metric_delta):
# "Mbid Album" matches nothing in the fake's text search, so only the recording can find it
matched = metric_delta("scrobbler_art_mbid_lookups_total", result="matched")
scrobble_with_mbid(user, "Radiohead", "Track", "Mbid Album", RECORDING_MBID)
art.want("Radiohead", "Mbid Album")
assert art.resolve_one_pending() is True
found = row("Radiohead", "Mbid Album")
assert (found.status, found.release_group_mbid) == ("found", "rg-found")
assert matched.delta == 1
def test_scrobble_mbid_with_no_matching_release_falls_back_to_text_search(
art_config, user, metric_delta
):
missed = metric_delta("scrobbler_art_mbid_lookups_total", result="missed")
scrobble_with_mbid(user, "Radiohead", "Track", "In Rainbows", UNMATCHED_RECORDING_MBID)
art.want("Radiohead", "In Rainbows")
art.resolve_one_pending()
assert row("Radiohead", "In Rainbows").release_group_mbid == "rg-found"
assert missed.delta == 1
def test_unknown_scrobble_mbid_falls_back_to_text_search(art_config, user):
unknown = "44444444-4444-4444-4444-444444444444"
scrobble_with_mbid(user, "Radiohead", "Track", "In Rainbows", unknown)
art.want("Radiohead", "In Rainbows")
art.resolve_one_pending()
assert row("Radiohead", "In Rainbows").status == "found"
def test_no_scrobble_mbid_means_no_recording_lookup(art_config, user, metric_delta):
tried = metric_delta("scrobbler_art_mbid_lookups_total", result="missed")
scrobble_with_mbid(user, "Radiohead", "Track", "In Rainbows", None)
art.want("Radiohead", "In Rainbows")
art.resolve_one_pending()
assert row("Radiohead", "In Rainbows").status == "found"
assert tried.delta == 0
def test_correction_with_search_text_ignores_the_scrobble_mbid(art_config, user):
scrobble_with_mbid(user, "Radiohead", "Track", "Mbid Album", RECORDING_MBID)
art.request_correction(user.id, "Radiohead", "Mbid Album", None, "No Art Album", None)
art.resolve_one_pending()
assert override(user, "Radiohead", "Mbid Album").status == "error" # searched the text given
def test_correction_by_release_mbid_is_resolved_from_the_release(art_config, user, metric_delta):
resolved = metric_delta(
"scrobbler_art_correction_resolutions_total", input="release_mbid", result="found"
)
art.request_correction(user.id, "Radiohead", "Inrainbows", None, None, None, FOUND_MBID)
assert art.resolve_one_pending() is True
fixed = override(user, "Radiohead", "Inrainbows")
assert (fixed.status, fixed.release_mbid) == ("found", FOUND_MBID)
assert art.read_override_file(fixed) == b"\xff\xd8\xff\xe0fake-jpeg-bytes"
assert resolved.delta == 1
def test_correction_api_accepts_a_release_mbid_but_not_both_ids(client, auth):
url = "/api/v1/art/album/correction"
ok = {"artist": "A", "album": "B", "release_mbid": FOUND_MBID}
response = client.put(url, headers=auth, json=ok)
assert response.status_code == 202
assert response.get_json()["release_mbid"] == FOUND_MBID
both = {**ok, "release_group_mbid": FOUND_MBID}
assert client.put(url, headers=auth, json=both).status_code == 422
bad = {"artist": "A", "album": "B", "release_mbid": "nope"}
assert client.put(url, headers=auth, json=bad).status_code == 422
+1
View File
@@ -50,6 +50,7 @@ def test_the_expected_dashboards_exist():
"usage",
"database",
"federation",
"album-art",
}
+3 -3
View File
@@ -79,18 +79,18 @@ def test_build_content_shape():
"My week in music: 312 plays",
"Top artists: 1. Radiohead (48) 2. Björk (31) 3. Portishead (22)",
"Most played: Reckoner by Radiohead (12 plays)",
"#Scrobbler",
"#Scrobbled",
]
assert html.startswith("<p><strong>My week in music: 312 plays</strong></p>")
assert "<ol><li>Radiohead" in html
assert "<em>Reckoner</em> by Radiohead" in html
assert html.endswith("<p>#Scrobbler</p>")
assert html.endswith("<p>#Scrobbled</p>")
assert "<script" not in html # sanity: nothing unescaped ever reaches the markup
def test_build_content_without_any_plays_this_week():
text, html = build_content(0, [], [])
assert text == "My week in music: 0 plays\n#Scrobbler"
assert text == "My week in music: 0 plays\n#Scrobbled"
assert "<ol>" not in html # no top-artists list when there isn't one
assert "Most played" not in html
+2 -2
View File
@@ -66,7 +66,7 @@ def test_urls_with_credentials_are_refused():
@pytest.fixture
def local_client():
client = Client("Scrobbler/test", insecure_testing=True)
client = Client("Scrobbled/test", insecure_testing=True)
yield client
client.close()
@@ -74,7 +74,7 @@ def local_client():
def test_get_json_and_user_agent(local_client, remote):
remote.routes["/doc"] = (200, {}, {"id": "x"})
assert local_client.get_json(remote.url("/doc")) == {"id": "x"}
assert remote.requests[0]["headers"]["User-Agent"] == "Scrobbler/test"
assert remote.requests[0]["headers"]["User-Agent"] == "Scrobbled/test"
assert "application/activity+json" in remote.requests[0]["headers"]["Accept"]
+1 -1
View File
@@ -151,7 +151,7 @@ def test_post_sent_after_30_seconds(fed_ctx, posting_user):
activity = db.session.get(FederationActivity, post.activity_id)
assert activity.activity_type == "Create"
assert activity.document["object"]["tag"] == [
{"type": "Hashtag", "name": "#Scrobbler"},
{"type": "Hashtag", "name": "#Scrobbled"},
{"type": "Hashtag", "name": "#NowPlaying"},
]
+3 -3
View File
@@ -160,7 +160,7 @@ def test_is_public_or_unlisted():
def test_hashtag():
assert vocab.hashtag("Scrobbler") == {"type": "Hashtag", "name": "#Scrobbler"}
assert vocab.hashtag("Scrobbled") == {"type": "Hashtag", "name": "#Scrobbled"}
def test_note():
@@ -172,14 +172,14 @@ def test_note():
url=f"{BASE}/post.html?id=1",
to=["FOLLOWERS"],
cc=[],
tags=["Scrobbler"],
tags=["Scrobbled"],
)
assert doc["type"] == "Note"
assert doc["attributedTo"] == f"{BASE}/users/alice"
assert doc["content"] == "<p>Hello</p>"
assert doc["contentMap"] == {"en": "<p>Hello</p>"}
assert (doc["to"], doc["cc"]) == (["FOLLOWERS"], [])
assert doc["tag"] == [{"type": "Hashtag", "name": "#Scrobbler"}]
assert doc["tag"] == [{"type": "Hashtag", "name": "#Scrobbled"}]
assert doc["sensitive"] is False
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
+1 -1
View File
@@ -50,7 +50,7 @@ def test_publish_creates_a_post_and_a_create_activity(fed_ctx, user, metric_delt
assert activity.document["object"]["type"] == "Note"
assert activity.document["object"]["content"] == "<p>312 plays</p>"
assert activity.document["object"]["contentMap"] == {"en": "<p>312 plays</p>"}
assert activity.document["object"]["tag"] == [{"type": "Hashtag", "name": "#Scrobbler"}]
assert activity.document["object"]["tag"] == [{"type": "Hashtag", "name": "#Scrobbled"}]
assert activity.public is False # followers-only, the default
+56
View File
@@ -0,0 +1,56 @@
import json
import logging
import pytest
from scrobbler.logsetup import JsonFormatter, configure_logging
@pytest.fixture(autouse=True)
def restore_root_logger():
root = logging.getLogger()
handlers, level = list(root.handlers), root.level
yield
root.handlers[:] = handlers
root.setLevel(level)
def _record(msg="hello %s", args=("world",), **extra):
record = logging.LogRecord("test.logger", logging.INFO, __file__, 1, msg, args, None)
record.__dict__.update(extra)
return record
def test_json_formatter_emits_fields_and_extras():
entry = json.loads(JsonFormatter().format(_record(task="art", duration_ms=12.5)))
assert entry["message"] == "hello world"
assert entry["level"] == "INFO"
assert entry["logger"] == "test.logger"
assert entry["task"] == "art"
assert entry["duration_ms"] == 12.5
assert "time" in entry
def test_json_formatter_includes_exceptions():
try:
raise ValueError("boom")
except ValueError:
record = _record()
import sys
record.exc_info = sys.exc_info()
assert "ValueError: boom" in json.loads(JsonFormatter().format(record))["exception"]
def test_configure_logging_is_idempotent_and_sets_level():
root = logging.getLogger()
configure_logging("DEBUG", "json")
configure_logging("warning", "text")
ours = [h for h in root.handlers if getattr(h, "_scrobbler_handler", False)]
assert len(ours) == 1
assert root.level == logging.WARNING
def test_unknown_level_falls_back_to_info():
configure_logging("LOUD", "text")
assert logging.getLogger().level == logging.INFO
+33
View File
@@ -87,6 +87,16 @@ def test_database_stats_collector(app, user, make_user):
active = {s.labels["window"]: s.value for s in families["scrobbler_active_users"].samples}
assert active == {"1h": 1, "24h": 1, "7d": 1}
assert families["scrobbler_now_playing_active"].samples[0].value == 1
cache = {s.labels["status"]: s.value for s in families["scrobbler_art_cache"].samples}
assert cache == {"pending": 0, "found": 0, "not_found": 0, "error": 0}
assert families["scrobbler_art_oldest_pending_seconds"].samples[0].value == 0
overrides = {
(s.labels["kind"], s.labels["status"]): s.value
for s in families["scrobbler_art_overrides"].samples
}
assert len(overrides) == 6 and not any(overrides.values())
assert families["scrobbler_art_override_oldest_pending_seconds"].samples[0].value == 0
assert families["scrobbler_art_unresolved_albums"].samples[0].value == 0
def test_database_stats_collector_caches(app, user):
@@ -156,3 +166,26 @@ def test_gunicorn_aggregates_worker_metrics(app, tmp_path):
]
assert openapi.value == 10
assert "scrobbler_users" in families
def test_database_stats_collector_counts_art_backlog(app, user):
from scrobbler.extensions import db
from scrobbler.models import AlbumArt, UserAlbumArt
db.session.add_all(
[
AlbumArt(artist="A", album="Lost", status="not_found"),
AlbumArt(artist="A", album="Fixed", status="error"),
AlbumArt(artist="A", album="Fine", status="found"),
UserAlbumArt(user_id=user.id, artist="a", album="fixed", kind="upload", status="found"),
UserAlbumArt(
user_id=user.id, artist="A", album="Waiting", kind="correction", status="pending"
),
]
)
db.session.commit()
values = DatabaseStatsCollector(app.config["SQLALCHEMY_DATABASE_URI"]).values()
assert values["art_unresolved"] == 1 # "Lost"; "Fixed" has a user's upload
assert values["art_overrides"][("upload", "found")] == 1
assert values["art_overrides"][("correction", "pending")] == 1
assert values["art_override_oldest_pending"] >= 0
+1 -1
View File
@@ -60,7 +60,7 @@ def https_server(app, tls_files):
@pytest.fixture
def network(https_server, api_app):
return pylast._Network(
name="Scrobbler",
name="Scrobbled",
homepage=f"https://{https_server}",
ws_server=(https_server, "/2.0/"),
api_key=api_app.api_key,
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff. Show more