11 Commits
Author SHA1 Message Date
matt 25a7ac7a20 Merge pull request 'Feature/song page design' (#2) from feature/song-page-design into main
CI / trigger-deploy (push) Successful in 2s
CI / notify (push) Successful in 5s
CI / assets (push) Successful in 8s
CI / lint (push) Successful in 14s
CI / test (push) Successful in 4m24s
CI / validate-monitoring (push) Successful in 10s
CI / federation-interop (push) Successful in 1m15s
CI / python-package (push) Successful in 17s
CI / images (push) Successful in 32s
Reviewed-on: #2
2026-10-05 15:59:46 +01:00
mattandClaude Sonnet 5 ae24c4a00e Redesign the song page around the dashboard's front-panel look
CI / validate-monitoring (push) Successful in 11s
CI / lint (push) Successful in 17s
CI / federation-interop (push) Successful in 1m40s
CI / test (push) Successful in 3m16s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / trigger-deploy (push) Skipped
CI / validate-monitoring (pull_request) Successful in 9s
CI / notify (push) Successful in 6s
CI / lint (pull_request) Successful in 18s
CI / federation-interop (pull_request) Successful in 1m10s
CI / test (pull_request) Successful in 4m33s
CI / images (pull_request) Skipped
CI / assets (pull_request) Skipped
CI / python-package (pull_request) Skipped
CI / trigger-deploy (pull_request) Skipped
CI / notify (pull_request) Successful in 6s
Previously the song page was a plain heading, a bare metadata list
and a history log. Now it gets its own moment on the glowing
amber display, reusing the dashboard's .panel/.display/.readouts/
.spectrum components verbatim: the track name lit up like a
now-playing display, play/first-played/last-played readouts, and a
90-day per-track play-activity chart.

Extracted the segmented spectrum chart out of dashboard.js into a
shared frontend/js/spectrum.js so both pages use the same renderer;
the dashboard's own output is unchanged.

Verified manually in-browser: the panel renders correctly, an
artist name with a slash round-trips, the not-found and
no-query-params states render into the panel, and the dashboard's
spectrum chart is pixel-for-pixel unchanged after the extraction.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-05 15:36:34 +01:00
mattandClaude Sonnet 5 86bf9fd302 Add daily play counts to the song detail endpoint
Scopes listen_counts() to a single artist/track, the same way
recent() was scoped for song history, so the song page can drive a
per-track activity chart over the last 90 days.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-05 15:33:06 +01:00
matt bef41fc2cc Merge pull request 'Feature/song lookup' (#1) from feature/song-lookup into main
CI / test (push) Successful in 3m45s
CI / lint (push) Successful in 13s
CI / validate-monitoring (push) Successful in 8s
CI / federation-interop (push) Successful in 1m38s
CI / assets (push) Successful in 8s
CI / python-package (push) Successful in 16s
CI / images (push) Successful in 29s
CI / trigger-deploy (push) Successful in 3s
CI / notify (push) Successful in 5s
Reviewed-on: #1
2026-10-05 14:58:37 +01:00
mattandClaude Sonnet 5 e1704b0b54 Apply ruff formatting to test_tracks.py
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 13s
CI / validate-monitoring (pull_request) Successful in 8s
CI / lint (pull_request) Successful in 15s
CI / federation-interop (push) Successful in 1m45s
CI / notify (push) Successful in 6s
CI / test (pull_request) Successful in 4m12s
CI / images (pull_request) Skipped
CI / assets (pull_request) Skipped
CI / python-package (pull_request) Skipped
CI / trigger-deploy (pull_request) Skipped
CI / notify (pull_request) Successful in 5s
CI / federation-interop (pull_request) Successful in 1m39s
CI / test (push) Successful in 4m4s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / trigger-deploy (push) Skipped
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-05 14:21:10 +01:00
mattandClaude Sonnet 5 88b53df909 Add song lookup UI: search a song and view its history + metadata
New song.html shows a song's aggregated metadata and full play
history (paginated), reached from the dashboard via a debounced
search box or by clicking a track in the "Most played" list.

Verified manually in-browser: search, click-through from Most played
(including an artist name with a slash), the not-found and
no-query-params states, and the pager.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-05 14:20:55 +01:00
mattandClaude Sonnet 5 d2f457a84d Add song lookup API: search a track and get its play history + metadata
New GET /api/v1/me/tracks/search finds songs by track or artist name;
GET /api/v1/me/tracks returns a song's aggregated metadata (album,
duration, mbid, etc. - most common non-null value per field) plus its
paginated scrobble history, identified by artist+track query params
since there's no normalized Track model.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-05 14:14:11 +01:00
mattandClaude Sonnet 5 50e2360d14 Fix a Monday-morning-flaky weekly preview test
CI / validate-monitoring (push) Successful in 8s
CI / python-package (push) Successful in 13s
CI / images (push) Successful in 22s
CI / trigger-deploy (push) Successful in 2s
CI / lint (push) Successful in 15s
CI / federation-interop (push) Successful in 1m36s
CI / test (push) Successful in 3m11s
CI / assets (push) Successful in 8s
CI / notify (push) Successful in 5s
test_preview_weekly_reflects_the_week_in_progress hardcoded its
scrobble at noon UTC on "this week's Monday", but the preview window
is [week start, now) - so it failed for real whenever CI ran before
noon UTC on a Monday (as it just did in run 624). Use now - 1 minute
instead, which is always inside the window regardless of what time
the test runs.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-28 11:27:45 +01:00
mattandClaude Sonnet 5 b307b11440 Add an Albums column to the dashboard's Most played pane
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 12s
CI / federation-interop (push) Successful in 1m38s
CI / test (push) Failing after 3m7s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / trigger-deploy (push) Skipped
CI / notify (push) Successful in 5s
Top albums were already available from the API (/me/top/albums, same
shape as artists/tracks) but never surfaced in the UI. Reuses the
existing renderRanking() helper; the charts grid is auto-fit, so the
third column drops in with no CSS changes.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-28 11:19:53 +01:00
mattandClaude Sonnet 5 dfdb5285da Split docs into an admin guide and a user guide
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 16s
CI / federation-interop (push) Successful in 1m41s
CI / test (push) Successful in 3m12s
CI / python-package (push) Skipped
CI / assets (push) Successful in 9s
CI / images (push) Successful in 1m32s
CI / trigger-deploy (push) Skipped
CI / notify (push) Successful in 6s
Renames deploy.md -> admin-guide.md and usage.md -> user-guide.md, and expands
each with content aimed squarely at its audience: the admin guide gains an
upgrade procedure, a restore procedure, an nginx+certbot TLS example, and a
troubleshooting section built from real issues hit during manual testing
(CORS_ORIGINS vs UI_BASE_URL, the sharing nav's browser-cache lag, and
mastodon.social's negative WebFinger caching); the user guide gains a getting-
started section and a matching end-user-facing troubleshooting section.
setup.md is unchanged apart from updated cross-links.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-28 00:23:56 +01:00
mattandClaude Sonnet 5 df8a114a0c ci: trigger ScrobbledDeploy on semver tag releases
CI / validate-monitoring (push) Successful in 8s
CI / federation-interop (push) Successful in 1m8s
CI / lint (push) Successful in 13s
CI / test (push) Successful in 3m15s
CI / python-package (push) Skipped
CI / assets (push) Successful in 9s
CI / images (push) Successful in 34s
CI / trigger-deploy (push) Skipped
CI / notify (push) Successful in 5s
After images publish for a v* tag, call the Gitea API to dispatch
ScrobbledDeploy's deploy workflow with the released version, so a
tagged release automatically redeploys the app tier.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-27 14:17:58 +01:00
19 changed files with 1230 additions and 181 deletions

No files matched your search

+18 -1
View File
@@ -101,6 +101,7 @@ jobs:
runs-on: ubuntu-latest
outputs:
tags: ${{ steps.version.outputs.image_tags }}
version: ${{ steps.version.outputs.version }}
steps:
- uses: actions/checkout@v4
- 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"
--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:
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()
runs-on: ubuntu-latest
steps:
+5 -5
View File
@@ -15,12 +15,12 @@ Prometheus ◄── API :9100/metrics, postgres-exporter ──► Grafana
## Docs
- **[Deploy](docs/deploy.md)** — running a real instance: images, configuration, TLS,
monitoring, backups, releases.
- **[Admin guide](docs/admin-guide.md)** — running a real instance: images,
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,
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/redoc` (a copy is committed at `docs/openapi.json`).
- **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
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.
## Licence
+131 -13
View File
@@ -1,11 +1,11 @@
# Deploying Scrobbler
# Admin guide
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).
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).
## Services
## Architecture
```
players / scrobblers ──► API /2.0/ Last.fm-compatible
@@ -21,7 +21,10 @@ Prometheus ◄── API :9100/metrics, postgres-exporter ──► Grafana
- **`db`**: PostgreSQL.
- With the `monitoring` profile: `prometheus`, `grafana`, `postgres-exporter`.
## Quick start
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
@@ -35,6 +38,9 @@ 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 |
@@ -57,8 +63,10 @@ In `docker compose`, host ports are set with `DB_PORT`, `API_PORT`, `UI_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 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)
@@ -87,13 +95,18 @@ Optional: `FEDERATION_BLOCKED_DOMAINS` (comma-separated, subdomains included),
`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). A minimal Caddy example, proxying
everything to the `ui` container (which itself forwards the fediverse paths to `api`):
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 {
@@ -101,11 +114,39 @@ scrobble.example {
}
```
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`.
directly for `/api/v1`, and make sure `CORS_ORIGINS` includes `https://scrobble.example`
regardless of which layout you pick.
## Monitoring
@@ -121,13 +162,41 @@ With `--profile monitoring`, Grafana (`GRAFANA_ADMIN_PASSWORD`) provisions a
evaluated by Prometheus and visible in Grafana, but nothing routes them anywhere without
Alertmanager.
## Backups
## 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.
## 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
@@ -143,3 +212,52 @@ and on `v*` tags, once lint, tests and the Prometheus config checks all pass:
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.
+267
View File
@@ -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": {
"get": {
"responses": {
@@ -3205,6 +3366,10 @@
"name": "Stats",
"description": "Your listening history and statistics"
},
{
"name": "Tracks",
"description": "Look up a specific song's history and metadata"
},
{
"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."
@@ -3662,6 +3827,108 @@
},
"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": {
"type": "object",
"properties": {
+4 -3
View File
@@ -1,7 +1,8 @@
# Working on Scrobbler
Setting up a local development environment. For running a real instance, see
[deploy.md](deploy.md). For what the service does, see [usage.md](usage.md).
Setting up a local development environment. For running a real instance, see the
[admin guide](admin-guide.md). For what the service does, see the
[user guide](user-guide.md).
## 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,
and `promtool` checks of the Prometheus config and alert rules.
- **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.
Repository secrets: `PKGS_USER`, `PKGS_PASSWORD`, `PKGS_API_KEY`, `NTFY_USER`,
-94
View File
@@ -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.
+119
View File
@@ -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.
+86
View File
@@ -582,6 +582,16 @@ input {
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 -------------------------------------------------------- */
.log {
list-style: none;
@@ -977,3 +987,79 @@ input {
.confirm-off .button-row {
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;
}
+9
View File
@@ -14,6 +14,14 @@
<main id="main">
<h1 class="visually-hidden">Overview</h1>
<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">
<div class="section-head">
<h2 id="charts-title">Most played</h2>
@@ -23,6 +31,7 @@
</div>
<div class="charts">
<div><h3 class="muted">Artists</h3><ol class="ranking" id="top-artists"></ol></div>
<div><h3 class="muted">Albums</h3><ol class="ranking" id="top-albums"></ol></div>
<div><h3 class="muted">Tracks</h3><ol class="ranking" id="top-tracks"></ol></div>
</div>
</section>
+73 -59
View File
@@ -1,6 +1,7 @@
import { api } from "./api.js";
import { errorBox, formatDate, formatDuration, h, num, replace, timeAgo } from "./dom.js";
import { errorBox, formatDuration, h, num, replace, timeAgo } from "./dom.js";
import { signedInPage } from "./layout.js";
import { spectrum } from "./spectrum.js";
const PERIODS = [
["7day", "7 days"],
@@ -9,7 +10,6 @@ const PERIODS = [
["overall", "All time"],
];
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 panel = document.getElementById("panel");
@@ -19,6 +19,7 @@ let progressTimer;
await signedInPage("index.html");
renderPeriodSelector();
initSongSearch();
await Promise.all([loadPanel(), loadTop(currentPeriod()), loadRecent()]).catch(showError);
setInterval(() => refreshDisplay().catch(() => {}), NOW_PLAYING_POLL_MS);
@@ -117,55 +118,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 ------------------------------------------------------------
function currentPeriod() {
@@ -199,15 +151,17 @@ function renderPeriodSelector() {
}
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/albums?period=${period}&limit=10`),
api(`/me/top/tracks?period=${period}&limit=10`),
]);
renderRanking(document.getElementById("top-artists"), artists.items, false);
renderRanking(document.getElementById("top-tracks"), tracks.items, true);
renderRanking(document.getElementById("top-albums"), albums.items, true);
renderRanking(document.getElementById("top-tracks"), tracks.items, true, true);
}
function renderRanking(list, items, withArtist) {
function renderRanking(list, items, withArtist, linkToSong = false) {
if (!items.length) {
replace(list, h("li", { class: "empty" }, "No plays in this period."));
return;
@@ -215,23 +169,83 @@ function renderRanking(list, items, withArtist) {
const max = items[0].playcount;
replace(
list,
items.map((item) =>
h(
items.map((item) => {
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",
{},
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: "meter",
"aria-hidden": "true",
style: `width: calc((100% - 2.75rem) * ${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 ----------------------------------------------------------
async function loadRecent() {
+114
View File
@@ -0,0 +1,114 @@
import { api } from "./api.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 display = h(
"div",
{ class: "display" },
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,
),
);
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"),
);
}
+55
View File
@@ -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"),
),
);
}
+25
View File
@@ -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>
+2 -1
View File
@@ -48,13 +48,14 @@ def init_app(app: Flask) -> None:
},
)
from scrobbler.api import apps, auth, health, imports, sessions, stats, tokens
from scrobbler.api import apps, auth, health, imports, sessions, stats, tokens, tracks
api.register_blueprint(auth.blp, url_prefix="/api/v1/auth")
api.register_blueprint(apps.blp, url_prefix="/api/v1/apps")
api.register_blueprint(sessions.blp, url_prefix="/api/v1/sessions")
api.register_blueprint(tokens.blp, url_prefix="/api/v1/tokens")
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(health.blp)
+56
View File
@@ -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,
}
+37
View File
@@ -139,6 +139,43 @@ class CountSchema(Schema):
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 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):
scrobbles = fields.Integer()
artists = fields.Integer()
+108 -3
View File
@@ -4,7 +4,7 @@ import math
from dataclasses import dataclass
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.models import Scrobble, User
@@ -67,6 +67,16 @@ def _display(column):
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]:
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()
@@ -79,12 +89,18 @@ def recent(
per_page: int = 50,
start: datetime | None = None,
end: datetime | None = None,
artist: str | None = None,
track: str | None = None,
) -> Page:
conditions = [Scrobble.user_id == user.id]
if start:
conditions.append(Scrobble.played_at >= start)
if 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())
rows, total = _paginate(query, page, per_page)
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)
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."""
if bucket not in BUCKETS: # interpolated into SQL below, so allow-list it
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")
query = (
select(bucket_col.label("bucket"), func.count())
.where(*_user_scrobbles(user, period))
.where(*conditions)
.group_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:
row = db.session.execute(
select(
+4 -2
View File
@@ -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):
# 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)
monday = now.date() - timedelta(days=now.weekday())
db.session.add(
Scrobble(
user_id=user.id,
artist="Radiohead",
track="Reckoner",
played_at=datetime(monday.year, monday.month, monday.day, 12, tzinfo=UTC),
played_at=now - timedelta(minutes=1),
)
)
db.session.commit()
+117
View File
@@ -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