Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
735556bf21 | ||
|
|
524b78a075 | ||
|
|
9c84a64d4e | ||
|
|
bee83cb9f3 | ||
|
|
87edaafe19 | ||
|
|
a887865f05 | ||
|
|
d0b8e1ed22 | ||
|
|
48fba1e0e2 | ||
|
|
6cd17d7586 | ||
|
|
83b27d7ba1 | ||
|
|
79193fbc8e | ||
|
|
2b984cca6e | ||
|
|
44abd70caa | ||
|
|
f106d68921 | ||
|
|
dfd2ef868b | ||
|
|
5bdeeddb0b | ||
|
|
7b169ea807 | ||
|
|
457e051828 | ||
|
|
25a7ac7a20 | ||
|
|
ae24c4a00e | ||
|
|
86bf9fd302 | ||
|
|
bef41fc2cc | ||
|
|
e1704b0b54 | ||
|
|
88b53df909 | ||
|
|
d2f457a84d | ||
|
|
50e2360d14 | ||
|
|
b307b11440 | ||
|
|
dfdb5285da | ||
|
|
df8a114a0c |
No files matched your search
@@ -16,6 +16,16 @@ METRICS_PORT=9100
|
|||||||
# Set to allow importing history straight from Last.fm (https://www.last.fm/api/account/create).
|
# Set to allow importing history straight from Last.fm (https://www.last.fm/api/account/create).
|
||||||
LASTFM_API_KEY=
|
LASTFM_API_KEY=
|
||||||
|
|
||||||
|
# Album art (MusicBrainz + Cover Art Archive, both free and keyless — no setup required).
|
||||||
|
# MusicBrainz asks for a contact URL/email in requests; falls back to UI_BASE_URL if unset.
|
||||||
|
MUSICBRAINZ_CONTACT=
|
||||||
|
# Where downloaded art is stored. docker compose points this at a shared volume; the
|
||||||
|
# default below is for running the api/worker directly (not in Docker).
|
||||||
|
ART_STORAGE_DIR=var/album-art
|
||||||
|
# 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)
|
# docker compose host ports (defaults shown)
|
||||||
API_PORT=5050
|
API_PORT=5050
|
||||||
UI_PORT=8080
|
UI_PORT=8080
|
||||||
|
|||||||
+18
-1
@@ -101,6 +101,7 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
outputs:
|
outputs:
|
||||||
tags: ${{ steps.version.outputs.image_tags }}
|
tags: ${{ steps.version.outputs.image_tags }}
|
||||||
|
version: ${{ steps.version.outputs.version }}
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: https://github.com/astral-sh/setup-uv@v6
|
- uses: https://github.com/astral-sh/setup-uv@v6
|
||||||
@@ -179,8 +180,24 @@ jobs:
|
|||||||
--publish-url "https://${{ vars.PKGS_HOST }}/pypi/${{ vars.PKGS_PYPI_FEED }}/legacy"
|
--publish-url "https://${{ vars.PKGS_HOST }}/pypi/${{ vars.PKGS_PYPI_FEED }}/legacy"
|
||||||
--username api --password "${{ secrets.PKGS_API_KEY }}"
|
--username api --password "${{ secrets.PKGS_API_KEY }}"
|
||||||
|
|
||||||
|
trigger-deploy:
|
||||||
|
needs: [images]
|
||||||
|
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Trigger ScrobbledDeploy
|
||||||
|
env:
|
||||||
|
VERSION: ${{ needs.images.outputs.version }}
|
||||||
|
TOKEN: ${{ secrets.SCROBBLEDDEPLOY_DISPATCH_TOKEN }}
|
||||||
|
run: |
|
||||||
|
curl -fsS -X POST \
|
||||||
|
-H "Authorization: token ${TOKEN}" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d "{\"ref\":\"main\",\"inputs\":{\"image_tag\":\"${VERSION}\"}}" \
|
||||||
|
"https://git.daubney.dev/api/v1/repos/matt/ScrobbledDeploy/actions/workflows/deploy.yml/dispatches"
|
||||||
|
|
||||||
notify:
|
notify:
|
||||||
needs: [lint, test, validate-monitoring, federation-interop, images, assets, python-package]
|
needs: [lint, test, validate-monitoring, federation-interop, images, assets, python-package, trigger-deploy]
|
||||||
if: always()
|
if: always()
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ htmlcov/
|
|||||||
|
|
||||||
# Runtime
|
# Runtime
|
||||||
prometheus_multiproc/
|
prometheus_multiproc/
|
||||||
|
var/album-art/
|
||||||
|
|
||||||
# IDEs
|
# IDEs
|
||||||
.idea/
|
.idea/
|
||||||
|
|||||||
@@ -15,12 +15,12 @@ Prometheus ◄── API :9100/metrics, postgres-exporter ──► Grafana
|
|||||||
|
|
||||||
## Docs
|
## Docs
|
||||||
|
|
||||||
- **[Deploy](docs/deploy.md)** — running a real instance: images, configuration, TLS,
|
- **[Admin guide](docs/admin-guide.md)** — running a real instance: images,
|
||||||
monitoring, backups, releases.
|
configuration, TLS, monitoring, backups, upgrades, troubleshooting.
|
||||||
|
- **[User guide](docs/user-guide.md)** — accounts and apps, connecting a player,
|
||||||
|
importing history, sharing on the fediverse.
|
||||||
- **[Set up](docs/setup.md)** — working on the code: local dev environment, migrations,
|
- **[Set up](docs/setup.md)** — working on the code: local dev environment, migrations,
|
||||||
tests, CI/CD.
|
tests, CI/CD.
|
||||||
- **[Use](docs/usage.md)** — accounts and apps, connecting a player, importing history,
|
|
||||||
sharing on the fediverse.
|
|
||||||
- **API reference**: `/api/openapi.json`, Swagger UI at `/api/docs`, ReDoc at
|
- **API reference**: `/api/openapi.json`, Swagger UI at `/api/docs`, ReDoc at
|
||||||
`/api/redoc` (a copy is committed at `docs/openapi.json`).
|
`/api/redoc` (a copy is committed at `docs/openapi.json`).
|
||||||
- **Federation internals**: `src/scrobbler/federation/README.md`. Design docs for how it
|
- **Federation internals**: `src/scrobbler/federation/README.md`. Design docs for how it
|
||||||
@@ -34,7 +34,7 @@ docker compose up -d # db, api (:5050), worker, ui (:8080)
|
|||||||
```
|
```
|
||||||
|
|
||||||
Open http://localhost:8080, create an account, then go to **Apps** and create an app for
|
Open http://localhost:8080, create an account, then go to **Apps** and create an app for
|
||||||
a player. See [docs/deploy.md](docs/deploy.md) for the published images, full
|
a player. See [docs/admin-guide.md](docs/admin-guide.md) for the published images, full
|
||||||
configuration reference and production notes.
|
configuration reference and production notes.
|
||||||
|
|
||||||
## Licence
|
## Licence
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -989,6 +989,131 @@
|
|||||||
"w": 12,
|
"w": 12,
|
||||||
"h": 8
|
"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
|
||||||
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -18,7 +18,7 @@ server {
|
|||||||
try_files $uri $uri/ =404;
|
try_files $uri $uri/ =404;
|
||||||
# Files aren't fingerprinted, so always revalidate.
|
# Files aren't fingerprinted, so always revalidate.
|
||||||
add_header Cache-Control "no-cache";
|
add_header Cache-Control "no-cache";
|
||||||
add_header Content-Security-Policy "default-src 'self'; connect-src 'self' ${API_BASE_URL}; img-src 'self' data:; style-src 'self'; font-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'" always;
|
add_header Content-Security-Policy "default-src 'self'; connect-src 'self' ${API_BASE_URL}; img-src 'self' data: blob:; style-src 'self'; font-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'" always;
|
||||||
add_header X-Content-Type-Options nosniff always;
|
add_header X-Content-Type-Options nosniff always;
|
||||||
add_header Referrer-Policy same-origin always;
|
add_header Referrer-Policy same-origin always;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -107,6 +107,43 @@ groups:
|
|||||||
summary: More than 20% of incoming fediverse signatures are failing
|
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').
|
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
|
- alert: PostgresDown
|
||||||
expr: pg_up == 0
|
expr: pg_up == 0
|
||||||
for: 2m
|
for: 2m
|
||||||
|
|||||||
@@ -34,6 +34,8 @@ services:
|
|||||||
WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2}
|
WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2}
|
||||||
FORWARDED_ALLOW_IPS: "*"
|
FORWARDED_ALLOW_IPS: "*"
|
||||||
LASTFM_API_KEY: ${LASTFM_API_KEY:-}
|
LASTFM_API_KEY: ${LASTFM_API_KEY:-}
|
||||||
|
MUSICBRAINZ_CONTACT: ${MUSICBRAINZ_CONTACT:-}
|
||||||
|
ART_STORAGE_DIR: ${ART_STORAGE_DIR:-/data/album-art}
|
||||||
FEDERATION_ENABLED: ${FEDERATION_ENABLED:-0}
|
FEDERATION_ENABLED: ${FEDERATION_ENABLED:-0}
|
||||||
FEDERATION_DOMAIN: ${FEDERATION_DOMAIN:-}
|
FEDERATION_DOMAIN: ${FEDERATION_DOMAIN:-}
|
||||||
FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-}
|
FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-}
|
||||||
@@ -42,6 +44,8 @@ services:
|
|||||||
- "${API_PORT:-5050}:8000"
|
- "${API_PORT:-5050}:8000"
|
||||||
expose:
|
expose:
|
||||||
- "9100" # metrics: internal network only
|
- "9100" # metrics: internal network only
|
||||||
|
volumes:
|
||||||
|
- album-art-data:/data/album-art
|
||||||
depends_on:
|
depends_on:
|
||||||
db:
|
db:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
@@ -57,6 +61,8 @@ services:
|
|||||||
DATABASE_URL: postgresql+psycopg://scrobbler:${POSTGRES_PASSWORD:-scrobbler}@db:5432/scrobbler
|
DATABASE_URL: postgresql+psycopg://scrobbler:${POSTGRES_PASSWORD:-scrobbler}@db:5432/scrobbler
|
||||||
SECRET_KEY: ${SECRET_KEY:-change-me}
|
SECRET_KEY: ${SECRET_KEY:-change-me}
|
||||||
LASTFM_API_KEY: ${LASTFM_API_KEY:-}
|
LASTFM_API_KEY: ${LASTFM_API_KEY:-}
|
||||||
|
MUSICBRAINZ_CONTACT: ${MUSICBRAINZ_CONTACT:-}
|
||||||
|
ART_STORAGE_DIR: ${ART_STORAGE_DIR:-/data/album-art}
|
||||||
FEDERATION_ENABLED: ${FEDERATION_ENABLED:-0}
|
FEDERATION_ENABLED: ${FEDERATION_ENABLED:-0}
|
||||||
FEDERATION_DOMAIN: ${FEDERATION_DOMAIN:-}
|
FEDERATION_DOMAIN: ${FEDERATION_DOMAIN:-}
|
||||||
FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-}
|
FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-}
|
||||||
@@ -64,6 +70,8 @@ services:
|
|||||||
RUN_MIGRATIONS: "0" # the api service applies them
|
RUN_MIGRATIONS: "0" # the api service applies them
|
||||||
expose:
|
expose:
|
||||||
- "9101" # metrics: internal network only
|
- "9101" # metrics: internal network only
|
||||||
|
volumes:
|
||||||
|
- album-art-data:/data/album-art
|
||||||
healthcheck:
|
healthcheck:
|
||||||
disable: true
|
disable: true
|
||||||
depends_on:
|
depends_on:
|
||||||
@@ -123,5 +131,6 @@ services:
|
|||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
db-data:
|
db-data:
|
||||||
|
album-art-data:
|
||||||
prometheus-data:
|
prometheus-data:
|
||||||
grafana-data:
|
grafana-data:
|
||||||
@@ -13,6 +13,8 @@ RUN uv sync --locked --no-dev --no-editable
|
|||||||
FROM python:3.13-slim
|
FROM python:3.13-slim
|
||||||
LABEL org.opencontainers.image.licenses="BSD-3-Clause"
|
LABEL org.opencontainers.image.licenses="BSD-3-Clause"
|
||||||
RUN useradd --system --uid 10001 --no-create-home scrobbler
|
RUN useradd --system --uid 10001 --no-create-home scrobbler
|
||||||
|
# Downloaded album art lives here, on a volume shared with the worker (which writes it).
|
||||||
|
RUN mkdir -p /data/album-art && chown scrobbler:scrobbler /data/album-art
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY --from=build /app/.venv /app/.venv
|
COPY --from=build /app/.venv /app/.venv
|
||||||
COPY gunicorn.conf.py docker/api-entrypoint.sh ./
|
COPY gunicorn.conf.py docker/api-entrypoint.sh ./
|
||||||
|
|||||||
@@ -0,0 +1,276 @@
|
|||||||
|
# Admin guide
|
||||||
|
|
||||||
|
Running a real Scrobbler 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).
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
players / scrobblers ──► API /2.0/ Last.fm-compatible
|
||||||
|
web UI (static files) ──► API /api/v1/ JSON API for the UI
|
||||||
|
API ──► PostgreSQL
|
||||||
|
Prometheus ◄── API :9100/metrics, postgres-exporter ──► Grafana
|
||||||
|
```
|
||||||
|
|
||||||
|
- **`api`**: Flask under gunicorn. API-only; it serves no HTML pages.
|
||||||
|
- **`ui`**: nginx serving the static frontend (`frontend/`, no build step).
|
||||||
|
- **`worker`**: `flask worker` — history imports, resolving and downloading album art
|
||||||
|
(MusicBrainz + Cover Art Archive), and background tasks for optional modules
|
||||||
|
(federation's deliveries, scheduled posts, and so on). This is the only service that
|
||||||
|
makes outbound calls to third-party APIs (Last.fm, MusicBrainz, Cover Art Archive, and
|
||||||
|
remote fediverse servers with federation on) — worth knowing if you're restricting
|
||||||
|
egress.
|
||||||
|
- **`db`**: PostgreSQL.
|
||||||
|
- With the `monitoring` profile: `prometheus`, `grafana`, `postgres-exporter`.
|
||||||
|
|
||||||
|
Everything Scrobbler needs to run is in these five services plus optional monitoring —
|
||||||
|
there's no separate cache, queue or search service to operate.
|
||||||
|
|
||||||
|
## Installing
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cp .env.example .env # then set SECRET_KEY and POSTGRES_PASSWORD
|
||||||
|
SCROBBLER_IMAGE_TAG=main docker compose up -d --no-build # or drop --no-build to build locally
|
||||||
|
```
|
||||||
|
|
||||||
|
Open `http://localhost:8080`, create an account, then go to **Apps** and create an app
|
||||||
|
for each player. Add `--profile monitoring` for Prometheus and Grafana.
|
||||||
|
|
||||||
|
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
|
||||||
|
read **Putting it behind TLS** below — the quick start above serves plain HTTP only.
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
| Variable | Used by | Default | Purpose |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `DATABASE_URL` | api | local Postgres | SQLAlchemy URL (`postgresql+psycopg://…`) |
|
||||||
|
| `SECRET_KEY` | api | `dev-insecure-secret` | Flask secret — set a real one |
|
||||||
|
| `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` |
|
||||||
|
| `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 |
|
||||||
|
|
||||||
|
In `docker compose`, host ports are set with `DB_PORT`, `API_PORT`, `UI_PORT`,
|
||||||
|
`PROMETHEUS_PORT` and `GRAFANA_PORT`.
|
||||||
|
|
||||||
|
`CORS_ORIGINS` and `UI_BASE_URL` answer different questions and can differ: the first is
|
||||||
|
*which browser origins may call the JSON API*, the second is *where the public identity
|
||||||
|
and sign-in redirects point*. Don't assume setting one sets the other —
|
||||||
|
`docker-compose.yml` passes them through independently, and forgetting to set
|
||||||
|
`CORS_ORIGINS` to your real public origin is the single most common cause of "the UI
|
||||||
|
can't reach the API" once you're off `localhost` (see Troubleshooting).
|
||||||
|
|
||||||
|
### Fediverse sharing (optional)
|
||||||
|
|
||||||
|
Off unless the server enables it, and then off for each user until they turn it on:
|
||||||
|
|
||||||
|
1. Set on the **api** and **worker**:
|
||||||
|
- `FEDERATION_ENABLED=1`
|
||||||
|
- `FEDERATION_DOMAIN`: the UI's host, e.g. `scrobble.example`
|
||||||
|
- `FEDERATION_BASE_URL`: the UI's origin, e.g. `https://scrobble.example`
|
||||||
|
- `FEDERATION_KEY_SECRET`: 32+ random characters
|
||||||
|
2. Give the **ui** container `API_INTERNAL_URL` (compose sets `http://api:8000`). It
|
||||||
|
forwards these paths to the API: `/.well-known/webfinger`, `/.well-known/nodeinfo`,
|
||||||
|
`/.well-known/host-meta`, `/nodeinfo/`, `/users/`, `/inbox` and `/actor`.
|
||||||
|
3. Serve the UI over **real HTTPS** on that domain — other fediverse servers only talk to
|
||||||
|
HTTPS, and won't accept a self-signed certificate.
|
||||||
|
|
||||||
|
Handles and actor URLs **can't change once anyone follows a user**, so choose the domain
|
||||||
|
carefully before enabling this in production.
|
||||||
|
|
||||||
|
`FEDERATION_KEY_SECRET` encrypts every user's signing key. **Back it up, and never
|
||||||
|
change it**: losing it means users' keys can't be read, and followers would have to
|
||||||
|
follow again.
|
||||||
|
|
||||||
|
Optional: `FEDERATION_BLOCKED_DOMAINS` (comma-separated, subdomains included),
|
||||||
|
`FEDERATION_DELIVERY_CONCURRENCY` (default 4), `FEDERATION_SIGNATURE_SCHEMES` (default
|
||||||
|
`draft-cavage,rfc9421`). The `worker` service must be running — it delivers outgoing
|
||||||
|
activities and processes incoming ones.
|
||||||
|
|
||||||
|
Once it's on, tell your users: they still need to opt in themselves under **Sharing** in
|
||||||
|
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
|
||||||
|
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).
|
||||||
|
|
||||||
|
Caddy, proxying everything to the `ui` container (which itself forwards the fediverse
|
||||||
|
paths to `api`), gets you a certificate automatically with no extra steps:
|
||||||
|
|
||||||
|
```
|
||||||
|
scrobble.example {
|
||||||
|
reverse_proxy localhost:8080
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
nginx with certbot, doing the same job:
|
||||||
|
|
||||||
|
```nginx
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name scrobble.example;
|
||||||
|
location / { return 301 https://$host$request_uri; }
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
server_name scrobble.example;
|
||||||
|
ssl_certificate /etc/letsencrypt/live/scrobble.example/fullchain.pem;
|
||||||
|
ssl_certificate_key /etc/letsencrypt/live/scrobble.example/privkey.pem;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://localhost:8080;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Forwarded-Proto https;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```sh
|
||||||
|
certbot --nginx -d scrobble.example
|
||||||
|
```
|
||||||
|
|
||||||
|
Point `UI_BASE_URL`/`FEDERATION_BASE_URL`/`FEDERATION_DOMAIN` at that same public
|
||||||
|
`https://scrobble.example` origin. The API (`API_PORT`, default 5050) doesn't need its
|
||||||
|
own public hostname unless you want browsers to reach it directly instead of through the
|
||||||
|
UI's proxy — set `API_BASE_URL` accordingly either way, since the browser calls it
|
||||||
|
directly for `/api/v1`, and make sure `CORS_ORIGINS` includes `https://scrobble.example`
|
||||||
|
regardless of which layout you pick.
|
||||||
|
|
||||||
|
## Monitoring
|
||||||
|
|
||||||
|
The API serves Prometheus metrics on `METRICS_PORT`, summed across gunicorn workers. All
|
||||||
|
series are prefixed `scrobbler_`: HTTP request rate/errors/latency, Last.fm calls and
|
||||||
|
auth failures, scrobble outcomes, database query latency and pool use, and gauges for
|
||||||
|
registered/active/currently-listening users. Labels never contain usernames, API keys or
|
||||||
|
track names.
|
||||||
|
|
||||||
|
With `--profile monitoring`, Grafana (`GRAFANA_ADMIN_PASSWORD`) provisions a
|
||||||
|
**Scrobbler** 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.
|
||||||
|
|
||||||
|
## Backups and restore
|
||||||
|
|
||||||
|
Back up, at minimum:
|
||||||
|
|
||||||
|
- The Postgres database (all scrobble history, accounts, federation state).
|
||||||
|
- `FEDERATION_KEY_SECRET`, if federation is on — it's the only thing that can decrypt
|
||||||
|
stored signing keys, and it's never derivable from the database alone.
|
||||||
|
- Your `.env` (or equivalent secrets store), so `SECRET_KEY` and the rest survive a
|
||||||
|
rebuild without inventing new ones.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose exec db pg_dump -U scrobbler scrobbler | gzip > backup-$(date +%F).sql.gz
|
||||||
|
```
|
||||||
|
|
||||||
|
To restore onto a fresh `db` volume:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
gunzip -c backup-2026-01-01.sql.gz | docker compose exec -T db psql -U scrobbler scrobbler
|
||||||
|
```
|
||||||
|
|
||||||
|
Restoring an older dump with federation on will leave followers pointed at posts that no
|
||||||
|
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 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
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose pull # or set SCROBBLER_IMAGE_TAG to a specific version
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
Migrations run automatically on API container start (`RUN_MIGRATIONS=1`, the default).
|
||||||
|
Take a database backup first for anything beyond a patch version — check
|
||||||
|
`docs/design/` and the Gitea release notes for the version you're jumping to if it spans
|
||||||
|
a major version.
|
||||||
|
|
||||||
|
## Releases
|
||||||
|
|
||||||
|
Gitea Actions (`.gitea/workflows/ci.yml`) builds and publishes on every push to `main`
|
||||||
|
and on `v*` tags, once lint, tests and the Prometheus config checks all pass:
|
||||||
|
|
||||||
|
- Both images push to the ProGet `scrobbler` Docker feed.
|
||||||
|
- The OpenAPI spec, dashboards and Prometheus config upload to the `scrobbler-assets`
|
||||||
|
feed.
|
||||||
|
- `v*` tags also publish the wheel/sdist to the `scrobbler-python` PyPI feed (as
|
||||||
|
`scrobby`; `scrobbler` on public PyPI is an unrelated project).
|
||||||
|
|
||||||
|
To release: tag `vX.Y.Z` on `main` and push the tag. That tag sets both the package and
|
||||||
|
image version. See [setup.md](setup.md) for the secrets/variables the workflow needs and
|
||||||
|
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
|
||||||
|
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`
|
||||||
|
or `www.scrobble.example`). Check with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -i -X OPTIONS https://scrobble.example/api/v1/auth/me \
|
||||||
|
-H "Origin: https://scrobble.example" -H "Access-Control-Request-Method: GET"
|
||||||
|
```
|
||||||
|
|
||||||
|
A missing `access-control-allow-origin` header in the response confirms it. This is
|
||||||
|
separate from `UI_BASE_URL` — setting one does not set the other.
|
||||||
|
|
||||||
|
**Federation looks enabled but the "Sharing" page/nav link doesn't appear for a user.**
|
||||||
|
First confirm federation is actually on server-side, independent of what any log line
|
||||||
|
says (gunicorn drops `log.info` by default unless something configures logging):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -o /dev/null -w '%{http_code}\n' https://scrobble.example/actor # 200 = federation is on
|
||||||
|
```
|
||||||
|
|
||||||
|
If that's `200`, the server is fine and the problem is client-side: the web UI caches
|
||||||
|
whether federation is available in the browser's `sessionStorage` for the tab, and
|
||||||
|
caches static JS in the ordinary browser cache. Ask the user to hard-refresh
|
||||||
|
(Ctrl/Cmd+Shift+R) or try a private window — if it works there, it's a stale cache, not
|
||||||
|
a server problem.
|
||||||
|
|
||||||
|
**A fediverse profile 404s from a specific remote server (e.g. mastodon.social) right
|
||||||
|
after you enable sharing, even though WebFinger looks correct from curl.** Large
|
||||||
|
instances cache a *negative* WebFinger lookup for a while. Confirm the server's own
|
||||||
|
response is correct first:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -H 'Accept: application/jrd+json' \
|
||||||
|
'https://scrobble.example/.well-known/webfinger?resource=acct:name@scrobble.example'
|
||||||
|
```
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
**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
|
||||||
|
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
|
||||||
|
instead.
|
||||||
-145
@@ -1,145 +0,0 @@
|
|||||||
# Deploying Scrobbler
|
|
||||||
|
|
||||||
This covers running a real instance: the published images, configuration, putting it
|
|
||||||
behind TLS, monitoring, backups and releases. For running the code locally to work on
|
|
||||||
it, see [setup.md](setup.md). For what the service does once it's running, see
|
|
||||||
[usage.md](usage.md).
|
|
||||||
|
|
||||||
## Services
|
|
||||||
|
|
||||||
```
|
|
||||||
players / scrobblers ──► API /2.0/ Last.fm-compatible
|
|
||||||
web UI (static files) ──► API /api/v1/ JSON API for the UI
|
|
||||||
API ──► PostgreSQL
|
|
||||||
Prometheus ◄── API :9100/metrics, postgres-exporter ──► Grafana
|
|
||||||
```
|
|
||||||
|
|
||||||
- **`api`**: Flask under gunicorn. API-only; it serves no HTML pages.
|
|
||||||
- **`ui`**: nginx serving the static frontend (`frontend/`, no build step).
|
|
||||||
- **`worker`**: `flask worker` — history imports and background tasks for optional
|
|
||||||
modules (federation's deliveries, scheduled posts, and so on).
|
|
||||||
- **`db`**: PostgreSQL.
|
|
||||||
- With the `monitoring` profile: `prometheus`, `grafana`, `postgres-exporter`.
|
|
||||||
|
|
||||||
## Quick start
|
|
||||||
|
|
||||||
```sh
|
|
||||||
cp .env.example .env # then set SECRET_KEY and POSTGRES_PASSWORD
|
|
||||||
SCROBBLER_IMAGE_TAG=main docker compose up -d --no-build # or drop --no-build to build locally
|
|
||||||
```
|
|
||||||
|
|
||||||
Open `http://localhost:8080`, create an account, then go to **Apps** and create an app
|
|
||||||
for each player. Add `--profile monitoring` for Prometheus and Grafana.
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
## Configuration
|
|
||||||
|
|
||||||
| Variable | Used by | Default | Purpose |
|
|
||||||
|---|---|---|---|
|
|
||||||
| `DATABASE_URL` | api | local Postgres | SQLAlchemy URL (`postgresql+psycopg://…`) |
|
|
||||||
| `SECRET_KEY` | api | `dev-insecure-secret` | Flask secret — set a real one |
|
|
||||||
| `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` |
|
|
||||||
| `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)) |
|
|
||||||
| `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 |
|
|
||||||
|
|
||||||
In `docker compose`, host ports are set with `DB_PORT`, `API_PORT`, `UI_PORT`,
|
|
||||||
`PROMETHEUS_PORT` and `GRAFANA_PORT`.
|
|
||||||
|
|
||||||
`CORS_ORIGINS` and `UI_BASE_URL` answer different questions and can differ: the first is
|
|
||||||
*which browser origins may call the JSON API*, the second is *where the public identity
|
|
||||||
and sign-in redirects point*. Don't assume setting one sets the other — `docker-compose.yml`
|
|
||||||
passes them through independently.
|
|
||||||
|
|
||||||
### Fediverse sharing (optional)
|
|
||||||
|
|
||||||
Off unless the server enables it, and then off for each user until they turn it on:
|
|
||||||
|
|
||||||
1. Set on the **api** and **worker**:
|
|
||||||
- `FEDERATION_ENABLED=1`
|
|
||||||
- `FEDERATION_DOMAIN`: the UI's host, e.g. `scrobble.example`
|
|
||||||
- `FEDERATION_BASE_URL`: the UI's origin, e.g. `https://scrobble.example`
|
|
||||||
- `FEDERATION_KEY_SECRET`: 32+ random characters
|
|
||||||
2. Give the **ui** container `API_INTERNAL_URL` (compose sets `http://api:8000`). It
|
|
||||||
forwards these paths to the API: `/.well-known/webfinger`, `/.well-known/nodeinfo`,
|
|
||||||
`/.well-known/host-meta`, `/nodeinfo/`, `/users/`, `/inbox` and `/actor`.
|
|
||||||
3. Serve the UI over **real HTTPS** on that domain — other fediverse servers only talk to
|
|
||||||
HTTPS, and won't accept a self-signed certificate.
|
|
||||||
|
|
||||||
Handles and actor URLs **can't change once anyone follows a user**, so choose the domain
|
|
||||||
carefully before enabling this in production.
|
|
||||||
|
|
||||||
`FEDERATION_KEY_SECRET` encrypts every user's signing key. **Back it up, and never
|
|
||||||
change it**: losing it means users' keys can't be read, and followers would have to
|
|
||||||
follow again.
|
|
||||||
|
|
||||||
Optional: `FEDERATION_BLOCKED_DOMAINS` (comma-separated, subdomains included),
|
|
||||||
`FEDERATION_DELIVERY_CONCURRENCY` (default 4), `FEDERATION_SIGNATURE_SCHEMES` (default
|
|
||||||
`draft-cavage,rfc9421`). The `worker` service must be running — it delivers outgoing
|
|
||||||
activities and processes incoming ones.
|
|
||||||
|
|
||||||
## Putting it behind TLS
|
|
||||||
|
|
||||||
Scrobbler 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). A minimal Caddy example, proxying
|
|
||||||
everything to the `ui` container (which itself forwards the fediverse paths to `api`):
|
|
||||||
|
|
||||||
```
|
|
||||||
scrobble.example {
|
|
||||||
reverse_proxy localhost:8080
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Point `UI_BASE_URL`/`FEDERATION_BASE_URL`/`FEDERATION_DOMAIN` at that same public
|
|
||||||
`https://scrobble.example` origin. The API (`API_PORT`, default 5050) doesn't need its
|
|
||||||
own public hostname unless you want browsers to reach it directly instead of through the
|
|
||||||
UI's proxy — set `API_BASE_URL` accordingly either way, since the browser calls it
|
|
||||||
directly for `/api/v1`.
|
|
||||||
|
|
||||||
## Monitoring
|
|
||||||
|
|
||||||
The API serves Prometheus metrics on `METRICS_PORT`, summed across gunicorn workers. All
|
|
||||||
series are prefixed `scrobbler_`: HTTP request rate/errors/latency, Last.fm calls and
|
|
||||||
auth failures, scrobble outcomes, database query latency and pool use, and gauges for
|
|
||||||
registered/active/currently-listening users. Labels never contain usernames, API keys or
|
|
||||||
track names.
|
|
||||||
|
|
||||||
With `--profile monitoring`, Grafana (`GRAFANA_ADMIN_PASSWORD`) provisions a
|
|
||||||
**Scrobbler** 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.
|
|
||||||
|
|
||||||
## Backups
|
|
||||||
|
|
||||||
Back up, at minimum:
|
|
||||||
|
|
||||||
- The Postgres database (all scrobble history, accounts, federation state).
|
|
||||||
- `FEDERATION_KEY_SECRET`, if federation is on — it's the only thing that can decrypt
|
|
||||||
stored signing keys, and it's never derivable from the database alone.
|
|
||||||
|
|
||||||
## Releases
|
|
||||||
|
|
||||||
Gitea Actions (`.gitea/workflows/ci.yml`) builds and publishes on every push to `main`
|
|
||||||
and on `v*` tags, once lint, tests and the Prometheus config checks all pass:
|
|
||||||
|
|
||||||
- Both images push to the ProGet `scrobbler` Docker feed.
|
|
||||||
- The OpenAPI spec, dashboards and Prometheus config upload to the `scrobbler-assets`
|
|
||||||
feed.
|
|
||||||
- `v*` tags also publish the wheel/sdist to the `scrobbler-python` PyPI feed (as
|
|
||||||
`scrobby`; `scrobbler` on public PyPI is an unrelated project).
|
|
||||||
|
|
||||||
To release: tag `vX.Y.Z` on `main` and push the tag. That tag sets both the package and
|
|
||||||
image version. See [setup.md](setup.md) for the secrets/variables the workflow needs and
|
|
||||||
how to run it locally before tagging.
|
|
||||||
@@ -992,6 +992,167 @@
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"/api/v1/me/tracks/search": {
|
||||||
|
"get": {
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"in": "query",
|
||||||
|
"name": "q",
|
||||||
|
"schema": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"maxLength": 200
|
||||||
|
},
|
||||||
|
"required": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"in": "query",
|
||||||
|
"name": "limit",
|
||||||
|
"schema": {
|
||||||
|
"type": "integer",
|
||||||
|
"default": 20,
|
||||||
|
"minimum": 1,
|
||||||
|
"maximum": 50
|
||||||
|
},
|
||||||
|
"required": false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"422": {
|
||||||
|
"$ref": "#/components/responses/UNPROCESSABLE_CONTENT"
|
||||||
|
},
|
||||||
|
"200": {
|
||||||
|
"description": "OK",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/components/schemas/TrackSearchResult"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"401": {
|
||||||
|
"description": "Not authenticated",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/Error"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"default": {
|
||||||
|
"$ref": "#/components/responses/DEFAULT_ERROR"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"summary": "Find a song by track or artist name",
|
||||||
|
"tags": [
|
||||||
|
"Tracks"
|
||||||
|
],
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"bearerAuth": []
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/api/v1/me/tracks": {
|
||||||
|
"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
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"in": "query",
|
||||||
|
"name": "artist",
|
||||||
|
"schema": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"maxLength": 500
|
||||||
|
},
|
||||||
|
"required": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"in": "query",
|
||||||
|
"name": "track",
|
||||||
|
"schema": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"maxLength": 500
|
||||||
|
},
|
||||||
|
"required": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"422": {
|
||||||
|
"$ref": "#/components/responses/UNPROCESSABLE_CONTENT"
|
||||||
|
},
|
||||||
|
"404": {
|
||||||
|
"description": "You've never scrobbled this song",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/Error"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"200": {
|
||||||
|
"description": "OK",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/TrackDetail"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"401": {
|
||||||
|
"description": "Not authenticated",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/Error"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"default": {
|
||||||
|
"$ref": "#/components/responses/DEFAULT_ERROR"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"summary": "A song's play history and recorded metadata",
|
||||||
|
"tags": [
|
||||||
|
"Tracks"
|
||||||
|
],
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"bearerAuth": []
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
"/api/v1/imports/options": {
|
"/api/v1/imports/options": {
|
||||||
"get": {
|
"get": {
|
||||||
"responses": {
|
"responses": {
|
||||||
@@ -1342,6 +1503,424 @@
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
"/api/v1/art/album": {
|
||||||
|
"get": {
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"in": "query",
|
||||||
|
"name": "artist",
|
||||||
|
"schema": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"maxLength": 500
|
||||||
|
},
|
||||||
|
"required": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"in": "query",
|
||||||
|
"name": "album",
|
||||||
|
"schema": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"maxLength": 500
|
||||||
|
},
|
||||||
|
"required": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"422": {
|
||||||
|
"$ref": "#/components/responses/UNPROCESSABLE_CONTENT"
|
||||||
|
},
|
||||||
|
"404": {
|
||||||
|
"description": "No cover art available yet",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/Error"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"200": {
|
||||||
|
"description": "The album's cover art (JPEG, PNG or WebP)"
|
||||||
|
},
|
||||||
|
"401": {
|
||||||
|
"description": "Not authenticated",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/Error"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"default": {
|
||||||
|
"$ref": "#/components/responses/DEFAULT_ERROR"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"summary": "An album's cover art",
|
||||||
|
"description": "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 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"
|
||||||
|
],
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"bearerAuth": []
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
"/healthz": {
|
"/healthz": {
|
||||||
"get": {
|
"get": {
|
||||||
"responses": {
|
"responses": {
|
||||||
@@ -3205,10 +3784,18 @@
|
|||||||
"name": "Stats",
|
"name": "Stats",
|
||||||
"description": "Your listening history and statistics"
|
"description": "Your listening history and statistics"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"name": "Tracks",
|
||||||
|
"description": "Look up a specific song's history and metadata"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"name": "Imports",
|
"name": "Imports",
|
||||||
"description": "Import listening history from a Last.fm export file, or straight from Last.fm. Imports run in the background; poll a job to follow its progress."
|
"description": "Import listening history from a Last.fm export file, or straight from Last.fm. Imports run in the background; poll a job to follow its progress."
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"name": "Art",
|
||||||
|
"description": "Album art, resolved from MusicBrainz / Cover Art Archive by a background worker. You can also upload your own art, or correct a failed lookup; those only change what you see."
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"name": "Health",
|
"name": "Health",
|
||||||
"description": "Liveness for load balancers and containers"
|
"description": "Liveness for load balancers and containers"
|
||||||
@@ -3662,6 +4249,108 @@
|
|||||||
},
|
},
|
||||||
"additionalProperties": false
|
"additionalProperties": false
|
||||||
},
|
},
|
||||||
|
"TrackSearchResult": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"artist": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"track": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"playcount": {
|
||||||
|
"type": "integer"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"additionalProperties": false
|
||||||
|
},
|
||||||
|
"TrackMetadata": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"album": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"album_artist": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"track_number": {
|
||||||
|
"type": [
|
||||||
|
"integer",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"duration": {
|
||||||
|
"type": [
|
||||||
|
"integer",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"mbid": {
|
||||||
|
"type": [
|
||||||
|
"string",
|
||||||
|
"null"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"playcount": {
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"first_played_at": {
|
||||||
|
"type": "string",
|
||||||
|
"format": "date-time"
|
||||||
|
},
|
||||||
|
"last_played_at": {
|
||||||
|
"type": "string",
|
||||||
|
"format": "date-time"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"additionalProperties": false
|
||||||
|
},
|
||||||
|
"TrackDetail": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"page": {
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"per_page": {
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"total": {
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"total_pages": {
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"artist": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"track": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"metadata": {
|
||||||
|
"$ref": "#/components/schemas/TrackMetadata"
|
||||||
|
},
|
||||||
|
"items": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/components/schemas/Scrobble"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"counts": {
|
||||||
|
"type": "array",
|
||||||
|
"description": "Daily plays over the last 90 days",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/components/schemas/Count"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"additionalProperties": false
|
||||||
|
},
|
||||||
"ImportOptions": {
|
"ImportOptions": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
@@ -3797,6 +4486,163 @@
|
|||||||
],
|
],
|
||||||
"additionalProperties": false
|
"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"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"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": {
|
"Health": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
|
|||||||
+4
-3
@@ -1,7 +1,8 @@
|
|||||||
# Working on Scrobbler
|
# Working on Scrobbler
|
||||||
|
|
||||||
Setting up a local development environment. For running a real instance, see
|
Setting up a local development environment. For running a real instance, see the
|
||||||
[deploy.md](deploy.md). For what the service does, see [usage.md](usage.md).
|
[admin guide](admin-guide.md). For what the service does, see the
|
||||||
|
[user guide](user-guide.md).
|
||||||
|
|
||||||
## Prerequisites
|
## Prerequisites
|
||||||
|
|
||||||
@@ -88,7 +89,7 @@ Everything runs from `.gitea/workflows/ci.yml`:
|
|||||||
- **Every push and PR**: lint, the migrations-vs-models check, tests against Postgres,
|
- **Every push and PR**: lint, the migrations-vs-models check, tests against Postgres,
|
||||||
and `promtool` checks of the Prometheus config and alert rules.
|
and `promtool` checks of the Prometheus config and alert rules.
|
||||||
- **Pushes to `main` and tags**, once those all pass: images and assets publish (see
|
- **Pushes to `main` and tags**, once those all pass: images and assets publish (see
|
||||||
[deploy.md](deploy.md#releases)).
|
[admin guide](admin-guide.md#releases)).
|
||||||
- **Every run** posts to the `ScrobblingService` topic on notify.daubney.dev.
|
- **Every run** posts to the `ScrobblingService` topic on notify.daubney.dev.
|
||||||
|
|
||||||
Repository secrets: `PKGS_USER`, `PKGS_PASSWORD`, `PKGS_API_KEY`, `NTFY_USER`,
|
Repository secrets: `PKGS_USER`, `PKGS_PASSWORD`, `PKGS_API_KEY`, `NTFY_USER`,
|
||||||
|
|||||||
@@ -1,94 +0,0 @@
|
|||||||
# Using Scrobbler
|
|
||||||
|
|
||||||
What the service does, once it's running. For getting an instance running, see
|
|
||||||
[deploy.md](deploy.md); for working on the code, see [setup.md](setup.md).
|
|
||||||
|
|
||||||
## Account and apps
|
|
||||||
|
|
||||||
Register in the web UI, then go to **Apps** and create one app per player or scrobbler
|
|
||||||
client you use — each gets its own API key and shared secret, and can be revoked on its
|
|
||||||
own from the **Sessions** page without affecting the others.
|
|
||||||
|
|
||||||
## Connecting a player
|
|
||||||
|
|
||||||
In the player's scrobbling settings, choose a custom or self-hosted Last.fm server:
|
|
||||||
|
|
||||||
- **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
|
|
||||||
|
|
||||||
Two sign-in flows are supported:
|
|
||||||
|
|
||||||
- **Mobile**: `auth.getMobileSession` with a username and password, sent as a POST body
|
|
||||||
over HTTPS.
|
|
||||||
- **Desktop**: `auth.getToken`, then the user approves at `/api/auth/` (redirects to the
|
|
||||||
web UI), then `auth.getSession`.
|
|
||||||
|
|
||||||
The legacy `authToken = md5(username + md5(password))` form isn't supported — checking
|
|
||||||
it would mean storing unsalted password hashes. pylast's `password_hash` option uses
|
|
||||||
that form; use `SessionKeyGenerator` (the desktop flow) instead.
|
|
||||||
|
|
||||||
Supported methods: `auth.getMobileSession`, `auth.getToken`, `auth.getSession`,
|
|
||||||
`track.scrobble` (up to 50 per request), `track.updateNowPlaying`, `user.getInfo`,
|
|
||||||
`user.getRecentTracks`, `user.getTopArtists`, `user.getTopAlbums`, `user.getTopTracks`.
|
|
||||||
`/api/docs` has the full parameters, rules and example responses for each.
|
|
||||||
|
|
||||||
A scrobble is ignored (not rejected) if the artist or track is empty, or the timestamp
|
|
||||||
is more than 14 days old or more than 5 minutes in the future. Resending the same
|
|
||||||
scrobble is accepted and stored once, so client retries are safe.
|
|
||||||
|
|
||||||
## Importing history
|
|
||||||
|
|
||||||
Open **Import** in the web UI:
|
|
||||||
|
|
||||||
- **An export file**:
|
|
||||||
- CSV from [lastfm-to-csv](https://benjaminbenben.com/lastfm-to-csv/), no header row,
|
|
||||||
artist/album/track/date columns.
|
|
||||||
- Any CSV or TSV with a header row naming artist, track and a date or Unix-time
|
|
||||||
column. Comma, semicolon and tab delimiters all work.
|
|
||||||
- A JSON export of `user.getRecentTracks` pages (such as lastfm.ghan.nl's), a single
|
|
||||||
`recenttracks` response, or a flat list of tracks.
|
|
||||||
- Files can be gzipped.
|
|
||||||
- **Last.fm directly**: enter a Last.fm username and the worker pages through that
|
|
||||||
account's public history. Only appears when the server has `LASTFM_API_KEY` set.
|
|
||||||
|
|
||||||
Imports run in the background; the page shows progress and can cancel one in flight.
|
|
||||||
Unlike live scrobbles, imports keep plays of any age (still skipping rows with no artist
|
|
||||||
or track, or plays dated in the future). Plays already in your history are skipped, so
|
|
||||||
importing the same export again is safe.
|
|
||||||
|
|
||||||
## Sharing on the fediverse
|
|
||||||
|
|
||||||
Only available when the server has federation enabled (ask whoever runs it, or see
|
|
||||||
[deploy.md](deploy.md#fediverse-sharing-optional) if that's you). Turn it on under
|
|
||||||
**Sharing**, and you're findable as `@name@<the server's host>` from Mastodon and other
|
|
||||||
fediverse apps:
|
|
||||||
|
|
||||||
- Follows are accepted automatically, or wait for your approval if you turn that on.
|
|
||||||
- **Followers** lists requests, followers and blocked accounts, with approve, decline,
|
|
||||||
remove, block and unblock.
|
|
||||||
|
|
||||||
Once someone follows, **Sharing**'s **What to post** section controls what they see:
|
|
||||||
|
|
||||||
- **Weekly summary**: play count and top artist(s), posted once a week (Monday 09:00 in
|
|
||||||
your own time zone, for the week that just ended). A live preview shows what it would
|
|
||||||
say so far.
|
|
||||||
- **Milestones**: total scrobbles, an artist's plays, and a new entry into your all-time
|
|
||||||
top 10 — each posted once, the first time it's reached. History already on file when
|
|
||||||
you turn sharing on, or added by an import, is never posted about retroactively.
|
|
||||||
|
|
||||||
Both are on by default and can be switched off independently. Posts use the same
|
|
||||||
visibility as your profile (followers only by default, or unlisted/public); **Posts**
|
|
||||||
lists your own posts with delete (sends a `Delete` to whoever received it).
|
|
||||||
|
|
||||||
**Now playing** is a separate, three-way choice:
|
|
||||||
|
|
||||||
- **Off** (default): nothing shown or posted.
|
|
||||||
- **Show on my profile**: a "Now playing: *Track* by Artist" field, refreshed at most
|
|
||||||
every 5 minutes while something's playing and cleared a few minutes after it stops.
|
|
||||||
- **Show on my profile and post**: the profile field, plus a post for each track played
|
|
||||||
30 seconds or more, at most one every 30 minutes, with the previous now-playing post
|
|
||||||
deleted once the new one is confirmed published.
|
|
||||||
|
|
||||||
Handles and actor URLs **can't change once anyone follows you**, so if you're the one
|
|
||||||
who gets to choose the server's domain, choose it carefully.
|
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
# User guide
|
||||||
|
|
||||||
|
What Scrobbler 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.
|
||||||
|
|
||||||
|
## Getting started
|
||||||
|
|
||||||
|
Register in the web UI, then go to **Apps** and create one app per player or scrobbler
|
||||||
|
client you use — each gets its own API key and shared secret, and can be revoked on its
|
||||||
|
own from the **Sessions** page without affecting the others. If a friend runs your
|
||||||
|
instance, ask them for its address; that's the only thing you need from them to get
|
||||||
|
going.
|
||||||
|
|
||||||
|
## Connecting a player
|
||||||
|
|
||||||
|
In the player's scrobbling settings, choose a custom or self-hosted Last.fm server:
|
||||||
|
|
||||||
|
- **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
|
||||||
|
|
||||||
|
Two sign-in flows are supported, and most players use one or the other automatically:
|
||||||
|
|
||||||
|
- **Mobile**: you enter your username and password directly in the player.
|
||||||
|
- **Desktop**: the player opens a browser page for you to approve, then signs itself in
|
||||||
|
— no password ever passed to the player.
|
||||||
|
|
||||||
|
A sign-in method that hashes your password before sending it (sometimes offered as a
|
||||||
|
"stored password" or "password hash" option, e.g. pylast's `password_hash`) isn't
|
||||||
|
supported — use the plain username/password or desktop-approval flow instead.
|
||||||
|
|
||||||
|
Supported methods, if your player lets you check: `auth.getMobileSession`,
|
||||||
|
`auth.getToken`, `auth.getSession`, `track.scrobble` (up to 50 per request),
|
||||||
|
`track.updateNowPlaying`, `user.getInfo`, `user.getRecentTracks`, `user.getTopArtists`,
|
||||||
|
`user.getTopAlbums`, `user.getTopTracks`. `/api/docs` on your instance has the full
|
||||||
|
parameters and example responses for each, if you're curious or debugging a client.
|
||||||
|
|
||||||
|
A play is silently skipped (not rejected as an error) if the artist or track name is
|
||||||
|
empty, or its timestamp is more than 14 days old or more than 5 minutes in the future.
|
||||||
|
Sending the same play twice — a common side effect of a player retrying after a network
|
||||||
|
blip — is accepted both times but only stored once, so retries are always safe.
|
||||||
|
|
||||||
|
**A legacy scrobbler that speaks the old 1.2 "handshake" protocol (rather than 2.0) won't
|
||||||
|
work here** — this is a client limitation, not a setting to fix. VLC's built-in
|
||||||
|
scrobbler is one example; look for a plugin or a different player with 2.0 support.
|
||||||
|
|
||||||
|
## Importing history
|
||||||
|
|
||||||
|
Open **Import** in the web UI:
|
||||||
|
|
||||||
|
- **An export file**:
|
||||||
|
- CSV from [lastfm-to-csv](https://benjaminbenben.com/lastfm-to-csv/), no header row,
|
||||||
|
artist/album/track/date columns.
|
||||||
|
- Any CSV or TSV with a header row naming artist, track and a date or Unix-time
|
||||||
|
column. Comma, semicolon and tab delimiters all work.
|
||||||
|
- A JSON export of `user.getRecentTracks` pages (such as lastfm.ghan.nl's), a single
|
||||||
|
`recenttracks` response, or a flat list of tracks.
|
||||||
|
- Files can be gzipped.
|
||||||
|
- **Last.fm directly**: enter a Last.fm username and the import runs against that
|
||||||
|
account's public history. Only appears if your instance's admin has set this up.
|
||||||
|
|
||||||
|
Imports run in the background — the page shows progress and you can cancel one in
|
||||||
|
flight. Unlike live scrobbles, imports keep plays of any age (still skipping rows with no
|
||||||
|
artist or track, or plays dated in the future). Plays already in your history are
|
||||||
|
skipped, so importing the same export again, or importing overlapping exports, is safe.
|
||||||
|
|
||||||
|
## Sharing on the fediverse
|
||||||
|
|
||||||
|
Only available if your instance's admin has turned this on — ask them, or check whether
|
||||||
|
**Sharing** appears in the navigation. Turn it on there, and you're findable as
|
||||||
|
`@name@<your instance's host>` from Mastodon and other fediverse apps.
|
||||||
|
|
||||||
|
- Follows are accepted automatically, or wait for your approval if you turn that on
|
||||||
|
under **Followers and discovery**.
|
||||||
|
- **Followers** lists requests, followers and blocked accounts, with approve, decline,
|
||||||
|
remove, block and unblock.
|
||||||
|
|
||||||
|
Once someone follows you, **Sharing**'s **What to post** section controls what they see:
|
||||||
|
|
||||||
|
- **Weekly summary**: your play count and top artist(s), posted once a week (Monday
|
||||||
|
09:00 in your own time zone, for the week that just ended). A live preview shows what
|
||||||
|
it would say so far.
|
||||||
|
- **Milestones**: total scrobbles, an artist's plays, and a new entry into your all-time
|
||||||
|
top 10 — each posted once, the first time you reach it. History already on file when
|
||||||
|
you turn sharing on, or added by an import, is never posted about retroactively.
|
||||||
|
|
||||||
|
Both are on by default and can be switched off independently. Posts use the same
|
||||||
|
visibility as your profile (followers only by default, or unlisted/public); **Posts**
|
||||||
|
lists your own posts, each with a delete button.
|
||||||
|
|
||||||
|
**Now playing** is a separate, three-way choice:
|
||||||
|
|
||||||
|
- **Off** (default): nothing shown or posted.
|
||||||
|
- **Show on my profile**: a "Now playing: *Track* by Artist" field on your profile,
|
||||||
|
refreshed at most every 5 minutes while something's playing and cleared a few minutes
|
||||||
|
after it stops.
|
||||||
|
- **Show on my profile and post**: the profile field, plus a post for each track played
|
||||||
|
30 seconds or more, at most one every 30 minutes, with the previous now-playing post
|
||||||
|
deleted once the new one is confirmed published.
|
||||||
|
|
||||||
|
**Your handle can't change once anyone follows you** — if you get to choose the
|
||||||
|
instance's domain yourself, or you're choosing which instance to join, bear that in mind
|
||||||
|
before you start sharing.
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
**I turned Sharing on but can't see it in the menu.** Try a hard refresh
|
||||||
|
(Ctrl/Cmd+Shift+R) or a private/incognito window. The menu remembers whether sharing is
|
||||||
|
available for the length of a browser tab, so it can lag behind a setting your admin just
|
||||||
|
changed.
|
||||||
|
|
||||||
|
**My profile 404s on a big instance like mastodon.social right after I start sharing.**
|
||||||
|
Some servers cache a "not found" for a little while after they first look you up. Give it
|
||||||
|
an hour, or try searching from a smaller instance to confirm your handle really works.
|
||||||
|
|
||||||
|
**A change I made under Sharing doesn't seem to have taken effect.** Make sure you
|
||||||
|
clicked **Save sharing settings** at the bottom of the page — ticking a box alone doesn't
|
||||||
|
save it.
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Album art · 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">
|
||||||
|
<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>
|
||||||
@@ -582,6 +582,16 @@ input {
|
|||||||
background: var(--slate);
|
background: var(--slate);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.ranking a.name {
|
||||||
|
color: inherit;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ranking a.name:hover,
|
||||||
|
.ranking a.name:focus-visible {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
/* ---- Listening log -------------------------------------------------------- */
|
/* ---- Listening log -------------------------------------------------------- */
|
||||||
.log {
|
.log {
|
||||||
list-style: none;
|
list-style: none;
|
||||||
@@ -615,6 +625,22 @@ input {
|
|||||||
color: var(--ink-soft);
|
color: var(--ink-soft);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Stack the track above a muted artist line and make the cell a link, like .ranking rows */
|
||||||
|
.log-stacked .by {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-stacked li a {
|
||||||
|
display: block;
|
||||||
|
color: inherit;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-stacked li a:hover,
|
||||||
|
.log-stacked li a:focus-visible {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
.log-day {
|
.log-day {
|
||||||
margin: 2rem 0 0.25rem;
|
margin: 2rem 0 0.25rem;
|
||||||
font-size: var(--step-0);
|
font-size: var(--step-0);
|
||||||
@@ -977,3 +1003,170 @@ input {
|
|||||||
.confirm-off .button-row {
|
.confirm-off .button-row {
|
||||||
margin-top: 0.75rem;
|
margin-top: 0.75rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ---- Song lookup ------------------------------------------------------------ */
|
||||||
|
.song-search {
|
||||||
|
position: relative;
|
||||||
|
max-width: 28rem;
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.song-search .field {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-results {
|
||||||
|
position: absolute;
|
||||||
|
z-index: 10;
|
||||||
|
inset-inline: 0;
|
||||||
|
top: 100%;
|
||||||
|
margin: 0.25rem 0 0;
|
||||||
|
padding: 0.35rem;
|
||||||
|
list-style: none;
|
||||||
|
background: var(--paper-raised);
|
||||||
|
border: 1px solid var(--rule);
|
||||||
|
border-radius: var(--radius-control);
|
||||||
|
box-shadow: 0 8px 24px rgb(0 0 0 / 0.12);
|
||||||
|
max-height: 18rem;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-results li {
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-results a {
|
||||||
|
display: block;
|
||||||
|
padding: 0.5rem 0.6rem;
|
||||||
|
border-radius: var(--radius-control);
|
||||||
|
color: inherit;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-results a:hover,
|
||||||
|
.search-results a:focus-visible {
|
||||||
|
background: var(--panel);
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-results .by {
|
||||||
|
display: block;
|
||||||
|
color: var(--ink-soft);
|
||||||
|
font-size: var(--step--1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-results .empty {
|
||||||
|
padding: 0.5rem 0.6rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.song-meta {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr));
|
||||||
|
gap: 1rem 2rem;
|
||||||
|
margin: 1.25rem 0 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.song-meta div {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.15rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.song-meta dt {
|
||||||
|
font-size: var(--step--1);
|
||||||
|
color: var(--ink-soft);
|
||||||
|
}
|
||||||
|
|
||||||
|
.song-meta dd {
|
||||||
|
margin: 0;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The song page's glowing display gets an art thumbnail alongside its text, when there's one */
|
||||||
|
.display-with-art {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.display-with-art .display-body {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.display-art {
|
||||||
|
width: 4.5rem;
|
||||||
|
height: 4.5rem;
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- Album art ---------------------------------------------------------------- */
|
||||||
|
.art-thumb {
|
||||||
|
display: block;
|
||||||
|
border-radius: var(--radius-control);
|
||||||
|
object-fit: cover;
|
||||||
|
background: var(--paper-raised);
|
||||||
|
border: 1px solid var(--rule);
|
||||||
|
}
|
||||||
|
|
||||||
|
.art-thumb-empty {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* No artwork: a plain ring, echoing .brand-mark's small round "lamp" motif */
|
||||||
|
.art-thumb-empty::after {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
inset: 32%;
|
||||||
|
border-radius: 50%;
|
||||||
|
border: 2px solid var(--bar);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Most played > Albums: a thumbnail column ahead of the rank */
|
||||||
|
.ranking-art li {
|
||||||
|
grid-template-columns: 2.25rem 2rem minmax(0, 1fr) auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ranking-art .art-thumb {
|
||||||
|
width: 2.25rem;
|
||||||
|
height: 2.25rem;
|
||||||
|
align-self: center; /* .ranking li aligns its other cells to baseline, which suits text, not art */
|
||||||
|
}
|
||||||
|
|
||||||
|
.ranking-art .meter {
|
||||||
|
left: 5.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Recently played / History: a thumbnail column ahead of the time */
|
||||||
|
.log-art li {
|
||||||
|
grid-template-columns: 2.25rem 8rem minmax(0, 1fr);
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-art.log-clock li {
|
||||||
|
grid-template-columns: 2.25rem 3.5rem minmax(0, 1fr);
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-art .art-thumb {
|
||||||
|
width: 2.25rem;
|
||||||
|
height: 2.25rem;
|
||||||
|
align-self: center; /* .log li items default to stretch/start, which suits text, not art */
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- 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;
|
||||||
|
}
|
||||||
+10
-1
@@ -14,6 +14,14 @@
|
|||||||
<main id="main">
|
<main id="main">
|
||||||
<h1 class="visually-hidden">Overview</h1>
|
<h1 class="visually-hidden">Overview</h1>
|
||||||
<div id="panel" class="panel" aria-live="polite"></div>
|
<div id="panel" class="panel" aria-live="polite"></div>
|
||||||
|
<section aria-labelledby="song-search-title" class="song-search">
|
||||||
|
<h2 id="song-search-title" class="visually-hidden">Find a song</h2>
|
||||||
|
<div class="field">
|
||||||
|
<label for="song-search">Find a song</label>
|
||||||
|
<input id="song-search" type="search" autocomplete="off" placeholder="Search your scrobbles…">
|
||||||
|
</div>
|
||||||
|
<ul class="search-results" id="song-search-results" hidden></ul>
|
||||||
|
</section>
|
||||||
<section aria-labelledby="charts-title">
|
<section aria-labelledby="charts-title">
|
||||||
<div class="section-head">
|
<div class="section-head">
|
||||||
<h2 id="charts-title">Most played</h2>
|
<h2 id="charts-title">Most played</h2>
|
||||||
@@ -23,6 +31,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="charts">
|
<div class="charts">
|
||||||
<div><h3 class="muted">Artists</h3><ol class="ranking" id="top-artists"></ol></div>
|
<div><h3 class="muted">Artists</h3><ol class="ranking" id="top-artists"></ol></div>
|
||||||
|
<div><h3 class="muted">Albums</h3><ol class="ranking ranking-art" id="top-albums"></ol></div>
|
||||||
<div><h3 class="muted">Tracks</h3><ol class="ranking" id="top-tracks"></ol></div>
|
<div><h3 class="muted">Tracks</h3><ol class="ranking" id="top-tracks"></ol></div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
@@ -31,7 +40,7 @@
|
|||||||
<h2 id="recent-title">Recently played</h2>
|
<h2 id="recent-title">Recently played</h2>
|
||||||
<a href="history.html">Full history</a>
|
<a href="history.html">Full history</a>
|
||||||
</div>
|
</div>
|
||||||
<ol class="log" id="recent"></ol>
|
<ol class="log log-stacked log-art" id="recent"></ol>
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
+26
-3
@@ -40,6 +40,29 @@ export function redirectToLogin() {
|
|||||||
location.href = `login.html?next=${encodeURIComponent(safeNext(here + location.search))}`;
|
location.href = `login.html?next=${encodeURIComponent(safeNext(here + location.search))}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Fetches a binary resource (e.g. album art) with the same bearer-auth transport as api(),
|
||||||
|
// returning a blob: object URL, or null on any failure (including a 404 "no art" response) -
|
||||||
|
// the caller treats "missing" and "couldn't fetch" the same way: show a placeholder.
|
||||||
|
export async function fetchImage(path) {
|
||||||
|
const headers = {};
|
||||||
|
const token = getToken();
|
||||||
|
if (token) headers.Authorization = `Bearer ${token}`;
|
||||||
|
|
||||||
|
let response;
|
||||||
|
try {
|
||||||
|
response = await fetch(`${apiBase}/api/v1${path}`, { headers });
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (response.status === 401) {
|
||||||
|
setToken(null);
|
||||||
|
redirectToLogin();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (!response.ok) return null;
|
||||||
|
return URL.createObjectURL(await response.blob());
|
||||||
|
}
|
||||||
|
|
||||||
export async function api(path, { method = "GET", body, auth = true } = {}) {
|
export async function api(path, { method = "GET", body, auth = true } = {}) {
|
||||||
const headers = {};
|
const headers = {};
|
||||||
if (body !== undefined) headers["Content-Type"] = "application/json";
|
if (body !== undefined) headers["Content-Type"] = "application/json";
|
||||||
@@ -79,7 +102,7 @@ export async function api(path, { method = "GET", body, auth = true } = {}) {
|
|||||||
|
|
||||||
// Turn webargs validation details into a single readable sentence.
|
// Turn webargs validation details into a single readable sentence.
|
||||||
export function describeError(error) {
|
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) {
|
if (fields) {
|
||||||
return Object.entries(fields)
|
return Object.entries(fields)
|
||||||
.map(([field, messages]) => `${field}: ${[].concat(messages).join(" ")}`)
|
.map(([field, messages]) => `${field}: ${[].concat(messages).join(" ")}`)
|
||||||
@@ -89,10 +112,10 @@ export function describeError(error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Multipart upload with progress (fetch can't report upload progress).
|
// 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) => {
|
return new Promise((resolve, reject) => {
|
||||||
const xhr = new XMLHttpRequest();
|
const xhr = new XMLHttpRequest();
|
||||||
xhr.open("POST", `${apiBase}/api/v1${path}`);
|
xhr.open(method, `${apiBase}/api/v1${path}`);
|
||||||
const token = getToken();
|
const token = getToken();
|
||||||
if (token) xhr.setRequestHeader("Authorization", `Bearer ${token}`);
|
if (token) xhr.setRequestHeader("Authorization", `Bearer ${token}`);
|
||||||
xhr.upload.addEventListener("progress", (event) => {
|
xhr.upload.addEventListener("progress", (event) => {
|
||||||
|
|||||||
@@ -0,0 +1,170 @@
|
|||||||
|
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 } = 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();
|
||||||
|
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}" },
|
||||||
|
),
|
||||||
|
h("button", { type: "submit", class: "button" }, "Look it up"),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
// A small thumbnail that starts as a placeholder and swaps itself for the real album art
|
||||||
|
// once (if) it resolves. Shared by every list/page that shows art.
|
||||||
|
|
||||||
|
import { fetchImage } from "./api.js";
|
||||||
|
import { h } from "./dom.js";
|
||||||
|
|
||||||
|
const cache = new Map(); // dedupes repeat/concurrent lookups for the same album within a page
|
||||||
|
|
||||||
|
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 = keyFor(artist, album);
|
||||||
|
if (!cache.has(key)) {
|
||||||
|
cache.set(
|
||||||
|
key,
|
||||||
|
fetchImage(`/art/album?artist=${encodeURIComponent(artist)}&album=${encodeURIComponent(album)}`),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
cache.get(key).then((url) => {
|
||||||
|
if (!url) return; // miss or failed fetch: leave the placeholder
|
||||||
|
// Not revoked: the same URL is shared by every thumbnail for this album on the page
|
||||||
|
// (see `cache` above), and this is a full-page-reload site, so the browser releases it
|
||||||
|
// on navigation anyway.
|
||||||
|
const img = h("img", { class: classes, alt: "", loading: "lazy" });
|
||||||
|
img.src = url;
|
||||||
|
el.replaceWith(img);
|
||||||
|
});
|
||||||
|
return el;
|
||||||
|
}
|
||||||
+84
-61
@@ -1,6 +1,8 @@
|
|||||||
import { api } from "./api.js";
|
import { api } from "./api.js";
|
||||||
import { errorBox, formatDate, formatDuration, h, num, replace, timeAgo } from "./dom.js";
|
import { artThumb } from "./art.js";
|
||||||
|
import { errorBox, formatDuration, h, num, replace, timeAgo } from "./dom.js";
|
||||||
import { signedInPage } from "./layout.js";
|
import { signedInPage } from "./layout.js";
|
||||||
|
import { spectrum } from "./spectrum.js";
|
||||||
|
|
||||||
const PERIODS = [
|
const PERIODS = [
|
||||||
["7day", "7 days"],
|
["7day", "7 days"],
|
||||||
@@ -9,7 +11,6 @@ const PERIODS = [
|
|||||||
["overall", "All time"],
|
["overall", "All time"],
|
||||||
];
|
];
|
||||||
const PERIOD_KEY = "scrobbler.period";
|
const PERIOD_KEY = "scrobbler.period";
|
||||||
const SEGMENTS = 10; // lit segments per spectrum column at the busiest day
|
|
||||||
const NOW_PLAYING_POLL_MS = 30_000;
|
const NOW_PLAYING_POLL_MS = 30_000;
|
||||||
|
|
||||||
const panel = document.getElementById("panel");
|
const panel = document.getElementById("panel");
|
||||||
@@ -19,6 +20,7 @@ let progressTimer;
|
|||||||
|
|
||||||
await signedInPage("index.html");
|
await signedInPage("index.html");
|
||||||
renderPeriodSelector();
|
renderPeriodSelector();
|
||||||
|
initSongSearch();
|
||||||
await Promise.all([loadPanel(), loadTop(currentPeriod()), loadRecent()]).catch(showError);
|
await Promise.all([loadPanel(), loadTop(currentPeriod()), loadRecent()]).catch(showError);
|
||||||
setInterval(() => refreshDisplay().catch(() => {}), NOW_PLAYING_POLL_MS);
|
setInterval(() => refreshDisplay().catch(() => {}), NOW_PLAYING_POLL_MS);
|
||||||
|
|
||||||
@@ -117,55 +119,6 @@ function readouts(summary) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Daily plays for the last 30 days, drawn as a segmented level meter.
|
|
||||||
function spectrum(counts) {
|
|
||||||
const NS = "http://www.w3.org/2000/svg";
|
|
||||||
const width = 1000;
|
|
||||||
const height = 96;
|
|
||||||
const gap = 4;
|
|
||||||
const max = Math.max(1, ...counts.map((c) => c.count));
|
|
||||||
const columnWidth = width / counts.length;
|
|
||||||
const segmentHeight = height / SEGMENTS;
|
|
||||||
const total = counts.reduce((sum, c) => sum + c.count, 0);
|
|
||||||
|
|
||||||
const svg = document.createElementNS(NS, "svg");
|
|
||||||
svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
|
|
||||||
svg.setAttribute("preserveAspectRatio", "none");
|
|
||||||
svg.setAttribute("role", "img");
|
|
||||||
svg.setAttribute("aria-label", `Plays per day over the last ${counts.length} days: ${num(total)} in total`);
|
|
||||||
|
|
||||||
counts.forEach((day, i) => {
|
|
||||||
const lit = day.count ? Math.max(1, Math.round((day.count / max) * SEGMENTS)) : 0;
|
|
||||||
const group = document.createElementNS(NS, "g");
|
|
||||||
const title = document.createElementNS(NS, "title");
|
|
||||||
title.textContent = `${formatDate(day.start)}: ${num(day.count)} ${day.count === 1 ? "play" : "plays"}`;
|
|
||||||
group.append(title);
|
|
||||||
for (let s = 0; s < SEGMENTS; s++) {
|
|
||||||
const rect = document.createElementNS(NS, "rect");
|
|
||||||
rect.setAttribute("x", i * columnWidth + gap / 2);
|
|
||||||
rect.setAttribute("y", height - (s + 1) * segmentHeight + 1.5);
|
|
||||||
rect.setAttribute("width", columnWidth - gap);
|
|
||||||
rect.setAttribute("height", segmentHeight - 3);
|
|
||||||
rect.setAttribute("class", s < lit ? "seg-on" : "seg-off");
|
|
||||||
group.append(rect);
|
|
||||||
}
|
|
||||||
svg.append(group);
|
|
||||||
});
|
|
||||||
|
|
||||||
return h(
|
|
||||||
"div",
|
|
||||||
{ class: "spectrum" },
|
|
||||||
svg,
|
|
||||||
h(
|
|
||||||
"div",
|
|
||||||
{ class: "spectrum-axis" },
|
|
||||||
h("span", {}, formatDate(counts[0].start)),
|
|
||||||
h("span", {}, `${num(total)} plays in 30 days`),
|
|
||||||
h("span", {}, "Today"),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- Most played ------------------------------------------------------------
|
// ---- Most played ------------------------------------------------------------
|
||||||
|
|
||||||
function currentPeriod() {
|
function currentPeriod() {
|
||||||
@@ -199,39 +152,103 @@ function renderPeriodSelector() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function loadTop(period) {
|
async function loadTop(period) {
|
||||||
const [artists, tracks] = await Promise.all([
|
const [artists, albums, tracks] = await Promise.all([
|
||||||
api(`/me/top/artists?period=${period}&limit=10`),
|
api(`/me/top/artists?period=${period}&limit=10`),
|
||||||
|
api(`/me/top/albums?period=${period}&limit=10`),
|
||||||
api(`/me/top/tracks?period=${period}&limit=10`),
|
api(`/me/top/tracks?period=${period}&limit=10`),
|
||||||
]);
|
]);
|
||||||
renderRanking(document.getElementById("top-artists"), artists.items, false);
|
renderRanking(document.getElementById("top-artists"), artists.items, false);
|
||||||
renderRanking(document.getElementById("top-tracks"), tracks.items, true);
|
renderRanking(document.getElementById("top-albums"), albums.items, true, false, true);
|
||||||
|
renderRanking(document.getElementById("top-tracks"), tracks.items, true, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderRanking(list, items, withArtist) {
|
function renderRanking(list, items, withArtist, linkToSong = false, withArt = false) {
|
||||||
if (!items.length) {
|
if (!items.length) {
|
||||||
replace(list, h("li", { class: "empty" }, "No plays in this period."));
|
replace(list, h("li", { class: "empty" }, "No plays in this period."));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const max = items[0].playcount;
|
const max = items[0].playcount;
|
||||||
|
const meterOffset = withArt ? "5.75rem" : "2.75rem";
|
||||||
replace(
|
replace(
|
||||||
list,
|
list,
|
||||||
items.map((item) =>
|
items.map((item) => {
|
||||||
h(
|
const by = withArtist ? h("span", { class: "by" }, item.artist) : null;
|
||||||
|
const name = linkToSong
|
||||||
|
? h("a", { class: "name", href: songHref(item.artist, item.name) }, item.name, by)
|
||||||
|
: h("span", { class: "name" }, item.name, by);
|
||||||
|
return h(
|
||||||
"li",
|
"li",
|
||||||
{},
|
{},
|
||||||
|
withArt ? artThumb(item.artist, item.name) : null,
|
||||||
h("span", { class: "rank" }, item.rank),
|
h("span", { class: "rank" }, item.rank),
|
||||||
h("span", { class: "name" }, item.name, withArtist ? h("span", { class: "by" }, item.artist) : null),
|
name,
|
||||||
h("span", { class: "plays" }, num(item.playcount)),
|
h("span", { class: "plays" }, num(item.playcount)),
|
||||||
h("span", {
|
h("span", {
|
||||||
class: "meter",
|
class: "meter",
|
||||||
"aria-hidden": "true",
|
"aria-hidden": "true",
|
||||||
style: `width: calc((100% - 2.75rem) * ${item.playcount / max})`,
|
style: `width: calc((100% - ${meterOffset}) * ${item.playcount / max})`,
|
||||||
}),
|
}),
|
||||||
),
|
);
|
||||||
),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function songHref(artist, track) {
|
||||||
|
return `song.html?artist=${encodeURIComponent(artist)}&track=${encodeURIComponent(track)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Song search --------------------------------------------------------------
|
||||||
|
|
||||||
|
function initSongSearch() {
|
||||||
|
const input = document.getElementById("song-search");
|
||||||
|
const results = document.getElementById("song-search-results");
|
||||||
|
let debounce;
|
||||||
|
let hideTimer;
|
||||||
|
|
||||||
|
input.addEventListener("input", () => {
|
||||||
|
clearTimeout(debounce);
|
||||||
|
const q = input.value.trim();
|
||||||
|
if (q.length < 2) {
|
||||||
|
results.hidden = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
debounce = setTimeout(() => runSearch(q), 250);
|
||||||
|
});
|
||||||
|
input.addEventListener("focus", () => {
|
||||||
|
if (results.childElementCount) results.hidden = false;
|
||||||
|
});
|
||||||
|
input.addEventListener("blur", () => {
|
||||||
|
hideTimer = setTimeout(() => (results.hidden = true), 150);
|
||||||
|
});
|
||||||
|
// Keep focus on mousedown so the subsequent click still lands on the result.
|
||||||
|
results.addEventListener("mousedown", (event) => event.preventDefault());
|
||||||
|
|
||||||
|
async function runSearch(q) {
|
||||||
|
let matches;
|
||||||
|
try {
|
||||||
|
matches = await api(`/me/tracks/search?q=${encodeURIComponent(q)}&limit=10`);
|
||||||
|
} catch {
|
||||||
|
return; // a flaky search box isn't worth surfacing an error for
|
||||||
|
}
|
||||||
|
clearTimeout(hideTimer);
|
||||||
|
if (!matches.length) {
|
||||||
|
replace(results, h("li", { class: "empty" }, "No matches."));
|
||||||
|
} else {
|
||||||
|
replace(
|
||||||
|
results,
|
||||||
|
matches.map((m) =>
|
||||||
|
h(
|
||||||
|
"li",
|
||||||
|
{},
|
||||||
|
h("a", { href: songHref(m.artist, m.track) }, m.track, h("span", { class: "by" }, m.artist)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
results.hidden = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ---- Recently played ----------------------------------------------------------
|
// ---- Recently played ----------------------------------------------------------
|
||||||
|
|
||||||
async function loadRecent() {
|
async function loadRecent() {
|
||||||
@@ -247,8 +264,14 @@ async function loadRecent() {
|
|||||||
h(
|
h(
|
||||||
"li",
|
"li",
|
||||||
{},
|
{},
|
||||||
|
artThumb(s.album_artist || s.artist, s.album),
|
||||||
h("time", { datetime: s.played_at, title: new Date(s.played_at).toLocaleString() }, timeAgo(s.played_at)),
|
h("time", { datetime: s.played_at, title: new Date(s.played_at).toLocaleString() }, timeAgo(s.played_at)),
|
||||||
h("span", {}, h("span", { class: "track" }, s.track), h("span", { class: "by" }, ` by ${s.artist}`)),
|
h(
|
||||||
|
"a",
|
||||||
|
{ href: songHref(s.artist, s.track) },
|
||||||
|
h("span", { class: "track" }, s.track),
|
||||||
|
h("span", { class: "by" }, s.artist),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { api } from "./api.js";
|
import { api } from "./api.js";
|
||||||
|
import { artThumb } from "./art.js";
|
||||||
import { errorBox, formatDay, formatTime, h, num, replace } from "./dom.js";
|
import { errorBox, formatDay, formatTime, h, num, replace } from "./dom.js";
|
||||||
import { signedInPage } from "./layout.js";
|
import { signedInPage } from "./layout.js";
|
||||||
|
|
||||||
@@ -38,11 +39,12 @@ function render(result) {
|
|||||||
h("h2", { class: "log-day" }, formatDay(scrobbles[0].played_at)),
|
h("h2", { class: "log-day" }, formatDay(scrobbles[0].played_at)),
|
||||||
h(
|
h(
|
||||||
"ol",
|
"ol",
|
||||||
{ class: "log log-clock" },
|
{ class: "log log-clock log-art" },
|
||||||
scrobbles.map((s) =>
|
scrobbles.map((s) =>
|
||||||
h(
|
h(
|
||||||
"li",
|
"li",
|
||||||
{},
|
{},
|
||||||
|
artThumb(s.album_artist || s.artist, s.album),
|
||||||
h("time", { datetime: s.played_at }, formatTime(s.played_at)),
|
h("time", { datetime: s.played_at }, formatTime(s.played_at)),
|
||||||
h(
|
h(
|
||||||
"span",
|
"span",
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { h, replace } from "./dom.js";
|
|||||||
const NAV = [
|
const NAV = [
|
||||||
["index.html", "Overview"],
|
["index.html", "Overview"],
|
||||||
["history.html", "History"],
|
["history.html", "History"],
|
||||||
|
["art.html", "Album art"],
|
||||||
["apps.html", "Apps"],
|
["apps.html", "Apps"],
|
||||||
["sessions.html", "Sessions"],
|
["sessions.html", "Sessions"],
|
||||||
["import.html", "Import"],
|
["import.html", "Import"],
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
import { api } from "./api.js";
|
||||||
|
import { artThumb } from "./art.js";
|
||||||
|
import { errorBox, formatDate, formatDay, formatDuration, formatTime, h, num, replace } from "./dom.js";
|
||||||
|
import { signedInPage } from "./layout.js";
|
||||||
|
import { spectrum } from "./spectrum.js";
|
||||||
|
|
||||||
|
const PER_PAGE = 50;
|
||||||
|
const panel = document.getElementById("panel");
|
||||||
|
const meta = document.getElementById("song-meta");
|
||||||
|
const history = document.getElementById("song-history");
|
||||||
|
const pager = document.getElementById("pager");
|
||||||
|
|
||||||
|
await signedInPage(null); // a permalink, not a top-level nav section
|
||||||
|
|
||||||
|
const params = new URLSearchParams(location.search);
|
||||||
|
const artist = params.get("artist") ?? "";
|
||||||
|
const track = params.get("track") ?? "";
|
||||||
|
const page = Math.max(1, Number.parseInt(params.get("page"), 10) || 1);
|
||||||
|
|
||||||
|
if (!artist || !track) {
|
||||||
|
replace(panel, h("p", { class: "notice" }, "Use the search box on the dashboard to find a song."));
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
const result = await api(
|
||||||
|
`/me/tracks?artist=${encodeURIComponent(artist)}&track=${encodeURIComponent(track)}&page=${page}&limit=${PER_PAGE}`,
|
||||||
|
);
|
||||||
|
render(result);
|
||||||
|
} catch (error) {
|
||||||
|
replace(
|
||||||
|
panel,
|
||||||
|
error.status === 404
|
||||||
|
? h("p", { class: "notice" }, `You've never scrobbled "${track}" by ${artist}.`)
|
||||||
|
: errorBox(error.message),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function render(result) {
|
||||||
|
document.title = `${result.track} · Scrobbler`;
|
||||||
|
const m = result.metadata;
|
||||||
|
|
||||||
|
const body = h(
|
||||||
|
"div",
|
||||||
|
{ class: "display-body" },
|
||||||
|
h("p", { class: "display-status" }, "Now viewing"),
|
||||||
|
h("p", { class: "display-track" }, result.track),
|
||||||
|
h(
|
||||||
|
"p",
|
||||||
|
{ class: "display-meta" },
|
||||||
|
h("strong", {}, result.artist),
|
||||||
|
m.album ? [" from ", h("strong", {}, m.album)] : null,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const display = m.album
|
||||||
|
? h("div", { class: "display display-with-art" }, artThumb(m.album_artist || result.artist, m.album, "display-art"), body)
|
||||||
|
: h("div", { class: "display" }, body);
|
||||||
|
replace(panel, display, readouts(m), spectrum(result.counts, `Plays of ${result.track}`, "90 days"));
|
||||||
|
|
||||||
|
const row = (label, value) =>
|
||||||
|
value === null || value === undefined ? null : h("div", {}, h("dt", {}, label), h("dd", {}, value));
|
||||||
|
replace(
|
||||||
|
meta,
|
||||||
|
row("Album artist", m.album_artist),
|
||||||
|
row("Track number", m.track_number),
|
||||||
|
row("Duration", m.duration ? formatDuration(m.duration) : null),
|
||||||
|
row("MusicBrainz ID", m.mbid),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!result.items.length) {
|
||||||
|
replace(history, h("p", { class: "empty" }, "Nothing here yet."));
|
||||||
|
} else {
|
||||||
|
// Group by local calendar day, same as the full history page.
|
||||||
|
const days = new Map();
|
||||||
|
for (const scrobble of result.items) {
|
||||||
|
const key = new Date(scrobble.played_at).toDateString();
|
||||||
|
if (!days.has(key)) days.set(key, []);
|
||||||
|
days.get(key).push(scrobble);
|
||||||
|
}
|
||||||
|
replace(
|
||||||
|
history,
|
||||||
|
[...days.values()].map((scrobbles) => [
|
||||||
|
h("h3", { class: "log-day" }, formatDay(scrobbles[0].played_at)),
|
||||||
|
h(
|
||||||
|
"ol",
|
||||||
|
{ class: "log log-clock" },
|
||||||
|
scrobbles.map((s) =>
|
||||||
|
h(
|
||||||
|
"li",
|
||||||
|
{},
|
||||||
|
h("time", { datetime: s.played_at }, formatTime(s.played_at)),
|
||||||
|
s.album ? h("span", { class: "by" }, `from ${s.album}`) : h("span"),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const link = (p) => `?artist=${encodeURIComponent(artist)}&track=${encodeURIComponent(track)}&page=${p}`;
|
||||||
|
replace(
|
||||||
|
pager,
|
||||||
|
result.page > 1 ? h("a", { class: "button button-quiet", href: link(result.page - 1) }, "Newer") : h("span"),
|
||||||
|
result.page < result.total_pages
|
||||||
|
? h("a", { class: "button button-quiet", href: link(result.page + 1) }, "Older")
|
||||||
|
: h("span"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function readouts(m) {
|
||||||
|
const item = (value, label) => h("div", {}, h("dt", {}, label), h("dd", {}, value));
|
||||||
|
return h(
|
||||||
|
"dl",
|
||||||
|
{ class: "readouts" },
|
||||||
|
item(num(m.playcount), "plays"),
|
||||||
|
item(formatDate(m.first_played_at), "first played"),
|
||||||
|
item(formatDate(m.last_played_at), "last played"),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
// A segmented level meter: daily play counts drawn as columns of lit/unlit segments,
|
||||||
|
// like a hi-fi spectrum analyser. Shared by the dashboard (30 days, all plays) and the
|
||||||
|
// song page (90 days, one track).
|
||||||
|
|
||||||
|
import { formatDate, h, num } from "./dom.js";
|
||||||
|
|
||||||
|
const SEGMENTS = 10; // lit segments per column at the busiest day
|
||||||
|
|
||||||
|
export function spectrum(counts, subject = "Plays", windowLabel = "30 days") {
|
||||||
|
const NS = "http://www.w3.org/2000/svg";
|
||||||
|
const width = 1000;
|
||||||
|
const height = 96;
|
||||||
|
const gap = 4;
|
||||||
|
const max = Math.max(1, ...counts.map((c) => c.count));
|
||||||
|
const columnWidth = width / counts.length;
|
||||||
|
const segmentHeight = height / SEGMENTS;
|
||||||
|
const total = counts.reduce((sum, c) => sum + c.count, 0);
|
||||||
|
|
||||||
|
const svg = document.createElementNS(NS, "svg");
|
||||||
|
svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
|
||||||
|
svg.setAttribute("preserveAspectRatio", "none");
|
||||||
|
svg.setAttribute("role", "img");
|
||||||
|
svg.setAttribute("aria-label", `${subject} per day over the last ${counts.length} days: ${num(total)} in total`);
|
||||||
|
|
||||||
|
counts.forEach((day, i) => {
|
||||||
|
const lit = day.count ? Math.max(1, Math.round((day.count / max) * SEGMENTS)) : 0;
|
||||||
|
const group = document.createElementNS(NS, "g");
|
||||||
|
const title = document.createElementNS(NS, "title");
|
||||||
|
title.textContent = `${formatDate(day.start)}: ${num(day.count)} ${day.count === 1 ? "play" : "plays"}`;
|
||||||
|
group.append(title);
|
||||||
|
for (let s = 0; s < SEGMENTS; s++) {
|
||||||
|
const rect = document.createElementNS(NS, "rect");
|
||||||
|
rect.setAttribute("x", i * columnWidth + gap / 2);
|
||||||
|
rect.setAttribute("y", height - (s + 1) * segmentHeight + 1.5);
|
||||||
|
rect.setAttribute("width", columnWidth - gap);
|
||||||
|
rect.setAttribute("height", segmentHeight - 3);
|
||||||
|
rect.setAttribute("class", s < lit ? "seg-on" : "seg-off");
|
||||||
|
group.append(rect);
|
||||||
|
}
|
||||||
|
svg.append(group);
|
||||||
|
});
|
||||||
|
|
||||||
|
return h(
|
||||||
|
"div",
|
||||||
|
{ class: "spectrum" },
|
||||||
|
svg,
|
||||||
|
h(
|
||||||
|
"div",
|
||||||
|
{ class: "spectrum-axis" },
|
||||||
|
h("span", {}, formatDate(counts[0].start)),
|
||||||
|
h("span", {}, `${num(total)} ${subject.toLowerCase()} in ${windowLabel}`),
|
||||||
|
h("span", {}, "Today"),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<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">
|
||||||
|
<link rel="stylesheet" href="css/style.css">
|
||||||
|
<script src="config.js"></script>
|
||||||
|
<script type="module" src="js/song.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header class="site-header" id="site-header"></header>
|
||||||
|
<main id="main">
|
||||||
|
<h1 class="visually-hidden">Song</h1>
|
||||||
|
<div id="panel" class="panel" aria-live="polite"></div>
|
||||||
|
<dl class="song-meta" id="song-meta"></dl>
|
||||||
|
<section aria-labelledby="song-history-title">
|
||||||
|
<h2 id="song-history-title">History</h2>
|
||||||
|
<div id="song-history"></div>
|
||||||
|
<nav class="pager" aria-label="Pages" id="pager"></nav>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -42,11 +42,13 @@ def create_app(config_object=None):
|
|||||||
)
|
)
|
||||||
|
|
||||||
from scrobbler.cli import imports_cli, worker_command
|
from scrobbler.cli import imports_cli, worker_command
|
||||||
|
from scrobbler.services import art as art_service
|
||||||
from scrobbler.services import imports as import_service
|
from scrobbler.services import imports as import_service
|
||||||
|
|
||||||
app.cli.add_command(worker_command)
|
app.cli.add_command(worker_command)
|
||||||
app.cli.add_command(imports_cli)
|
app.cli.add_command(imports_cli)
|
||||||
import_service.register_worker_tasks(app)
|
import_service.register_worker_tasks(app)
|
||||||
|
art_service.register_worker_tasks(app)
|
||||||
|
|
||||||
from scrobbler.metrics import db as db_metrics
|
from scrobbler.metrics import db as db_metrics
|
||||||
|
|
||||||
|
|||||||
@@ -48,14 +48,16 @@ def init_app(app: Flask) -> None:
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
from scrobbler.api import apps, auth, health, imports, sessions, stats, tokens
|
from scrobbler.api import apps, art, auth, health, imports, sessions, stats, tokens, tracks
|
||||||
|
|
||||||
api.register_blueprint(auth.blp, url_prefix="/api/v1/auth")
|
api.register_blueprint(auth.blp, url_prefix="/api/v1/auth")
|
||||||
api.register_blueprint(apps.blp, url_prefix="/api/v1/apps")
|
api.register_blueprint(apps.blp, url_prefix="/api/v1/apps")
|
||||||
api.register_blueprint(sessions.blp, url_prefix="/api/v1/sessions")
|
api.register_blueprint(sessions.blp, url_prefix="/api/v1/sessions")
|
||||||
api.register_blueprint(tokens.blp, url_prefix="/api/v1/tokens")
|
api.register_blueprint(tokens.blp, url_prefix="/api/v1/tokens")
|
||||||
api.register_blueprint(stats.blp, url_prefix="/api/v1/me")
|
api.register_blueprint(stats.blp, url_prefix="/api/v1/me")
|
||||||
|
api.register_blueprint(tracks.blp, url_prefix="/api/v1/me/tracks")
|
||||||
api.register_blueprint(imports.blp, url_prefix="/api/v1/imports")
|
api.register_blueprint(imports.blp, url_prefix="/api/v1/imports")
|
||||||
|
api.register_blueprint(art.blp, url_prefix="/api/v1/art")
|
||||||
api.register_blueprint(health.blp)
|
api.register_blueprint(health.blp)
|
||||||
|
|
||||||
from scrobbler.openapi import lastfm
|
from scrobbler.openapi import lastfm
|
||||||
|
|||||||
@@ -0,0 +1,176 @@
|
|||||||
|
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,
|
||||||
|
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. "
|
||||||
|
"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 (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
|
||||||
|
|
||||||
|
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 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")
|
||||||
|
art.request_correction(
|
||||||
|
g.user.id,
|
||||||
|
body["artist"],
|
||||||
|
body["album"],
|
||||||
|
body.get("search_artist"),
|
||||||
|
body.get("search_album"),
|
||||||
|
str(mbid) if 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"]),
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
from flask import g
|
||||||
|
from flask_smorest import Blueprint, abort
|
||||||
|
|
||||||
|
from scrobbler.api.decorators import authenticated
|
||||||
|
from scrobbler.schemas import (
|
||||||
|
ErrorSchema,
|
||||||
|
TrackDetailArgsSchema,
|
||||||
|
TrackDetailSchema,
|
||||||
|
TrackSearchArgsSchema,
|
||||||
|
TrackSearchResultSchema,
|
||||||
|
)
|
||||||
|
from scrobbler.services import stats
|
||||||
|
|
||||||
|
blp = Blueprint("Tracks", __name__, description="Look up a specific song's history and metadata")
|
||||||
|
|
||||||
|
|
||||||
|
@blp.route("/search", methods=["GET"])
|
||||||
|
@authenticated(blp)
|
||||||
|
@blp.arguments(TrackSearchArgsSchema, location="query")
|
||||||
|
@blp.response(200, TrackSearchResultSchema(many=True))
|
||||||
|
def search(args):
|
||||||
|
"""Find a song by track or artist name"""
|
||||||
|
return stats.track_search(g.user, args["q"], args["limit"])
|
||||||
|
|
||||||
|
|
||||||
|
@blp.route("", methods=["GET"])
|
||||||
|
@authenticated(blp)
|
||||||
|
@blp.arguments(TrackDetailArgsSchema, location="query")
|
||||||
|
@blp.response(200, TrackDetailSchema)
|
||||||
|
@blp.alt_response(404, schema=ErrorSchema, description="You've never scrobbled this song")
|
||||||
|
def detail(args):
|
||||||
|
"""A song's play history and recorded metadata"""
|
||||||
|
metadata = stats.track_metadata(g.user, args["artist"], args["track"])
|
||||||
|
if metadata is None:
|
||||||
|
abort(404, code="not_found", message="You've never scrobbled this song")
|
||||||
|
history = stats.recent(
|
||||||
|
g.user,
|
||||||
|
page=args["page"],
|
||||||
|
per_page=args["limit"],
|
||||||
|
artist=args["artist"],
|
||||||
|
track=args["track"],
|
||||||
|
)
|
||||||
|
counts = stats.listen_counts(
|
||||||
|
g.user, period="3month", bucket="day", artist=args["artist"], track=args["track"]
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"artist": metadata.artist,
|
||||||
|
"track": metadata.track,
|
||||||
|
"metadata": metadata,
|
||||||
|
"items": history.items,
|
||||||
|
"counts": counts,
|
||||||
|
"page": history.page,
|
||||||
|
"per_page": history.per_page,
|
||||||
|
"total": history.total,
|
||||||
|
"total_pages": history.total_pages,
|
||||||
|
}
|
||||||
@@ -54,6 +54,22 @@ class Config:
|
|||||||
LASTFM_API_KEY = os.environ.get("LASTFM_API_KEY", "")
|
LASTFM_API_KEY = os.environ.get("LASTFM_API_KEY", "")
|
||||||
LASTFM_API_URL = os.environ.get("LASTFM_API_URL", "https://ws.audioscrobbler.com/2.0/")
|
LASTFM_API_URL = os.environ.get("LASTFM_API_URL", "https://ws.audioscrobbler.com/2.0/")
|
||||||
LASTFM_REQUEST_INTERVAL = float(os.environ.get("LASTFM_REQUEST_INTERVAL", "0.25"))
|
LASTFM_REQUEST_INTERVAL = float(os.environ.get("LASTFM_REQUEST_INTERVAL", "0.25"))
|
||||||
|
|
||||||
|
# Album art: MusicBrainz release-group search + Cover Art Archive, both free and keyless.
|
||||||
|
MUSICBRAINZ_API_URL = os.environ.get("MUSICBRAINZ_API_URL", "https://musicbrainz.org/ws/2/")
|
||||||
|
COVERART_API_URL = os.environ.get("COVERART_API_URL", "https://coverartarchive.org/")
|
||||||
|
# MusicBrainz requires a descriptive contact in the User-Agent or it throttles/blocks us.
|
||||||
|
MUSICBRAINZ_CONTACT = os.environ.get("MUSICBRAINZ_CONTACT", "") or UI_BASE_URL
|
||||||
|
MUSICBRAINZ_REQUEST_INTERVAL = float(os.environ.get("MUSICBRAINZ_REQUEST_INTERVAL", "1.0"))
|
||||||
|
MUSICBRAINZ_RETRIES = int(os.environ.get("MUSICBRAINZ_RETRIES", "2"))
|
||||||
|
ART_NOT_FOUND_RETRY_DAYS = int(os.environ.get("ART_NOT_FOUND_RETRY_DAYS", "30"))
|
||||||
|
ART_ERROR_RETRY_SECONDS = int(os.environ.get("ART_ERROR_RETRY_SECONDS", "3600"))
|
||||||
|
# Downloaded art is kept here, named by the album_art row's id. Needs write access
|
||||||
|
# from the worker (which downloads it) and read access from the api (which serves it).
|
||||||
|
ART_STORAGE_DIR = os.environ.get("ART_STORAGE_DIR", "var/album-art")
|
||||||
|
# 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)))
|
IMPORT_MAX_BYTES = int(os.environ.get("IMPORT_MAX_BYTES", str(200 * 1024 * 1024)))
|
||||||
MAX_CONTENT_LENGTH = IMPORT_MAX_BYTES + 1024 * 1024 # uploads are the largest requests
|
MAX_CONTENT_LENGTH = IMPORT_MAX_BYTES + 1024 * 1024 # uploads are the largest requests
|
||||||
# IMPORT_WORKER_METRICS_PORT is the pre-0.3 name, still honoured.
|
# IMPORT_WORKER_METRICS_PORT is the pre-0.3 name, still honoured.
|
||||||
|
|||||||
@@ -250,10 +250,11 @@ def note(
|
|||||||
to: list[str],
|
to: list[str],
|
||||||
cc: list[str],
|
cc: list[str],
|
||||||
tags: list[str] = (),
|
tags: list[str] = (),
|
||||||
|
attachment: list[dict] = (),
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""A post (weekly summary or milestone). No `@context`: it's always embedded in the
|
"""A post (now playing, weekly summary or milestone). No `@context`: it's always
|
||||||
Create that carries the same addressing, as Mastodon does."""
|
embedded in the Create that carries the same addressing, as Mastodon does."""
|
||||||
return {
|
doc = {
|
||||||
"id": note_id,
|
"id": note_id,
|
||||||
"type": "Note",
|
"type": "Note",
|
||||||
"attributedTo": actor_id,
|
"attributedTo": actor_id,
|
||||||
@@ -266,6 +267,9 @@ def note(
|
|||||||
"tag": [hashtag(t) for t in tags],
|
"tag": [hashtag(t) for t in tags],
|
||||||
"sensitive": False,
|
"sensitive": False,
|
||||||
}
|
}
|
||||||
|
if attachment:
|
||||||
|
doc["attachment"] = list(attachment)
|
||||||
|
return doc
|
||||||
|
|
||||||
|
|
||||||
def create(activity_id: str, actor_id: str, obj: dict, *, to: list[str], cc: list[str]) -> dict:
|
def create(activity_id: str, actor_id: str, obj: dict, *, to: list[str], cc: list[str]) -> dict:
|
||||||
|
|||||||
@@ -87,6 +87,7 @@ def publish(
|
|||||||
text: str,
|
text: str,
|
||||||
html: str,
|
html: str,
|
||||||
tags: tuple[str, ...] = DEFAULT_TAGS,
|
tags: tuple[str, ...] = DEFAULT_TAGS,
|
||||||
|
attachment: list[dict] = (),
|
||||||
) -> FederationPost | None:
|
) -> FederationPost | None:
|
||||||
"""Post `text`/`html` for the user, keyed by `kind:key`.
|
"""Post `text`/`html` for the user, keyed by `kind:key`.
|
||||||
|
|
||||||
@@ -116,6 +117,7 @@ def publish(
|
|||||||
to=to,
|
to=to,
|
||||||
cc=cc,
|
cc=cc,
|
||||||
tags=list(tags),
|
tags=list(tags),
|
||||||
|
attachment=list(attachment),
|
||||||
)
|
)
|
||||||
# activity.id is a Python-generated UUID (see activities.store), so it's already
|
# activity.id is a Python-generated UUID (see activities.store), so it's already
|
||||||
# usable below without a flush.
|
# usable below without a flush.
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ from scrobbler.federation import activities, actors, followers, publishing, shar
|
|||||||
from scrobbler.federation import metrics as fed_metrics
|
from scrobbler.federation import metrics as fed_metrics
|
||||||
from scrobbler.federation.models import FederationNowPlaying, FederationPost, FederationSettings
|
from scrobbler.federation.models import FederationNowPlaying, FederationPost, FederationSettings
|
||||||
from scrobbler.federation.protocol import content, vocab
|
from scrobbler.federation.protocol import content, vocab
|
||||||
from scrobbler.services import accounts
|
from scrobbler.services import accounts, art
|
||||||
from scrobbler.services.scrobbles import get_now_playing
|
from scrobbler.services.scrobbles import get_now_playing
|
||||||
|
|
||||||
KIND = "now_playing"
|
KIND = "now_playing"
|
||||||
@@ -80,10 +80,36 @@ def _build_content(playing) -> tuple[str, str]:
|
|||||||
return text, html
|
return text, html
|
||||||
|
|
||||||
|
|
||||||
|
def _attachment_for(playing) -> list[dict]:
|
||||||
|
"""Cover art for the post, if we have an album and can resolve it. Cover Art
|
||||||
|
Archive's sized convenience endpoints (what art.lookup() resolves to) are always
|
||||||
|
JPEG, whatever the original upload was."""
|
||||||
|
if not playing.album:
|
||||||
|
return []
|
||||||
|
result = art.lookup(playing.artist, playing.album)
|
||||||
|
if result.status != "found":
|
||||||
|
return []
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"type": "Image",
|
||||||
|
"mediaType": "image/jpeg",
|
||||||
|
"url": result.image_url,
|
||||||
|
"name": f"Cover art for {playing.album}",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
def _post_now_playing(user, playing, key: str, state: FederationNowPlaying, now: datetime) -> str:
|
def _post_now_playing(user, playing, key: str, state: FederationNowPlaying, now: datetime) -> str:
|
||||||
text, html = _build_content(playing)
|
text, html = _build_content(playing)
|
||||||
post = publishing.publish(
|
post = publishing.publish(
|
||||||
user.id, user.username, KIND, key, text=text, html=html, tags=("Scrobbler", "NowPlaying")
|
user.id,
|
||||||
|
user.username,
|
||||||
|
KIND,
|
||||||
|
key,
|
||||||
|
text=text,
|
||||||
|
html=html,
|
||||||
|
tags=("Scrobbler", "NowPlaying"),
|
||||||
|
attachment=_attachment_for(playing),
|
||||||
)
|
)
|
||||||
if post is None:
|
if post is None:
|
||||||
return "none"
|
return "none"
|
||||||
|
|||||||
@@ -122,6 +122,72 @@ worker_tasks_total = Counter(
|
|||||||
["task", "outcome"],
|
["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_correction_resolutions_total = Counter(
|
||||||
|
"scrobbler_art_correction_resolutions_total",
|
||||||
|
"Worker outcome of a manual correction, by input (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
|
# Database
|
||||||
db_query_duration_seconds = Histogram(
|
db_query_duration_seconds = Histogram(
|
||||||
"scrobbler_db_query_duration_seconds",
|
"scrobbler_db_query_duration_seconds",
|
||||||
@@ -150,4 +216,9 @@ COLLECTED = {
|
|||||||
"active_users": "scrobbler_active_users",
|
"active_users": "scrobbler_active_users",
|
||||||
"now_playing_active": "scrobbler_now_playing_active",
|
"now_playing_active": "scrobbler_now_playing_active",
|
||||||
"import_jobs": "scrobbler_import_jobs",
|
"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",
|
||||||
}
|
}
|
||||||
@@ -12,6 +12,9 @@ from sqlalchemy.pool import NullPool
|
|||||||
|
|
||||||
from scrobbler.metrics import COLLECTED
|
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"}
|
ACTIVE_WINDOWS = {"1h": "1 hour", "24h": "24 hours", "7d": "7 days"}
|
||||||
|
|
||||||
|
|
||||||
@@ -46,11 +49,48 @@ class DatabaseStatsCollector(Collector):
|
|||||||
)
|
)
|
||||||
).all()
|
).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 {
|
return {
|
||||||
"users": users,
|
"users": users,
|
||||||
"active": active,
|
"active": active,
|
||||||
"now_playing": now_playing,
|
"now_playing": now_playing,
|
||||||
"import_jobs": {s: import_jobs.get(s, 0) for s in ("pending", "running")},
|
"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:
|
def values(self) -> dict | None:
|
||||||
@@ -85,3 +125,32 @@ class DatabaseStatsCollector(Collector):
|
|||||||
for status, count in values["import_jobs"].items():
|
for status, count in values["import_jobs"].items():
|
||||||
jobs.add_metric([status], count)
|
jobs.add_metric([status], count)
|
||||||
yield jobs
|
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"],
|
||||||
|
)
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
"""album art cache
|
||||||
|
|
||||||
|
Revision ID: 3ba21eb1ea0c
|
||||||
|
Revises: e7fb730bac15
|
||||||
|
Create Date: 2026-10-06 16:58:58.755196
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = "3ba21eb1ea0c"
|
||||||
|
down_revision = "e7fb730bac15"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table(
|
||||||
|
"album_art",
|
||||||
|
sa.Column("id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("artist", sa.Text(), nullable=False),
|
||||||
|
sa.Column("album", sa.Text(), nullable=False),
|
||||||
|
sa.Column("status", sa.String(length=16), nullable=False),
|
||||||
|
sa.Column("image_url", sa.Text(), nullable=True),
|
||||||
|
sa.Column("release_group_mbid", sa.String(length=36), nullable=True),
|
||||||
|
sa.Column("error_code", sa.String(length=64), nullable=True),
|
||||||
|
sa.Column("checked_at", sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
)
|
||||||
|
with op.batch_alter_table("album_art", schema=None) as batch_op:
|
||||||
|
batch_op.create_index(
|
||||||
|
"uq_album_art_artist_album_lower",
|
||||||
|
[sa.literal_column("lower(artist)"), sa.literal_column("lower(album)")],
|
||||||
|
unique=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
with op.batch_alter_table("album_art", schema=None) as batch_op:
|
||||||
|
batch_op.drop_index("uq_album_art_artist_album_lower")
|
||||||
|
|
||||||
|
op.drop_table("album_art")
|
||||||
|
# ### end Alembic commands ###
|
||||||
@@ -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")
|
||||||
@@ -157,3 +157,65 @@ class ImportJob(db.Model):
|
|||||||
started_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
started_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||||
finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||||
heartbeat_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
heartbeat_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||||
|
|
||||||
|
|
||||||
|
class AlbumArt(db.Model):
|
||||||
|
"""Cached MusicBrainz + Cover Art Archive lookup for one (artist, album).
|
||||||
|
|
||||||
|
Global, not per-user: this is data about the real-world release, not a user's own data.
|
||||||
|
A row always exists once looked up — a miss or an error is cached too, so repeat requests
|
||||||
|
for an album with no art skip the upstream calls until due for a recheck.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = "album_art"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
artist: Mapped[str] = mapped_column(Text)
|
||||||
|
album: Mapped[str] = mapped_column(Text)
|
||||||
|
status: Mapped[str] = mapped_column(String(16)) # found, not_found or error
|
||||||
|
image_url: Mapped[str | None] = mapped_column(Text) # set iff status == "found"
|
||||||
|
release_group_mbid: Mapped[str | None] = mapped_column(String(36))
|
||||||
|
error_code: Mapped[str | None] = mapped_column(String(64)) # set iff status == "error"
|
||||||
|
checked_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||||
|
|
||||||
|
__table_args__ = (
|
||||||
|
Index(
|
||||||
|
"uq_album_art_artist_album_lower", func.lower(artist), func.lower(album), unique=True
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
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))
|
||||||
|
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,
|
||||||
|
),
|
||||||
|
)
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
validation and the generated OpenAPI document."""
|
validation and the generated OpenAPI document."""
|
||||||
|
|
||||||
from flask_smorest.fields import Upload
|
from flask_smorest.fields import Upload
|
||||||
from marshmallow import Schema, fields, validate
|
from marshmallow import Schema, ValidationError, fields, validate, validates_schema
|
||||||
|
|
||||||
|
|
||||||
class ErrorDetailSchema(Schema):
|
class ErrorDetailSchema(Schema):
|
||||||
@@ -139,6 +139,98 @@ class CountSchema(Schema):
|
|||||||
count = fields.Integer()
|
count = fields.Integer()
|
||||||
|
|
||||||
|
|
||||||
|
class TrackSearchArgsSchema(Schema):
|
||||||
|
q = fields.String(required=True, validate=validate.Length(min=1, max=200))
|
||||||
|
limit = fields.Integer(load_default=20, validate=validate.Range(min=1, max=50))
|
||||||
|
|
||||||
|
|
||||||
|
class TrackSearchResultSchema(Schema):
|
||||||
|
artist = fields.String()
|
||||||
|
track = fields.String(attribute="name")
|
||||||
|
playcount = fields.Integer()
|
||||||
|
|
||||||
|
|
||||||
|
class TrackDetailArgsSchema(PageArgsSchema):
|
||||||
|
artist = fields.String(required=True, validate=validate.Length(min=1, max=500))
|
||||||
|
track = fields.String(required=True, validate=validate.Length(min=1, max=500))
|
||||||
|
|
||||||
|
|
||||||
|
class AlbumArtArgsSchema(Schema):
|
||||||
|
artist = fields.String(required=True, validate=validate.Length(min=1, max=500))
|
||||||
|
album = fields.String(required=True, validate=validate.Length(min=1, max=500))
|
||||||
|
|
||||||
|
|
||||||
|
class 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"}
|
||||||
|
)
|
||||||
|
|
||||||
|
@validates_schema
|
||||||
|
def _needs_a_correction(self, data, **kwargs):
|
||||||
|
if not any(k in data for k in ("search_artist", "search_album", "release_group_mbid")):
|
||||||
|
raise ValidationError("Give a search_artist, search_album or release_group_mbid")
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
|
track_number = fields.Integer(allow_none=True)
|
||||||
|
duration = fields.Integer(allow_none=True)
|
||||||
|
mbid = fields.String(allow_none=True)
|
||||||
|
playcount = fields.Integer()
|
||||||
|
first_played_at = fields.DateTime()
|
||||||
|
last_played_at = fields.DateTime()
|
||||||
|
|
||||||
|
|
||||||
|
class TrackDetailSchema(PageMetaSchema):
|
||||||
|
artist = fields.String()
|
||||||
|
track = fields.String()
|
||||||
|
metadata = fields.Nested(TrackMetadataSchema)
|
||||||
|
items = fields.List(fields.Nested(ScrobbleSchema))
|
||||||
|
counts = fields.List(
|
||||||
|
fields.Nested(CountSchema), metadata={"description": "Daily plays over the last 90 days"}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class SummarySchema(Schema):
|
class SummarySchema(Schema):
|
||||||
scrobbles = fields.Integer()
|
scrobbles = fields.Integer()
|
||||||
artists = fields.Integer()
|
artists = fields.Integer()
|
||||||
|
|||||||
@@ -0,0 +1,611 @@
|
|||||||
|
"""Album art: MusicBrainz release-group search + Cover Art Archive, both free and keyless.
|
||||||
|
|
||||||
|
Every (artist, album) lookup is cached in `AlbumArt` — a miss or an error is cached too, so
|
||||||
|
repeat requests for an album we can't find art for don't keep hammering the upstream APIs.
|
||||||
|
`lookup()` resolves *where* the art is (and never raises); `fetch_image()` streams the bytes
|
||||||
|
from there.
|
||||||
|
|
||||||
|
`lookup()` itself is still a live, synchronous resolution — fine for its one caller
|
||||||
|
(`federation/publishing/now_playing.py`, already running from a background worker task, not
|
||||||
|
a request). The web-facing `/api/v1/art/album` endpoint does NOT call `lookup()`: it only
|
||||||
|
ever reads via `get_cached()`/`read_file()`, both pure local reads with no network call, so
|
||||||
|
a page can never be slowed down by a MusicBrainz/Cover Art Archive round trip. A cache miss
|
||||||
|
there calls `want()` (a fast DB write, "please resolve this") instead, and a background
|
||||||
|
worker task (`resolve_one_pending()`, registered by `register_worker_tasks()`) does the
|
||||||
|
actual resolving plus downloading the image bytes to `ART_STORAGE_DIR`, completely
|
||||||
|
decoupled from any request.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
from 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 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, 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'([+\-&|!(){}\[\]^"~*?:\\/])')
|
||||||
|
|
||||||
|
|
||||||
|
def _escape(value: str) -> str:
|
||||||
|
return _LUCENE_SPECIAL.sub(r"\\\1", value)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ArtResult:
|
||||||
|
status: str # "found", "not_found" or "error"
|
||||||
|
image_url: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ImageBytes:
|
||||||
|
body: bytes
|
||||||
|
content_type: str
|
||||||
|
|
||||||
|
|
||||||
|
class ArtFetchFailed(Exception):
|
||||||
|
"""The resolved image URL couldn't be fetched."""
|
||||||
|
|
||||||
|
|
||||||
|
def _user_agent() -> str:
|
||||||
|
from scrobbler import __version__
|
||||||
|
|
||||||
|
contact = current_app.config["MUSICBRAINZ_CONTACT"]
|
||||||
|
return f"Scrobbler/{__version__} ( {contact} )"
|
||||||
|
|
||||||
|
|
||||||
|
_last_musicbrainz_call = 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def _throttled_request(url: str, method: str = "GET") -> urllib.request.Request:
|
||||||
|
global _last_musicbrainz_call
|
||||||
|
interval = current_app.config["MUSICBRAINZ_REQUEST_INTERVAL"]
|
||||||
|
wait = interval - (time.monotonic() - _last_musicbrainz_call)
|
||||||
|
if wait > 0:
|
||||||
|
time.sleep(wait)
|
||||||
|
_last_musicbrainz_call = time.monotonic()
|
||||||
|
return urllib.request.Request(url, method=method, headers={"User-Agent": _user_agent()})
|
||||||
|
|
||||||
|
|
||||||
|
def _stale(row: AlbumArt) -> bool:
|
||||||
|
if row.status == "found":
|
||||||
|
return False
|
||||||
|
now = datetime.now(UTC)
|
||||||
|
if row.status == "error":
|
||||||
|
threshold = timedelta(seconds=current_app.config["ART_ERROR_RETRY_SECONDS"])
|
||||||
|
else:
|
||||||
|
threshold = timedelta(days=current_app.config["ART_NOT_FOUND_RETRY_DAYS"])
|
||||||
|
return now - row.checked_at > threshold
|
||||||
|
|
||||||
|
|
||||||
|
def _find_release_group(artist: str, album: str) -> str | None:
|
||||||
|
"""A matching release-group's MBID, or None if MusicBrainz has no match."""
|
||||||
|
api_url = current_app.config["MUSICBRAINZ_API_URL"]
|
||||||
|
query = f'releasegroup:"{_escape(album)}" AND artist:"{_escape(artist)}"'
|
||||||
|
params = urllib.parse.urlencode({"query": query, "fmt": "json", "limit": "5"})
|
||||||
|
retries = current_app.config["MUSICBRAINZ_RETRIES"]
|
||||||
|
for attempt in range(retries + 1):
|
||||||
|
request = _throttled_request(f"{api_url}release-group/?{params}")
|
||||||
|
try:
|
||||||
|
with (
|
||||||
|
_upstream_call("musicbrainz"),
|
||||||
|
urllib.request.urlopen(request, timeout=10) as response,
|
||||||
|
):
|
||||||
|
body = json.load(response)
|
||||||
|
except urllib.error.HTTPError as err:
|
||||||
|
if attempt == retries or err.code < 500:
|
||||||
|
raise
|
||||||
|
except (urllib.error.URLError, TimeoutError):
|
||||||
|
if attempt == retries:
|
||||||
|
raise
|
||||||
|
else:
|
||||||
|
groups = body.get("release-groups") or []
|
||||||
|
return groups[0]["id"] if groups else None
|
||||||
|
time.sleep(min(10, 2**attempt))
|
||||||
|
raise TimeoutError("MusicBrainz request exhausted its retries")
|
||||||
|
|
||||||
|
|
||||||
|
def _cover_art_url(release_group_mbid: str) -> str | None:
|
||||||
|
"""The release-group's front cover URL, or None if Cover Art Archive has none.
|
||||||
|
|
||||||
|
Cover Art Archive redirects to archive.org for the actual image, which is
|
||||||
|
occasionally slow — retried the same way as the MusicBrainz search, with a longer
|
||||||
|
per-attempt timeout to give that redirect room.
|
||||||
|
"""
|
||||||
|
coverart_url = current_app.config["COVERART_API_URL"]
|
||||||
|
url = f"{coverart_url}release-group/{release_group_mbid}/front-500"
|
||||||
|
retries = current_app.config["MUSICBRAINZ_RETRIES"]
|
||||||
|
for attempt in range(retries + 1):
|
||||||
|
request = urllib.request.Request(url, method="HEAD")
|
||||||
|
try:
|
||||||
|
with _upstream_call("coverart"), urllib.request.urlopen(request, timeout=15):
|
||||||
|
return url
|
||||||
|
except urllib.error.HTTPError as err:
|
||||||
|
if err.code == 404:
|
||||||
|
return None
|
||||||
|
if attempt == retries or err.code < 500:
|
||||||
|
raise
|
||||||
|
except (urllib.error.URLError, TimeoutError):
|
||||||
|
if attempt == retries:
|
||||||
|
raise
|
||||||
|
time.sleep(min(10, 2**attempt))
|
||||||
|
raise TimeoutError("Cover Art Archive request exhausted its retries")
|
||||||
|
|
||||||
|
|
||||||
|
def get_cached(artist: str, album: str) -> AlbumArt | None:
|
||||||
|
"""Plain cache read by (artist, album). No network, no write."""
|
||||||
|
return db.session.scalar(
|
||||||
|
select(AlbumArt).where(
|
||||||
|
func.lower(AlbumArt.artist) == artist.lower(),
|
||||||
|
func.lower(AlbumArt.album) == album.lower(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve(artist: str, album: str) -> tuple[ArtResult, str | None, str | None]:
|
||||||
|
"""Live MusicBrainz + Cover Art Archive resolution, no caching involved. Returns
|
||||||
|
(result, release_group_mbid, error_code). Never raises."""
|
||||||
|
release_group_mbid = None
|
||||||
|
try:
|
||||||
|
release_group_mbid = _find_release_group(artist, album)
|
||||||
|
image_url = _cover_art_url(release_group_mbid) if release_group_mbid else None
|
||||||
|
status = "found" if image_url else "not_found"
|
||||||
|
return ArtResult(status, image_url), release_group_mbid, None
|
||||||
|
except Exception as err: # noqa: BLE001 - any upstream failure degrades to a cached "error"
|
||||||
|
log.warning("Album art lookup failed for %r/%r: %s", artist, album, err)
|
||||||
|
return ArtResult("error"), release_group_mbid, type(err).__name__
|
||||||
|
|
||||||
|
|
||||||
|
def _store(
|
||||||
|
artist: str,
|
||||||
|
album: str,
|
||||||
|
result: ArtResult,
|
||||||
|
release_group_mbid: str | None,
|
||||||
|
error_code: str | None,
|
||||||
|
) -> None:
|
||||||
|
values = {
|
||||||
|
"artist": artist,
|
||||||
|
"album": album,
|
||||||
|
"status": result.status,
|
||||||
|
"image_url": result.image_url,
|
||||||
|
"release_group_mbid": release_group_mbid,
|
||||||
|
"error_code": error_code,
|
||||||
|
"checked_at": datetime.now(UTC),
|
||||||
|
}
|
||||||
|
stmt = insert(AlbumArt).values(**values)
|
||||||
|
stmt = stmt.on_conflict_do_update(
|
||||||
|
index_elements=[func.lower(AlbumArt.artist), func.lower(AlbumArt.album)], set_=values
|
||||||
|
)
|
||||||
|
db.session.execute(stmt)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def lookup(artist: str, album: str) -> ArtResult:
|
||||||
|
"""Cached (artist, album) art resolution, resolving live on a cache miss. Never
|
||||||
|
raises. Used by ActivityPub posting, which already runs from a worker task - not
|
||||||
|
used by the web-facing endpoint, which must never block on a live lookup (see
|
||||||
|
get_cached()/want() below)."""
|
||||||
|
existing = get_cached(artist, album)
|
||||||
|
if existing is not None and not _stale(existing):
|
||||||
|
return ArtResult(existing.status, existing.image_url)
|
||||||
|
result, release_group_mbid, error_code = _resolve(artist, album)
|
||||||
|
metrics.art_resolutions_total.labels("inline", result.status).inc()
|
||||||
|
_store(artist, album, result, release_group_mbid, error_code)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def want(artist: str, album: str) -> None:
|
||||||
|
"""Record that we'd like art for (artist, album), for the background worker to
|
||||||
|
resolve. A fast, network-free write; a no-op if a row already exists (any status)."""
|
||||||
|
stmt = insert(AlbumArt).values(
|
||||||
|
artist=artist, album=album, status="pending", checked_at=datetime.now(UTC)
|
||||||
|
)
|
||||||
|
stmt = stmt.on_conflict_do_nothing(
|
||||||
|
index_elements=[func.lower(AlbumArt.artist), func.lower(AlbumArt.album)]
|
||||||
|
)
|
||||||
|
db.session.execute(stmt)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def requeue(row: AlbumArt) -> None:
|
||||||
|
"""Asks the worker to (re)resolve a row - used when a 'found' row's file has gone
|
||||||
|
missing (e.g. one resolved before local file storage existed)."""
|
||||||
|
row.status = "pending"
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def _file_path(row_id: int) -> Path:
|
||||||
|
return Path(current_app.config["ART_STORAGE_DIR"]) / f"{row_id}.jpg"
|
||||||
|
|
||||||
|
|
||||||
|
def read_file(row_id: int) -> bytes | None:
|
||||||
|
"""The downloaded image bytes for a resolved row, or None if not downloaded."""
|
||||||
|
try:
|
||||||
|
return _file_path(row_id).read_bytes()
|
||||||
|
except FileNotFoundError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_image(image_url: str) -> ImageBytes:
|
||||||
|
"""Streams the bytes from image_url. Raises ArtFetchFailed on any problem."""
|
||||||
|
try:
|
||||||
|
with _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,
|
||||||
|
) -> None:
|
||||||
|
"""Queue a corrected lookup (different search text, or a known MusicBrainz
|
||||||
|
release-group) 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,
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
if override
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
}
|
||||||
|
for artist, album, scrobbles, cached, override in rows
|
||||||
|
]
|
||||||
|
return items, total
|
||||||
|
|
||||||
|
|
||||||
|
# --- Worker --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _claim_pending() -> AlbumArt | None:
|
||||||
|
"""Atomically takes one row due for resolution (new, or a stale not_found/error)."""
|
||||||
|
not_found_cutoff = datetime.now(UTC) - timedelta(
|
||||||
|
days=current_app.config["ART_NOT_FOUND_RETRY_DAYS"]
|
||||||
|
)
|
||||||
|
error_cutoff = datetime.now(UTC) - timedelta(
|
||||||
|
seconds=current_app.config["ART_ERROR_RETRY_SECONDS"]
|
||||||
|
)
|
||||||
|
row = db.session.scalar(
|
||||||
|
select(AlbumArt)
|
||||||
|
.where(
|
||||||
|
or_(
|
||||||
|
AlbumArt.status == "pending",
|
||||||
|
(AlbumArt.status == "not_found") & (AlbumArt.checked_at < not_found_cutoff),
|
||||||
|
(AlbumArt.status == "error") & (AlbumArt.checked_at < error_cutoff),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.order_by(AlbumArt.checked_at)
|
||||||
|
.limit(1)
|
||||||
|
.with_for_update(skip_locked=True)
|
||||||
|
)
|
||||||
|
if row is None:
|
||||||
|
db.session.rollback()
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
def _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 goes straight to
|
||||||
|
Cover Art Archive, otherwise the (corrected) text is searched. Never raises."""
|
||||||
|
if not row.release_group_mbid:
|
||||||
|
result, _, error_code = _resolve(
|
||||||
|
row.search_artist or row.artist, row.search_album or row.album
|
||||||
|
)
|
||||||
|
return result, error_code
|
||||||
|
try:
|
||||||
|
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 = "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. 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:
|
||||||
|
image = fetch_image(result.image_url)
|
||||||
|
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)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def register_worker_tasks(app) -> None:
|
||||||
|
from scrobbler import worker
|
||||||
|
|
||||||
|
worker.register_task(app, "art", resolve_one_pending)
|
||||||
@@ -4,7 +4,7 @@ import math
|
|||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import UTC, date, datetime, timedelta
|
from datetime import UTC, date, datetime, timedelta
|
||||||
|
|
||||||
from sqlalchemy import Select, func, literal_column, select
|
from sqlalchemy import Select, func, literal_column, or_, select
|
||||||
|
|
||||||
from scrobbler.extensions import db
|
from scrobbler.extensions import db
|
||||||
from scrobbler.models import Scrobble, User
|
from scrobbler.models import Scrobble, User
|
||||||
@@ -67,6 +67,16 @@ def _display(column):
|
|||||||
return func.mode().within_group(column.collate("C"))
|
return func.mode().within_group(column.collate("C"))
|
||||||
|
|
||||||
|
|
||||||
|
def _mode_text(column):
|
||||||
|
"""Most common non-null spelling in the group, ignoring rows where it's unset."""
|
||||||
|
return func.mode().within_group(column.collate("C")).filter(column.is_not(None))
|
||||||
|
|
||||||
|
|
||||||
|
def _mode(column):
|
||||||
|
"""Most common non-null value in the group, ignoring rows where it's unset."""
|
||||||
|
return func.mode().within_group(column).filter(column.is_not(None))
|
||||||
|
|
||||||
|
|
||||||
def _paginate(query: Select, page: int, per_page: int) -> tuple[list, int]:
|
def _paginate(query: Select, page: int, per_page: int) -> tuple[list, int]:
|
||||||
total = db.session.scalar(select(func.count()).select_from(query.subquery()))
|
total = db.session.scalar(select(func.count()).select_from(query.subquery()))
|
||||||
rows = db.session.execute(query.limit(per_page).offset((page - 1) * per_page)).all()
|
rows = db.session.execute(query.limit(per_page).offset((page - 1) * per_page)).all()
|
||||||
@@ -79,12 +89,18 @@ def recent(
|
|||||||
per_page: int = 50,
|
per_page: int = 50,
|
||||||
start: datetime | None = None,
|
start: datetime | None = None,
|
||||||
end: datetime | None = None,
|
end: datetime | None = None,
|
||||||
|
artist: str | None = None,
|
||||||
|
track: str | None = None,
|
||||||
) -> Page:
|
) -> Page:
|
||||||
conditions = [Scrobble.user_id == user.id]
|
conditions = [Scrobble.user_id == user.id]
|
||||||
if start:
|
if start:
|
||||||
conditions.append(Scrobble.played_at >= start)
|
conditions.append(Scrobble.played_at >= start)
|
||||||
if end:
|
if end:
|
||||||
conditions.append(Scrobble.played_at <= end)
|
conditions.append(Scrobble.played_at <= end)
|
||||||
|
if artist:
|
||||||
|
conditions.append(func.lower(Scrobble.artist) == artist.lower())
|
||||||
|
if track:
|
||||||
|
conditions.append(func.lower(Scrobble.track) == track.lower())
|
||||||
query = select(Scrobble).where(*conditions).order_by(Scrobble.played_at.desc())
|
query = select(Scrobble).where(*conditions).order_by(Scrobble.played_at.desc())
|
||||||
rows, total = _paginate(query, page, per_page)
|
rows, total = _paginate(query, page, per_page)
|
||||||
return Page([row[0] for row in rows], page, per_page, total)
|
return Page([row[0] for row in rows], page, per_page, total)
|
||||||
@@ -147,14 +163,25 @@ def top_tracks(user: User, period: str = "overall", page: int = 1, per_page: int
|
|||||||
return Page(items, page, per_page, total)
|
return Page(items, page, per_page, total)
|
||||||
|
|
||||||
|
|
||||||
def listen_counts(user: User, period: str = "1month", bucket: str = "day") -> list[dict]:
|
def listen_counts(
|
||||||
|
user: User,
|
||||||
|
period: str = "1month",
|
||||||
|
bucket: str = "day",
|
||||||
|
artist: str | None = None,
|
||||||
|
track: str | None = None,
|
||||||
|
) -> list[dict]:
|
||||||
"""Scrobbles per bucket (UTC). Empty buckets are included for day buckets."""
|
"""Scrobbles per bucket (UTC). Empty buckets are included for day buckets."""
|
||||||
if bucket not in BUCKETS: # interpolated into SQL below, so allow-list it
|
if bucket not in BUCKETS: # interpolated into SQL below, so allow-list it
|
||||||
raise ValueError(f"bucket must be one of {BUCKETS}")
|
raise ValueError(f"bucket must be one of {BUCKETS}")
|
||||||
|
conditions = _user_scrobbles(user, period)
|
||||||
|
if artist:
|
||||||
|
conditions.append(func.lower(Scrobble.artist) == artist.lower())
|
||||||
|
if track:
|
||||||
|
conditions.append(func.lower(Scrobble.track) == track.lower())
|
||||||
bucket_col = func.date_trunc(literal_column(f"'{bucket}'"), Scrobble.played_at, "UTC")
|
bucket_col = func.date_trunc(literal_column(f"'{bucket}'"), Scrobble.played_at, "UTC")
|
||||||
query = (
|
query = (
|
||||||
select(bucket_col.label("bucket"), func.count())
|
select(bucket_col.label("bucket"), func.count())
|
||||||
.where(*_user_scrobbles(user, period))
|
.where(*conditions)
|
||||||
.group_by("bucket")
|
.group_by("bucket")
|
||||||
.order_by("bucket")
|
.order_by("bucket")
|
||||||
)
|
)
|
||||||
@@ -217,6 +244,84 @@ def top_tracks_between(
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class TrackMetadata:
|
||||||
|
artist: str
|
||||||
|
track: str
|
||||||
|
album: str | None
|
||||||
|
album_artist: str | None
|
||||||
|
track_number: int | None
|
||||||
|
duration: int | None
|
||||||
|
mbid: str | None
|
||||||
|
playcount: int
|
||||||
|
first_played_at: datetime
|
||||||
|
last_played_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
def track_metadata(user: User, artist: str, track: str) -> TrackMetadata | None:
|
||||||
|
"""Canonical name and aggregated metadata for one song, or None if never played.
|
||||||
|
|
||||||
|
Each metadata field is the most common non-null value recorded for it; an exact tie
|
||||||
|
is resolved by mode()'s own (unspecified) ordering rather than a hand-rolled tiebreak.
|
||||||
|
"""
|
||||||
|
row = db.session.execute(
|
||||||
|
select(
|
||||||
|
_display(Scrobble.artist),
|
||||||
|
_display(Scrobble.track),
|
||||||
|
_mode_text(Scrobble.album),
|
||||||
|
_mode_text(Scrobble.album_artist),
|
||||||
|
_mode(Scrobble.track_number),
|
||||||
|
_mode(Scrobble.duration),
|
||||||
|
_mode_text(Scrobble.mbid),
|
||||||
|
func.count(),
|
||||||
|
func.min(Scrobble.played_at),
|
||||||
|
func.max(Scrobble.played_at),
|
||||||
|
).where(
|
||||||
|
Scrobble.user_id == user.id,
|
||||||
|
func.lower(Scrobble.artist) == artist.lower(),
|
||||||
|
func.lower(Scrobble.track) == track.lower(),
|
||||||
|
)
|
||||||
|
).one()
|
||||||
|
playcount = row[7]
|
||||||
|
if not playcount:
|
||||||
|
return None
|
||||||
|
return TrackMetadata(
|
||||||
|
artist=row[0],
|
||||||
|
track=row[1],
|
||||||
|
album=row[2],
|
||||||
|
album_artist=row[3],
|
||||||
|
track_number=row[4],
|
||||||
|
duration=row[5],
|
||||||
|
mbid=row[6],
|
||||||
|
playcount=playcount,
|
||||||
|
first_played_at=row[8],
|
||||||
|
last_played_at=row[9],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def track_search(user: User, q: str, limit: int = 20) -> list[TopItem]:
|
||||||
|
"""Tracks whose name or artist contains q (case-insensitive), ranked by playcount."""
|
||||||
|
q = q.strip().lower()
|
||||||
|
if not q:
|
||||||
|
return []
|
||||||
|
keys = (func.lower(Scrobble.track), func.lower(Scrobble.artist))
|
||||||
|
plays = func.count().label("plays")
|
||||||
|
query = (
|
||||||
|
select(_display(Scrobble.track), _display(Scrobble.artist), plays)
|
||||||
|
.where(
|
||||||
|
Scrobble.user_id == user.id,
|
||||||
|
or_(func.lower(Scrobble.track).contains(q), func.lower(Scrobble.artist).contains(q)),
|
||||||
|
)
|
||||||
|
.group_by(*keys)
|
||||||
|
.order_by(plays.desc(), *keys)
|
||||||
|
.limit(limit)
|
||||||
|
)
|
||||||
|
rows = db.session.execute(query).all()
|
||||||
|
return [
|
||||||
|
TopItem(i + 1, name, count, artist=artist) for i, (name, artist, count) in enumerate(rows)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
def summary(user: User) -> dict:
|
def summary(user: User) -> dict:
|
||||||
row = db.session.execute(
|
row = db.session.execute(
|
||||||
select(
|
select(
|
||||||
|
|||||||
@@ -0,0 +1,748 @@
|
|||||||
|
import io
|
||||||
|
import json
|
||||||
|
import pathlib
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import urllib.parse
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from werkzeug.serving import make_server
|
||||||
|
|
||||||
|
from scrobbler.extensions import db
|
||||||
|
from scrobbler.models import AlbumArt, 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 = {
|
||||||
|
"In Rainbows": "rg-found", # has art
|
||||||
|
"No Art Album": "rg-no-art", # MB match, but Cover Art Archive has nothing
|
||||||
|
"Boom Album": "rg-boom", # MB match, but Cover Art Archive 500s on HEAD
|
||||||
|
"Download Fail Album": "rg-dl-fail", # HEAD succeeds, but the GET download 500s
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _fake_musicbrainz_caa(environ, start_response):
|
||||||
|
method, path = environ["REQUEST_METHOD"], environ["PATH_INFO"]
|
||||||
|
|
||||||
|
if path == "/release-group/" and method == "GET":
|
||||||
|
query = urllib.parse.parse_qs(environ.get("QUERY_STRING", ""))["query"][0]
|
||||||
|
if "Query Boom" in query:
|
||||||
|
start_response("500 Internal Server Error", [("Content-Type", "text/plain")])
|
||||||
|
return [b"boom"]
|
||||||
|
match = next((v for k, v in _RELEASE_GROUPS.items() if k in query), None)
|
||||||
|
groups = [{"id": match}] if match else []
|
||||||
|
body = json.dumps({"release-groups": groups}).encode()
|
||||||
|
start_response(
|
||||||
|
"200 OK", [("Content-Type", "application/json"), ("Content-Length", str(len(body)))]
|
||||||
|
)
|
||||||
|
return [body]
|
||||||
|
|
||||||
|
if path in ("/release-group/rg-found/front-500", f"/release-group/{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)
|
||||||
|
return [] if method == "HEAD" else [body]
|
||||||
|
|
||||||
|
if path == "/release-group/rg-boom/front-500":
|
||||||
|
start_response("500 Internal Server Error", [("Content-Type", "text/plain")])
|
||||||
|
return [b"boom"]
|
||||||
|
|
||||||
|
if path == "/release-group/rg-dl-fail/front-500":
|
||||||
|
if method == "HEAD":
|
||||||
|
start_response("200 OK", [("Content-Type", "image/jpeg")])
|
||||||
|
return []
|
||||||
|
start_response("500 Internal Server Error", [("Content-Type", "text/plain")])
|
||||||
|
return [b"boom"]
|
||||||
|
|
||||||
|
start_response("404 Not Found", [("Content-Type", "text/plain")])
|
||||||
|
return [b"not found"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def fake_art_api():
|
||||||
|
server = make_server("127.0.0.1", 0, _fake_musicbrainz_caa, threaded=True)
|
||||||
|
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||||
|
thread.start()
|
||||||
|
yield f"http://127.0.0.1:{server.server_port}/"
|
||||||
|
server.shutdown()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def art_config(app, fake_art_api, tmp_path):
|
||||||
|
keys = (
|
||||||
|
"MUSICBRAINZ_API_URL",
|
||||||
|
"COVERART_API_URL",
|
||||||
|
"MUSICBRAINZ_REQUEST_INTERVAL",
|
||||||
|
"MUSICBRAINZ_RETRIES",
|
||||||
|
"ART_STORAGE_DIR",
|
||||||
|
)
|
||||||
|
saved = {k: app.config[k] for k in keys}
|
||||||
|
app.config.update(
|
||||||
|
MUSICBRAINZ_API_URL=fake_art_api,
|
||||||
|
COVERART_API_URL=fake_art_api,
|
||||||
|
MUSICBRAINZ_REQUEST_INTERVAL=0,
|
||||||
|
MUSICBRAINZ_RETRIES=0,
|
||||||
|
ART_STORAGE_DIR=str(tmp_path),
|
||||||
|
)
|
||||||
|
yield
|
||||||
|
app.config.update(saved)
|
||||||
|
|
||||||
|
|
||||||
|
def row(artist, album):
|
||||||
|
return db.session.scalar(
|
||||||
|
db.select(AlbumArt).where(
|
||||||
|
db.func.lower(AlbumArt.artist) == artist.lower(),
|
||||||
|
db.func.lower(AlbumArt.album) == album.lower(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def insert(artist, album, status, days_ago=0.0, image_url=None):
|
||||||
|
db.session.add(
|
||||||
|
AlbumArt(
|
||||||
|
artist=artist,
|
||||||
|
album=album,
|
||||||
|
status=status,
|
||||||
|
image_url=image_url,
|
||||||
|
checked_at=datetime.now(UTC) - timedelta(days=days_ago),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
|
||||||
|
# --- lookup() (still live-resolving: used by ActivityPub posting, out of scope here) -----------
|
||||||
|
|
||||||
|
|
||||||
|
def test_lookup_finds_art(art_config):
|
||||||
|
result = art.lookup("Radiohead", "In Rainbows")
|
||||||
|
assert result.status == "found"
|
||||||
|
assert result.image_url.endswith("/release-group/rg-found/front-500")
|
||||||
|
assert row("Radiohead", "In Rainbows").status == "found"
|
||||||
|
|
||||||
|
|
||||||
|
def test_lookup_no_musicbrainz_match_is_not_found(art_config):
|
||||||
|
result = art.lookup("Nobody", "Nothing At All")
|
||||||
|
assert result == art.ArtResult("not_found")
|
||||||
|
|
||||||
|
|
||||||
|
def test_lookup_musicbrainz_match_but_no_cover_art_is_not_found(art_config):
|
||||||
|
result = art.lookup("Someone", "No Art Album")
|
||||||
|
assert result == art.ArtResult("not_found")
|
||||||
|
|
||||||
|
|
||||||
|
def test_lookup_upstream_error_is_cached_not_raised(app, art_config):
|
||||||
|
result = art.lookup("Someone", "Boom Album")
|
||||||
|
assert result.status == "error"
|
||||||
|
assert row("Someone", "Boom Album").error_code
|
||||||
|
|
||||||
|
|
||||||
|
def test_lookup_search_error_is_cached_not_raised(app, art_config):
|
||||||
|
result = art.lookup("Someone", "Query Boom")
|
||||||
|
assert result.status == "error"
|
||||||
|
|
||||||
|
|
||||||
|
def test_lookup_is_case_insensitive_and_cached(app, art_config):
|
||||||
|
art.lookup("Radiohead", "In Rainbows")
|
||||||
|
# Point at a port nothing listens on: if the different-cased call weren't a cache hit on
|
||||||
|
# the same row, it would fail to reach the network and come back as "error".
|
||||||
|
app.config.update(
|
||||||
|
MUSICBRAINZ_API_URL="http://127.0.0.1:1/", COVERART_API_URL="http://127.0.0.1:1/"
|
||||||
|
)
|
||||||
|
result = art.lookup("radiohead", "in rainbows")
|
||||||
|
assert result.status == "found"
|
||||||
|
|
||||||
|
|
||||||
|
def test_lookup_fresh_cache_hit_skips_the_network(app, art_config, fake_art_api):
|
||||||
|
insert("Fresh Artist", "Fresh Album", "not_found", days_ago=0)
|
||||||
|
app.config.update(
|
||||||
|
MUSICBRAINZ_API_URL="http://127.0.0.1:1/", COVERART_API_URL="http://127.0.0.1:1/"
|
||||||
|
)
|
||||||
|
result = art.lookup("Fresh Artist", "Fresh Album")
|
||||||
|
assert result.status == "not_found"
|
||||||
|
|
||||||
|
|
||||||
|
def test_stale_not_found_row_is_rechecked(app, art_config):
|
||||||
|
insert("Radiohead", "In Rainbows", "not_found", days_ago=31)
|
||||||
|
result = art.lookup("Radiohead", "In Rainbows")
|
||||||
|
assert result.status == "found" # the live fake server actually has art for this album
|
||||||
|
|
||||||
|
|
||||||
|
def test_fresh_not_found_row_is_not_rechecked(app, art_config):
|
||||||
|
insert("Radiohead", "In Rainbows", "not_found", days_ago=1)
|
||||||
|
result = art.lookup("Radiohead", "In Rainbows")
|
||||||
|
assert result.status == "not_found" # cache hit, even though the live server has art
|
||||||
|
|
||||||
|
|
||||||
|
def test_stale_error_row_is_rechecked(app, art_config):
|
||||||
|
db.session.add(
|
||||||
|
AlbumArt(
|
||||||
|
artist="Radiohead",
|
||||||
|
album="In Rainbows",
|
||||||
|
status="error",
|
||||||
|
error_code="TimeoutError",
|
||||||
|
checked_at=datetime.now(UTC) - timedelta(hours=2),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
db.session.commit()
|
||||||
|
result = art.lookup("Radiohead", "In Rainbows")
|
||||||
|
assert result.status == "found"
|
||||||
|
|
||||||
|
|
||||||
|
def test_found_row_is_never_rechecked(app, art_config):
|
||||||
|
insert(
|
||||||
|
"Someone", "No Art Album", "found", days_ago=9999, image_url="https://example.com/old.jpg"
|
||||||
|
)
|
||||||
|
result = art.lookup("Someone", "No Art Album")
|
||||||
|
assert result.image_url == "https://example.com/old.jpg"
|
||||||
|
|
||||||
|
|
||||||
|
# --- fetch_image() -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_image_streams_the_bytes(art_config):
|
||||||
|
result = art.lookup("Radiohead", "In Rainbows")
|
||||||
|
image = art.fetch_image(result.image_url)
|
||||||
|
assert image.body == b"\xff\xd8\xff\xe0fake-jpeg-bytes"
|
||||||
|
assert image.content_type == "image/jpeg"
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_image_raises_on_failure(art_config):
|
||||||
|
with pytest.raises(art.ArtFetchFailed):
|
||||||
|
art.fetch_image("http://127.0.0.1:1/nope.jpg")
|
||||||
|
|
||||||
|
|
||||||
|
# --- get_cached() / want() / requeue() / read_file() ----------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_cached_returns_none_for_unseen_album(art_config):
|
||||||
|
assert art.get_cached("Nobody", "Nothing") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_cached_is_case_insensitive(art_config):
|
||||||
|
insert("Radiohead", "In Rainbows", "found", image_url="https://example.com/a.jpg")
|
||||||
|
assert art.get_cached("radiohead", "in rainbows").image_url == "https://example.com/a.jpg"
|
||||||
|
|
||||||
|
|
||||||
|
def test_want_creates_a_pending_row(art_config):
|
||||||
|
art.want("New Artist", "New Album")
|
||||||
|
assert row("New Artist", "New Album").status == "pending"
|
||||||
|
|
||||||
|
|
||||||
|
def test_want_is_a_noop_if_a_row_already_exists(art_config):
|
||||||
|
insert("Radiohead", "In Rainbows", "found", image_url="https://example.com/a.jpg")
|
||||||
|
art.want("Radiohead", "In Rainbows")
|
||||||
|
assert row("Radiohead", "In Rainbows").status == "found" # untouched, not reset to pending
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_file_returns_none_when_not_downloaded(art_config):
|
||||||
|
assert art.read_file(999_999) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_file_returns_the_bytes(app, art_config):
|
||||||
|
path = pathlib.Path(app.config["ART_STORAGE_DIR"]) / "123.jpg"
|
||||||
|
path.write_bytes(b"hello")
|
||||||
|
assert art.read_file(123) == b"hello"
|
||||||
|
|
||||||
|
|
||||||
|
def test_requeue_marks_a_row_pending(art_config):
|
||||||
|
insert("Someone", "Old Album", "found", image_url="https://example.com/a.jpg")
|
||||||
|
art.requeue(row("Someone", "Old Album"))
|
||||||
|
assert row("Someone", "Old Album").status == "pending"
|
||||||
|
|
||||||
|
|
||||||
|
# --- resolve_one_pending() (the worker task) ------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_one_pending_resolves_and_downloads(art_config):
|
||||||
|
art.want("Radiohead", "In Rainbows")
|
||||||
|
assert art.resolve_one_pending() is True
|
||||||
|
cached = row("Radiohead", "In Rainbows")
|
||||||
|
assert cached.status == "found"
|
||||||
|
assert art.read_file(cached.id) == b"\xff\xd8\xff\xe0fake-jpeg-bytes"
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_one_pending_handles_not_found(art_config):
|
||||||
|
art.want("Nobody", "Nothing")
|
||||||
|
assert art.resolve_one_pending() is True
|
||||||
|
assert row("Nobody", "Nothing").status == "not_found"
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_one_pending_handles_upstream_error(art_config):
|
||||||
|
art.want("Someone", "Boom Album")
|
||||||
|
assert art.resolve_one_pending() is True
|
||||||
|
cached = row("Someone", "Boom Album")
|
||||||
|
assert cached.status == "error"
|
||||||
|
assert cached.error_code
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_one_pending_download_failure_is_cached_as_error(art_config):
|
||||||
|
art.want("Someone", "Download Fail Album")
|
||||||
|
assert art.resolve_one_pending() is True
|
||||||
|
cached = row("Someone", "Download Fail Album")
|
||||||
|
assert cached.status == "error" # not left "found" with no file on disk
|
||||||
|
assert art.read_file(cached.id) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_one_pending_returns_false_when_nothing_to_do(art_config):
|
||||||
|
assert art.resolve_one_pending() is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_one_pending_picks_up_stale_not_found(art_config):
|
||||||
|
insert("Radiohead", "In Rainbows", "not_found", days_ago=31)
|
||||||
|
assert art.resolve_one_pending() is True
|
||||||
|
assert row("Radiohead", "In Rainbows").status == "found"
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_one_pending_picks_up_stale_error(art_config):
|
||||||
|
db.session.add(
|
||||||
|
AlbumArt(
|
||||||
|
artist="Radiohead",
|
||||||
|
album="In Rainbows",
|
||||||
|
status="error",
|
||||||
|
error_code="TimeoutError",
|
||||||
|
checked_at=datetime.now(UTC) - timedelta(hours=2),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
db.session.commit()
|
||||||
|
assert art.resolve_one_pending() is True
|
||||||
|
assert row("Radiohead", "In Rainbows").status == "found"
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_one_pending_ignores_fresh_not_found(art_config):
|
||||||
|
insert("Radiohead", "In Rainbows", "not_found", days_ago=1)
|
||||||
|
assert art.resolve_one_pending() is False
|
||||||
|
|
||||||
|
|
||||||
|
# --- GET /api/v1/art/album -------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_album_art_requires_auth(client):
|
||||||
|
assert client.get("/api/v1/art/album?artist=A&album=B").status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_album_art_requires_artist_and_album(client, auth):
|
||||||
|
assert client.get("/api/v1/art/album?artist=A", headers=auth).status_code == 422
|
||||||
|
assert client.get("/api/v1/art/album?album=B", headers=auth).status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
def test_album_art_404s_and_queues_an_unseen_album(client, auth, art_config):
|
||||||
|
response = client.get("/api/v1/art/album?artist=New+Artist&album=New+Album", headers=auth)
|
||||||
|
assert response.status_code == 404
|
||||||
|
assert response.get_json()["error"]["code"] == "no_album_art"
|
||||||
|
assert row("New Artist", "New Album").status == "pending"
|
||||||
|
|
||||||
|
|
||||||
|
def test_album_art_never_calls_the_network(client, auth, app, art_config):
|
||||||
|
# Point at a port nothing listens on: the endpoint must still respond (fast, 404)
|
||||||
|
# without ever trying to reach it — proof it's a cache-only read.
|
||||||
|
app.config.update(
|
||||||
|
MUSICBRAINZ_API_URL="http://127.0.0.1:1/", COVERART_API_URL="http://127.0.0.1:1/"
|
||||||
|
)
|
||||||
|
response = client.get("/api/v1/art/album?artist=Another&album=Album", headers=auth)
|
||||||
|
assert response.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_album_art_404s_while_pending(client, auth, art_config):
|
||||||
|
art.want("Radiohead", "In Rainbows")
|
||||||
|
response = client.get("/api/v1/art/album?artist=Radiohead&album=In+Rainbows", headers=auth)
|
||||||
|
assert response.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_album_art_returns_the_image_once_resolved(client, auth, art_config):
|
||||||
|
art.want("Radiohead", "In Rainbows")
|
||||||
|
art.resolve_one_pending()
|
||||||
|
response = client.get("/api/v1/art/album?artist=Radiohead&album=In+Rainbows", headers=auth)
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.data == b"\xff\xd8\xff\xe0fake-jpeg-bytes"
|
||||||
|
assert response.content_type == "image/jpeg"
|
||||||
|
assert response.headers["Cache-Control"] == "private, max-age=604800"
|
||||||
|
|
||||||
|
|
||||||
|
def test_album_art_404s_when_resolved_not_found(client, auth, art_config):
|
||||||
|
art.want("Nobody", "Nothing")
|
||||||
|
art.resolve_one_pending()
|
||||||
|
response = client.get("/api/v1/art/album?artist=Nobody&album=Nothing", headers=auth)
|
||||||
|
assert response.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_album_art_requeues_a_found_row_with_a_missing_file(client, auth, art_config):
|
||||||
|
insert("Legacy", "Album", "found", image_url="https://example.com/old.jpg")
|
||||||
|
response = client.get("/api/v1/art/album?artist=Legacy&album=Album", headers=auth)
|
||||||
|
assert response.status_code == 404
|
||||||
|
assert row("Legacy", "Album").status == "pending" # requeued for the worker to redo
|
||||||
|
|
||||||
|
|
||||||
|
# --- 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
|
||||||
@@ -50,6 +50,7 @@ def test_the_expected_dashboards_exist():
|
|||||||
"usage",
|
"usage",
|
||||||
"database",
|
"database",
|
||||||
"federation",
|
"federation",
|
||||||
|
"album-art",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -190,14 +190,16 @@ def test_public_post_404s_for_followers_only_deleted_or_unknown(fed_client, fed_
|
|||||||
|
|
||||||
|
|
||||||
def test_preview_weekly_reflects_the_week_in_progress(fed_client, fed_auth, fed_ctx, user):
|
def test_preview_weekly_reflects_the_week_in_progress(fed_client, fed_auth, fed_ctx, user):
|
||||||
|
# The preview window is [this week's Monday 00:00, now) - a play has to be in the
|
||||||
|
# past relative to the moment the test runs, not just dated "this Monday", or this
|
||||||
|
# flakes whenever CI happens to run before noon UTC on a Monday.
|
||||||
now = datetime.now(UTC)
|
now = datetime.now(UTC)
|
||||||
monday = now.date() - timedelta(days=now.weekday())
|
|
||||||
db.session.add(
|
db.session.add(
|
||||||
Scrobble(
|
Scrobble(
|
||||||
user_id=user.id,
|
user_id=user.id,
|
||||||
artist="Radiohead",
|
artist="Radiohead",
|
||||||
track="Reckoner",
|
track="Reckoner",
|
||||||
played_at=datetime(monday.year, monday.month, monday.day, 12, tzinfo=UTC),
|
played_at=now - timedelta(minutes=1),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|||||||
@@ -8,18 +8,33 @@ from scrobbler.extensions import db
|
|||||||
from scrobbler.federation import sharing
|
from scrobbler.federation import sharing
|
||||||
from scrobbler.federation.models import FederationActivity, FederationNowPlaying, FederationPost
|
from scrobbler.federation.models import FederationActivity, FederationNowPlaying, FederationPost
|
||||||
from scrobbler.federation.publishing import now_playing
|
from scrobbler.federation.publishing import now_playing
|
||||||
from scrobbler.models import NowPlaying
|
from scrobbler.models import AlbumArt, NowPlaying
|
||||||
from scrobbler.services.scrobbles import TrackInput, update_now_playing
|
from scrobbler.services.scrobbles import TrackInput, update_now_playing
|
||||||
|
|
||||||
|
|
||||||
def play(user, artist="Radiohead", track="Reckoner") -> datetime:
|
def play(user, artist="Radiohead", track="Reckoner", album=None) -> datetime:
|
||||||
"""Sets the track as playing (started_at = now) and returns that now, so tests
|
"""Sets the track as playing (started_at = now) and returns that now, so tests
|
||||||
always measure elapsed/throttle time relative to when it actually started, not a
|
always measure elapsed/throttle time relative to when it actually started, not a
|
||||||
fixed constant that would drift from real test-execution time."""
|
fixed constant that would drift from real test-execution time."""
|
||||||
update_now_playing(user, TrackInput(artist=artist, track=track))
|
update_now_playing(user, TrackInput(artist=artist, track=track, album=album))
|
||||||
return datetime.now(UTC)
|
return datetime.now(UTC)
|
||||||
|
|
||||||
|
|
||||||
|
def cache_art(artist: str, album: str, status: str, image_url: str | None = None) -> None:
|
||||||
|
"""Primes the AlbumArt cache directly, so art.lookup() is a cache hit and never
|
||||||
|
makes a real network call during tests."""
|
||||||
|
db.session.add(
|
||||||
|
AlbumArt(
|
||||||
|
artist=artist,
|
||||||
|
album=album,
|
||||||
|
status=status,
|
||||||
|
image_url=image_url,
|
||||||
|
checked_at=datetime.now(UTC),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
|
||||||
def stop_playing(user):
|
def stop_playing(user):
|
||||||
"""Expire (rather than delete) the row, matching how it naturally goes away."""
|
"""Expire (rather than delete) the row, matching how it naturally goes away."""
|
||||||
db.session.get(NowPlaying, user.id).expires_at = datetime.now(UTC) - timedelta(minutes=1)
|
db.session.get(NowPlaying, user.id).expires_at = datetime.now(UTC) - timedelta(minutes=1)
|
||||||
@@ -141,6 +156,44 @@ def test_post_sent_after_30_seconds(fed_ctx, posting_user):
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_post_includes_album_art_when_known(fed_ctx, posting_user):
|
||||||
|
cache_art(
|
||||||
|
"Radiohead",
|
||||||
|
"In Rainbows",
|
||||||
|
"found",
|
||||||
|
image_url="https://coverartarchive.org/release-group/test/front-500",
|
||||||
|
)
|
||||||
|
now = play(posting_user, album="In Rainbows")
|
||||||
|
now_playing.check_and_post(posting_user.id, now + timedelta(seconds=31))
|
||||||
|
[post] = posts_for(posting_user.id)
|
||||||
|
activity = db.session.get(FederationActivity, post.activity_id)
|
||||||
|
assert activity.document["object"]["attachment"] == [
|
||||||
|
{
|
||||||
|
"type": "Image",
|
||||||
|
"mediaType": "image/jpeg",
|
||||||
|
"url": "https://coverartarchive.org/release-group/test/front-500",
|
||||||
|
"name": "Cover art for In Rainbows",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_post_has_no_attachment_without_an_album(fed_ctx, posting_user):
|
||||||
|
now = play(posting_user) # no album
|
||||||
|
now_playing.check_and_post(posting_user.id, now + timedelta(seconds=31))
|
||||||
|
[post] = posts_for(posting_user.id)
|
||||||
|
activity = db.session.get(FederationActivity, post.activity_id)
|
||||||
|
assert "attachment" not in activity.document["object"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_post_has_no_attachment_when_art_is_not_found(fed_ctx, posting_user):
|
||||||
|
cache_art("Radiohead", "Some Rare Bootleg", "not_found")
|
||||||
|
now = play(posting_user, album="Some Rare Bootleg")
|
||||||
|
now_playing.check_and_post(posting_user.id, now + timedelta(seconds=31))
|
||||||
|
[post] = posts_for(posting_user.id)
|
||||||
|
activity = db.session.get(FederationActivity, post.activity_id)
|
||||||
|
assert "attachment" not in activity.document["object"]
|
||||||
|
|
||||||
|
|
||||||
def test_post_throttled_within_30_minutes(fed_ctx, posting_user):
|
def test_post_throttled_within_30_minutes(fed_ctx, posting_user):
|
||||||
now = play(posting_user, track="Reckoner")
|
now = play(posting_user, track="Reckoner")
|
||||||
now_playing.check_and_post(posting_user.id, now + timedelta(seconds=31))
|
now_playing.check_and_post(posting_user.id, now + timedelta(seconds=31))
|
||||||
|
|||||||
@@ -182,6 +182,27 @@ def test_note():
|
|||||||
assert doc["tag"] == [{"type": "Hashtag", "name": "#Scrobbler"}]
|
assert doc["tag"] == [{"type": "Hashtag", "name": "#Scrobbler"}]
|
||||||
assert doc["sensitive"] is False
|
assert doc["sensitive"] is False
|
||||||
assert "@context" not in doc # carried by the wrapping Create instead
|
assert "@context" not in doc # carried by the wrapping Create instead
|
||||||
|
assert "attachment" not in doc # omitted entirely, not an empty list, when there's none
|
||||||
|
|
||||||
|
|
||||||
|
def test_note_with_attachment():
|
||||||
|
image = {
|
||||||
|
"type": "Image",
|
||||||
|
"mediaType": "image/jpeg",
|
||||||
|
"url": f"{BASE}/art.jpg",
|
||||||
|
"name": "Cover art",
|
||||||
|
}
|
||||||
|
doc = vocab.note(
|
||||||
|
f"{BASE}/users/alice/posts/1",
|
||||||
|
actor_id=f"{BASE}/users/alice",
|
||||||
|
content_html="<p>Hello</p>",
|
||||||
|
published="2026-01-05T09:00:00Z",
|
||||||
|
url=f"{BASE}/post.html?id=1",
|
||||||
|
to=["FOLLOWERS"],
|
||||||
|
cc=[],
|
||||||
|
attachment=[image],
|
||||||
|
)
|
||||||
|
assert doc["attachment"] == [image]
|
||||||
|
|
||||||
|
|
||||||
def test_create_wraps_a_note_with_the_same_addressing():
|
def test_create_wraps_a_note_with_the_same_addressing():
|
||||||
|
|||||||
@@ -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}
|
active = {s.labels["window"]: s.value for s in families["scrobbler_active_users"].samples}
|
||||||
assert active == {"1h": 1, "24h": 1, "7d": 1}
|
assert active == {"1h": 1, "24h": 1, "7d": 1}
|
||||||
assert families["scrobbler_now_playing_active"].samples[0].value == 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):
|
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 openapi.value == 10
|
||||||
assert "scrobbler_users" in families
|
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
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from scrobbler.extensions import db
|
||||||
|
from scrobbler.models import Scrobble
|
||||||
|
|
||||||
|
NOW = datetime.now(UTC)
|
||||||
|
|
||||||
|
|
||||||
|
def add(
|
||||||
|
user,
|
||||||
|
artist,
|
||||||
|
track,
|
||||||
|
album=None,
|
||||||
|
album_artist=None,
|
||||||
|
track_number=None,
|
||||||
|
duration=None,
|
||||||
|
mbid=None,
|
||||||
|
days_ago=0.0,
|
||||||
|
):
|
||||||
|
db.session.add(
|
||||||
|
Scrobble(
|
||||||
|
user_id=user.id,
|
||||||
|
artist=artist,
|
||||||
|
track=track,
|
||||||
|
album=album,
|
||||||
|
album_artist=album_artist,
|
||||||
|
track_number=track_number,
|
||||||
|
duration=duration,
|
||||||
|
mbid=mbid,
|
||||||
|
played_at=NOW - timedelta(days=days_ago),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def history(user, make_user):
|
||||||
|
# Radiohead: 3 recent plays of Reckoner (mixed capitalisation) + 1 old Nude
|
||||||
|
add(user, "Radiohead", "Reckoner", "In Rainbows", duration=290, mbid="abc", days_ago=0.1)
|
||||||
|
add(user, "radiohead", "reckoner", "in rainbows", duration=290, mbid="abc", days_ago=0.2)
|
||||||
|
add(user, "Radiohead", "Reckoner", None, duration=290, mbid=None, days_ago=0.3)
|
||||||
|
add(user, "Radiohead", "Nude", "In Rainbows", days_ago=100)
|
||||||
|
# Someone else's plays must never show up
|
||||||
|
other = make_user(username="mallory")
|
||||||
|
add(other, "Radiohead", "Reckoner", "In Rainbows", days_ago=0.1)
|
||||||
|
db.session.commit()
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_matches_track_name_case_insensitively(client, auth, history):
|
||||||
|
body = client.get("/api/v1/me/tracks/search?q=reck", headers=auth).get_json()
|
||||||
|
assert [(r["track"], r["artist"], r["playcount"]) for r in body] == [
|
||||||
|
("Reckoner", "Radiohead", 3)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_matches_artist_name(client, auth, history):
|
||||||
|
body = client.get("/api/v1/me/tracks/search?q=radio", headers=auth).get_json()
|
||||||
|
tracks = {r["track"] for r in body}
|
||||||
|
assert tracks == {"Reckoner", "Nude"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_excludes_other_users_and_respects_limit(client, auth, history):
|
||||||
|
body = client.get("/api/v1/me/tracks/search?q=e&limit=1", headers=auth).get_json()
|
||||||
|
assert len(body) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_requires_a_query(client, auth):
|
||||||
|
assert client.get("/api/v1/me/tracks/search", headers=auth).status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
def test_detail_aggregates_metadata_and_merges_capitalisation(client, auth, history):
|
||||||
|
body = client.get("/api/v1/me/tracks?artist=radiohead&track=RECKONER", headers=auth).get_json()
|
||||||
|
assert body["artist"] == "Radiohead"
|
||||||
|
assert body["track"] == "Reckoner"
|
||||||
|
metadata = body["metadata"]
|
||||||
|
assert metadata["album"] == "In Rainbows" # most common non-null value
|
||||||
|
assert metadata["duration"] == 290
|
||||||
|
assert metadata["mbid"] == "abc" # most common non-null value
|
||||||
|
assert metadata["playcount"] == 3
|
||||||
|
assert metadata["first_played_at"] is not None
|
||||||
|
assert metadata["last_played_at"] is not None
|
||||||
|
assert [s["artist"] for s in body["items"]] == ["Radiohead", "radiohead", "Radiohead"]
|
||||||
|
assert body["total"] == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_detail_unknown_track_returns_404(client, auth, history):
|
||||||
|
response = client.get("/api/v1/me/tracks?artist=Nobody&track=Nothing", headers=auth)
|
||||||
|
assert response.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_detail_requires_auth(client):
|
||||||
|
assert client.get("/api/v1/me/tracks?artist=A&track=B").status_code == 401
|
||||||
|
assert client.get("/api/v1/me/tracks/search?q=a").status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_detail_counts_are_daily_and_scoped_to_the_track(client, auth, history):
|
||||||
|
body = client.get("/api/v1/me/tracks?artist=Radiohead&track=Reckoner", headers=auth).get_json()
|
||||||
|
counts = body["counts"]
|
||||||
|
assert len(counts) == 91 # 90 days back plus today
|
||||||
|
# Nude (100 days ago, outside the window) and Mallory's Reckoner plays don't count.
|
||||||
|
assert sum(c["count"] for c in counts) == 3
|
||||||
|
assert counts[-1]["start"] == NOW.date().isoformat()
|
||||||
|
assert counts[-1]["count"] == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_detail_pagination(client, auth, history):
|
||||||
|
first = client.get(
|
||||||
|
"/api/v1/me/tracks?artist=Radiohead&track=Reckoner&limit=2&page=1", headers=auth
|
||||||
|
).get_json()
|
||||||
|
second = client.get(
|
||||||
|
"/api/v1/me/tracks?artist=Radiohead&track=Reckoner&limit=2&page=2", headers=auth
|
||||||
|
).get_json()
|
||||||
|
assert (first["total"], first["total_pages"]) == (3, 2)
|
||||||
|
assert len(first["items"]) == 2
|
||||||
|
assert len(second["items"]) == 1
|
||||||
Reference in new issue
Block a user