pylast end-to-end compatibility test and README
- Serves the app over HTTPS with a throwaway certificate and drives it with pylast: web-auth sign-in, now playing, single and batch scrobbles (non-ASCII too), recent tracks, top artists, play count, and Last.fm error codes surfacing as pylast WSError - README: architecture, running with compose, configuration, connecting players, development workflow, monitoring and CI/CD Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
This commit is contained in:
1 parent
0a1685e80e
commit
d7c6830cf7
3 files changed
+276
No files matched your search
@@ -0,0 +1,142 @@
|
|||||||
|
# Scrobbler
|
||||||
|
|
||||||
|
A self-hosted music scrobbling service. It speaks the **Last.fm (Audioscrobbler 2.0) API**, so players and scrobblers that let you set a custom Last.fm server can use it unchanged. It also has a web UI for your listening history.
|
||||||
|
|
||||||
|
```
|
||||||
|
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** (`src/scrobbler/`): Flask under gunicorn. It is API-only and serves no pages.
|
||||||
|
- **Web UI** (`frontend/`): plain HTML, CSS and JavaScript with no build step. Host it anywhere static files can be served.
|
||||||
|
- **Docs**: OpenAPI at `/api/openapi.json`, Swagger UI at `/api/docs` and ReDoc at `/api/redoc`. A copy of the spec is committed at `docs/openapi.json`.
|
||||||
|
- **Monitoring**: Prometheus metrics, four provisioned Grafana dashboards, and alert rules.
|
||||||
|
|
||||||
|
## Run it
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cp .env.example .env # then set SECRET_KEY and POSTGRES_PASSWORD
|
||||||
|
docker compose up -d # db, api (:5050), ui (:8080)
|
||||||
|
docker compose --profile monitoring up -d # + Prometheus (:9090), Grafana (:3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
Open http://localhost:8080, create an account, then go to **Apps** and create an app for each player.
|
||||||
|
|
||||||
|
To run the published images instead of building them locally:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
SCROBBLER_IMAGE_TAG=main docker compose up -d --no-build
|
||||||
|
```
|
||||||
|
|
||||||
|
The images are `pkgs.daubney.dev/scrobbler/scrobbler-api` and `pkgs.daubney.dev/scrobbler/scrobbler-ui`.
|
||||||
|
|
||||||
|
### Configuration
|
||||||
|
|
||||||
|
| Variable | Used by | Default | Purpose |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `DATABASE_URL` | api | local Postgres | SQLAlchemy URL (`postgresql+psycopg://…`) |
|
||||||
|
| `SECRET_KEY` | api | `dev-insecure-secret` | Flask secret |
|
||||||
|
| `CORS_ORIGINS` | api | `http://localhost:8080` | Comma-separated UI origins allowed to call `/api/v1` |
|
||||||
|
| `UI_BASE_URL` | api | `http://localhost:8080` | Where `/api/auth/` sends users to approve desktop sign-ins |
|
||||||
|
| `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 |
|
||||||
|
| `API_BASE_URL` | ui image | `http://localhost:5050` | API location, written into `config.js` and the CSP |
|
||||||
|
|
||||||
|
In `docker compose` the host ports are set with `DB_PORT`, `API_PORT`, `UI_PORT`, `PROMETHEUS_PORT` and `GRAFANA_PORT`.
|
||||||
|
|
||||||
|
## Connecting a player
|
||||||
|
|
||||||
|
In the player's scrobbling settings, choose a custom or self-hosted Last.fm server and enter:
|
||||||
|
|
||||||
|
- **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 ways of signing in 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/` (which redirects to the web UI), then `auth.getSession`.
|
||||||
|
|
||||||
|
The legacy `authToken = md5(username + md5(password))` form is **not supported**, because checking it would mean storing unsalted password hashes. pylast's `password_hash` option uses that form. With pylast, 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` lists the parameters, rules and example responses for each method.
|
||||||
|
|
||||||
|
Scrobbles are ignored (not rejected) if the artist or track is empty, or if the timestamp is more than 14 days old or more than 5 minutes in the future. Sending the same scrobble again is accepted and stored once, so client retries are safe.
|
||||||
|
|
||||||
|
## Develop
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose up -d db # Postgres with a scrobbler_test database
|
||||||
|
uv sync
|
||||||
|
uv run flask --app scrobbler db upgrade
|
||||||
|
uv run flask --app scrobbler run --port 5050 # API (port 5000 is taken by AirPlay on macOS)
|
||||||
|
python -m http.server 8080 -d frontend # UI
|
||||||
|
uv run pytest # needs TEST_DATABASE_URL (see .env.example)
|
||||||
|
uv run ruff check && uv run ruff format --check
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Migrations**: after changing `models.py`, run `uv run flask --app scrobbler db migrate -m "…"`. CI fails if the models and migrations disagree.
|
||||||
|
- **API docs**: after changing an endpoint, run `uv run flask --app scrobbler openapi write --format=json docs/openapi.json`. A test fails if the committed spec is stale. Every route has to appear in the spec, and every UI route has to declare bearer auth.
|
||||||
|
- **Demo traffic**: `uv run python scripts/generate_traffic.py --minutes 5` sends a realistic mix of scrobbles and errors, so the dashboards have something to show.
|
||||||
|
|
||||||
|
The test suite includes an end-to-end run with [pylast](https://github.com/pylast/pylast) over HTTPS and a real two-worker gunicorn run, which checks that metrics aggregate across workers.
|
||||||
|
|
||||||
|
## Monitoring
|
||||||
|
|
||||||
|
The API serves Prometheus metrics on `METRICS_PORT`, summed across gunicorn workers. All series are prefixed `scrobbler_`:
|
||||||
|
|
||||||
|
- **HTTP**: request rate, errors and latency per endpoint
|
||||||
|
- **Last.fm**: calls, errors by Last.fm error code, and authentication failures by reason
|
||||||
|
- **Scrobbles**: accepted, duplicate and ignored (with the reason), batch size, and how late scrobbles arrive
|
||||||
|
- **Database**: query latency and connection-pool use
|
||||||
|
- **Users**: registered, active, and listening now (computed from the database and cached for 60s)
|
||||||
|
|
||||||
|
Labels never contain users, keys or track names.
|
||||||
|
|
||||||
|
With the `monitoring` profile, Grafana (admin password `GRAFANA_ADMIN_PASSWORD`) has a **Scrobbler** folder with four dashboards:
|
||||||
|
|
||||||
|
- API overview
|
||||||
|
- Last.fm API
|
||||||
|
- Usage
|
||||||
|
- Database
|
||||||
|
|
||||||
|
Alert rules live in `deploy/prometheus/alerts.yml`:
|
||||||
|
|
||||||
|
- API down
|
||||||
|
- 5xx ratio
|
||||||
|
- p95 latency
|
||||||
|
- authentication-failure spike
|
||||||
|
- ignored-scrobble ratio
|
||||||
|
- database pool saturated
|
||||||
|
- Postgres down
|
||||||
|
|
||||||
|
They're evaluated by Prometheus and appear in Grafana. Nothing routes them anywhere yet; that needs Alertmanager.
|
||||||
|
|
||||||
|
Tests check that every metric a dashboard or alert uses actually exists.
|
||||||
|
|
||||||
|
## CI/CD (Gitea Actions)
|
||||||
|
|
||||||
|
- **`ci.yml`** runs on every push and PR:
|
||||||
|
- lint
|
||||||
|
- the migrations check
|
||||||
|
- tests against Postgres
|
||||||
|
- `promtool` checks of the Prometheus config and alert rules
|
||||||
|
- **`publish.yml`** runs on `main` and on `v*` tags. It builds and pushes both images to the ProGet `scrobbler` Docker feed, and uploads the OpenAPI spec, dashboards and Prometheus config to the `scrobbler-assets` feed. On tags it also publishes the wheel to the `scrobbler-python` PyPI feed.
|
||||||
|
- **Notifications**: every workflow run is posted to the `ScrobblingService` topic on notify.daubney.dev.
|
||||||
|
|
||||||
|
The workflows need these repository secrets and variables:
|
||||||
|
|
||||||
|
- **Secrets**: `PKGS_USER`, `PKGS_PASSWORD`, `PKGS_API_KEY`, `NTFY_USER`, `NTFY_PASSWORD`
|
||||||
|
- **Variables**: `PKGS_HOST`, `PKGS_DOCKER_FEED`, `PKGS_PYPI_FEED`, `PKGS_ASSET_FEED`, `NTFY_URL`, `NTFY_TOPIC`
|
||||||
|
|
||||||
|
To release, tag `vX.Y.Z` on `main`. The tag sets the package version.
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
name = "scrobbler"
|
name = "scrobbler"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
description = "Self-hosted, Last.fm-compatible music scrobbling service"
|
description = "Self-hosted, Last.fm-compatible music scrobbling service"
|
||||||
|
readme = "README.md"
|
||||||
requires-python = ">=3.13"
|
requires-python = ">=3.13"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"flask>=3.1.3",
|
"flask>=3.1.3",
|
||||||
|
|||||||
@@ -0,0 +1,133 @@
|
|||||||
|
"""End-to-end compatibility check with pylast, a widely used Last.fm client.
|
||||||
|
|
||||||
|
pylast always talks HTTPS, so the app is served over TLS with a throwaway
|
||||||
|
self-signed certificate that only pylast's SSL context is told to trust.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from urllib.parse import parse_qs, urlsplit
|
||||||
|
|
||||||
|
import pylast
|
||||||
|
import pytest
|
||||||
|
from werkzeug.serving import make_server
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.skipif(shutil.which("openssl") is None, reason="needs openssl")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def tls_files(tmp_path_factory):
|
||||||
|
directory = tmp_path_factory.mktemp("tls")
|
||||||
|
cert, key = directory / "cert.pem", directory / "key.pem"
|
||||||
|
subprocess.run(
|
||||||
|
[
|
||||||
|
"openssl",
|
||||||
|
"req",
|
||||||
|
"-x509",
|
||||||
|
"-newkey",
|
||||||
|
"rsa:2048",
|
||||||
|
"-nodes",
|
||||||
|
"-days",
|
||||||
|
"1",
|
||||||
|
"-subj",
|
||||||
|
"/CN=127.0.0.1",
|
||||||
|
"-addext",
|
||||||
|
"subjectAltName=IP:127.0.0.1",
|
||||||
|
"-keyout",
|
||||||
|
str(key),
|
||||||
|
"-out",
|
||||||
|
str(cert),
|
||||||
|
],
|
||||||
|
check=True,
|
||||||
|
capture_output=True,
|
||||||
|
)
|
||||||
|
return cert, key
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def https_server(app, tls_files):
|
||||||
|
cert, key = tls_files
|
||||||
|
server = make_server("127.0.0.1", 0, app, threaded=True, ssl_context=(str(cert), str(key)))
|
||||||
|
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||||
|
thread.start()
|
||||||
|
pylast.SSL_CONTEXT.load_verify_locations(cafile=str(cert))
|
||||||
|
yield f"127.0.0.1:{server.server_port}"
|
||||||
|
server.shutdown()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def network(https_server, api_app):
|
||||||
|
return pylast._Network(
|
||||||
|
name="Scrobbler",
|
||||||
|
homepage=f"https://{https_server}",
|
||||||
|
ws_server=(https_server, "/2.0/"),
|
||||||
|
api_key=api_app.api_key,
|
||||||
|
api_secret=api_app.shared_secret,
|
||||||
|
session_key="",
|
||||||
|
username="",
|
||||||
|
password_hash="",
|
||||||
|
domain_names={0: https_server},
|
||||||
|
urls={
|
||||||
|
"album": "",
|
||||||
|
"artist": "",
|
||||||
|
"event": "",
|
||||||
|
"country": "",
|
||||||
|
"playlist": "",
|
||||||
|
"tag": "",
|
||||||
|
"track": "",
|
||||||
|
"group": "",
|
||||||
|
"user": "user/%(name)s",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_pylast_end_to_end(network, client, auth, user):
|
||||||
|
# Desktop auth: pylast fetches a token and builds the approval URL...
|
||||||
|
generator = pylast.SessionKeyGenerator(network)
|
||||||
|
auth_url = generator.get_web_auth_url()
|
||||||
|
assert urlsplit(auth_url).path == "/api/auth/"
|
||||||
|
token = parse_qs(urlsplit(auth_url).query)["token"][0]
|
||||||
|
|
||||||
|
# ...the user approves it in the web UI...
|
||||||
|
approved = client.post("/api/v1/tokens/approve", json={"token": token}, headers=auth)
|
||||||
|
assert approved.status_code == 204
|
||||||
|
|
||||||
|
# ...and pylast exchanges it for a session key.
|
||||||
|
network.session_key = generator.get_web_auth_session_key(auth_url)
|
||||||
|
assert len(network.session_key) == 32
|
||||||
|
|
||||||
|
network.update_now_playing(
|
||||||
|
artist="Radiohead", title="Reckoner", album="In Rainbows", duration=290
|
||||||
|
)
|
||||||
|
now = int(time.time())
|
||||||
|
network.scrobble(artist="Radiohead", title="Nude", timestamp=now - 600, album="In Rainbows")
|
||||||
|
network.scrobble_many(
|
||||||
|
[
|
||||||
|
{"artist": "Björk", "title": "Jóga", "timestamp": now - 1200},
|
||||||
|
{"artist": "Portishead", "title": "Roads", "timestamp": now - 1800, "album": "Dummy"},
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
lastfm_user = network.get_user("alice")
|
||||||
|
assert lastfm_user.get_now_playing().title == "Reckoner"
|
||||||
|
recent = lastfm_user.get_recent_tracks(limit=10, now_playing=False)
|
||||||
|
assert [(p.track.artist.name, p.track.title) for p in recent] == [
|
||||||
|
("Radiohead", "Nude"),
|
||||||
|
("Björk", "Jóga"),
|
||||||
|
("Portishead", "Roads"),
|
||||||
|
]
|
||||||
|
assert recent[0].album == "In Rainbows"
|
||||||
|
assert int(recent[0].timestamp) == now - 600
|
||||||
|
|
||||||
|
top = lastfm_user.get_top_artists(period=pylast.PERIOD_7DAYS)
|
||||||
|
assert {item.item.name for item in top} == {"Radiohead", "Björk", "Portishead"}
|
||||||
|
assert lastfm_user.get_playcount() == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_pylast_sees_lastfm_errors(network):
|
||||||
|
network.session_key = "0" * 32
|
||||||
|
with pytest.raises(pylast.WSError) as error:
|
||||||
|
network.scrobble(artist="A", title="T", timestamp=int(time.time()))
|
||||||
|
assert error.value.get_id() == "9"
|
||||||
Reference in new issue
Block a user