4 Commits
Author SHA1 Message Date
mattandClaude Opus 5.5 e40a074a64 Import page in the web UI, worker service and import monitoring
CI / validate-monitoring (push) Successful in 7s
CI / lint (push) Successful in 11s
CI / test (push) Successful in 43s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 5s
- New Import page: upload an export (with upload progress) or, when the
  server has a Last.fm API key, import straight from a Last.fm username;
  jobs list with live progress, counts, errors and cancelling
- docker compose runs the import worker from the API image; the API
  image no longer sets PROMETHEUS_MULTIPROC_DIR (gunicorn.conf.py does,
  and other commands must not inherit multiprocess mode)
- Prometheus scrapes the worker; Usage dashboard gains an Imports row;
  ImportWorkerDown and ImportJobsWaiting alerts
- README and .env.example document imports and LASTFM_API_KEY

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 15:10:15 +01:00
mattandClaude Opus 5.5 eebd7b8730 Imports API: upload exports, pull from Last.fm, follow progress
CI / assets (push) Successful in 8s
CI / images (push) Successful in 31s
CI / notify (push) Successful in 6s
CI / validate-monitoring (push) Successful in 9s
CI / lint (push) Successful in 13s
CI / test (push) Successful in 47s
CI / python-package (push) Skipped
- /api/v1/imports/options lists the available sources; `lastfm` only
  appears when the server has a Last.fm API key
- POST /imports/file (multipart; format detected or forced with
  ?format=), POST /imports/lastfm, GET /imports, GET /imports/{id},
  POST /imports/{id}/cancel
- Upload size limit (IMPORT_MAX_BYTES, default 200 MB) with a 413
- Documented in OpenAPI under the Imports tag

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 15:04:15 +01:00
mattandClaude Opus 5.5 6fc9d91fa2 History imports: parsers, import jobs and the import worker
CI / test (push) Successful in 41s
CI / validate-monitoring (push) Successful in 7s
CI / lint (push) Successful in 10s
CI / assets (push) Successful in 8s
CI / python-package (push) Skipped
CI / images (push) Successful in 28s
CI / notify (push) Successful in 7s
- Import jobs (import_jobs table): uploaded exports stored gzipped,
  processed by `flask imports worker`, which claims jobs with
  SKIP LOCKED, inserts in chunks with progress, supports cancelling and
  re-queues jobs whose worker died
- CSV: lastfm-to-csv (no header) or any header-labelled CSV/TSV with
  comma, semicolon or tab delimiters; several date formats and Unix
  seconds/milliseconds
- JSON: pages of user.getRecentTracks (e.g. lastfm.ghan.nl), a single
  recenttracks response, or a flat list; gzipped files accepted
- Last.fm API pull (only when LASTFM_API_KEY is set): pages through
  user.getRecentTracks up to the job's creation time, rate limited,
  with retries and resume
- Imports keep plays older than 14 days, skip empty/future ones and
  dedupe against existing history
- Import metrics and pending/running job gauges

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 15:02:31 +01:00
mattandClaude Opus 5.5 e29abe05dd Rename the Python distribution to scrobby
CI / assets (push) Successful in 8s
CI / images (push) Successful in 31s
CI / notify (push) Successful in 5s
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 12s
CI / test (push) Successful in 36s
CI / python-package (push) Skipped
`scrobbler` on public PyPI is an unrelated project, so installing with
PyPI as an extra index could pick up the wrong package. The import name
stays `scrobbler`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 14:58:29 +01:00
28 changed files with 2521 additions and 9 deletions

No files matched your search

+3
View File
@@ -13,6 +13,9 @@ UI_BASE_URL=http://localhost:8080
# Prometheus metrics are served on a separate port. # Prometheus metrics are served on a separate port.
METRICS_PORT=9100 METRICS_PORT=9100
# Set to allow importing history straight from Last.fm (https://www.last.fm/api/account/create).
LASTFM_API_KEY=
# docker compose host ports (defaults shown) # docker compose host ports (defaults shown)
API_PORT=5050 API_PORT=5050
UI_PORT=8080 UI_PORT=8080
+23 -2
View File
@@ -12,13 +12,14 @@ Prometheus ◄── API :9100/metrics, postgres-exporter ──► Grafana
- **API** (`src/scrobbler/`): Flask under gunicorn. It is API-only and serves no pages. - **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. - **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`. - **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`.
- **Import worker**: `flask imports worker` imports Last.fm history in the background, from export files or straight from Last.fm.
- **Monitoring**: Prometheus metrics, four provisioned Grafana dashboards, and alert rules. - **Monitoring**: Prometheus metrics, four provisioned Grafana dashboards, and alert rules.
## Run it ## Run it
```sh ```sh
cp .env.example .env # then set SECRET_KEY and POSTGRES_PASSWORD cp .env.example .env # then set SECRET_KEY and POSTGRES_PASSWORD
docker compose up -d # db, api (:5050), ui (:8080) docker compose up -d # db, api (:5050), worker, ui (:8080)
docker compose --profile monitoring up -d # + Prometheus (:9090), Grafana (:3000) docker compose --profile monitoring up -d # + Prometheus (:9090), Grafana (:3000)
``` ```
@@ -44,6 +45,9 @@ The images are `pkgs.daubney.dev/scrobbler/scrobbler-api` and `pkgs.daubney.dev/
| `METRICS_PORT` | api | `9100` | Prometheus metrics port (keep it off the public network) | | `METRICS_PORT` | api | `9100` | Prometheus metrics port (keep it off the public network) |
| `WEB_CONCURRENCY` | api | `2` | gunicorn workers | | `WEB_CONCURRENCY` | api | `2` | gunicorn workers |
| `RUN_MIGRATIONS` | api image | `1` | Apply database migrations on start | | `RUN_MIGRATIONS` | api image | `1` | Apply database migrations on start |
| `LASTFM_API_KEY` | api, worker | *(unset)* | Enables importing straight from Last.fm ([get a key](https://www.last.fm/api/account/create)) |
| `IMPORT_MAX_BYTES` | api | 200 MB | Largest export file accepted |
| `IMPORT_WORKER_METRICS_PORT` | worker | `9101` | The worker's Prometheus metrics port |
| `API_BASE_URL` | ui image | `http://localhost:5050` | API location, written into `config.js` and the CSP | | `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`. In `docker compose` the host ports are set with `DB_PORT`, `API_PORT`, `UI_PORT`, `PROMETHEUS_PORT` and `GRAFANA_PORT`.
@@ -73,6 +77,21 @@ Supported methods:
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. 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.
## Importing Last.fm history
Open **Import** in the web UI. You can import from:
- **An export file**:
- CSV from [lastfm-to-csv](https://benjaminbenben.com/lastfm-to-csv/), with no header row and artist, album, track and 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. This option only appears when the server has `LASTFM_API_KEY` set.
Imports run in the background in the `worker` service. The page shows progress, and an import can be cancelled.
Unlike live scrobbles, imports keep plays of any age. They still skip rows with no artist or track, and plays dated in the future. Plays already in your history are skipped, so importing again is safe.
## Develop ## Develop
```sh ```sh
@@ -81,6 +100,7 @@ uv sync
uv run flask --app scrobbler db upgrade uv run flask --app scrobbler db upgrade
uv run flask --app scrobbler run --port 5050 # API (port 5000 is taken by AirPlay on macOS) 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 python -m http.server 8080 -d frontend # UI
uv run flask --app scrobbler imports worker # process imports
uv run pytest # needs TEST_DATABASE_URL (see .env.example) uv run pytest # needs TEST_DATABASE_URL (see .env.example)
uv run ruff check && uv run ruff format --check uv run ruff check && uv run ruff format --check
``` ```
@@ -113,6 +133,7 @@ With the `monitoring` profile, Grafana (admin password `GRAFANA_ADMIN_PASSWORD`)
Alert rules live in `deploy/prometheus/alerts.yml`: Alert rules live in `deploy/prometheus/alerts.yml`:
- API down - API down
- import worker down, or imports left waiting
- 5xx ratio - 5xx ratio
- p95 latency - p95 latency
- authentication-failure spike - authentication-failure spike
@@ -136,7 +157,7 @@ Everything runs from `.gitea/workflows/ci.yml`:
- **Pushes to `main` and `v*` tags**, once every check has passed: - **Pushes to `main` and `v*` tags**, once every check has passed:
- both images are pushed to the ProGet `scrobbler` Docker feed. `main` builds are tagged `main` and `sha-<commit>`; tags are tagged `<version>`, `latest` and `sha-<commit>`. - both images are pushed to the ProGet `scrobbler` Docker feed. `main` builds are tagged `main` and `sha-<commit>`; tags are tagged `<version>`, `latest` and `sha-<commit>`.
- the OpenAPI spec, dashboards and Prometheus config are uploaded to the `scrobbler-assets` feed under `scrobbler/<version>/` or `scrobbler/main/`. - the OpenAPI spec, dashboards and Prometheus config are uploaded to the `scrobbler-assets` feed under `scrobbler/<version>/` or `scrobbler/main/`.
- **`v*` tags** also publish the wheel and sdist to the `scrobbler-python` PyPI feed. - **`v*` tags** also publish the wheel and sdist to the `scrobbler-python` PyPI feed, as the `scrobby` distribution. The import name is `scrobbler`. (`scrobbler` on public PyPI is an unrelated project.)
- **Every run** is posted to the `ScrobblingService` topic on notify.daubney.dev. - **Every run** is posted to the `ScrobblingService` topic on notify.daubney.dev.
The workflow needs these repository secrets and variables: The workflow needs these repository secrets and variables:
+359
View File
@@ -569,6 +569,365 @@
"w": 12, "w": 12,
"h": 8 "h": 8
} }
},
{
"type": "row",
"title": "Imports",
"id": 13,
"collapsed": false,
"gridPos": {
"x": 0,
"y": 32,
"w": 24,
"h": 1
},
"panels": []
},
{
"type": "stat",
"title": "Imports waiting",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "max(scrobbler_import_jobs{status=\"pending\"})",
"legendFormat": "__auto",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "text",
"value": null
},
{
"color": "orange",
"value": 1
}
]
}
},
"overrides": []
},
"options": {
"reduceOptions": {
"calcs": [
"lastNotNull"
],
"fields": "",
"values": false
},
"colorMode": "value",
"graphMode": "area",
"textMode": "auto",
"justifyMode": "auto"
},
"id": 14,
"gridPos": {
"x": 0,
"y": 33,
"w": 4,
"h": 5
}
},
{
"type": "stat",
"title": "Imports running",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "max(scrobbler_import_jobs{status=\"running\"})",
"legendFormat": "__auto",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"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": 15,
"gridPos": {
"x": 4,
"y": 33,
"w": 4,
"h": 5
}
},
{
"type": "stat",
"title": "Import worker",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "up{job=\"scrobbler-worker\"}",
"legendFormat": "__auto",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "text",
"value": null
}
]
},
"mappings": [
{
"type": "value",
"options": {
"0": {
"text": "Down",
"color": "red"
},
"1": {
"text": "Up",
"color": "green"
}
}
}
]
},
"overrides": []
},
"options": {
"reduceOptions": {
"calcs": [
"lastNotNull"
],
"fields": "",
"values": false
},
"colorMode": "value",
"graphMode": "area",
"textMode": "auto",
"justifyMode": "auto"
},
"id": 16,
"gridPos": {
"x": 8,
"y": 33,
"w": 4,
"h": 5
}
},
{
"type": "timeseries",
"title": "Import jobs finished",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (status) (increase(scrobbler_imports_total{status!=\"created\"}[$__rate_interval]))",
"legendFormat": "{{status}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"custom": {
"lineWidth": 1,
"fillOpacity": 70,
"showPoints": "never",
"spanNulls": true,
"stacking": {
"mode": "normal",
"group": "A"
},
"drawStyle": "bars"
},
"min": 0
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"id": 17,
"gridPos": {
"x": 12,
"y": 33,
"w": 12,
"h": 5
}
},
{
"type": "timeseries",
"title": "Imported rows / min",
"description": "Rows read from exports or Last.fm: imported, already in the user's history, or skipped.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (source, result) (rate(scrobbler_imported_scrobbles_total[$__rate_interval])) * 60",
"legendFormat": "{{source}} {{result}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"custom": {
"lineWidth": 2,
"fillOpacity": 40,
"showPoints": "never",
"spanNulls": true,
"stacking": {
"mode": "normal",
"group": "A"
}
},
"min": 0
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"id": 18,
"gridPos": {
"x": 0,
"y": 38,
"w": 12,
"h": 8
}
},
{
"type": "timeseries",
"title": "Import duration (p95)",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.95, sum by (le, source) (rate(scrobbler_import_duration_seconds_bucket[$__range])))",
"legendFormat": "{{source}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "s",
"custom": {
"lineWidth": 2,
"fillOpacity": 10,
"showPoints": "never",
"spanNulls": true
},
"min": 0
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"id": 19,
"gridPos": {
"x": 12,
"y": 38,
"w": 12,
"h": 8
}
} }
] ]
} }
+16
View File
@@ -57,6 +57,22 @@ groups:
summary: Every pooled database connection is in use summary: Every pooled database connection is in use
description: Workers are running on overflow connections; requests may queue. description: Workers are running on overflow connections; requests may queue.
- alert: ImportWorkerDown
expr: up{job="scrobbler-worker"} == 0
for: 5m
labels: {severity: warning}
annotations:
summary: The import worker isn't running
description: History imports will wait until it's back.
- alert: ImportJobsWaiting
expr: max(scrobbler_import_jobs{status="pending"}) > 0 and max(scrobbler_import_jobs{status="running"}) == 0
for: 15m
labels: {severity: warning}
annotations:
summary: Imports have been waiting for 15 minutes with nothing running
description: The import worker is probably stopped or stuck.
- alert: PostgresDown - alert: PostgresDown
expr: pg_up == 0 expr: pg_up == 0
for: 2m for: 2m
+4
View File
@@ -10,6 +10,10 @@ scrape_configs:
static_configs: static_configs:
- targets: ["api:9100"] - targets: ["api:9100"]
- job_name: scrobbler-worker
static_configs:
- targets: ["worker:9101"]
- job_name: postgres - job_name: postgres
static_configs: static_configs:
- targets: ["postgres-exporter:9187"] - targets: ["postgres-exporter:9187"]
+22 -1
View File
@@ -1,4 +1,4 @@
# Core services: docker compose up # Core services: docker compose up (db, api, worker, ui)
# With monitoring: docker compose --profile monitoring up # With monitoring: docker compose --profile monitoring up
# Published images: SCROBBLER_IMAGE_TAG=main docker compose up --no-build # Published images: SCROBBLER_IMAGE_TAG=main docker compose up --no-build
name: scrobbler name: scrobbler
@@ -33,6 +33,7 @@ services:
UI_BASE_URL: ${UI_BASE_URL:-http://localhost:8080} UI_BASE_URL: ${UI_BASE_URL:-http://localhost:8080}
WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2} WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2}
FORWARDED_ALLOW_IPS: "*" FORWARDED_ALLOW_IPS: "*"
LASTFM_API_KEY: ${LASTFM_API_KEY:-}
ports: ports:
- "${API_PORT:-5050}:8000" - "${API_PORT:-5050}:8000"
expose: expose:
@@ -41,6 +42,26 @@ services:
db: db:
condition: service_healthy condition: service_healthy
# Processes history imports (uploaded exports and pulls from Last.fm).
worker:
image: ${SCROBBLER_REGISTRY:-pkgs.daubney.dev/scrobbler}/scrobbler-api:${SCROBBLER_IMAGE_TAG:-local}
build:
context: .
dockerfile: docker/api.Dockerfile
command: ["flask", "--app", "scrobbler", "imports", "worker"]
environment:
DATABASE_URL: postgresql+psycopg://scrobbler:${POSTGRES_PASSWORD:-scrobbler}@db:5432/scrobbler
SECRET_KEY: ${SECRET_KEY:-change-me}
LASTFM_API_KEY: ${LASTFM_API_KEY:-}
RUN_MIGRATIONS: "0" # the api service applies them
expose:
- "9101" # metrics: internal network only
healthcheck:
disable: true
depends_on:
api:
condition: service_healthy
ui: ui:
image: ${SCROBBLER_REGISTRY:-pkgs.daubney.dev/scrobbler}/scrobbler-ui:${SCROBBLER_IMAGE_TAG:-local} image: ${SCROBBLER_REGISTRY:-pkgs.daubney.dev/scrobbler}/scrobbler-ui:${SCROBBLER_IMAGE_TAG:-local}
build: build:
+2 -1
View File
@@ -15,9 +15,10 @@ RUN useradd --system --uid 10001 --no-create-home scrobbler
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 ./
# PROMETHEUS_MULTIPROC_DIR is set by gunicorn.conf.py for the API only: prometheus_client
# enters multiprocess mode whenever it's set, which other commands (the worker) don't want.
ENV PATH=/app/.venv/bin:$PATH \ ENV PATH=/app/.venv/bin:$PATH \
PYTHONUNBUFFERED=1 \ PYTHONUNBUFFERED=1 \
PROMETHEUS_MULTIPROC_DIR=/tmp/scrobbler-metrics \
BIND=0.0.0.0:8000 \ BIND=0.0.0.0:8000 \
METRICS_PORT=9100 \ METRICS_PORT=9100 \
OPENAPI_DOCS_ENABLED=1 OPENAPI_DOCS_ENABLED=1
+489
View File
@@ -992,6 +992,356 @@
] ]
} }
}, },
"/api/v1/imports/options": {
"get": {
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ImportOptions"
}
}
}
},
"401": {
"description": "Not authenticated",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"default": {
"$ref": "#/components/responses/DEFAULT_ERROR"
}
},
"summary": "What can be imported",
"description": "Pulling from Last.fm is only offered when the server has a Last.fm API key.",
"tags": [
"Imports"
],
"security": [
{
"bearerAuth": []
}
]
}
},
"/api/v1/imports/file": {
"post": {
"parameters": [
{
"in": "query",
"name": "format",
"description": "Detected from the file name and contents when `auto`",
"schema": {
"type": "string",
"default": "auto",
"enum": [
"auto",
"csv",
"json"
]
},
"required": false
}
],
"responses": {
"422": {
"$ref": "#/components/responses/UNPROCESSABLE_CONTENT"
},
"413": {
"description": "File too large",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"400": {
"description": "Empty or unsupported file",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"202": {
"description": "Accepted",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ImportJob"
}
}
}
},
"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/ImportFile"
}
}
}
},
"summary": "Import an export file",
"description": "Accepts lastfm-to-csv CSV files, other CSV/TSV files with a header row, and JSON\nexports of user.getRecentTracks pages. Files may be gzipped.",
"tags": [
"Imports"
],
"security": [
{
"bearerAuth": []
}
]
}
},
"/api/v1/imports/lastfm": {
"post": {
"responses": {
"422": {
"$ref": "#/components/responses/UNPROCESSABLE_CONTENT"
},
"400": {
"description": "Last.fm import isn't configured",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"202": {
"description": "Accepted",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ImportJob"
}
}
}
},
"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/LastfmImport"
}
}
}
},
"summary": "Import from Last.fm",
"description": "Copies a Last.fm user's public scrobble history into your account.",
"tags": [
"Imports"
],
"security": [
{
"bearerAuth": []
}
]
}
},
"/api/v1/imports": {
"get": {
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/ImportJob"
}
}
}
}
},
"401": {
"description": "Not authenticated",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"default": {
"$ref": "#/components/responses/DEFAULT_ERROR"
}
},
"summary": "Your recent imports",
"tags": [
"Imports"
],
"security": [
{
"bearerAuth": []
}
]
}
},
"/api/v1/imports/{job_id}": {
"get": {
"responses": {
"404": {
"description": "No such import",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ImportJob"
}
}
}
},
"401": {
"description": "Not authenticated",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"default": {
"$ref": "#/components/responses/DEFAULT_ERROR"
}
},
"summary": "One import's progress",
"tags": [
"Imports"
],
"security": [
{
"bearerAuth": []
}
]
},
"parameters": [
{
"in": "path",
"name": "job_id",
"required": true,
"schema": {
"type": "integer",
"minimum": 0
}
}
]
},
"/api/v1/imports/{job_id}/cancel": {
"post": {
"responses": {
"404": {
"description": "No such import",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ImportJob"
}
}
}
},
"401": {
"description": "Not authenticated",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"default": {
"$ref": "#/components/responses/DEFAULT_ERROR"
}
},
"summary": "Cancel an import",
"description": "Stops a waiting or running import. Scrobbles already imported are kept.",
"tags": [
"Imports"
],
"security": [
{
"bearerAuth": []
}
]
},
"parameters": [
{
"in": "path",
"name": "job_id",
"required": true,
"schema": {
"type": "integer",
"minimum": 0
}
}
]
},
"/healthz": { "/healthz": {
"get": { "get": {
"responses": { "responses": {
@@ -1529,6 +1879,10 @@
"name": "Stats", "name": "Stats",
"description": "Your listening history and statistics" "description": "Your listening history and statistics"
}, },
{
"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."
},
{ {
"name": "Health", "name": "Health",
"description": "Liveness for load balancers and containers" "description": "Liveness for load balancers and containers"
@@ -1974,6 +2328,141 @@
}, },
"additionalProperties": false "additionalProperties": false
}, },
"ImportOptions": {
"type": "object",
"properties": {
"sources": {
"type": "array",
"description": "`lastfm` is only listed when the server has a Last.fm API key",
"items": {
"type": "string",
"enum": [
"csv",
"json",
"lastfm"
]
}
},
"max_upload_bytes": {
"type": "integer"
}
},
"additionalProperties": false
},
"ImportFile": {
"type": "object",
"properties": {
"file": {
"description": "CSV or JSON export, optionally gzipped",
"type": "string",
"format": "binary"
}
},
"required": [
"file"
],
"additionalProperties": false
},
"ImportJob": {
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"source": {
"type": "string",
"enum": [
"csv",
"json",
"lastfm"
]
},
"status": {
"type": "string",
"enum": [
"pending",
"running",
"completed",
"failed",
"cancelled"
]
},
"filename": {
"type": [
"string",
"null"
]
},
"lastfm_username": {
"type": [
"string",
"null"
]
},
"total": {
"type": [
"integer",
"null"
],
"description": "Rows or tracks to process, once known"
},
"processed": {
"type": "integer"
},
"imported": {
"type": "integer",
"description": "New scrobbles added"
},
"duplicates": {
"type": "integer",
"description": "Already in your history"
},
"skipped": {
"type": "integer",
"description": "No artist/track, bad date, or future"
},
"error": {
"type": [
"string",
"null"
]
},
"created_at": {
"type": "string",
"format": "date-time"
},
"started_at": {
"type": [
"string",
"null"
],
"format": "date-time"
},
"finished_at": {
"type": [
"string",
"null"
],
"format": "date-time"
}
},
"additionalProperties": false
},
"LastfmImport": {
"type": "object",
"properties": {
"username": {
"type": "string",
"minLength": 1,
"maxLength": 64,
"example": "rj"
}
},
"required": [
"username"
],
"additionalProperties": false
},
"Health": { "Health": {
"type": "object", "type": "object",
"properties": { "properties": {
+65
View File
@@ -779,3 +779,68 @@ input {
transition: width 1s linear; transition: width 1s linear;
} }
} }
/* ---- Import --------------------------------------------------------------- */
.import-sources {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 22rem), 1fr));
gap: 2rem 3rem;
margin-bottom: 3rem;
}
.import-sources section + section {
margin-top: 0;
}
.import-sources h2 {
margin-bottom: 0.4rem;
}
.import-sources .muted {
margin-bottom: 1.1rem;
}
.stacked-form .button {
margin-top: 0.25rem;
}
.field input[type="file"] {
padding: 0.45rem;
}
.bar {
height: 6px;
border-radius: 3px;
background: var(--bar);
overflow: hidden;
margin: 0.6rem 0;
}
.bar-fill {
height: 100%;
width: 0;
background: var(--slate);
}
.upload-progress {
margin-bottom: 1rem;
}
.import-status {
margin-top: 0.35rem;
}
.import-running .bar-fill {
background: var(--ok);
}
.import-date {
font-size: var(--step--1);
margin-top: 0.25rem;
}
@media (prefers-reduced-motion: no-preference) {
.bar-fill {
transition: width 0.4s ease-out;
}
}
+53
View File
@@ -0,0 +1,53 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Import · Scrobbler</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
<link rel="stylesheet" href="css/style.css">
<script src="config.js"></script>
<script type="module" src="js/import.js"></script>
</head>
<body>
<header class="site-header" id="site-header"></header>
<main id="main">
<h1 class="page-title">Import history</h1>
<p class="lede">Bring in your Last.fm history. Plays that are already here are skipped, so importing the same history twice is safe.</p>
<div id="messages"></div>
<div class="import-sources">
<section aria-labelledby="file-title">
<h2 id="file-title">From an export file</h2>
<p class="muted">A CSV from lastfm-to-csv, any CSV with artist, track and date columns, or a JSON export of your scrobbles. Gzipped files work too.</p>
<form id="file-form" class="stacked-form">
<div class="field">
<label for="file">Export file</label>
<input id="file" name="file" type="file" accept=".csv,.tsv,.txt,.json,.gz" required>
<span class="hint" id="file-limit"></span>
</div>
<div class="upload-progress" id="upload-progress" hidden>
<div class="bar" aria-hidden="true"><div class="bar-fill"></div></div>
<span class="muted" role="status"></span>
</div>
<button class="button" type="submit">Upload and import</button>
</form>
</section>
<section aria-labelledby="lastfm-title" id="lastfm-section" hidden>
<h2 id="lastfm-title">Straight from Last.fm</h2>
<p class="muted">Copies the public scrobble history of a Last.fm account. Large histories take a few minutes; you can leave this page while it runs.</p>
<form id="lastfm-form" class="stacked-form">
<div class="field">
<label for="lastfm-username">Last.fm username</label>
<input id="lastfm-username" name="username" required maxlength="64" autocomplete="off" spellcheck="false">
</div>
<button class="button" type="submit">Import from Last.fm</button>
</form>
</section>
</div>
<section aria-labelledby="jobs-title">
<h2 id="jobs-title" class="section-head">Your imports</h2>
<ul class="rows" id="jobs"></ul>
</section>
</main>
</body>
</html>
+43
View File
@@ -87,3 +87,46 @@ export function describeError(error) {
} }
return error.message; return error.message;
} }
// Multipart upload with progress (fetch can't report upload progress).
export function upload(path, formData, onProgress) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("POST", `${apiBase}/api/v1${path}`);
const token = getToken();
if (token) xhr.setRequestHeader("Authorization", `Bearer ${token}`);
xhr.upload.addEventListener("progress", (event) => {
if (event.lengthComputable) onProgress?.(event.loaded / event.total);
});
xhr.addEventListener("error", () =>
reject(new ApiError(0, "network", `Can't reach the Scrobbler API at ${apiBase}. Check that it's running.`)),
);
xhr.addEventListener("load", () => {
let data = null;
try {
data = JSON.parse(xhr.responseText);
} catch {
// Not JSON (e.g. a proxy's error page)
}
if (xhr.status === 401) {
setToken(null);
redirectToLogin();
return;
}
if (xhr.status >= 200 && xhr.status < 300) {
resolve(data);
return;
}
const error = data?.error ?? {};
reject(
new ApiError(
xhr.status,
error.code ?? "error",
error.message ?? (xhr.status === 413 ? "That file is too large." : `Upload failed (${xhr.status}).`),
error.details,
),
);
});
xhr.send(formData);
});
}
+164
View File
@@ -0,0 +1,164 @@
import { api, describeError, upload } from "./api.js";
import { errorBox, formatDate, h, num, replace, timeAgo } from "./dom.js";
import { signedInPage } from "./layout.js";
const POLL_MS = 2000;
// Declared before the top-level awaits below, which render jobs straight away.
const STATUS_TEXT = {
pending: "Waiting to start",
running: "Importing",
completed: "Finished",
failed: "Failed",
cancelled: "Cancelled",
};
const messages = document.getElementById("messages");
const jobsList = document.getElementById("jobs");
const fileForm = document.getElementById("file-form");
const lastfmForm = document.getElementById("lastfm-form");
const progress = document.getElementById("upload-progress");
let pollTimer;
await signedInPage("import.html");
try {
const options = await api("/imports/options");
document.getElementById("file-limit").textContent = `Up to ${formatBytes(options.max_upload_bytes)}.`;
document.getElementById("lastfm-section").hidden = !options.sources.includes("lastfm");
} catch (error) {
replace(messages, errorBox(error.message));
}
await refresh();
fileForm.addEventListener("submit", async (event) => {
event.preventDefault();
const file = fileForm.elements.file.files[0];
if (!file) return;
const button = fileForm.querySelector("button");
const fill = progress.querySelector(".bar-fill");
const status = progress.querySelector("[role=status]");
button.disabled = true;
progress.hidden = false;
replace(messages);
try {
const data = new FormData();
data.append("file", file);
await upload("/imports/file", data, (fraction) => {
fill.style.width = `${Math.round(fraction * 100)}%`;
status.textContent = fraction < 1 ? `Uploading ${Math.round(fraction * 100)}%` : "Starting the import";
});
fileForm.reset();
await refresh();
} catch (error) {
replace(messages, errorBox(describeError(error)));
} finally {
button.disabled = false;
progress.hidden = true;
fill.style.width = "0";
}
});
lastfmForm.addEventListener("submit", async (event) => {
event.preventDefault();
const button = lastfmForm.querySelector("button");
button.disabled = true;
replace(messages);
try {
await api("/imports/lastfm", { method: "POST", body: { username: lastfmForm.elements.username.value.trim() } });
lastfmForm.reset();
await refresh();
} catch (error) {
replace(messages, errorBox(describeError(error)));
} finally {
button.disabled = false;
}
});
async function refresh() {
clearTimeout(pollTimer);
let jobs;
try {
jobs = await api("/imports");
} catch (error) {
replace(jobsList, h("li", {}, errorBox(error.message)));
return;
}
if (!jobs.length) {
replace(jobsList, h("li", { class: "empty" }, "Nothing imported yet."));
return;
}
replace(jobsList, jobs.map(jobRow));
if (jobs.some((job) => job.status === "pending" || job.status === "running")) {
pollTimer = setTimeout(refresh, POLL_MS);
}
}
function jobRow(job) {
const title = job.source === "lastfm" ? `Last.fm: ${job.lastfm_username}` : job.filename;
const active = job.status === "pending" || job.status === "running";
const fraction = job.total ? Math.min(1, job.processed / job.total) : 0;
const when = job.finished_at ?? job.started_at ?? job.created_at;
const counts = [
`${num(job.imported)} added`,
job.duplicates ? `${num(job.duplicates)} already in your history` : null,
job.skipped ? `${num(job.skipped)} skipped` : null,
].filter(Boolean);
return h(
"li",
{ class: `import-job import-${job.status}` },
h(
"div",
{ class: "row-head" },
h("span", { class: "row-title" }, title),
active
? h(
"button",
{ type: "button", class: "button button-quiet", onclick: () => cancel(job) },
"Cancel import",
)
: null,
),
h(
"p",
{ class: "import-status" },
h("strong", {}, STATUS_TEXT[job.status] ?? job.status),
` ${timeAgo(when)}`,
job.status === "running" && job.total ? `, ${num(job.processed)} of ${num(job.total)}` : "",
),
active
? h(
"div",
{
class: "bar",
role: "progressbar",
"aria-valuemin": 0,
"aria-valuemax": 100,
"aria-valuenow": Math.round(fraction * 100),
"aria-label": `Progress of ${title}`,
},
h("div", { class: "bar-fill", style: `width: ${fraction * 100}%` }),
)
: null,
job.status === "pending" && Date.now() - new Date(job.created_at) > 60_000
? h("p", { class: "muted" }, "Still waiting? The import worker may not be running on the server.")
: null,
job.processed || job.status === "completed" ? h("p", { class: "muted" }, counts.join(", ")) : null,
job.error ? h("p", { class: "notice notice-error" }, job.error) : null,
h("p", { class: "muted import-date" }, `Started ${formatDate(job.created_at)}`),
);
}
async function cancel(job) {
try {
await api(`/imports/${job.id}/cancel`, { method: "POST" });
} catch (error) {
replace(messages, errorBox(error.message));
}
await refresh();
}
function formatBytes(bytes) {
const mb = bytes / (1024 * 1024);
return mb >= 1 ? `${num(Math.round(mb))} MB` : `${num(Math.round(bytes / 1024))} KB`;
}
+1
View File
@@ -8,6 +8,7 @@ const NAV = [
["history.html", "History"], ["history.html", "History"],
["apps.html", "Apps"], ["apps.html", "Apps"],
["sessions.html", "Sessions"], ["sessions.html", "Sessions"],
["import.html", "Import"],
]; ];
// Renders the header and returns the signed-in user (redirecting if there isn't one). // Renders the header and returns the signed-in user (redirecting if there isn't one).
+1 -1
View File
@@ -1,5 +1,5 @@
[project] [project]
name = "scrobbler" name = "scrobby"
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" readme = "README.md"
+5 -1
View File
@@ -3,7 +3,7 @@
from importlib.metadata import PackageNotFoundError, version from importlib.metadata import PackageNotFoundError, version
try: try:
__version__ = version("scrobbler") # set from the release tag at build time __version__ = version("scrobby") # distribution name; set from the release tag at build time
except PackageNotFoundError: # running from a source tree without installing except PackageNotFoundError: # running from a source tree without installing
__version__ = "0.0.0+unknown" __version__ = "0.0.0+unknown"
@@ -37,6 +37,10 @@ def create_app(config_object=None):
max_age=600, max_age=600,
) )
from scrobbler.cli import imports_cli
app.cli.add_command(imports_cli)
from scrobbler.metrics import db as db_metrics from scrobbler.metrics import db as db_metrics
with app.app_context(): with app.app_context():
+2 -1
View File
@@ -43,13 +43,14 @@ def init_app(app: Flask) -> None:
}, },
) )
from scrobbler.api import apps, auth, health, sessions, stats, tokens from scrobbler.api import apps, auth, health, imports, sessions, stats, tokens
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(imports.blp, url_prefix="/api/v1/imports")
api.register_blueprint(health.blp) api.register_blueprint(health.blp)
from scrobbler.openapi import lastfm from scrobbler.openapi import lastfm
+108
View File
@@ -0,0 +1,108 @@
from flask import current_app, g
from flask_smorest import Blueprint, abort
from scrobbler.api.decorators import authenticated
from scrobbler.schemas import (
ErrorSchema,
ImportFileSchema,
ImportFormatSchema,
ImportJobSchema,
ImportOptionsSchema,
LastfmImportSchema,
)
from scrobbler.services import imports
blp = Blueprint(
"Imports",
__name__,
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."
),
)
@blp.route("/options", methods=["GET"])
@authenticated(blp)
@blp.response(200, ImportOptionsSchema)
def options():
"""What can be imported
Pulling from Last.fm is only offered when the server has a Last.fm API key.
"""
sources = ["csv", "json"] + (["lastfm"] if imports.lastfm_pull_available() else [])
return {"sources": sources, "max_upload_bytes": current_app.config["IMPORT_MAX_BYTES"]}
@blp.route("/file", methods=["POST"])
@authenticated(blp)
@blp.arguments(ImportFileSchema, location="files")
@blp.arguments(ImportFormatSchema, location="query")
@blp.response(202, ImportJobSchema)
@blp.alt_response(400, schema=ErrorSchema, description="Empty or unsupported file")
@blp.alt_response(413, schema=ErrorSchema, description="File too large")
def import_file(files, query):
"""Import an export file
Accepts lastfm-to-csv CSV files, other CSV/TSV files with a header row, and JSON
exports of user.getRecentTracks pages. Files may be gzipped.
"""
upload = files["file"]
raw = upload.read(current_app.config["IMPORT_MAX_BYTES"] + 1)
if len(raw) > current_app.config["IMPORT_MAX_BYTES"]:
abort(413, code="file_too_large", message="That file is larger than this server accepts.")
try:
return imports.create_file_import(g.user, upload.filename, raw, query["format"])
except imports.ImportFailed as err:
abort(400, code=err.code, message=err.message)
@blp.route("/lastfm", methods=["POST"])
@authenticated(blp)
@blp.arguments(LastfmImportSchema)
@blp.response(202, ImportJobSchema)
@blp.alt_response(400, schema=ErrorSchema, description="Last.fm import isn't configured")
def import_lastfm(body):
"""Import from Last.fm
Copies a Last.fm user's public scrobble history into your account.
"""
try:
return imports.create_lastfm_import(g.user, body["username"])
except imports.ImportFailed as err:
abort(400, code=err.code, message=err.message)
@blp.route("", methods=["GET"])
@authenticated(blp)
@blp.response(200, ImportJobSchema(many=True))
def list_imports():
"""Your recent imports"""
return imports.list_jobs(g.user)
@blp.route("/<int:job_id>", methods=["GET"])
@authenticated(blp)
@blp.response(200, ImportJobSchema)
@blp.alt_response(404, schema=ErrorSchema, description="No such import")
def get_import(job_id):
"""One import's progress"""
job = imports.get_job(g.user, job_id)
if job is None:
abort(404, code="not_found", message="No such import")
return job
@blp.route("/<int:job_id>/cancel", methods=["POST"])
@authenticated(blp)
@blp.response(200, ImportJobSchema)
@blp.alt_response(404, schema=ErrorSchema, description="No such import")
def cancel_import(job_id):
"""Cancel an import
Stops a waiting or running import. Scrobbles already imported are kept.
"""
job = imports.cancel_job(g.user, job_id)
if job is None:
abort(404, code="not_found", message="No such import")
return job
+23
View File
@@ -0,0 +1,23 @@
import logging
import click
from flask import current_app
from flask.cli import AppGroup
imports_cli = AppGroup("imports", help="History imports.")
@imports_cli.command("worker")
@click.option("--once", is_flag=True, help="Process waiting jobs, then exit.")
@click.option("--poll", default=2.0, show_default=True, help="Seconds between checks when idle.")
@click.option("--metrics/--no-metrics", default=True, help="Serve Prometheus metrics.")
def worker(once: bool, poll: float, metrics: bool) -> None:
"""Process import jobs: uploaded Last.fm exports and pulls from Last.fm."""
from scrobbler.services.imports import run_worker
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
if metrics:
from scrobbler.metrics.server import start_metrics_server
start_metrics_server(current_app.config["IMPORT_WORKER_METRICS_PORT"])
run_worker(poll_seconds=poll, once=once)
+9
View File
@@ -49,6 +49,15 @@ class Config:
}, },
} }
# History imports. Pulling from Last.fm is offered only when an API key is set
# (get one at https://www.last.fm/api/account/create).
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_REQUEST_INTERVAL = float(os.environ.get("LASTFM_REQUEST_INTERVAL", "0.25"))
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
IMPORT_WORKER_METRICS_PORT = int(os.environ.get("IMPORT_WORKER_METRICS_PORT", "9101"))
# Last.fm behaviour # Last.fm behaviour
AUTH_TOKEN_TTL_SECONDS = 60 * 60 AUTH_TOKEN_TTL_SECONDS = 60 * 60
UI_TOKEN_TTL_DAYS = 30 UI_TOKEN_TTL_DAYS = 30
+19
View File
@@ -97,6 +97,24 @@ registrations_total = Counter(
"User registrations", "User registrations",
) )
# History imports (counted by the import worker)
imports_total = Counter(
"scrobbler_imports_total",
"Import jobs by source and lifecycle event (created, completed, failed, cancelled)",
["source", "status"],
)
imported_scrobbles_total = Counter(
"scrobbler_imported_scrobbles_total",
"Rows read by imports, by outcome",
["source", "result"],
)
import_duration_seconds = Histogram(
"scrobbler_import_duration_seconds",
"Time to process an import job",
["source"],
buckets=(1, 5, 15, 30, 60, 120, 300, 600, 1800, 3600, 7200),
)
# Database # Database
db_query_duration_seconds = Histogram( db_query_duration_seconds = Histogram(
"scrobbler_db_query_duration_seconds", "scrobbler_db_query_duration_seconds",
@@ -124,4 +142,5 @@ COLLECTED = {
"users": "scrobbler_users", "users": "scrobbler_users",
"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",
} }
+20 -1
View File
@@ -38,7 +38,20 @@ class DatabaseStatsCollector(Collector):
now_playing = conn.execute( now_playing = conn.execute(
text("SELECT count(*) FROM now_playing WHERE expires_at > now()") text("SELECT count(*) FROM now_playing WHERE expires_at > now()")
).scalar_one() ).scalar_one()
return {"users": users, "active": active, "now_playing": now_playing} import_jobs = dict(
conn.execute(
text(
"SELECT status, count(*) FROM import_jobs "
"WHERE status IN ('pending', 'running') GROUP BY status"
)
).all()
)
return {
"users": users,
"active": active,
"now_playing": now_playing,
"import_jobs": {s: import_jobs.get(s, 0) for s in ("pending", "running")},
}
def values(self) -> dict | None: def values(self) -> dict | None:
with self._lock: with self._lock:
@@ -66,3 +79,9 @@ class DatabaseStatsCollector(Collector):
"Users currently playing a track", "Users currently playing a track",
value=values["now_playing"], value=values["now_playing"],
) )
jobs = GaugeMetricFamily(
COLLECTED["import_jobs"], "Import jobs waiting or in progress", labels=["status"]
)
for status, count in values["import_jobs"].items():
jobs.add_metric([status], count)
yield jobs
@@ -0,0 +1,58 @@
"""import jobs
Revision ID: e7fb730bac15
Revises: d6113d27cce6
Create Date: 2026-09-25 14:59:23.375055
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'e7fb730bac15'
down_revision = 'd6113d27cce6'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('import_jobs',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('source', sa.String(length=16), nullable=False),
sa.Column('status', sa.String(length=16), nullable=False),
sa.Column('filename', sa.String(length=255), nullable=True),
sa.Column('lastfm_username', sa.String(length=64), nullable=True),
sa.Column('payload', sa.LargeBinary(), nullable=True),
sa.Column('total', sa.Integer(), nullable=True),
sa.Column('processed', sa.Integer(), nullable=False),
sa.Column('imported', sa.Integer(), nullable=False),
sa.Column('duplicates', sa.Integer(), nullable=False),
sa.Column('skipped', sa.Integer(), nullable=False),
sa.Column('error', sa.Text(), nullable=True),
sa.Column('next_page', sa.Integer(), nullable=True),
sa.Column('pull_until', sa.DateTime(timezone=True), nullable=True),
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
sa.Column('started_at', sa.DateTime(timezone=True), nullable=True),
sa.Column('finished_at', sa.DateTime(timezone=True), nullable=True),
sa.Column('heartbeat_at', sa.DateTime(timezone=True), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
with op.batch_alter_table('import_jobs', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_import_jobs_status'), ['status'], unique=False)
batch_op.create_index(batch_op.f('ix_import_jobs_user_id'), ['user_id'], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('import_jobs', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_import_jobs_user_id'))
batch_op.drop_index(batch_op.f('ix_import_jobs_status'))
op.drop_table('import_jobs')
# ### end Alembic commands ###
+31
View File
@@ -5,6 +5,7 @@ from sqlalchemy import (
ForeignKey, ForeignKey,
Index, Index,
Integer, Integer,
LargeBinary,
String, String,
Text, Text,
UniqueConstraint, UniqueConstraint,
@@ -126,3 +127,33 @@ class NowPlaying(db.Model):
duration: Mapped[int | None] = mapped_column(Integer) duration: Mapped[int | None] = mapped_column(Integer)
started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True)) expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
class ImportJob(db.Model):
"""A history import: an uploaded export file, or a pull from the Last.fm API.
Created by the API and processed by the import worker (`flask imports worker`).
"""
__tablename__ = "import_jobs"
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
source: Mapped[str] = mapped_column(String(16)) # csv, json or lastfm
status: Mapped[str] = mapped_column(String(16), default="pending", index=True)
filename: Mapped[str | None] = mapped_column(String(255))
lastfm_username: Mapped[str | None] = mapped_column(String(64))
payload: Mapped[bytes | None] = mapped_column(LargeBinary, deferred=True) # gzipped upload
total: Mapped[int | None] = mapped_column(Integer) # rows or tracks, once known
processed: Mapped[int] = mapped_column(Integer, default=0)
imported: Mapped[int] = mapped_column(Integer, default=0)
duplicates: Mapped[int] = mapped_column(Integer, default=0)
skipped: Mapped[int] = mapped_column(Integer, default=0)
error: Mapped[str | None] = mapped_column(Text)
# Last.fm pulls resume from here, and only fetch scrobbles before pull_until.
next_page: Mapped[int | None] = mapped_column(Integer)
pull_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
started_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))
+53
View File
@@ -1,6 +1,7 @@
"""Marshmallow schemas for the /api/v1 JSON API. They drive both request """Marshmallow schemas for the /api/v1 JSON API. They drive both request
validation and the generated OpenAPI document.""" validation and the generated OpenAPI document."""
from flask_smorest.fields import Upload
from marshmallow import Schema, fields, validate from marshmallow import Schema, fields, validate
@@ -143,3 +144,55 @@ class SummarySchema(Schema):
artists = fields.Integer() artists = fields.Integer()
tracks = fields.Integer() tracks = fields.Integer()
first_scrobble_at = fields.DateTime(allow_none=True) first_scrobble_at = fields.DateTime(allow_none=True)
IMPORT_SOURCES = ["csv", "json", "lastfm"]
IMPORT_STATUSES = ["pending", "running", "completed", "failed", "cancelled"]
class ImportOptionsSchema(Schema):
sources = fields.List(
fields.String(validate=validate.OneOf(IMPORT_SOURCES)),
metadata={"description": "`lastfm` is only listed when the server has a Last.fm API key"},
)
max_upload_bytes = fields.Integer()
class ImportJobSchema(Schema):
id = fields.Integer()
source = fields.String(validate=validate.OneOf(IMPORT_SOURCES))
status = fields.String(validate=validate.OneOf(IMPORT_STATUSES))
filename = fields.String(allow_none=True)
lastfm_username = fields.String(allow_none=True)
total = fields.Integer(
allow_none=True, metadata={"description": "Rows or tracks to process, once known"}
)
processed = fields.Integer()
imported = fields.Integer(metadata={"description": "New scrobbles added"})
duplicates = fields.Integer(metadata={"description": "Already in your history"})
skipped = fields.Integer(metadata={"description": "No artist/track, bad date, or future"})
error = fields.String(allow_none=True)
created_at = fields.DateTime()
started_at = fields.DateTime(allow_none=True)
finished_at = fields.DateTime(allow_none=True)
class ImportFileSchema(Schema):
file = Upload(
required=True,
metadata={"description": "CSV or JSON export, optionally gzipped"},
)
class ImportFormatSchema(Schema):
format = fields.String(
load_default="auto",
validate=validate.OneOf(["auto", "csv", "json"]),
metadata={"description": "Detected from the file name and contents when `auto`"},
)
class LastfmImportSchema(Schema):
username = fields.String(
required=True, validate=validate.Length(min=1, max=64), metadata={"example": "rj"}
)
+569
View File
@@ -0,0 +1,569 @@
"""Importing listening history: Last.fm export files and pulls from the Last.fm API.
Jobs are created by the API and processed by the import worker (`flask imports
worker`), because large histories take longer than a request should.
Supported inputs:
* CSV from lastfm-to-csv (no header: artist, album, track, date) or any CSV/TSV
with a header naming the columns (artist, album, track/name/title, and one of
uts/timestamp/date/utc_time). Comma, semicolon and tab delimiters are detected.
* JSON: an array of user.getRecentTracks pages (e.g. lastfm.ghan.nl exports),
a single {"recenttracks": ...} response, or a flat list of track objects.
* The Last.fm API: user.getRecentTracks for a Last.fm username, paged, rate
limited and resumable.
"""
import csv
import gzip
import io
import json
import logging
import time
import urllib.error
import urllib.parse
import urllib.request
from collections.abc import Iterable, Iterator
from datetime import UTC, datetime, timedelta
from flask import current_app
from sqlalchemy import update
from sqlalchemy.dialects.postgresql import insert
from scrobbler import metrics
from scrobbler.extensions import db
from scrobbler.models import ImportJob, Scrobble, User
from scrobbler.services.scrobbles import MAX_TEXT, TrackInput
log = logging.getLogger(__name__)
SOURCES = ("csv", "json", "lastfm")
ACTIVE = ("pending", "running")
CHUNK = 1000
GZIP_MAGIC = b"\x1f\x8b"
class ImportFailed(ValueError):
"""An import can't be started or its input can't be read."""
def __init__(self, code: str, message: str):
self.code, self.message = code, message
super().__init__(message)
def _now() -> datetime:
return datetime.now(UTC)
# --- Parsing -----------------------------------------------------------------------
_DATE_FORMATS = (
"%d %b %Y %H:%M", # lastfm-to-csv: "31 Jan 2021 14:05"
"%d %b %Y, %H:%M", # Last.fm API "#text": "31 Jan 2021, 14:05"
"%Y-%m-%d %H:%M:%S",
"%Y-%m-%dT%H:%M:%S",
"%Y-%m-%dT%H:%M:%SZ",
"%Y-%m-%d %H:%M",
)
def parse_time(value: str | int | None) -> int | None:
"""Unix seconds from a Unix time (seconds or milliseconds) or a UTC date string."""
if value is None:
return None
text = str(value).strip()
if not text:
return None
if text.isdigit():
number = int(text)
return number // 1000 if number > 10**11 else number
try:
parsed = datetime.fromisoformat(text.replace("Z", "+00:00"))
return int((parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)).timestamp())
except ValueError:
pass
for fmt in _DATE_FORMATS:
try:
return int(datetime.strptime(text, fmt).replace(tzinfo=UTC).timestamp())
except ValueError:
continue
return None
def _clean(value) -> str | None:
if isinstance(value, dict): # {"#text": "...", "mbid": "..."} or {"name": "..."}
value = value.get("#text", value.get("name"))
text = ("" if value is None else str(value)).strip()
return text[:MAX_TEXT] or None
def _mbid(value) -> str | None:
mbid = _clean(value)
return mbid if mbid and len(mbid) <= 36 else None
_HEADER_ALIASES = {
"artist": {"artist", "artist_name", "artistname"},
"album": {"album", "album_name", "albumname"},
"track": {"track", "track_name", "trackname", "name", "title", "song"},
"time": {"uts", "timestamp", "date", "utc_time", "time", "played_at", "datetime", "date#"},
"album_artist": {"album_artist", "albumartist"},
"mbid": {"track_mbid", "mbid"},
}
def _header_map(row: list[str]) -> dict[str, int] | None:
mapping: dict[str, int] = {}
for index, cell in enumerate(row):
key = cell.strip().lower().replace(" ", "_")
for field, aliases in _HEADER_ALIASES.items():
if key in aliases and field not in mapping:
mapping[field] = index
return mapping if {"artist", "track", "time"} <= mapping.keys() else None
def parse_csv(text: str) -> Iterator[TrackInput | None]:
"""Yields a TrackInput per row, or None for rows that can't be used."""
sample = text[:4096]
try:
dialect = csv.Sniffer().sniff(sample, delimiters=",;\t")
except csv.Error:
dialect = csv.excel
reader = csv.reader(io.StringIO(text), dialect)
first = next(reader, None)
if first is None:
return
columns = _header_map(first)
rows: Iterable[list[str]] = reader
if columns is None:
# lastfm-to-csv has no header: artist, album, track, date
columns = {"artist": 0, "album": 1, "track": 2, "time": 3}
rows = _prepend(first, reader)
def cell(row: list[str], field: str) -> str | None:
index = columns.get(field)
return row[index] if index is not None and index < len(row) else None
for row in rows:
if not any(c.strip() for c in row):
continue
timestamp = parse_time(cell(row, "time"))
if timestamp is None:
yield None
continue
yield TrackInput(
artist=_clean(cell(row, "artist")) or "",
track=_clean(cell(row, "track")) or "",
album=_clean(cell(row, "album")),
album_artist=_clean(cell(row, "album_artist")),
mbid=_mbid(cell(row, "mbid")),
timestamp=timestamp,
)
def _prepend(first, rest):
yield first
yield from rest
def _track_from_json(track: dict) -> TrackInput | None:
"""A track object as found in user.getRecentTracks (compact or extended)."""
if not isinstance(track, dict):
return None
if (track.get("@attr") or {}).get("nowplaying") == "true":
return None # no timestamp: it's still playing
date = track.get("date")
timestamp = parse_time(
date.get("uts") or date.get("#text")
if isinstance(date, dict)
else date or track.get("uts") or track.get("timestamp")
)
if timestamp is None:
return None
return TrackInput(
artist=_clean(track.get("artist")) or "",
track=_clean(track.get("name") or track.get("track") or track.get("title")) or "",
album=_clean(track.get("album")),
mbid=_mbid(track.get("mbid")),
timestamp=timestamp,
)
def _json_tracks(data) -> Iterator[dict]:
if isinstance(data, dict):
if "recenttracks" in data:
data = data["recenttracks"]
if "track" in data:
tracks = data["track"]
yield from tracks if isinstance(tracks, list) else [tracks]
return
raise ImportFailed("unrecognised_json", "The JSON doesn't look like a Last.fm export.")
if isinstance(data, list):
for item in data:
if isinstance(item, dict) and (
"recenttracks" in item or isinstance(item.get("track"), list | dict)
):
yield from _json_tracks(item) # a page of tracks
else:
yield item # a flat list of tracks
return
raise ImportFailed("unrecognised_json", "The JSON doesn't look like a Last.fm export.")
def parse_json(text: str) -> Iterator[TrackInput | None]:
try:
data = json.loads(text)
except json.JSONDecodeError as err:
raise ImportFailed("invalid_json", f"The file isn't valid JSON: {err.msg}") from err
for track in _json_tracks(data):
yield _track_from_json(track)
def detect_format(filename: str | None, raw: bytes) -> str:
name = (filename or "").lower().removesuffix(".gz")
if name.endswith(".json"):
return "json"
if name.endswith((".csv", ".tsv", ".txt")):
return "csv"
if raw[:2] == GZIP_MAGIC:
with gzip.open(io.BytesIO(raw)) as unzipped:
raw = unzipped.read(64)
return "json" if raw.lstrip()[:1] in (b"[", b"{") else "csv"
def _decode(raw: bytes) -> str:
if raw[:2] == GZIP_MAGIC: # a gzipped export
raw = gzip.decompress(raw)
for encoding in ("utf-8-sig", "utf-16"):
try:
return raw.decode(encoding)
except UnicodeDecodeError:
continue
return raw.decode("latin-1")
# --- Jobs ----------------------------------------------------------------------------
def lastfm_pull_available() -> bool:
return bool(current_app.config.get("LASTFM_API_KEY"))
def create_file_import(
user: User, filename: str | None, raw: bytes, fmt: str = "auto"
) -> ImportJob:
if not raw.strip():
raise ImportFailed("empty_file", "The file is empty.")
source = detect_format(filename, raw) if fmt == "auto" else fmt
if source not in ("csv", "json"):
raise ImportFailed("unsupported_format", "Upload a CSV or JSON export.")
job = ImportJob(
user_id=user.id,
source=source,
filename=(filename or "upload")[:255],
payload=gzip.compress(raw, compresslevel=6),
)
db.session.add(job)
db.session.commit()
metrics.imports_total.labels(source=source, status="created").inc()
return job
def create_lastfm_import(user: User, lastfm_username: str) -> ImportJob:
if not lastfm_pull_available():
raise ImportFailed(
"lastfm_not_configured", "Importing from Last.fm isn't set up on this server."
)
username = lastfm_username.strip()
if not username:
raise ImportFailed("missing_username", "Enter your Last.fm username.")
job = ImportJob(
user_id=user.id,
source="lastfm",
lastfm_username=username[:64],
next_page=1,
pull_until=_now(),
)
db.session.add(job)
db.session.commit()
metrics.imports_total.labels(source="lastfm", status="created").inc()
return job
def list_jobs(user: User, limit: int = 20) -> list[ImportJob]:
return list(
db.session.scalars(
db.select(ImportJob)
.filter_by(user_id=user.id)
.order_by(ImportJob.created_at.desc())
.limit(limit)
)
)
def get_job(user: User, job_id: int) -> ImportJob | None:
return db.session.scalar(db.select(ImportJob).filter_by(id=job_id, user_id=user.id))
def cancel_job(user: User, job_id: int) -> ImportJob | None:
job = get_job(user, job_id)
if job is None:
return None
if job.status in ACTIVE:
job.status = "cancelled"
job.finished_at = _now()
job.payload = None
db.session.commit()
metrics.imports_total.labels(source=job.source, status="cancelled").inc()
return job
# --- Storing -------------------------------------------------------------------------
def _usable(item: TrackInput | None, now: datetime) -> bool:
"""Imports keep old plays (that's the point), but not empty or future ones."""
if item is None or not item.artist or not item.track:
return False
limit = current_app.config["SCROBBLE_MAX_FUTURE_SECONDS"]
return datetime.fromtimestamp(item.timestamp, UTC) - now <= timedelta(seconds=limit)
def store_chunk(job: ImportJob, items: list[TrackInput | None]) -> None:
"""Insert one chunk and update the job's counters (the caller commits)."""
now = _now()
rows, seen = [], set()
skipped = repeated = 0
for item in items:
if not _usable(item, now):
skipped += 1
continue
played_at = datetime.fromtimestamp(item.timestamp, UTC)
key = (played_at, item.artist, item.track)
if key in seen: # the same play twice in one chunk: ON CONFLICT can't handle that
repeated += 1
continue
seen.add(key)
rows.append(
{
"user_id": job.user_id,
"artist": item.artist,
"track": item.track,
"album": item.album,
"album_artist": item.album_artist,
"mbid": item.mbid,
"played_at": played_at,
"submitted_at": now,
}
)
inserted = 0
if rows:
inserted = len(
db.session.execute(
insert(Scrobble)
.values(rows)
.on_conflict_do_nothing(constraint="uq_scrobbles_dedupe")
.returning(Scrobble.id)
).all()
)
duplicates = len(rows) - inserted + repeated
job.imported += inserted
job.duplicates += duplicates
job.skipped += skipped
job.processed += len(items)
job.heartbeat_at = now
counter = metrics.imported_scrobbles_total
counter.labels(source=job.source, result="imported").inc(inserted)
counter.labels(source=job.source, result="duplicate").inc(duplicates)
counter.labels(source=job.source, result="skipped").inc(skipped)
def _cancelled(job: ImportJob) -> bool:
status = db.session.scalar(db.select(ImportJob.status).filter_by(id=job.id))
return status == "cancelled"
def _chunks(items: Iterable, size: int = CHUNK) -> Iterator[list]:
chunk = []
for item in items:
chunk.append(item)
if len(chunk) == size:
yield chunk
chunk = []
if chunk:
yield chunk
def _process_file(job: ImportJob) -> None:
text = _decode(gzip.decompress(job.payload))
parse = parse_json if job.source == "json" else parse_csv
items = list(parse(text))
job.total = len(items)
db.session.commit()
for chunk in _chunks(items):
if _cancelled(job):
return
store_chunk(job, chunk)
db.session.commit()
# --- Last.fm API pull ------------------------------------------------------------------
class LastfmClient:
def __init__(self, api_url: str, api_key: str, interval: float, retries: int = 4):
self.api_url, self.api_key = api_url, api_key
self.interval, self.retries = interval, retries
self._last_call = 0.0
def recent_tracks(self, username: str, page: int, until: datetime) -> dict:
params = {
"method": "user.getRecentTracks",
"user": username,
"api_key": self.api_key,
"format": "json",
"limit": "200",
"page": str(page),
"to": str(int(until.timestamp())),
}
url = f"{self.api_url}?{urllib.parse.urlencode(params)}"
for attempt in range(self.retries + 1):
wait = self.interval - (time.monotonic() - self._last_call)
if wait > 0:
time.sleep(wait)
self._last_call = time.monotonic()
try:
with urllib.request.urlopen(url, timeout=30) as response:
body = json.load(response)
except urllib.error.HTTPError as err:
body = _json_or_none(err)
code = (body or {}).get("error")
if code == 6: # "User not found"
raise ImportFailed(
"lastfm_user_not_found", "No Last.fm user with that name."
) from err
if code in (10, 26):
raise ImportFailed(
"lastfm_key_rejected", "Last.fm rejected this server's API key."
) from err
if attempt == self.retries or (err.code < 500 and code != 29):
raise ImportFailed(
"lastfm_error", f"Last.fm returned an error ({err.code})."
) from err
except (urllib.error.URLError, TimeoutError) as err:
if attempt == self.retries:
raise ImportFailed("lastfm_unreachable", "Couldn't reach Last.fm.") from err
else:
if "error" in body:
raise ImportFailed(
"lastfm_error", body.get("message", "Last.fm returned an error.")
)
return body
time.sleep(min(30, 2**attempt)) # back off before retrying
raise ImportFailed("lastfm_unreachable", "Couldn't reach Last.fm.")
def _json_or_none(err: urllib.error.HTTPError) -> dict | None:
try:
return json.load(err)
except (json.JSONDecodeError, ValueError):
return None
def _process_lastfm(job: ImportJob) -> None:
config = current_app.config
client = LastfmClient(
config["LASTFM_API_URL"], config["LASTFM_API_KEY"], config["LASTFM_REQUEST_INTERVAL"]
)
page = job.next_page or 1
while True:
if _cancelled(job):
return
body = client.recent_tracks(job.lastfm_username, page, job.pull_until)
recent = body.get("recenttracks", {})
attrs = recent.get("@attr", {})
total_pages = int(attrs.get("totalPages") or 0)
job.total = int(attrs.get("total") or 0)
tracks = list(_json_tracks(body))
store_chunk(job, [_track_from_json(t) for t in tracks])
job.next_page = page + 1
db.session.commit()
if page >= total_pages or not tracks:
return
page += 1
# --- Worker ----------------------------------------------------------------------------
def claim_next_job() -> ImportJob | None:
"""Atomically take the oldest pending job (safe with several workers)."""
job = db.session.scalar(
db.select(ImportJob)
.filter_by(status="pending")
.order_by(ImportJob.created_at)
.limit(1)
.with_for_update(skip_locked=True)
)
if job is None:
db.session.rollback()
return None
job.status = "running"
job.started_at = job.started_at or _now()
job.heartbeat_at = _now()
db.session.commit()
return job
def requeue_stalled(max_age: timedelta = timedelta(minutes=5)) -> int:
"""Put back jobs whose worker died mid-way (no heartbeat for a while)."""
result = db.session.execute(
update(ImportJob)
.where(ImportJob.status == "running", ImportJob.heartbeat_at < _now() - max_age)
.values(status="pending")
)
db.session.commit()
return result.rowcount
def process_job(job: ImportJob) -> None:
started = time.perf_counter()
try:
if job.source == "lastfm":
_process_lastfm(job)
else:
_process_file(job)
except ImportFailed as err:
db.session.rollback()
_finish(job, "failed", err.message)
except Exception:
log.exception("import job %s failed", job.id)
db.session.rollback()
_finish(
job, "failed", "The import failed unexpectedly. Try again, or check the server logs."
)
else:
if not _cancelled(job):
_finish(job, "completed")
metrics.import_duration_seconds.labels(source=job.source).observe(time.perf_counter() - started)
def _finish(job: ImportJob, status: str, error: str | None = None) -> None:
job = db.session.get(ImportJob, job.id) # reload after a rollback
job.status, job.error, job.finished_at = status, error, _now()
job.payload = None
db.session.commit()
metrics.imports_total.labels(source=job.source, status=status).inc()
def run_worker(poll_seconds: float = 2.0, once: bool = False) -> None:
requeue_stalled()
while True:
job = claim_next_job()
if job is not None:
log.info("import job %s (%s) for user %s started", job.id, job.source, job.user_id)
process_job(job)
log.info("import job %s finished: %s", job.id, job.status)
continue
if once:
return
time.sleep(poll_seconds)
+271
View File
@@ -0,0 +1,271 @@
import gzip
import json
import threading
from datetime import UTC, datetime, timedelta
import pytest
from werkzeug.serving import make_server
from scrobbler.extensions import db
from scrobbler.models import ImportJob, Scrobble
from scrobbler.services import imports
from scrobbler.services.imports import ImportFailed, parse_csv, parse_json, parse_time
NOW = datetime.now(UTC).replace(microsecond=0)
def ts(days_ago: float) -> int:
return int((NOW - timedelta(days=days_ago)).timestamp())
def fmt(days_ago: float, pattern="%d %b %Y %H:%M") -> str:
return (NOW - timedelta(days=days_ago)).strftime(pattern)
def stored(user):
return db.session.scalars(
db.select(Scrobble).filter_by(user_id=user.id).order_by(Scrobble.played_at.desc())
).all()
def run_all():
imports.run_worker(once=True)
db.session.expire_all()
# --- Parsing ---------------------------------------------------------------------------
@pytest.mark.parametrize(
("value", "expected"),
[
("1700000000", 1700000000),
("1700000000000", 1700000000), # milliseconds
("14 Nov 2023 22:13", 1700000000 - 20),
("14 Nov 2023, 22:13", 1700000000 - 20),
("2023-11-14T22:13:20Z", 1700000000),
("2023-11-14 22:13:20", 1700000000),
("not a date", None),
("", None),
],
)
def test_parse_time(value, expected):
assert parse_time(value) == expected
def test_lastfm_to_csv_without_header():
text = f'Radiohead,In Rainbows,Reckoner,{fmt(400)}\n"Björk, Guðmundsdóttir",,Jóga,{fmt(1)}\n'
first, second = parse_csv(text)
assert (first.artist, first.album, first.track) == ("Radiohead", "In Rainbows", "Reckoner")
assert first.timestamp == ts(400) - ts(400) % 60
assert (second.artist, second.album) == ("Björk, Guðmundsdóttir", None)
def test_csv_with_header_semicolons_and_extra_columns():
text = (
"uts;utc_time;artist;artist_mbid;album;album_mbid;track;track_mbid\n"
f"{ts(3)};x;Portishead;;Dummy;;Roads;9b3c1a2e-0000-0000-0000-000000000000\n"
f"bad;x;Portishead;;Dummy;;Glory Box;\n"
)
good, bad = parse_csv(text)
assert (good.artist, good.track, good.album, good.timestamp) == (
"Portishead",
"Roads",
"Dummy",
ts(3),
)
assert good.mbid == "9b3c1a2e-0000-0000-0000-000000000000"
assert bad is None
def test_json_page_export_skips_now_playing():
pages = [
{
"track": [
{"artist": {"#text": "Nobody"}, "name": "Live", "@attr": {"nowplaying": "true"}},
{
"artist": {"#text": "Radiohead", "mbid": ""},
"album": {"#text": "In Rainbows"},
"name": "Nude",
"date": {"uts": str(ts(2)), "#text": "ignored"},
},
],
"@attr": {"page": "1"},
},
{"track": {"artist": {"name": "Björk"}, "name": "Hunter", "date": {"uts": str(ts(5))}}},
]
items = list(parse_json(json.dumps(pages)))
assert items[0] is None
assert [(i.artist, i.track) for i in items[1:]] == [("Radiohead", "Nude"), ("Björk", "Hunter")]
def test_json_recenttracks_response_and_flat_list():
response = {
"recenttracks": {"track": [{"artist": "A", "name": "T", "date": {"uts": str(ts(1))}}]}
}
assert [i.track for i in parse_json(json.dumps(response))] == ["T"]
flat = [{"artist": "A", "track": "U", "timestamp": ts(1)}]
assert [i.track for i in parse_json(json.dumps(flat))] == ["U"]
def test_json_errors():
with pytest.raises(ImportFailed, match="valid JSON"):
list(parse_json("{nope"))
with pytest.raises(ImportFailed, match="Last.fm export"):
list(parse_json('{"something": "else"}'))
def test_format_detection():
assert imports.detect_format("export.json", b"x") == "json"
assert imports.detect_format("scrobbles.csv", b"[") == "csv"
assert imports.detect_format(None, b' [{"a": 1}]') == "json"
assert imports.detect_format("export", b"artist,album") == "csv"
# --- File jobs ---------------------------------------------------------------------------
def test_file_import_keeps_old_plays_and_dedupes(app, user, metric_delta):
imported = metric_delta("scrobbler_imported_scrobbles_total", source="csv", result="imported")
completed = metric_delta("scrobbler_imports_total", source="csv", status="completed")
text = (
f"Radiohead,In Rainbows,Reckoner,{fmt(900)}\n" # years old: fine for an import
f"Radiohead,In Rainbows,Reckoner,{fmt(900)}\n" # repeated row
f",No Artist,Track,{fmt(3)}\n" # skipped
f"Future,,Track,{fmt(-2)}\n" # skipped: in the future
f"Portishead,Dummy,Roads,not-a-date\n" # skipped: no time
f"Björk,Homogenic,Jóga,{fmt(1)}\n"
)
job = imports.create_file_import(user, "export.csv", text.encode())
assert (job.source, job.status) == ("csv", "pending")
run_all()
job = db.session.get(ImportJob, job.id)
assert job.status == "completed"
assert (job.total, job.processed, job.imported, job.duplicates, job.skipped) == (6, 6, 2, 1, 3)
assert job.payload is None
assert [s.track for s in stored(user)] == ["Jóga", "Reckoner"]
assert (imported.delta, completed.delta) == (2, 1)
# Importing the same export again adds nothing
again = imports.create_file_import(user, "export.csv", text.encode())
run_all()
again = db.session.get(ImportJob, again.id)
assert (again.imported, again.duplicates) == (0, 3)
assert len(stored(user)) == 2
def test_gzipped_json_upload(app, user):
data = [{"artist": "A", "name": f"T{i}", "date": {"uts": str(ts(30 + i))}} for i in range(2500)]
raw = gzip.compress(json.dumps(data).encode())
job = imports.create_file_import(user, "export.json.gz", raw)
run_all()
job = db.session.get(ImportJob, job.id)
assert (job.source, job.status, job.imported) == ("json", "completed", 2500)
def test_bad_file_fails_the_job_with_a_reason(app, user, metric_delta):
failed = metric_delta("scrobbler_imports_total", source="json", status="failed")
job = imports.create_file_import(user, "export.json", b'{"not": "an export"}')
run_all()
job = db.session.get(ImportJob, job.id)
assert job.status == "failed"
assert "Last.fm export" in job.error
assert failed.delta == 1
def test_empty_upload_is_rejected(app, user):
with pytest.raises(ImportFailed):
imports.create_file_import(user, "empty.csv", b" \n")
def test_cancelled_jobs_are_not_processed(app, user):
job = imports.create_file_import(user, "export.csv", f"A,,T,{fmt(1)}\n".encode())
imports.cancel_job(user, job.id)
run_all()
job = db.session.get(ImportJob, job.id)
assert job.status == "cancelled"
assert stored(user) == []
def test_stalled_jobs_are_requeued(app, user):
job = imports.create_file_import(user, "export.csv", f"A,,T,{fmt(1)}\n".encode())
job.status = "running"
job.heartbeat_at = datetime.now(UTC) - timedelta(minutes=10)
db.session.commit()
assert imports.requeue_stalled() == 1
run_all()
assert db.session.get(ImportJob, job.id).status == "completed"
def test_jobs_are_private(app, user, make_user):
job = imports.create_file_import(user, "export.csv", f"A,,T,{fmt(1)}\n".encode())
other = make_user(username="mallory")
assert imports.get_job(other, job.id) is None
assert imports.cancel_job(other, job.id) is None
# --- Last.fm pull ------------------------------------------------------------------------
@pytest.fixture(scope="module")
def fake_lastfm(app):
"""This app's own Last.fm-compatible API stands in for last.fm."""
server = make_server("127.0.0.1", 0, app, threaded=True)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
yield f"http://127.0.0.1:{server.server_port}/2.0/"
server.shutdown()
@pytest.fixture
def lastfm_config(app, fake_lastfm, api_app):
saved = {
k: app.config[k] for k in ("LASTFM_API_KEY", "LASTFM_API_URL", "LASTFM_REQUEST_INTERVAL")
}
app.config.update(
LASTFM_API_KEY=api_app.api_key, LASTFM_API_URL=fake_lastfm, LASTFM_REQUEST_INTERVAL=0
)
yield
app.config.update(saved)
def test_lastfm_pull_needs_an_api_key(app, user):
assert not imports.lastfm_pull_available()
with pytest.raises(ImportFailed) as err:
imports.create_lastfm_import(user, "someone")
assert err.value.code == "lastfm_not_configured"
def test_lastfm_pull_pages_through_history(app, lastfm_config, user, make_user, metric_delta):
remote = make_user(username="remote")
db.session.add_all(
Scrobble(
user_id=remote.id,
artist="Artist",
track=f"Track {i}",
played_at=NOW - timedelta(hours=i + 1),
)
for i in range(450)
)
db.session.commit()
imported = metric_delta(
"scrobbler_imported_scrobbles_total", source="lastfm", result="imported"
)
job = imports.create_lastfm_import(user, "remote")
run_all()
job = db.session.get(ImportJob, job.id)
assert job.status == "completed", job.error
assert (job.total, job.imported, job.next_page) == (450, 450, 4) # 3 pages of 200
assert len(stored(user)) == 450
assert imported.delta == 450
def test_lastfm_pull_unknown_user(app, lastfm_config, user):
job = imports.create_lastfm_import(user, "nobody-by-that-name")
run_all()
job = db.session.get(ImportJob, job.id)
assert job.status == "failed"
assert job.error == "No Last.fm user with that name."
+107
View File
@@ -0,0 +1,107 @@
import io
from datetime import UTC, datetime, timedelta
import pytest
from scrobbler.services import imports
def csv_bytes(n=3) -> bytes:
day = datetime.now(UTC) - timedelta(days=400)
rows = [
f"Artist,Album,Track {i},{(day + timedelta(minutes=i)).strftime('%d %b %Y %H:%M')}"
for i in range(n)
]
return ("\n".join(rows) + "\n").encode()
def upload(client, auth, data: bytes, name="export.csv", query=""):
return client.post(
f"/api/v1/imports/file{query}",
data={"file": (io.BytesIO(data), name)},
headers=auth,
content_type="multipart/form-data",
)
def test_options_hide_lastfm_without_an_api_key(client, auth, app):
body = client.get("/api/v1/imports/options", headers=auth).get_json()
assert body["sources"] == ["csv", "json"]
assert body["max_upload_bytes"] == app.config["IMPORT_MAX_BYTES"]
def test_options_offer_lastfm_with_an_api_key(client, auth, app):
app.config["LASTFM_API_KEY"] = "configured"
try:
body = client.get("/api/v1/imports/options", headers=auth).get_json()
finally:
app.config["LASTFM_API_KEY"] = ""
assert body["sources"] == ["csv", "json", "lastfm"]
def test_upload_then_follow_progress(client, auth):
response = upload(client, auth, csv_bytes(3))
assert response.status_code == 202
job = response.get_json()
assert (job["source"], job["status"], job["filename"]) == ("csv", "pending", "export.csv")
imports.run_worker(once=True)
done = client.get(f"/api/v1/imports/{job['id']}", headers=auth).get_json()
assert (done["status"], done["imported"], done["total"]) == ("completed", 3, 3)
assert client.get("/api/v1/me/summary", headers=auth).get_json()["scrobbles"] == 3
assert [j["id"] for j in client.get("/api/v1/imports", headers=auth).get_json()] == [job["id"]]
def test_forced_format(client, auth):
response = upload(
client,
auth,
b'[{"artist": "A", "name": "T", "uts": 1600000000}]',
name="data.txt",
query="?format=json",
)
assert response.get_json()["source"] == "json"
def test_empty_upload_is_a_400(client, auth):
response = upload(client, auth, b"")
assert response.status_code == 400
assert response.get_json()["error"]["code"] == "empty_file"
def test_too_large_upload_is_a_413(client, auth, app):
saved = app.config["IMPORT_MAX_BYTES"]
app.config["IMPORT_MAX_BYTES"] = 10
try:
response = upload(client, auth, csv_bytes(3))
finally:
app.config["IMPORT_MAX_BYTES"] = saved
assert response.status_code == 413
assert response.get_json()["error"]["code"] == "file_too_large"
def test_lastfm_import_without_api_key(client, auth):
response = client.post("/api/v1/imports/lastfm", json={"username": "rj"}, headers=auth)
assert response.status_code == 400
assert response.get_json()["error"]["code"] == "lastfm_not_configured"
def test_cancel(client, auth):
job = upload(client, auth, csv_bytes(1)).get_json()
cancelled = client.post(f"/api/v1/imports/{job['id']}/cancel", headers=auth).get_json()
assert cancelled["status"] == "cancelled"
def test_other_users_imports_are_hidden(client, auth, make_user):
from scrobbler.services.accounts import issue_ui_token
job = upload(client, auth, csv_bytes(1)).get_json()
other = {"Authorization": f"Bearer {issue_ui_token(make_user(username='mallory'))}"}
assert client.get(f"/api/v1/imports/{job['id']}", headers=other).status_code == 404
assert client.post(f"/api/v1/imports/{job['id']}/cancel", headers=other).status_code == 404
assert client.get("/api/v1/imports", headers=other).get_json() == []
@pytest.mark.parametrize("path", ["/api/v1/imports", "/api/v1/imports/options"])
def test_imports_need_auth(client, path):
assert client.get(path).status_code == 401
Generated
+1 -1
View File
@@ -826,7 +826,7 @@ wheels = [
] ]
[[package]] [[package]]
name = "scrobbler" name = "scrobby"
version = "0.1.0" version = "0.1.0"
source = { editable = "." } source = { editable = "." }
dependencies = [ dependencies = [